code
stringlengths 13
6.09M
| order_type
stringclasses 2
values | original_example
dict | step_ids
listlengths 1
5
|
|---|---|---|---|
import main.Tools
class EnigmaRotor:
def __init__(self, entrata, uscita, rotore_succ=None, flag=True):
self.entrata=entrata.copy()
self.uscita=uscita.copy()
self.numeroSpostamenti=0
self.flag=flag
self.rotore_succ=rotore_succ
#Imposta il rotore sull'elemento specificato: l'elemento comparirà in cima al vettore
def impostaPosizione(self, elemento):
self.numeroSpostamenti=0
while(not(self.entrata[0].__eq__(elemento))):
self.sposta()
#Data la posizione nel vettore 'entrata', si cerca la lettera corrispondente nel vettore 'uscita' e si restituisce
#la sua posizione
def posizioneSinistra(self, posizione):
return main.Tools.search(self.uscita, self.entrata[posizione])
#Data la posizione nel vettore 'uscita', si cerca la lettera corrispondente nel vettore 'entrata' e si restituisce
#la sua posizione
def posizioneDestra(self, posizione):
return main.Tools.search(self.entrata, self.uscita[posizione])
#Sposta di una posizione gli elementi dei vettori
def muovi(self):
if self.flag==True:
self.numeroSpostamenti=self.numeroSpostamenti+1
self.sposta()
if self.numeroSpostamenti>26 and not(self.rotore_succ is None):
self.rotore_succ.muovi()
self.numeroSpostamenti=0
def sposta(self):
elementoEntrata = self.entrata.pop(0)
elementoUscita = self.uscita.pop(0)
self.entrata.append(elementoEntrata)
self.uscita.append(elementoUscita)
def getEntrata(self):
return self.entrata
def getUscita(self):
return self.uscita
def __str__(self):
return '{'+str(self.entrata)+', '+str(self.uscita)+'}'
|
normal
|
{
"blob_id": "c14673b56cb31efb5d79859dd0f6f3c6806e1056",
"index": 3576,
"step-1": "<mask token>\n\n\nclass EnigmaRotor:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def getEntrata(self):\n return self.entrata\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass EnigmaRotor:\n\n def __init__(self, entrata, uscita, rotore_succ=None, flag=True):\n self.entrata = entrata.copy()\n self.uscita = uscita.copy()\n self.numeroSpostamenti = 0\n self.flag = flag\n self.rotore_succ = rotore_succ\n\n def impostaPosizione(self, elemento):\n self.numeroSpostamenti = 0\n while not self.entrata[0].__eq__(elemento):\n self.sposta()\n <mask token>\n\n def posizioneDestra(self, posizione):\n return main.Tools.search(self.entrata, self.uscita[posizione])\n\n def muovi(self):\n if self.flag == True:\n self.numeroSpostamenti = self.numeroSpostamenti + 1\n self.sposta()\n if self.numeroSpostamenti > 26 and not self.rotore_succ is None:\n self.rotore_succ.muovi()\n self.numeroSpostamenti = 0\n\n def sposta(self):\n elementoEntrata = self.entrata.pop(0)\n elementoUscita = self.uscita.pop(0)\n self.entrata.append(elementoEntrata)\n self.uscita.append(elementoUscita)\n\n def getEntrata(self):\n return self.entrata\n\n def getUscita(self):\n return self.uscita\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass EnigmaRotor:\n\n def __init__(self, entrata, uscita, rotore_succ=None, flag=True):\n self.entrata = entrata.copy()\n self.uscita = uscita.copy()\n self.numeroSpostamenti = 0\n self.flag = flag\n self.rotore_succ = rotore_succ\n\n def impostaPosizione(self, elemento):\n self.numeroSpostamenti = 0\n while not self.entrata[0].__eq__(elemento):\n self.sposta()\n\n def posizioneSinistra(self, posizione):\n return main.Tools.search(self.uscita, self.entrata[posizione])\n\n def posizioneDestra(self, posizione):\n return main.Tools.search(self.entrata, self.uscita[posizione])\n\n def muovi(self):\n if self.flag == True:\n self.numeroSpostamenti = self.numeroSpostamenti + 1\n self.sposta()\n if self.numeroSpostamenti > 26 and not self.rotore_succ is None:\n self.rotore_succ.muovi()\n self.numeroSpostamenti = 0\n\n def sposta(self):\n elementoEntrata = self.entrata.pop(0)\n elementoUscita = self.uscita.pop(0)\n self.entrata.append(elementoEntrata)\n self.uscita.append(elementoUscita)\n\n def getEntrata(self):\n return self.entrata\n\n def getUscita(self):\n return self.uscita\n\n def __str__(self):\n return '{' + str(self.entrata) + ', ' + str(self.uscita) + '}'\n",
"step-4": "import main.Tools\n\n\nclass EnigmaRotor:\n\n def __init__(self, entrata, uscita, rotore_succ=None, flag=True):\n self.entrata = entrata.copy()\n self.uscita = uscita.copy()\n self.numeroSpostamenti = 0\n self.flag = flag\n self.rotore_succ = rotore_succ\n\n def impostaPosizione(self, elemento):\n self.numeroSpostamenti = 0\n while not self.entrata[0].__eq__(elemento):\n self.sposta()\n\n def posizioneSinistra(self, posizione):\n return main.Tools.search(self.uscita, self.entrata[posizione])\n\n def posizioneDestra(self, posizione):\n return main.Tools.search(self.entrata, self.uscita[posizione])\n\n def muovi(self):\n if self.flag == True:\n self.numeroSpostamenti = self.numeroSpostamenti + 1\n self.sposta()\n if self.numeroSpostamenti > 26 and not self.rotore_succ is None:\n self.rotore_succ.muovi()\n self.numeroSpostamenti = 0\n\n def sposta(self):\n elementoEntrata = self.entrata.pop(0)\n elementoUscita = self.uscita.pop(0)\n self.entrata.append(elementoEntrata)\n self.uscita.append(elementoUscita)\n\n def getEntrata(self):\n return self.entrata\n\n def getUscita(self):\n return self.uscita\n\n def __str__(self):\n return '{' + str(self.entrata) + ', ' + str(self.uscita) + '}'\n",
"step-5": "import main.Tools\n\nclass EnigmaRotor:\n\n def __init__(self, entrata, uscita, rotore_succ=None, flag=True):\n self.entrata=entrata.copy()\n self.uscita=uscita.copy()\n self.numeroSpostamenti=0\n self.flag=flag\n self.rotore_succ=rotore_succ\n\n #Imposta il rotore sull'elemento specificato: l'elemento comparirà in cima al vettore\n def impostaPosizione(self, elemento):\n self.numeroSpostamenti=0\n while(not(self.entrata[0].__eq__(elemento))):\n self.sposta()\n\n #Data la posizione nel vettore 'entrata', si cerca la lettera corrispondente nel vettore 'uscita' e si restituisce\n #la sua posizione\n def posizioneSinistra(self, posizione):\n return main.Tools.search(self.uscita, self.entrata[posizione])\n\n #Data la posizione nel vettore 'uscita', si cerca la lettera corrispondente nel vettore 'entrata' e si restituisce\n #la sua posizione\n def posizioneDestra(self, posizione):\n return main.Tools.search(self.entrata, self.uscita[posizione])\n\n #Sposta di una posizione gli elementi dei vettori\n def muovi(self):\n if self.flag==True:\n self.numeroSpostamenti=self.numeroSpostamenti+1\n self.sposta()\n if self.numeroSpostamenti>26 and not(self.rotore_succ is None):\n self.rotore_succ.muovi()\n self.numeroSpostamenti=0\n\n def sposta(self):\n elementoEntrata = self.entrata.pop(0)\n elementoUscita = self.uscita.pop(0)\n self.entrata.append(elementoEntrata)\n self.uscita.append(elementoUscita)\n\n def getEntrata(self):\n return self.entrata\n\n def getUscita(self):\n return self.uscita\n\n def __str__(self):\n return '{'+str(self.entrata)+', '+str(self.uscita)+'}'\n",
"step-ids": [
2,
8,
10,
11,
12
]
}
|
[
2,
8,
10,
11,
12
] |
<|reserved_special_token_0|>
class Workout(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def addRepeat(self, names, durations, count):
self.workout.append(Repeat(names, durations, count))
def generateCode(self, filename=None):
if not filename is None:
file = open(filename, 'w')
else:
file = sys.stdout
def wr(txt):
file.write(txt + '\n')
wr('/* Reset */')
wr('if (SUUNTO_DURATION == 0) {')
wr(' STEP = 0;')
wr(' PREVSTEP = 0;')
wr(' STEPSTARTTIME = 0;')
wr(' STEPSTARTDIST = 0;')
wr(' STEPTIME = 0;')
wr(' STEPDIST = 0;')
wr('}')
wr('')
wr('/* Next step */')
wr('if (STEP != PREVSTEP) {')
wr(' Suunto.alarmBeep();')
wr(' STEPSTARTTIME = SUUNTO_DURATION;')
wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')
wr('}')
wr('')
wr('/* Update */')
wr('PREVSTEP = STEP;')
wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')
wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')
wr('')
step = 0
for w in self.workout:
step = w.generateCode(file, step, self.postfixEnabled)
wr('/* Check result */')
wr('if ( RESULT <= 0 ) {')
wr(' STEP = STEP + 1;')
wr(' RESULT = 0;')
wr('}')
if not filename is None:
file.close()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Workout(object):
<|reserved_special_token_0|>
def addStep(self, name, duration):
self.workout.append(Step(name, duration))
def addRepeat(self, names, durations, count):
self.workout.append(Repeat(names, durations, count))
def generateCode(self, filename=None):
if not filename is None:
file = open(filename, 'w')
else:
file = sys.stdout
def wr(txt):
file.write(txt + '\n')
wr('/* Reset */')
wr('if (SUUNTO_DURATION == 0) {')
wr(' STEP = 0;')
wr(' PREVSTEP = 0;')
wr(' STEPSTARTTIME = 0;')
wr(' STEPSTARTDIST = 0;')
wr(' STEPTIME = 0;')
wr(' STEPDIST = 0;')
wr('}')
wr('')
wr('/* Next step */')
wr('if (STEP != PREVSTEP) {')
wr(' Suunto.alarmBeep();')
wr(' STEPSTARTTIME = SUUNTO_DURATION;')
wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')
wr('}')
wr('')
wr('/* Update */')
wr('PREVSTEP = STEP;')
wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')
wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')
wr('')
step = 0
for w in self.workout:
step = w.generateCode(file, step, self.postfixEnabled)
wr('/* Check result */')
wr('if ( RESULT <= 0 ) {')
wr(' STEP = STEP + 1;')
wr(' RESULT = 0;')
wr('}')
if not filename is None:
file.close()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Workout(object):
def __init__(self):
self.workout = []
self.steps = []
self.postfixEnabled = True
def addStep(self, name, duration):
self.workout.append(Step(name, duration))
def addRepeat(self, names, durations, count):
self.workout.append(Repeat(names, durations, count))
def generateCode(self, filename=None):
if not filename is None:
file = open(filename, 'w')
else:
file = sys.stdout
def wr(txt):
file.write(txt + '\n')
wr('/* Reset */')
wr('if (SUUNTO_DURATION == 0) {')
wr(' STEP = 0;')
wr(' PREVSTEP = 0;')
wr(' STEPSTARTTIME = 0;')
wr(' STEPSTARTDIST = 0;')
wr(' STEPTIME = 0;')
wr(' STEPDIST = 0;')
wr('}')
wr('')
wr('/* Next step */')
wr('if (STEP != PREVSTEP) {')
wr(' Suunto.alarmBeep();')
wr(' STEPSTARTTIME = SUUNTO_DURATION;')
wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')
wr('}')
wr('')
wr('/* Update */')
wr('PREVSTEP = STEP;')
wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')
wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')
wr('')
step = 0
for w in self.workout:
step = w.generateCode(file, step, self.postfixEnabled)
wr('/* Check result */')
wr('if ( RESULT <= 0 ) {')
wr(' STEP = STEP + 1;')
wr(' RESULT = 0;')
wr('}')
if not filename is None:
file.close()
<|reserved_special_token_1|>
import sys
from .step import Step
from .repeat import Repeat
class Workout(object):
def __init__(self):
self.workout = []
self.steps = []
self.postfixEnabled = True
def addStep(self, name, duration):
self.workout.append(Step(name, duration))
def addRepeat(self, names, durations, count):
self.workout.append(Repeat(names, durations, count))
def generateCode(self, filename=None):
if not filename is None:
file = open(filename, 'w')
else:
file = sys.stdout
def wr(txt):
file.write(txt + '\n')
wr('/* Reset */')
wr('if (SUUNTO_DURATION == 0) {')
wr(' STEP = 0;')
wr(' PREVSTEP = 0;')
wr(' STEPSTARTTIME = 0;')
wr(' STEPSTARTDIST = 0;')
wr(' STEPTIME = 0;')
wr(' STEPDIST = 0;')
wr('}')
wr('')
wr('/* Next step */')
wr('if (STEP != PREVSTEP) {')
wr(' Suunto.alarmBeep();')
wr(' STEPSTARTTIME = SUUNTO_DURATION;')
wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')
wr('}')
wr('')
wr('/* Update */')
wr('PREVSTEP = STEP;')
wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')
wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')
wr('')
step = 0
for w in self.workout:
step = w.generateCode(file, step, self.postfixEnabled)
wr('/* Check result */')
wr('if ( RESULT <= 0 ) {')
wr(' STEP = STEP + 1;')
wr(' RESULT = 0;')
wr('}')
if not filename is None:
file.close()
<|reserved_special_token_1|>
# Import
import sys
from .step import Step
from .repeat import Repeat
# Workout
class Workout(object):
def __init__(self):
self.workout = []
self.steps = []
self.postfixEnabled = True
# TODO: check that len(name) <= 6
def addStep(self, name, duration):
self.workout.append(Step(name, duration))
# TODO: check that len(name) <= 6 - len(count)
def addRepeat(self, names, durations, count):
self.workout.append(Repeat(names, durations, count))
def generateCode(self, filename=None):
# Open
if not filename is None:
file = open(filename, 'w')
else:
file = sys.stdout
def wr(txt):
file.write(txt + '\n')
# Generate
wr('/* Reset */')
wr('if (SUUNTO_DURATION == 0) {')
wr(' STEP = 0;')
wr(' PREVSTEP = 0;')
wr(' STEPSTARTTIME = 0;')
wr(' STEPSTARTDIST = 0;')
wr(' STEPTIME = 0;')
wr(' STEPDIST = 0;')
wr('}')
wr('')
wr('/* Next step */')
wr('if (STEP != PREVSTEP) {')
wr(' Suunto.alarmBeep();')
wr(' STEPSTARTTIME = SUUNTO_DURATION;')
wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')
wr('}')
wr('')
wr('/* Update */')
wr('PREVSTEP = STEP;')
wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')
wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')
wr('')
step = 0
for w in self.workout:
step = w.generateCode(file,step,self.postfixEnabled)
wr('/* Check result */')
wr('if ( RESULT <= 0 ) {')
wr(' STEP = STEP + 1;')
wr(' RESULT = 0;')
wr('}')
# Close
if not filename is None:
file.close()
|
flexible
|
{
"blob_id": "3f80c4c212259a8f3ff96bcc745fd28a85dac3ba",
"index": 8807,
"step-1": "<mask token>\n\n\nclass Workout(object):\n <mask token>\n <mask token>\n\n def addRepeat(self, names, durations, count):\n self.workout.append(Repeat(names, durations, count))\n\n def generateCode(self, filename=None):\n if not filename is None:\n file = open(filename, 'w')\n else:\n file = sys.stdout\n\n def wr(txt):\n file.write(txt + '\\n')\n wr('/* Reset */')\n wr('if (SUUNTO_DURATION == 0) {')\n wr(' STEP = 0;')\n wr(' PREVSTEP = 0;')\n wr(' STEPSTARTTIME = 0;')\n wr(' STEPSTARTDIST = 0;')\n wr(' STEPTIME = 0;')\n wr(' STEPDIST = 0;')\n wr('}')\n wr('')\n wr('/* Next step */')\n wr('if (STEP != PREVSTEP) {')\n wr(' Suunto.alarmBeep();')\n wr(' STEPSTARTTIME = SUUNTO_DURATION;')\n wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')\n wr('}')\n wr('')\n wr('/* Update */')\n wr('PREVSTEP = STEP;')\n wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')\n wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')\n wr('')\n step = 0\n for w in self.workout:\n step = w.generateCode(file, step, self.postfixEnabled)\n wr('/* Check result */')\n wr('if ( RESULT <= 0 ) {')\n wr(' STEP = STEP + 1;')\n wr(' RESULT = 0;')\n wr('}')\n if not filename is None:\n file.close()\n",
"step-2": "<mask token>\n\n\nclass Workout(object):\n <mask token>\n\n def addStep(self, name, duration):\n self.workout.append(Step(name, duration))\n\n def addRepeat(self, names, durations, count):\n self.workout.append(Repeat(names, durations, count))\n\n def generateCode(self, filename=None):\n if not filename is None:\n file = open(filename, 'w')\n else:\n file = sys.stdout\n\n def wr(txt):\n file.write(txt + '\\n')\n wr('/* Reset */')\n wr('if (SUUNTO_DURATION == 0) {')\n wr(' STEP = 0;')\n wr(' PREVSTEP = 0;')\n wr(' STEPSTARTTIME = 0;')\n wr(' STEPSTARTDIST = 0;')\n wr(' STEPTIME = 0;')\n wr(' STEPDIST = 0;')\n wr('}')\n wr('')\n wr('/* Next step */')\n wr('if (STEP != PREVSTEP) {')\n wr(' Suunto.alarmBeep();')\n wr(' STEPSTARTTIME = SUUNTO_DURATION;')\n wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')\n wr('}')\n wr('')\n wr('/* Update */')\n wr('PREVSTEP = STEP;')\n wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')\n wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')\n wr('')\n step = 0\n for w in self.workout:\n step = w.generateCode(file, step, self.postfixEnabled)\n wr('/* Check result */')\n wr('if ( RESULT <= 0 ) {')\n wr(' STEP = STEP + 1;')\n wr(' RESULT = 0;')\n wr('}')\n if not filename is None:\n file.close()\n",
"step-3": "<mask token>\n\n\nclass Workout(object):\n\n def __init__(self):\n self.workout = []\n self.steps = []\n self.postfixEnabled = True\n\n def addStep(self, name, duration):\n self.workout.append(Step(name, duration))\n\n def addRepeat(self, names, durations, count):\n self.workout.append(Repeat(names, durations, count))\n\n def generateCode(self, filename=None):\n if not filename is None:\n file = open(filename, 'w')\n else:\n file = sys.stdout\n\n def wr(txt):\n file.write(txt + '\\n')\n wr('/* Reset */')\n wr('if (SUUNTO_DURATION == 0) {')\n wr(' STEP = 0;')\n wr(' PREVSTEP = 0;')\n wr(' STEPSTARTTIME = 0;')\n wr(' STEPSTARTDIST = 0;')\n wr(' STEPTIME = 0;')\n wr(' STEPDIST = 0;')\n wr('}')\n wr('')\n wr('/* Next step */')\n wr('if (STEP != PREVSTEP) {')\n wr(' Suunto.alarmBeep();')\n wr(' STEPSTARTTIME = SUUNTO_DURATION;')\n wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')\n wr('}')\n wr('')\n wr('/* Update */')\n wr('PREVSTEP = STEP;')\n wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')\n wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')\n wr('')\n step = 0\n for w in self.workout:\n step = w.generateCode(file, step, self.postfixEnabled)\n wr('/* Check result */')\n wr('if ( RESULT <= 0 ) {')\n wr(' STEP = STEP + 1;')\n wr(' RESULT = 0;')\n wr('}')\n if not filename is None:\n file.close()\n",
"step-4": "import sys\nfrom .step import Step\nfrom .repeat import Repeat\n\n\nclass Workout(object):\n\n def __init__(self):\n self.workout = []\n self.steps = []\n self.postfixEnabled = True\n\n def addStep(self, name, duration):\n self.workout.append(Step(name, duration))\n\n def addRepeat(self, names, durations, count):\n self.workout.append(Repeat(names, durations, count))\n\n def generateCode(self, filename=None):\n if not filename is None:\n file = open(filename, 'w')\n else:\n file = sys.stdout\n\n def wr(txt):\n file.write(txt + '\\n')\n wr('/* Reset */')\n wr('if (SUUNTO_DURATION == 0) {')\n wr(' STEP = 0;')\n wr(' PREVSTEP = 0;')\n wr(' STEPSTARTTIME = 0;')\n wr(' STEPSTARTDIST = 0;')\n wr(' STEPTIME = 0;')\n wr(' STEPDIST = 0;')\n wr('}')\n wr('')\n wr('/* Next step */')\n wr('if (STEP != PREVSTEP) {')\n wr(' Suunto.alarmBeep();')\n wr(' STEPSTARTTIME = SUUNTO_DURATION;')\n wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')\n wr('}')\n wr('')\n wr('/* Update */')\n wr('PREVSTEP = STEP;')\n wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')\n wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')\n wr('')\n step = 0\n for w in self.workout:\n step = w.generateCode(file, step, self.postfixEnabled)\n wr('/* Check result */')\n wr('if ( RESULT <= 0 ) {')\n wr(' STEP = STEP + 1;')\n wr(' RESULT = 0;')\n wr('}')\n if not filename is None:\n file.close()\n",
"step-5": "# Import\nimport sys\nfrom .step import Step\nfrom .repeat import Repeat\n\n# Workout\nclass Workout(object):\n\n def __init__(self):\n self.workout = []\n self.steps = []\n self.postfixEnabled = True\n\n # TODO: check that len(name) <= 6\n def addStep(self, name, duration):\n self.workout.append(Step(name, duration))\n\n # TODO: check that len(name) <= 6 - len(count)\n def addRepeat(self, names, durations, count):\n self.workout.append(Repeat(names, durations, count))\n\n def generateCode(self, filename=None):\n\n # Open\n if not filename is None:\n file = open(filename, 'w')\n else:\n file = sys.stdout\n\n def wr(txt):\n file.write(txt + '\\n')\n\n # Generate\n wr('/* Reset */')\n wr('if (SUUNTO_DURATION == 0) {')\n wr(' STEP = 0;')\n wr(' PREVSTEP = 0;')\n wr(' STEPSTARTTIME = 0;')\n wr(' STEPSTARTDIST = 0;')\n wr(' STEPTIME = 0;')\n wr(' STEPDIST = 0;')\n wr('}')\n wr('')\n\n wr('/* Next step */')\n wr('if (STEP != PREVSTEP) {')\n wr(' Suunto.alarmBeep();')\n wr(' STEPSTARTTIME = SUUNTO_DURATION;')\n wr(' STEPSTARTDIST = SUUNTO_DISTANCE*1000;')\n wr('}')\n wr('')\n \n wr('/* Update */')\n wr('PREVSTEP = STEP;')\n wr('STEPTIME = SUUNTO_DURATION - STEPSTARTTIME;')\n wr('STEPDIST = SUUNTO_DISTANCE*1000 - STEPSTARTDIST;')\n wr('')\n\n step = 0\n for w in self.workout:\n step = w.generateCode(file,step,self.postfixEnabled)\n\n wr('/* Check result */')\n wr('if ( RESULT <= 0 ) {')\n wr(' STEP = STEP + 1;')\n wr(' RESULT = 0;')\n wr('}')\n\n # Close\n if not filename is None:\n file.close()\n\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
#!/usr/bin/env python3
from collections import deque
from itertools import permutations
INS_ADD = 1
INS_MULTIPLY = 2
INS_INPUT = 3
INS_OUTPUT = 4
INS_JUMP_IF_TRUE = 5
INS_JUMP_IF_FALSE = 6
INS_LESS_THAN = 7
INS_EQUALS = 8
INS_ADJUST_RELATIVE_BASE = 9
INS_DONE = 99
MODE_POSITION = 0
MODE_IMMEDIATE = 1
MODE_RELATIVE = 2
class InvalidInstructionException (Exception):
def __init__(self, instruction):
super().__init__("<%d>" % instruction)
class InvalidModeException (Exception):
pass
class Computer:
def __init__(self, data, inputs, memory_size=8192, interactive=True):
self._memory = [0] * memory_size
for i in range(len(data)):
self._memory[i] = data[i]
self._pc = 0
self._inputs = deque(inputs)
self._outputs = []
self._relative_base = 0
self._interactive = interactive
def input(self, value):
self._inputs.append(value)
def _parse_modes(self, instruction):
i = "%.5d" % instruction
return (int(i[2]), int(i[1]), int(i[0]))
def _fetch(self):
instruction = self._memory[self._pc]
self._pc += 1
if instruction > 100:
return instruction % 100, self._parse_modes(instruction)
else:
return instruction, (MODE_POSITION, MODE_POSITION, MODE_POSITION)
def _pop(self):
v = self._memory[self._pc]
self._pc += 1
return v
def _load(self, a, mode):
if mode == MODE_IMMEDIATE:
return a
elif mode == MODE_POSITION:
return self._memory[a]
elif mode == MODE_RELATIVE:
return self._memory[self._relative_base + a]
else:
raise InvalidModeException()
def _store(self, a, mode, v):
if mode == MODE_IMMEDIATE:
pass
if mode == MODE_POSITION:
self._memory[a] = v
elif mode == MODE_RELATIVE:
self._memory[self._relative_base + a] = v
else:
raise InvalidModeException()
def _add(self, modes, a, b, d):
self._store(d, modes[2], self._load(a, modes[0]) + self._load(b, modes[1]))
def _multiply(self, modes, a, b, d):
self._store(d, modes[2], self._load(a, modes[0]) * self._load(b, modes[1]))
def _input(self, modes, a):
if self._interactive:
self._store(a, modes[0], int(input("=> ")))
else:
self._store(a, modes[0], self._inputs.popleft())
def _output(self, modes, s):
v = self._load(s, modes[0])
if self._interactive:
print(v)
else:
self._outputs.append(v)
def _jump_if_true(self, modes, a, d):
if self._load(a, modes[0]) != 0:
self._pc = self._load(d, modes[1])
def _jump_if_false(self, modes, a, d):
if self._load(a, modes[0]) == 0:
self._pc = self._load(d, modes[1])
def _less_than(self, modes, a, b, d):
if self._load(a, modes[0]) < self._load(b, modes[1]):
self._store(d, modes[2], 1)
else:
self._store(d, modes[2], 0)
def _equals(self, modes, a, b, d):
if self._load(a, modes[0]) == self._load(b, modes[1]):
self._store(d, modes[2], 1)
else:
self._store(d, modes[2], 0)
def _adjust_relative_base(self, modes, a):
self._relative_base += self._load(a, modes[0])
def run(self, debug = False):
while True:
instruction, modes = self._fetch()
if debug:
print(instruction, modes)
if instruction == INS_ADD:
self._add(modes, self._pop(), self._pop(), self._pop())
elif instruction == INS_MULTIPLY:
self._multiply(modes, self._pop(), self._pop(), self._pop())
elif instruction == INS_INPUT:
self._input(modes, self._pop())
elif instruction == INS_OUTPUT:
v = self._output(modes, self._pop())
if not self._interactive:
return v
elif instruction == INS_JUMP_IF_TRUE:
self._jump_if_true(modes, self._pop(), self._pop())
elif instruction == INS_JUMP_IF_FALSE:
self._jump_if_false(modes, self._pop(), self._pop())
elif instruction == INS_LESS_THAN:
self._less_than(modes, self._pop(), self._pop(), self._pop())
elif instruction == INS_EQUALS:
self._equals(modes, self._pop(), self._pop(), self._pop())
elif instruction == INS_ADJUST_RELATIVE_BASE:
self._adjust_relative_base(modes, self._pop())
elif instruction == INS_DONE:
return self._outputs
else:
raise InvalidInstructionException(instruction)
PROGRAM = [1102,34463338,34463338,63,1007,63,34463338,63,1005,63,53,1101,0,3,1000,109,988,209,12,9,1000,209,6,209,3,203,0,1008,1000,1,63,1005,63,65,1008,1000,2,63,1005,63,904,1008,1000,0,63,1005,63,58,4,25,104,0,99,4,0,104,0,99,4,17,104,0,99,0,0,1101,0,396,1029,1101,0,356,1023,1101,401,0,1028,1101,24,0,1008,1101,33,0,1019,1101,35,0,1010,1102,359,1,1022,1102,32,1,1001,1101,37,0,1004,1101,0,31,1009,1101,0,30,1003,1101,28,0,1002,1102,1,36,1014,1102,20,1,1012,1101,21,0,1000,1101,0,22,1015,1102,23,1,1013,1102,1,1,1021,1102,1,39,1007,1102,26,1,1017,1101,0,38,1016,1101,0,437,1024,1102,432,1,1025,1101,0,421,1026,1101,0,29,1005,1101,27,0,1011,1102,1,0,1020,1101,0,25,1018,1101,0,414,1027,1102,34,1,1006,109,6,2108,33,-3,63,1005,63,201,1001,64,1,64,1105,1,203,4,187,1002,64,2,64,109,14,21108,40,40,-6,1005,1014,221,4,209,1105,1,225,1001,64,1,64,1002,64,2,64,109,-21,2102,1,3,63,1008,63,28,63,1005,63,251,4,231,1001,64,1,64,1106,0,251,1002,64,2,64,109,12,2101,0,-3,63,1008,63,21,63,1005,63,275,1001,64,1,64,1105,1,277,4,257,1002,64,2,64,109,-10,1207,1,27,63,1005,63,293,1105,1,299,4,283,1001,64,1,64,1002,64,2,64,109,9,21108,41,42,3,1005,1013,315,1105,1,321,4,305,1001,64,1,64,1002,64,2,64,109,-12,1202,6,1,63,1008,63,37,63,1005,63,347,4,327,1001,64,1,64,1105,1,347,1002,64,2,64,109,29,2105,1,-4,1105,1,365,4,353,1001,64,1,64,1002,64,2,64,109,-17,2108,32,-9,63,1005,63,387,4,371,1001,64,1,64,1105,1,387,1002,64,2,64,109,17,2106,0,1,4,393,1105,1,405,1001,64,1,64,1002,64,2,64,109,1,2106,0,-1,1001,64,1,64,1106,0,423,4,411,1002,64,2,64,109,-13,2105,1,9,4,429,1106,0,441,1001,64,1,64,1002,64,2,64,109,3,21107,42,41,-1,1005,1017,461,1001,64,1,64,1106,0,463,4,447,1002,64,2,64,109,-4,21107,43,44,1,1005,1015,481,4,469,1106,0,485,1001,64,1,64,1002,64,2,64,109,-6,21101,44,0,6,1008,1014,47,63,1005,63,505,1106,0,511,4,491,1001,64,1,64,1002,64,2,64,109,-6,1208,-1,32,63,1005,63,529,4,517,1105,1,533,1001,64,1,64,1002,64,2,64,109,11,1205,7,545,1106,0,551,4,539,1001,64,1,64,1002,64,2,64,109,11,21102,45,1,-7,1008,1017,48,63,1005,63,575,1001,64,1,64,1106,0,577,4,557,1002,64,2,64,109,-8,1206,5,593,1001,64,1,64,1105,1,595,4,583,1002,64,2,64,109,7,1206,-3,609,4,601,1106,0,613,1001,64,1,64,1002,64,2,64,109,-10,2101,0,-6,63,1008,63,39,63,1005,63,635,4,619,1106,0,639,1001,64,1,64,1002,64,2,64,109,-9,1208,0,39,63,1005,63,655,1106,0,661,4,645,1001,64,1,64,1002,64,2,64,109,4,2107,25,0,63,1005,63,681,1001,64,1,64,1105,1,683,4,667,1002,64,2,64,109,-5,2107,31,-2,63,1005,63,701,4,689,1106,0,705,1001,64,1,64,1002,64,2,64,109,19,1205,-1,719,4,711,1105,1,723,1001,64,1,64,1002,64,2,64,109,-17,1201,3,0,63,1008,63,24,63,1005,63,745,4,729,1106,0,749,1001,64,1,64,1002,64,2,64,109,13,21102,46,1,-3,1008,1015,46,63,1005,63,771,4,755,1105,1,775,1001,64,1,64,1002,64,2,64,109,-13,1207,4,32,63,1005,63,793,4,781,1106,0,797,1001,64,1,64,1002,64,2,64,109,7,2102,1,-9,63,1008,63,27,63,1005,63,821,1001,64,1,64,1105,1,823,4,803,1002,64,2,64,109,-18,1201,8,0,63,1008,63,25,63,1005,63,847,1001,64,1,64,1106,0,849,4,829,1002,64,2,64,109,23,21101,47,0,2,1008,1019,47,63,1005,63,871,4,855,1106,0,875,1001,64,1,64,1002,64,2,64,109,-22,1202,5,1,63,1008,63,19,63,1005,63,899,1001,64,1,64,1106,0,901,4,881,4,64,99,21102,27,1,1,21102,1,915,0,1105,1,922,21201,1,25165,1,204,1,99,109,3,1207,-2,3,63,1005,63,964,21201,-2,-1,1,21102,942,1,0,1105,1,922,22102,1,1,-1,21201,-2,-3,1,21101,0,957,0,1105,1,922,22201,1,-1,-2,1106,0,968,21201,-2,0,-2,109,-3,2105,1,0]
if __name__ == "__main__":
c = Computer(PROGRAM, [])
c.run()
|
normal
|
{
"blob_id": "121fddf022c4eed7fd00e81edcb2df6a7a3b7510",
"index": 4903,
"step-1": "<mask token>\n\n\nclass Computer:\n\n def __init__(self, data, inputs, memory_size=8192, interactive=True):\n self._memory = [0] * memory_size\n for i in range(len(data)):\n self._memory[i] = data[i]\n self._pc = 0\n self._inputs = deque(inputs)\n self._outputs = []\n self._relative_base = 0\n self._interactive = interactive\n\n def input(self, value):\n self._inputs.append(value)\n\n def _parse_modes(self, instruction):\n i = '%.5d' % instruction\n return int(i[2]), int(i[1]), int(i[0])\n\n def _fetch(self):\n instruction = self._memory[self._pc]\n self._pc += 1\n if instruction > 100:\n return instruction % 100, self._parse_modes(instruction)\n else:\n return instruction, (MODE_POSITION, MODE_POSITION, MODE_POSITION)\n\n def _pop(self):\n v = self._memory[self._pc]\n self._pc += 1\n return v\n\n def _load(self, a, mode):\n if mode == MODE_IMMEDIATE:\n return a\n elif mode == MODE_POSITION:\n return self._memory[a]\n elif mode == MODE_RELATIVE:\n return self._memory[self._relative_base + a]\n else:\n raise InvalidModeException()\n\n def _store(self, a, mode, v):\n if mode == MODE_IMMEDIATE:\n pass\n if mode == MODE_POSITION:\n self._memory[a] = v\n elif mode == MODE_RELATIVE:\n self._memory[self._relative_base + a] = v\n else:\n raise InvalidModeException()\n\n def _add(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) + self._load(b,\n modes[1]))\n\n def _multiply(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) * self._load(b,\n modes[1]))\n\n def _input(self, modes, a):\n if self._interactive:\n self._store(a, modes[0], int(input('=> ')))\n else:\n self._store(a, modes[0], self._inputs.popleft())\n\n def _output(self, modes, s):\n v = self._load(s, modes[0])\n if self._interactive:\n print(v)\n else:\n self._outputs.append(v)\n\n def _jump_if_true(self, modes, a, d):\n if self._load(a, modes[0]) != 0:\n self._pc = self._load(d, modes[1])\n\n def _jump_if_false(self, modes, a, d):\n if self._load(a, modes[0]) == 0:\n self._pc = self._load(d, modes[1])\n\n def _less_than(self, modes, a, b, d):\n if self._load(a, modes[0]) < self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _equals(self, modes, a, b, d):\n if self._load(a, modes[0]) == self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _adjust_relative_base(self, modes, a):\n self._relative_base += self._load(a, modes[0])\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass InvalidModeException(Exception):\n pass\n\n\nclass Computer:\n\n def __init__(self, data, inputs, memory_size=8192, interactive=True):\n self._memory = [0] * memory_size\n for i in range(len(data)):\n self._memory[i] = data[i]\n self._pc = 0\n self._inputs = deque(inputs)\n self._outputs = []\n self._relative_base = 0\n self._interactive = interactive\n\n def input(self, value):\n self._inputs.append(value)\n\n def _parse_modes(self, instruction):\n i = '%.5d' % instruction\n return int(i[2]), int(i[1]), int(i[0])\n\n def _fetch(self):\n instruction = self._memory[self._pc]\n self._pc += 1\n if instruction > 100:\n return instruction % 100, self._parse_modes(instruction)\n else:\n return instruction, (MODE_POSITION, MODE_POSITION, MODE_POSITION)\n\n def _pop(self):\n v = self._memory[self._pc]\n self._pc += 1\n return v\n\n def _load(self, a, mode):\n if mode == MODE_IMMEDIATE:\n return a\n elif mode == MODE_POSITION:\n return self._memory[a]\n elif mode == MODE_RELATIVE:\n return self._memory[self._relative_base + a]\n else:\n raise InvalidModeException()\n\n def _store(self, a, mode, v):\n if mode == MODE_IMMEDIATE:\n pass\n if mode == MODE_POSITION:\n self._memory[a] = v\n elif mode == MODE_RELATIVE:\n self._memory[self._relative_base + a] = v\n else:\n raise InvalidModeException()\n\n def _add(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) + self._load(b,\n modes[1]))\n\n def _multiply(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) * self._load(b,\n modes[1]))\n\n def _input(self, modes, a):\n if self._interactive:\n self._store(a, modes[0], int(input('=> ')))\n else:\n self._store(a, modes[0], self._inputs.popleft())\n\n def _output(self, modes, s):\n v = self._load(s, modes[0])\n if self._interactive:\n print(v)\n else:\n self._outputs.append(v)\n\n def _jump_if_true(self, modes, a, d):\n if self._load(a, modes[0]) != 0:\n self._pc = self._load(d, modes[1])\n\n def _jump_if_false(self, modes, a, d):\n if self._load(a, modes[0]) == 0:\n self._pc = self._load(d, modes[1])\n\n def _less_than(self, modes, a, b, d):\n if self._load(a, modes[0]) < self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _equals(self, modes, a, b, d):\n if self._load(a, modes[0]) == self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _adjust_relative_base(self, modes, a):\n self._relative_base += self._load(a, modes[0])\n\n def run(self, debug=False):\n while True:\n instruction, modes = self._fetch()\n if debug:\n print(instruction, modes)\n if instruction == INS_ADD:\n self._add(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_MULTIPLY:\n self._multiply(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_INPUT:\n self._input(modes, self._pop())\n elif instruction == INS_OUTPUT:\n v = self._output(modes, self._pop())\n if not self._interactive:\n return v\n elif instruction == INS_JUMP_IF_TRUE:\n self._jump_if_true(modes, self._pop(), self._pop())\n elif instruction == INS_JUMP_IF_FALSE:\n self._jump_if_false(modes, self._pop(), self._pop())\n elif instruction == INS_LESS_THAN:\n self._less_than(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_EQUALS:\n self._equals(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_ADJUST_RELATIVE_BASE:\n self._adjust_relative_base(modes, self._pop())\n elif instruction == INS_DONE:\n return self._outputs\n else:\n raise InvalidInstructionException(instruction)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass InvalidInstructionException(Exception):\n\n def __init__(self, instruction):\n super().__init__('<%d>' % instruction)\n\n\nclass InvalidModeException(Exception):\n pass\n\n\nclass Computer:\n\n def __init__(self, data, inputs, memory_size=8192, interactive=True):\n self._memory = [0] * memory_size\n for i in range(len(data)):\n self._memory[i] = data[i]\n self._pc = 0\n self._inputs = deque(inputs)\n self._outputs = []\n self._relative_base = 0\n self._interactive = interactive\n\n def input(self, value):\n self._inputs.append(value)\n\n def _parse_modes(self, instruction):\n i = '%.5d' % instruction\n return int(i[2]), int(i[1]), int(i[0])\n\n def _fetch(self):\n instruction = self._memory[self._pc]\n self._pc += 1\n if instruction > 100:\n return instruction % 100, self._parse_modes(instruction)\n else:\n return instruction, (MODE_POSITION, MODE_POSITION, MODE_POSITION)\n\n def _pop(self):\n v = self._memory[self._pc]\n self._pc += 1\n return v\n\n def _load(self, a, mode):\n if mode == MODE_IMMEDIATE:\n return a\n elif mode == MODE_POSITION:\n return self._memory[a]\n elif mode == MODE_RELATIVE:\n return self._memory[self._relative_base + a]\n else:\n raise InvalidModeException()\n\n def _store(self, a, mode, v):\n if mode == MODE_IMMEDIATE:\n pass\n if mode == MODE_POSITION:\n self._memory[a] = v\n elif mode == MODE_RELATIVE:\n self._memory[self._relative_base + a] = v\n else:\n raise InvalidModeException()\n\n def _add(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) + self._load(b,\n modes[1]))\n\n def _multiply(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) * self._load(b,\n modes[1]))\n\n def _input(self, modes, a):\n if self._interactive:\n self._store(a, modes[0], int(input('=> ')))\n else:\n self._store(a, modes[0], self._inputs.popleft())\n\n def _output(self, modes, s):\n v = self._load(s, modes[0])\n if self._interactive:\n print(v)\n else:\n self._outputs.append(v)\n\n def _jump_if_true(self, modes, a, d):\n if self._load(a, modes[0]) != 0:\n self._pc = self._load(d, modes[1])\n\n def _jump_if_false(self, modes, a, d):\n if self._load(a, modes[0]) == 0:\n self._pc = self._load(d, modes[1])\n\n def _less_than(self, modes, a, b, d):\n if self._load(a, modes[0]) < self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _equals(self, modes, a, b, d):\n if self._load(a, modes[0]) == self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _adjust_relative_base(self, modes, a):\n self._relative_base += self._load(a, modes[0])\n\n def run(self, debug=False):\n while True:\n instruction, modes = self._fetch()\n if debug:\n print(instruction, modes)\n if instruction == INS_ADD:\n self._add(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_MULTIPLY:\n self._multiply(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_INPUT:\n self._input(modes, self._pop())\n elif instruction == INS_OUTPUT:\n v = self._output(modes, self._pop())\n if not self._interactive:\n return v\n elif instruction == INS_JUMP_IF_TRUE:\n self._jump_if_true(modes, self._pop(), self._pop())\n elif instruction == INS_JUMP_IF_FALSE:\n self._jump_if_false(modes, self._pop(), self._pop())\n elif instruction == INS_LESS_THAN:\n self._less_than(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_EQUALS:\n self._equals(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_ADJUST_RELATIVE_BASE:\n self._adjust_relative_base(modes, self._pop())\n elif instruction == INS_DONE:\n return self._outputs\n else:\n raise InvalidInstructionException(instruction)\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass InvalidInstructionException(Exception):\n\n def __init__(self, instruction):\n super().__init__('<%d>' % instruction)\n\n\nclass InvalidModeException(Exception):\n pass\n\n\nclass Computer:\n\n def __init__(self, data, inputs, memory_size=8192, interactive=True):\n self._memory = [0] * memory_size\n for i in range(len(data)):\n self._memory[i] = data[i]\n self._pc = 0\n self._inputs = deque(inputs)\n self._outputs = []\n self._relative_base = 0\n self._interactive = interactive\n\n def input(self, value):\n self._inputs.append(value)\n\n def _parse_modes(self, instruction):\n i = '%.5d' % instruction\n return int(i[2]), int(i[1]), int(i[0])\n\n def _fetch(self):\n instruction = self._memory[self._pc]\n self._pc += 1\n if instruction > 100:\n return instruction % 100, self._parse_modes(instruction)\n else:\n return instruction, (MODE_POSITION, MODE_POSITION, MODE_POSITION)\n\n def _pop(self):\n v = self._memory[self._pc]\n self._pc += 1\n return v\n\n def _load(self, a, mode):\n if mode == MODE_IMMEDIATE:\n return a\n elif mode == MODE_POSITION:\n return self._memory[a]\n elif mode == MODE_RELATIVE:\n return self._memory[self._relative_base + a]\n else:\n raise InvalidModeException()\n\n def _store(self, a, mode, v):\n if mode == MODE_IMMEDIATE:\n pass\n if mode == MODE_POSITION:\n self._memory[a] = v\n elif mode == MODE_RELATIVE:\n self._memory[self._relative_base + a] = v\n else:\n raise InvalidModeException()\n\n def _add(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) + self._load(b,\n modes[1]))\n\n def _multiply(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) * self._load(b,\n modes[1]))\n\n def _input(self, modes, a):\n if self._interactive:\n self._store(a, modes[0], int(input('=> ')))\n else:\n self._store(a, modes[0], self._inputs.popleft())\n\n def _output(self, modes, s):\n v = self._load(s, modes[0])\n if self._interactive:\n print(v)\n else:\n self._outputs.append(v)\n\n def _jump_if_true(self, modes, a, d):\n if self._load(a, modes[0]) != 0:\n self._pc = self._load(d, modes[1])\n\n def _jump_if_false(self, modes, a, d):\n if self._load(a, modes[0]) == 0:\n self._pc = self._load(d, modes[1])\n\n def _less_than(self, modes, a, b, d):\n if self._load(a, modes[0]) < self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _equals(self, modes, a, b, d):\n if self._load(a, modes[0]) == self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _adjust_relative_base(self, modes, a):\n self._relative_base += self._load(a, modes[0])\n\n def run(self, debug=False):\n while True:\n instruction, modes = self._fetch()\n if debug:\n print(instruction, modes)\n if instruction == INS_ADD:\n self._add(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_MULTIPLY:\n self._multiply(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_INPUT:\n self._input(modes, self._pop())\n elif instruction == INS_OUTPUT:\n v = self._output(modes, self._pop())\n if not self._interactive:\n return v\n elif instruction == INS_JUMP_IF_TRUE:\n self._jump_if_true(modes, self._pop(), self._pop())\n elif instruction == INS_JUMP_IF_FALSE:\n self._jump_if_false(modes, self._pop(), self._pop())\n elif instruction == INS_LESS_THAN:\n self._less_than(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_EQUALS:\n self._equals(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_ADJUST_RELATIVE_BASE:\n self._adjust_relative_base(modes, self._pop())\n elif instruction == INS_DONE:\n return self._outputs\n else:\n raise InvalidInstructionException(instruction)\n\n\n<mask token>\nif __name__ == '__main__':\n c = Computer(PROGRAM, [])\n c.run()\n",
"step-5": "#!/usr/bin/env python3\n\n\nfrom collections import deque\nfrom itertools import permutations\n\n\nINS_ADD = 1\nINS_MULTIPLY = 2\nINS_INPUT = 3\nINS_OUTPUT = 4\nINS_JUMP_IF_TRUE = 5\nINS_JUMP_IF_FALSE = 6\nINS_LESS_THAN = 7\nINS_EQUALS = 8\nINS_ADJUST_RELATIVE_BASE = 9\nINS_DONE = 99\n\nMODE_POSITION = 0\nMODE_IMMEDIATE = 1\nMODE_RELATIVE = 2\n\n\nclass InvalidInstructionException (Exception):\n def __init__(self, instruction):\n super().__init__(\"<%d>\" % instruction)\n\n\nclass InvalidModeException (Exception):\n pass\n\n\nclass Computer:\n\n def __init__(self, data, inputs, memory_size=8192, interactive=True):\n self._memory = [0] * memory_size\n for i in range(len(data)):\n self._memory[i] = data[i]\n self._pc = 0\n self._inputs = deque(inputs)\n self._outputs = []\n self._relative_base = 0\n self._interactive = interactive\n\n def input(self, value):\n self._inputs.append(value)\n \n def _parse_modes(self, instruction):\n i = \"%.5d\" % instruction\n return (int(i[2]), int(i[1]), int(i[0]))\n \n def _fetch(self):\n instruction = self._memory[self._pc]\n self._pc += 1\n if instruction > 100:\n return instruction % 100, self._parse_modes(instruction)\n else:\n return instruction, (MODE_POSITION, MODE_POSITION, MODE_POSITION)\n\n def _pop(self):\n v = self._memory[self._pc]\n self._pc += 1\n return v\n \n def _load(self, a, mode):\n if mode == MODE_IMMEDIATE:\n return a\n elif mode == MODE_POSITION:\n return self._memory[a]\n elif mode == MODE_RELATIVE:\n return self._memory[self._relative_base + a]\n else:\n raise InvalidModeException()\n\n def _store(self, a, mode, v):\n if mode == MODE_IMMEDIATE:\n pass\n if mode == MODE_POSITION:\n self._memory[a] = v\n elif mode == MODE_RELATIVE:\n self._memory[self._relative_base + a] = v\n else:\n raise InvalidModeException()\n \n def _add(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) + self._load(b, modes[1]))\n \n def _multiply(self, modes, a, b, d):\n self._store(d, modes[2], self._load(a, modes[0]) * self._load(b, modes[1]))\n\n def _input(self, modes, a):\n if self._interactive:\n self._store(a, modes[0], int(input(\"=> \")))\n else:\n self._store(a, modes[0], self._inputs.popleft())\n\n def _output(self, modes, s):\n v = self._load(s, modes[0])\n if self._interactive:\n print(v)\n else:\n self._outputs.append(v)\n \n def _jump_if_true(self, modes, a, d):\n if self._load(a, modes[0]) != 0:\n self._pc = self._load(d, modes[1])\n\n def _jump_if_false(self, modes, a, d):\n if self._load(a, modes[0]) == 0:\n self._pc = self._load(d, modes[1])\n\n def _less_than(self, modes, a, b, d):\n if self._load(a, modes[0]) < self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _equals(self, modes, a, b, d):\n if self._load(a, modes[0]) == self._load(b, modes[1]):\n self._store(d, modes[2], 1)\n else:\n self._store(d, modes[2], 0)\n\n def _adjust_relative_base(self, modes, a):\n self._relative_base += self._load(a, modes[0])\n \n def run(self, debug = False):\n while True:\n instruction, modes = self._fetch()\n if debug:\n print(instruction, modes)\n if instruction == INS_ADD:\n self._add(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_MULTIPLY:\n self._multiply(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_INPUT:\n self._input(modes, self._pop())\n elif instruction == INS_OUTPUT:\n v = self._output(modes, self._pop())\n if not self._interactive:\n return v\n elif instruction == INS_JUMP_IF_TRUE:\n self._jump_if_true(modes, self._pop(), self._pop())\n elif instruction == INS_JUMP_IF_FALSE:\n self._jump_if_false(modes, self._pop(), self._pop())\n elif instruction == INS_LESS_THAN:\n self._less_than(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_EQUALS:\n self._equals(modes, self._pop(), self._pop(), self._pop())\n elif instruction == INS_ADJUST_RELATIVE_BASE:\n self._adjust_relative_base(modes, self._pop())\n elif instruction == INS_DONE:\n return self._outputs\n else:\n raise InvalidInstructionException(instruction)\n\n\nPROGRAM = [1102,34463338,34463338,63,1007,63,34463338,63,1005,63,53,1101,0,3,1000,109,988,209,12,9,1000,209,6,209,3,203,0,1008,1000,1,63,1005,63,65,1008,1000,2,63,1005,63,904,1008,1000,0,63,1005,63,58,4,25,104,0,99,4,0,104,0,99,4,17,104,0,99,0,0,1101,0,396,1029,1101,0,356,1023,1101,401,0,1028,1101,24,0,1008,1101,33,0,1019,1101,35,0,1010,1102,359,1,1022,1102,32,1,1001,1101,37,0,1004,1101,0,31,1009,1101,0,30,1003,1101,28,0,1002,1102,1,36,1014,1102,20,1,1012,1101,21,0,1000,1101,0,22,1015,1102,23,1,1013,1102,1,1,1021,1102,1,39,1007,1102,26,1,1017,1101,0,38,1016,1101,0,437,1024,1102,432,1,1025,1101,0,421,1026,1101,0,29,1005,1101,27,0,1011,1102,1,0,1020,1101,0,25,1018,1101,0,414,1027,1102,34,1,1006,109,6,2108,33,-3,63,1005,63,201,1001,64,1,64,1105,1,203,4,187,1002,64,2,64,109,14,21108,40,40,-6,1005,1014,221,4,209,1105,1,225,1001,64,1,64,1002,64,2,64,109,-21,2102,1,3,63,1008,63,28,63,1005,63,251,4,231,1001,64,1,64,1106,0,251,1002,64,2,64,109,12,2101,0,-3,63,1008,63,21,63,1005,63,275,1001,64,1,64,1105,1,277,4,257,1002,64,2,64,109,-10,1207,1,27,63,1005,63,293,1105,1,299,4,283,1001,64,1,64,1002,64,2,64,109,9,21108,41,42,3,1005,1013,315,1105,1,321,4,305,1001,64,1,64,1002,64,2,64,109,-12,1202,6,1,63,1008,63,37,63,1005,63,347,4,327,1001,64,1,64,1105,1,347,1002,64,2,64,109,29,2105,1,-4,1105,1,365,4,353,1001,64,1,64,1002,64,2,64,109,-17,2108,32,-9,63,1005,63,387,4,371,1001,64,1,64,1105,1,387,1002,64,2,64,109,17,2106,0,1,4,393,1105,1,405,1001,64,1,64,1002,64,2,64,109,1,2106,0,-1,1001,64,1,64,1106,0,423,4,411,1002,64,2,64,109,-13,2105,1,9,4,429,1106,0,441,1001,64,1,64,1002,64,2,64,109,3,21107,42,41,-1,1005,1017,461,1001,64,1,64,1106,0,463,4,447,1002,64,2,64,109,-4,21107,43,44,1,1005,1015,481,4,469,1106,0,485,1001,64,1,64,1002,64,2,64,109,-6,21101,44,0,6,1008,1014,47,63,1005,63,505,1106,0,511,4,491,1001,64,1,64,1002,64,2,64,109,-6,1208,-1,32,63,1005,63,529,4,517,1105,1,533,1001,64,1,64,1002,64,2,64,109,11,1205,7,545,1106,0,551,4,539,1001,64,1,64,1002,64,2,64,109,11,21102,45,1,-7,1008,1017,48,63,1005,63,575,1001,64,1,64,1106,0,577,4,557,1002,64,2,64,109,-8,1206,5,593,1001,64,1,64,1105,1,595,4,583,1002,64,2,64,109,7,1206,-3,609,4,601,1106,0,613,1001,64,1,64,1002,64,2,64,109,-10,2101,0,-6,63,1008,63,39,63,1005,63,635,4,619,1106,0,639,1001,64,1,64,1002,64,2,64,109,-9,1208,0,39,63,1005,63,655,1106,0,661,4,645,1001,64,1,64,1002,64,2,64,109,4,2107,25,0,63,1005,63,681,1001,64,1,64,1105,1,683,4,667,1002,64,2,64,109,-5,2107,31,-2,63,1005,63,701,4,689,1106,0,705,1001,64,1,64,1002,64,2,64,109,19,1205,-1,719,4,711,1105,1,723,1001,64,1,64,1002,64,2,64,109,-17,1201,3,0,63,1008,63,24,63,1005,63,745,4,729,1106,0,749,1001,64,1,64,1002,64,2,64,109,13,21102,46,1,-3,1008,1015,46,63,1005,63,771,4,755,1105,1,775,1001,64,1,64,1002,64,2,64,109,-13,1207,4,32,63,1005,63,793,4,781,1106,0,797,1001,64,1,64,1002,64,2,64,109,7,2102,1,-9,63,1008,63,27,63,1005,63,821,1001,64,1,64,1105,1,823,4,803,1002,64,2,64,109,-18,1201,8,0,63,1008,63,25,63,1005,63,847,1001,64,1,64,1106,0,849,4,829,1002,64,2,64,109,23,21101,47,0,2,1008,1019,47,63,1005,63,871,4,855,1106,0,875,1001,64,1,64,1002,64,2,64,109,-22,1202,5,1,63,1008,63,19,63,1005,63,899,1001,64,1,64,1106,0,901,4,881,4,64,99,21102,27,1,1,21102,1,915,0,1105,1,922,21201,1,25165,1,204,1,99,109,3,1207,-2,3,63,1005,63,964,21201,-2,-1,1,21102,942,1,0,1105,1,922,22102,1,1,-1,21201,-2,-3,1,21101,0,957,0,1105,1,922,22201,1,-1,-2,1106,0,968,21201,-2,0,-2,109,-3,2105,1,0]\n\n\nif __name__ == \"__main__\":\n c = Computer(PROGRAM, [])\n c.run()\n",
"step-ids": [
17,
19,
21,
22,
25
]
}
|
[
17,
19,
21,
22,
25
] |
#!/usr/bin/env/ python
# -*- coding:utf-8 -*-
# Created by: Vanish
# Created on: 2019/9/25
import numpy as np
from scipy import optimize
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def costReg(theta, X, y, lamda):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
reg = (lamda / (2 * len(X))) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))
return np.sum(first - second) / len(X) + reg
def gradientReg(theta, X, y, lamda):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
parameters = int(theta.ravel().shape[1])
grad = np.zeros(parameters)
error = sigmoid(X * theta.T) - y
for i in range(parameters):
term = np.multiply(error, X[:, i])
if (i == 0):
grad[i] = np.sum(term) / len(X)
else:
grad[i] = (np.sum(term) / len(X)) + ((lamda / len(X)) * theta[:, i])
return grad
def predict(theta, X):
probability = sigmoid(X * theta.T)
return [1 if x >= 0.5 else 0 for x in probability]
def implement_for_LR(X_train, X_test, y_train, y_test,lamda=1):
n = X_train.shape[1]
# convert to numpy arrays and initalize the parameter array theta
X_train = np.array(X_train.values)
y_train = np.array(y_train.values)
theta = np.zeros(n)
result = optimize.fmin_tnc(func=costReg, x0=theta, fprime=gradientReg, args=(X_train, y_train, lamda))
theta_min = np.matrix(result[0])
predictions = predict(theta_min, X_test)
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y_test)]
accuracy = (sum(map(int, correct)) % len(correct))
print('accuracy = {0}%'.format(accuracy))
|
normal
|
{
"blob_id": "991c361043eb1539a80b5e8e1db44bc365e7e639",
"index": 6345,
"step-1": "<mask token>\n\n\ndef predict(theta, X):\n probability = sigmoid(X * theta.T)\n return [(1 if x >= 0.5 else 0) for x in probability]\n\n\ndef implement_for_LR(X_train, X_test, y_train, y_test, lamda=1):\n n = X_train.shape[1]\n X_train = np.array(X_train.values)\n y_train = np.array(y_train.values)\n theta = np.zeros(n)\n result = optimize.fmin_tnc(func=costReg, x0=theta, fprime=gradientReg,\n args=(X_train, y_train, lamda))\n theta_min = np.matrix(result[0])\n predictions = predict(theta_min, X_test)\n correct = [(1 if a == 1 and b == 1 or a == 0 and b == 0 else 0) for a,\n b in zip(predictions, y_test)]\n accuracy = sum(map(int, correct)) % len(correct)\n print('accuracy = {0}%'.format(accuracy))\n",
"step-2": "<mask token>\n\n\ndef gradientReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n parameters = int(theta.ravel().shape[1])\n grad = np.zeros(parameters)\n error = sigmoid(X * theta.T) - y\n for i in range(parameters):\n term = np.multiply(error, X[:, i])\n if i == 0:\n grad[i] = np.sum(term) / len(X)\n else:\n grad[i] = np.sum(term) / len(X) + lamda / len(X) * theta[:, i]\n return grad\n\n\ndef predict(theta, X):\n probability = sigmoid(X * theta.T)\n return [(1 if x >= 0.5 else 0) for x in probability]\n\n\ndef implement_for_LR(X_train, X_test, y_train, y_test, lamda=1):\n n = X_train.shape[1]\n X_train = np.array(X_train.values)\n y_train = np.array(y_train.values)\n theta = np.zeros(n)\n result = optimize.fmin_tnc(func=costReg, x0=theta, fprime=gradientReg,\n args=(X_train, y_train, lamda))\n theta_min = np.matrix(result[0])\n predictions = predict(theta_min, X_test)\n correct = [(1 if a == 1 and b == 1 or a == 0 and b == 0 else 0) for a,\n b in zip(predictions, y_test)]\n accuracy = sum(map(int, correct)) % len(correct)\n print('accuracy = {0}%'.format(accuracy))\n",
"step-3": "<mask token>\n\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\n\ndef costReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n first = np.multiply(-y, np.log(sigmoid(X * theta.T)))\n second = np.multiply(1 - y, np.log(1 - sigmoid(X * theta.T)))\n reg = lamda / (2 * len(X)) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2)\n )\n return np.sum(first - second) / len(X) + reg\n\n\ndef gradientReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n parameters = int(theta.ravel().shape[1])\n grad = np.zeros(parameters)\n error = sigmoid(X * theta.T) - y\n for i in range(parameters):\n term = np.multiply(error, X[:, i])\n if i == 0:\n grad[i] = np.sum(term) / len(X)\n else:\n grad[i] = np.sum(term) / len(X) + lamda / len(X) * theta[:, i]\n return grad\n\n\ndef predict(theta, X):\n probability = sigmoid(X * theta.T)\n return [(1 if x >= 0.5 else 0) for x in probability]\n\n\ndef implement_for_LR(X_train, X_test, y_train, y_test, lamda=1):\n n = X_train.shape[1]\n X_train = np.array(X_train.values)\n y_train = np.array(y_train.values)\n theta = np.zeros(n)\n result = optimize.fmin_tnc(func=costReg, x0=theta, fprime=gradientReg,\n args=(X_train, y_train, lamda))\n theta_min = np.matrix(result[0])\n predictions = predict(theta_min, X_test)\n correct = [(1 if a == 1 and b == 1 or a == 0 and b == 0 else 0) for a,\n b in zip(predictions, y_test)]\n accuracy = sum(map(int, correct)) % len(correct)\n print('accuracy = {0}%'.format(accuracy))\n",
"step-4": "import numpy as np\nfrom scipy import optimize\n\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\n\ndef costReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n first = np.multiply(-y, np.log(sigmoid(X * theta.T)))\n second = np.multiply(1 - y, np.log(1 - sigmoid(X * theta.T)))\n reg = lamda / (2 * len(X)) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2)\n )\n return np.sum(first - second) / len(X) + reg\n\n\ndef gradientReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n parameters = int(theta.ravel().shape[1])\n grad = np.zeros(parameters)\n error = sigmoid(X * theta.T) - y\n for i in range(parameters):\n term = np.multiply(error, X[:, i])\n if i == 0:\n grad[i] = np.sum(term) / len(X)\n else:\n grad[i] = np.sum(term) / len(X) + lamda / len(X) * theta[:, i]\n return grad\n\n\ndef predict(theta, X):\n probability = sigmoid(X * theta.T)\n return [(1 if x >= 0.5 else 0) for x in probability]\n\n\ndef implement_for_LR(X_train, X_test, y_train, y_test, lamda=1):\n n = X_train.shape[1]\n X_train = np.array(X_train.values)\n y_train = np.array(y_train.values)\n theta = np.zeros(n)\n result = optimize.fmin_tnc(func=costReg, x0=theta, fprime=gradientReg,\n args=(X_train, y_train, lamda))\n theta_min = np.matrix(result[0])\n predictions = predict(theta_min, X_test)\n correct = [(1 if a == 1 and b == 1 or a == 0 and b == 0 else 0) for a,\n b in zip(predictions, y_test)]\n accuracy = sum(map(int, correct)) % len(correct)\n print('accuracy = {0}%'.format(accuracy))\n",
"step-5": "#!/usr/bin/env/ python\n# -*- coding:utf-8 -*-\n# Created by: Vanish\n# Created on: 2019/9/25\n\n\nimport numpy as np\nfrom scipy import optimize\n\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef costReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n first = np.multiply(-y, np.log(sigmoid(X * theta.T)))\n second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))\n reg = (lamda / (2 * len(X))) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))\n return np.sum(first - second) / len(X) + reg\n\ndef gradientReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n\n parameters = int(theta.ravel().shape[1])\n grad = np.zeros(parameters)\n\n error = sigmoid(X * theta.T) - y\n\n for i in range(parameters):\n term = np.multiply(error, X[:, i])\n\n if (i == 0):\n grad[i] = np.sum(term) / len(X)\n else:\n grad[i] = (np.sum(term) / len(X)) + ((lamda / len(X)) * theta[:, i])\n\n return grad\n\ndef predict(theta, X):\n probability = sigmoid(X * theta.T)\n return [1 if x >= 0.5 else 0 for x in probability]\n\ndef implement_for_LR(X_train, X_test, y_train, y_test,lamda=1):\n n = X_train.shape[1]\n # convert to numpy arrays and initalize the parameter array theta\n X_train = np.array(X_train.values)\n y_train = np.array(y_train.values)\n theta = np.zeros(n)\n\n result = optimize.fmin_tnc(func=costReg, x0=theta, fprime=gradientReg, args=(X_train, y_train, lamda))\n\n theta_min = np.matrix(result[0])\n predictions = predict(theta_min, X_test)\n correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y_test)]\n accuracy = (sum(map(int, correct)) % len(correct))\n print('accuracy = {0}%'.format(accuracy))",
"step-ids": [
2,
3,
5,
6,
7
]
}
|
[
2,
3,
5,
6,
7
] |
import random
from typing import List
from faker import Faker
from call_center.src.actors.agent import InsuranceAgent
from call_center.src.actors.consumer import Consumer
from call_center.src.common.person import (
AGE,
AVAILABLE,
INSURANCE_OPERATION,
PHONE_NUMBER,
INCOME,
CARS_COUNT,
KIDS_COUNT,
STATE,
RENT,
BUY,
)
from call_center.src.common.singleton_meta import SingletonMeta
CONSUMER_COUNT = 1000
AGENTS_COUNT = 20
FAKE = Faker("en_US")
class ActorsCreator(metaclass=SingletonMeta):
"""
Singleton class which acts as a container for both Agents and Consumers.
In a real-world scenario, we would have a database containing both actors/consumers.
This is a replacement, for the sake of example.
"""
def __init__(self):
self.consumers = ActorsCreator.create_consumers()
self.agents = ActorsCreator.create_agents()
def __del__(self):
self.stop_all_agents()
@staticmethod
def create_consumers() -> List[Consumer]:
"""
Create the consumers. Consumers are created with randomized attributes.
:return: A new list of Consumer.
"""
consumers = []
for consumer in range(CONSUMER_COUNT):
consumers.append(
Consumer(
{
AGE: FAKE.random_int(min=0, max=120),
STATE: FAKE.state(),
KIDS_COUNT: FAKE.random_int(min=0, max=12),
CARS_COUNT: FAKE.random_int(min=0, max=10),
INSURANCE_OPERATION: random.choice((RENT, BUY)),
INCOME: FAKE.random_int(min=0, max=99999999999),
PHONE_NUMBER: FAKE.phone_number(),
AVAILABLE: True,
}
)
)
return consumers
@staticmethod
def create_agents() -> List[InsuranceAgent]:
"""
Create the InsuranceAgents. Consumers are created with randomized attributes.
:return: A new list of InsuranceAgent.
"""
agents = []
for consumer in range(AGENTS_COUNT):
insurance_agent = InsuranceAgent(
personal_info={
AGE: FAKE.random_int(min=0, max=120),
STATE: FAKE.state(),
KIDS_COUNT: FAKE.random_int(min=0, max=12),
CARS_COUNT: FAKE.random_int(min=0, max=10),
INSURANCE_OPERATION: random.choice((RENT, BUY)),
INCOME: FAKE.random_int(min=0, max=1000000),
PHONE_NUMBER: FAKE.phone_number(),
AVAILABLE: True,
},
call_acceptance_criteria=[
{
"person_attribute": AGE,
"comparison_operator": random.choice(("<", ">")),
"value": FAKE.random_int(
min=0,
max=120,
),
},
{
"person_attribute": INCOME,
"comparison_operator": random.choice(("<", ">")),
"value": FAKE.random_int(
min=0,
max=1000000,
),
},
{
"person_attribute": KIDS_COUNT,
"comparison_operator": random.choice(("<", ">")),
"value": FAKE.random_int(
min=0,
max=12,
),
},
{
"person_attribute": CARS_COUNT,
"comparison_operator": random.choice(("<", ">")),
"value": FAKE.random_int(
min=0,
max=12,
),
},
{
"person_attribute": INSURANCE_OPERATION,
"comparison_operator": random.choice(("<", ">")),
"value": random.choice((RENT, BUY)),
},
],
)
agents.append(insurance_agent)
return agents
def stop_all_agents(self):
"""
Gracefully stop all agents threads on self deletion.
To find more on agents' threads, see agent.py
:return:
"""
for agent in self.agents:
if agent.available:
agent.stop_activity()
|
normal
|
{
"blob_id": "db31a69c57f773a79e5eaa8b3443b0366fd74861",
"index": 8565,
"step-1": "<mask token>\n\n\nclass ActorsCreator(metaclass=SingletonMeta):\n <mask token>\n\n def __init__(self):\n self.consumers = ActorsCreator.create_consumers()\n self.agents = ActorsCreator.create_agents()\n\n def __del__(self):\n self.stop_all_agents()\n\n @staticmethod\n def create_consumers() ->List[Consumer]:\n \"\"\"\n Create the consumers. Consumers are created with randomized attributes.\n :return: A new list of Consumer.\n \"\"\"\n consumers = []\n for consumer in range(CONSUMER_COUNT):\n consumers.append(Consumer({AGE: FAKE.random_int(min=0, max=120),\n STATE: FAKE.state(), KIDS_COUNT: FAKE.random_int(min=0, max\n =12), CARS_COUNT: FAKE.random_int(min=0, max=10),\n INSURANCE_OPERATION: random.choice((RENT, BUY)), INCOME:\n FAKE.random_int(min=0, max=99999999999), PHONE_NUMBER: FAKE\n .phone_number(), AVAILABLE: True}))\n return consumers\n\n @staticmethod\n def create_agents() ->List[InsuranceAgent]:\n \"\"\"\n Create the InsuranceAgents. Consumers are created with randomized attributes.\n :return: A new list of InsuranceAgent.\n \"\"\"\n agents = []\n for consumer in range(AGENTS_COUNT):\n insurance_agent = InsuranceAgent(personal_info={AGE: FAKE.\n random_int(min=0, max=120), STATE: FAKE.state(), KIDS_COUNT:\n FAKE.random_int(min=0, max=12), CARS_COUNT: FAKE.random_int\n (min=0, max=10), INSURANCE_OPERATION: random.choice((RENT,\n BUY)), INCOME: FAKE.random_int(min=0, max=1000000),\n PHONE_NUMBER: FAKE.phone_number(), AVAILABLE: True},\n call_acceptance_criteria=[{'person_attribute': AGE,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=120)}, {'person_attribute':\n INCOME, 'comparison_operator': random.choice(('<', '>')),\n 'value': FAKE.random_int(min=0, max=1000000)}, {\n 'person_attribute': KIDS_COUNT, 'comparison_operator':\n random.choice(('<', '>')), 'value': FAKE.random_int(min=0,\n max=12)}, {'person_attribute': CARS_COUNT,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=12)}, {'person_attribute':\n INSURANCE_OPERATION, 'comparison_operator': random.choice((\n '<', '>')), 'value': random.choice((RENT, BUY))}])\n agents.append(insurance_agent)\n return agents\n\n def stop_all_agents(self):\n \"\"\"\n Gracefully stop all agents threads on self deletion.\n To find more on agents' threads, see agent.py\n :return:\n \"\"\"\n for agent in self.agents:\n if agent.available:\n agent.stop_activity()\n",
"step-2": "<mask token>\n\n\nclass ActorsCreator(metaclass=SingletonMeta):\n \"\"\"\n Singleton class which acts as a container for both Agents and Consumers.\n In a real-world scenario, we would have a database containing both actors/consumers.\n This is a replacement, for the sake of example.\n \"\"\"\n\n def __init__(self):\n self.consumers = ActorsCreator.create_consumers()\n self.agents = ActorsCreator.create_agents()\n\n def __del__(self):\n self.stop_all_agents()\n\n @staticmethod\n def create_consumers() ->List[Consumer]:\n \"\"\"\n Create the consumers. Consumers are created with randomized attributes.\n :return: A new list of Consumer.\n \"\"\"\n consumers = []\n for consumer in range(CONSUMER_COUNT):\n consumers.append(Consumer({AGE: FAKE.random_int(min=0, max=120),\n STATE: FAKE.state(), KIDS_COUNT: FAKE.random_int(min=0, max\n =12), CARS_COUNT: FAKE.random_int(min=0, max=10),\n INSURANCE_OPERATION: random.choice((RENT, BUY)), INCOME:\n FAKE.random_int(min=0, max=99999999999), PHONE_NUMBER: FAKE\n .phone_number(), AVAILABLE: True}))\n return consumers\n\n @staticmethod\n def create_agents() ->List[InsuranceAgent]:\n \"\"\"\n Create the InsuranceAgents. Consumers are created with randomized attributes.\n :return: A new list of InsuranceAgent.\n \"\"\"\n agents = []\n for consumer in range(AGENTS_COUNT):\n insurance_agent = InsuranceAgent(personal_info={AGE: FAKE.\n random_int(min=0, max=120), STATE: FAKE.state(), KIDS_COUNT:\n FAKE.random_int(min=0, max=12), CARS_COUNT: FAKE.random_int\n (min=0, max=10), INSURANCE_OPERATION: random.choice((RENT,\n BUY)), INCOME: FAKE.random_int(min=0, max=1000000),\n PHONE_NUMBER: FAKE.phone_number(), AVAILABLE: True},\n call_acceptance_criteria=[{'person_attribute': AGE,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=120)}, {'person_attribute':\n INCOME, 'comparison_operator': random.choice(('<', '>')),\n 'value': FAKE.random_int(min=0, max=1000000)}, {\n 'person_attribute': KIDS_COUNT, 'comparison_operator':\n random.choice(('<', '>')), 'value': FAKE.random_int(min=0,\n max=12)}, {'person_attribute': CARS_COUNT,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=12)}, {'person_attribute':\n INSURANCE_OPERATION, 'comparison_operator': random.choice((\n '<', '>')), 'value': random.choice((RENT, BUY))}])\n agents.append(insurance_agent)\n return agents\n\n def stop_all_agents(self):\n \"\"\"\n Gracefully stop all agents threads on self deletion.\n To find more on agents' threads, see agent.py\n :return:\n \"\"\"\n for agent in self.agents:\n if agent.available:\n agent.stop_activity()\n",
"step-3": "<mask token>\nCONSUMER_COUNT = 1000\nAGENTS_COUNT = 20\nFAKE = Faker('en_US')\n\n\nclass ActorsCreator(metaclass=SingletonMeta):\n \"\"\"\n Singleton class which acts as a container for both Agents and Consumers.\n In a real-world scenario, we would have a database containing both actors/consumers.\n This is a replacement, for the sake of example.\n \"\"\"\n\n def __init__(self):\n self.consumers = ActorsCreator.create_consumers()\n self.agents = ActorsCreator.create_agents()\n\n def __del__(self):\n self.stop_all_agents()\n\n @staticmethod\n def create_consumers() ->List[Consumer]:\n \"\"\"\n Create the consumers. Consumers are created with randomized attributes.\n :return: A new list of Consumer.\n \"\"\"\n consumers = []\n for consumer in range(CONSUMER_COUNT):\n consumers.append(Consumer({AGE: FAKE.random_int(min=0, max=120),\n STATE: FAKE.state(), KIDS_COUNT: FAKE.random_int(min=0, max\n =12), CARS_COUNT: FAKE.random_int(min=0, max=10),\n INSURANCE_OPERATION: random.choice((RENT, BUY)), INCOME:\n FAKE.random_int(min=0, max=99999999999), PHONE_NUMBER: FAKE\n .phone_number(), AVAILABLE: True}))\n return consumers\n\n @staticmethod\n def create_agents() ->List[InsuranceAgent]:\n \"\"\"\n Create the InsuranceAgents. Consumers are created with randomized attributes.\n :return: A new list of InsuranceAgent.\n \"\"\"\n agents = []\n for consumer in range(AGENTS_COUNT):\n insurance_agent = InsuranceAgent(personal_info={AGE: FAKE.\n random_int(min=0, max=120), STATE: FAKE.state(), KIDS_COUNT:\n FAKE.random_int(min=0, max=12), CARS_COUNT: FAKE.random_int\n (min=0, max=10), INSURANCE_OPERATION: random.choice((RENT,\n BUY)), INCOME: FAKE.random_int(min=0, max=1000000),\n PHONE_NUMBER: FAKE.phone_number(), AVAILABLE: True},\n call_acceptance_criteria=[{'person_attribute': AGE,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=120)}, {'person_attribute':\n INCOME, 'comparison_operator': random.choice(('<', '>')),\n 'value': FAKE.random_int(min=0, max=1000000)}, {\n 'person_attribute': KIDS_COUNT, 'comparison_operator':\n random.choice(('<', '>')), 'value': FAKE.random_int(min=0,\n max=12)}, {'person_attribute': CARS_COUNT,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=12)}, {'person_attribute':\n INSURANCE_OPERATION, 'comparison_operator': random.choice((\n '<', '>')), 'value': random.choice((RENT, BUY))}])\n agents.append(insurance_agent)\n return agents\n\n def stop_all_agents(self):\n \"\"\"\n Gracefully stop all agents threads on self deletion.\n To find more on agents' threads, see agent.py\n :return:\n \"\"\"\n for agent in self.agents:\n if agent.available:\n agent.stop_activity()\n",
"step-4": "import random\nfrom typing import List\nfrom faker import Faker\nfrom call_center.src.actors.agent import InsuranceAgent\nfrom call_center.src.actors.consumer import Consumer\nfrom call_center.src.common.person import AGE, AVAILABLE, INSURANCE_OPERATION, PHONE_NUMBER, INCOME, CARS_COUNT, KIDS_COUNT, STATE, RENT, BUY\nfrom call_center.src.common.singleton_meta import SingletonMeta\nCONSUMER_COUNT = 1000\nAGENTS_COUNT = 20\nFAKE = Faker('en_US')\n\n\nclass ActorsCreator(metaclass=SingletonMeta):\n \"\"\"\n Singleton class which acts as a container for both Agents and Consumers.\n In a real-world scenario, we would have a database containing both actors/consumers.\n This is a replacement, for the sake of example.\n \"\"\"\n\n def __init__(self):\n self.consumers = ActorsCreator.create_consumers()\n self.agents = ActorsCreator.create_agents()\n\n def __del__(self):\n self.stop_all_agents()\n\n @staticmethod\n def create_consumers() ->List[Consumer]:\n \"\"\"\n Create the consumers. Consumers are created with randomized attributes.\n :return: A new list of Consumer.\n \"\"\"\n consumers = []\n for consumer in range(CONSUMER_COUNT):\n consumers.append(Consumer({AGE: FAKE.random_int(min=0, max=120),\n STATE: FAKE.state(), KIDS_COUNT: FAKE.random_int(min=0, max\n =12), CARS_COUNT: FAKE.random_int(min=0, max=10),\n INSURANCE_OPERATION: random.choice((RENT, BUY)), INCOME:\n FAKE.random_int(min=0, max=99999999999), PHONE_NUMBER: FAKE\n .phone_number(), AVAILABLE: True}))\n return consumers\n\n @staticmethod\n def create_agents() ->List[InsuranceAgent]:\n \"\"\"\n Create the InsuranceAgents. Consumers are created with randomized attributes.\n :return: A new list of InsuranceAgent.\n \"\"\"\n agents = []\n for consumer in range(AGENTS_COUNT):\n insurance_agent = InsuranceAgent(personal_info={AGE: FAKE.\n random_int(min=0, max=120), STATE: FAKE.state(), KIDS_COUNT:\n FAKE.random_int(min=0, max=12), CARS_COUNT: FAKE.random_int\n (min=0, max=10), INSURANCE_OPERATION: random.choice((RENT,\n BUY)), INCOME: FAKE.random_int(min=0, max=1000000),\n PHONE_NUMBER: FAKE.phone_number(), AVAILABLE: True},\n call_acceptance_criteria=[{'person_attribute': AGE,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=120)}, {'person_attribute':\n INCOME, 'comparison_operator': random.choice(('<', '>')),\n 'value': FAKE.random_int(min=0, max=1000000)}, {\n 'person_attribute': KIDS_COUNT, 'comparison_operator':\n random.choice(('<', '>')), 'value': FAKE.random_int(min=0,\n max=12)}, {'person_attribute': CARS_COUNT,\n 'comparison_operator': random.choice(('<', '>')), 'value':\n FAKE.random_int(min=0, max=12)}, {'person_attribute':\n INSURANCE_OPERATION, 'comparison_operator': random.choice((\n '<', '>')), 'value': random.choice((RENT, BUY))}])\n agents.append(insurance_agent)\n return agents\n\n def stop_all_agents(self):\n \"\"\"\n Gracefully stop all agents threads on self deletion.\n To find more on agents' threads, see agent.py\n :return:\n \"\"\"\n for agent in self.agents:\n if agent.available:\n agent.stop_activity()\n",
"step-5": "import random\n\nfrom typing import List\n\nfrom faker import Faker\n\nfrom call_center.src.actors.agent import InsuranceAgent\nfrom call_center.src.actors.consumer import Consumer\nfrom call_center.src.common.person import (\n AGE,\n AVAILABLE,\n INSURANCE_OPERATION,\n PHONE_NUMBER,\n INCOME,\n CARS_COUNT,\n KIDS_COUNT,\n STATE,\n RENT,\n BUY,\n)\nfrom call_center.src.common.singleton_meta import SingletonMeta\n\nCONSUMER_COUNT = 1000\nAGENTS_COUNT = 20\nFAKE = Faker(\"en_US\")\n\n\nclass ActorsCreator(metaclass=SingletonMeta):\n \"\"\"\n Singleton class which acts as a container for both Agents and Consumers.\n In a real-world scenario, we would have a database containing both actors/consumers.\n This is a replacement, for the sake of example.\n \"\"\"\n\n def __init__(self):\n self.consumers = ActorsCreator.create_consumers()\n self.agents = ActorsCreator.create_agents()\n\n def __del__(self):\n self.stop_all_agents()\n\n @staticmethod\n def create_consumers() -> List[Consumer]:\n \"\"\"\n Create the consumers. Consumers are created with randomized attributes.\n :return: A new list of Consumer.\n \"\"\"\n consumers = []\n for consumer in range(CONSUMER_COUNT):\n consumers.append(\n Consumer(\n {\n AGE: FAKE.random_int(min=0, max=120),\n STATE: FAKE.state(),\n KIDS_COUNT: FAKE.random_int(min=0, max=12),\n CARS_COUNT: FAKE.random_int(min=0, max=10),\n INSURANCE_OPERATION: random.choice((RENT, BUY)),\n INCOME: FAKE.random_int(min=0, max=99999999999),\n PHONE_NUMBER: FAKE.phone_number(),\n AVAILABLE: True,\n }\n )\n )\n return consumers\n\n @staticmethod\n def create_agents() -> List[InsuranceAgent]:\n \"\"\"\n Create the InsuranceAgents. Consumers are created with randomized attributes.\n :return: A new list of InsuranceAgent.\n \"\"\"\n agents = []\n for consumer in range(AGENTS_COUNT):\n insurance_agent = InsuranceAgent(\n personal_info={\n AGE: FAKE.random_int(min=0, max=120),\n STATE: FAKE.state(),\n KIDS_COUNT: FAKE.random_int(min=0, max=12),\n CARS_COUNT: FAKE.random_int(min=0, max=10),\n INSURANCE_OPERATION: random.choice((RENT, BUY)),\n INCOME: FAKE.random_int(min=0, max=1000000),\n PHONE_NUMBER: FAKE.phone_number(),\n AVAILABLE: True,\n },\n call_acceptance_criteria=[\n {\n \"person_attribute\": AGE,\n \"comparison_operator\": random.choice((\"<\", \">\")),\n \"value\": FAKE.random_int(\n min=0,\n max=120,\n ),\n },\n {\n \"person_attribute\": INCOME,\n \"comparison_operator\": random.choice((\"<\", \">\")),\n \"value\": FAKE.random_int(\n min=0,\n max=1000000,\n ),\n },\n {\n \"person_attribute\": KIDS_COUNT,\n \"comparison_operator\": random.choice((\"<\", \">\")),\n \"value\": FAKE.random_int(\n min=0,\n max=12,\n ),\n },\n {\n \"person_attribute\": CARS_COUNT,\n \"comparison_operator\": random.choice((\"<\", \">\")),\n \"value\": FAKE.random_int(\n min=0,\n max=12,\n ),\n },\n {\n \"person_attribute\": INSURANCE_OPERATION,\n \"comparison_operator\": random.choice((\"<\", \">\")),\n \"value\": random.choice((RENT, BUY)),\n },\n ],\n )\n agents.append(insurance_agent)\n return agents\n\n def stop_all_agents(self):\n \"\"\"\n Gracefully stop all agents threads on self deletion.\n To find more on agents' threads, see agent.py\n :return:\n \"\"\"\n for agent in self.agents:\n if agent.available:\n agent.stop_activity()\n",
"step-ids": [
6,
7,
8,
9,
10
]
}
|
[
6,
7,
8,
9,
10
] |
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from practice_app.models import Person
class PersonAdmin(admin.ModelAdmin):
pass
admin.site.register(Person)
|
normal
|
{
"blob_id": "d90aeaaa682b371afb4771ecfbf1077fc12520b4",
"index": 3873,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass PersonAdmin(admin.ModelAdmin):\n pass\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass PersonAdmin(admin.ModelAdmin):\n pass\n\n\nadmin.site.register(Person)\n",
"step-4": "from django.contrib import admin\nfrom django.contrib import admin\nfrom practice_app.models import Person\n\n\nclass PersonAdmin(admin.ModelAdmin):\n pass\n\n\nadmin.site.register(Person)\n",
"step-5": "from django.contrib import admin\n\n# Register your models here.\nfrom django.contrib import admin\nfrom practice_app.models import Person\n\n\nclass PersonAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(Person)",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class pairtron:
def affiliation_cleaner(self, affiliation):
affiliation = str(affiliation)
affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',
' ')
while ' ;' in affiliation:
affiliation = affiliation.replace(' ;', ';')
while ';;' in affiliation:
affiliation = affiliation.replace(';;', ';')
return affiliation
def zeta0_creation(self, indexed_files_dir, merge_columns):
""" Returns pandas dataframe which has latest record for each manual id after merging all "sheet_name"
in the previously indexed_files which are present in "indexed_files_dir"
"""
indexed_files = [file for file in os.listdir(indexed_files_dir) if
not file.startswith('~')]
indexed_files_dict = {}
indexed_files_dict.clear()
dateList = []
del dateList[:]
for file in indexed_files:
dated = file.split('_')[-1].split('.')[0]
dated = dated[4:] + dated[:4]
dateList.append(dated)
indexed_files_dict[dated] = file
dataframes = {}
for dated, file in indexed_files_dict.items():
file_name = indexed_files_dir + '\\' + file
dataframes[dated] = pd.read_excel(file_name, sheet_name=0)
dataframes[dated]['file_date'] = dated
dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in
dataframes[dated]['manual_id']]
merged_df = pd.concat([dataframes[dated] for dated in dateList],
ignore_index=True)
merged_df = merged_df.sort_values('file_date', ascending=False)
zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')
pd.set_option('mode.chained_assignment', None)
for col in zeta0.columns:
zeta0[col] = zeta0[col].astype('str')
zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else
x)
zeta0 = zeta0.sort_values('mid', ascending=True)
if 'manual_id' not in merge_columns:
merge_columns.append('manual_id')
zeta0 = zeta0[merge_columns]
return zeta0
<|reserved_special_token_0|>
def selectionAfterJoin(self, df, cols, common_cols):
for col in common_cols:
if col != 'manual_id':
df[col] = np.where(df['{}_left'.format(col)].isnull() | df[
'{}_right'.format(col)].notnull() & (df['{}_right'.
format(col)] != '') & (df['{}_left'.format(col)] != df[
'{}_right'.format(col)]), df['{}_right'.format(col)],
df['{}_left'.format(col)])
drop_list = ['{}_left'.format(col) for col in common_cols if col !=
'manual_id']
drop_list.extend(['{}_right'.format(col) for col in common_cols if
col != 'manual_id'])
df.drop(drop_list, axis=1, inplace=True)
return df[cols]
def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):
wb = load_workbook(filename=self.dest_file)
ws = wb[sheets[0]]
ws.title = sheets[0].replace('ACRONYM', acronym)
try:
curr_df = pd.read_excel(src)
except:
curr_df = pd.read_csv(src)
if zeta0_df is not None:
curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',
right_on='manual_id', how='left', suffixes=('_left', '_right'))
common_columns = [col for col in curr_df.columns if col in
zeta0_df.columns]
self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,
common_columns)
else:
self.source_df = curr_df
session_list = self.source_df.fillna('').values.tolist()
for row_iter in range(len(session_list)):
print(row_iter)
for col_iter in range(len(session_list[row_iter])):
print(col_iter)
ws.cell(row=row_iter + 2, column=col_iter + 1
).value = self.affiliation_cleaner(session_list[
row_iter][col_iter])
wb.save(self.dest_file)
def process_merger(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.copy_larvol_xlsx(template, acronym)
if merge.upper() == 'YES':
zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)
self.update_larvol_xlsx(source_file, acronym, sheets, columns,
zeta0)
else:
self.update_larvol_xlsx(source_file, acronym, sheets, columns)
def separated_by_number(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
affiliations_dict = {}
prev_affiliation = None
for affiliation in affiliations_list:
if affiliation != '':
group = re.findall('\\d+', affiliation)
if group != []:
num = list(map(int, group))[0]
affiliations_dict[str(num)] = str(num).join(affiliation
.split(str(num))[1:]).strip(',. ')
prev_affiliation = num
elif prev_affiliation is not None:
num = prev_affiliation
affiliations_dict[str(num)] = affiliations_dict[str(num)
] + '; ' + affiliation.strip(',. ')
prev_affiliation = num
for author in authors_list:
group = re.findall('\\d+', author)
num_list = list(map(int, group))
if num_list != []:
author_name = author.split(str(num_list[0]))[0].strip(',.-; ')
else:
author_name = author.strip(',.-; ')
for num in num_list:
try:
elem = affiliations_dict[str(num)]
except:
affiliations_dict[str(num)] = ''
cprint(
"Exception for manual_id: {} as affiliation index {} wasn't found"
.format(manual_id, str(num)), 'yellow', attrs=['bold'])
affiliation_name = '; '.join([affiliations_dict[str(num)].strip
(',.- ') for num in num_list])
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def separated_by_semicolon(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
try:
affiliation_name = affiliations_list[iter].strip(',.- ')
except:
affiliation_name = ''
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def processData(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.process_merger(source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns)
self.process_pairtron(sheets[1])
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class pairtron:
def affiliation_cleaner(self, affiliation):
affiliation = str(affiliation)
affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',
' ')
while ' ;' in affiliation:
affiliation = affiliation.replace(' ;', ';')
while ';;' in affiliation:
affiliation = affiliation.replace(';;', ';')
return affiliation
def zeta0_creation(self, indexed_files_dir, merge_columns):
""" Returns pandas dataframe which has latest record for each manual id after merging all "sheet_name"
in the previously indexed_files which are present in "indexed_files_dir"
"""
indexed_files = [file for file in os.listdir(indexed_files_dir) if
not file.startswith('~')]
indexed_files_dict = {}
indexed_files_dict.clear()
dateList = []
del dateList[:]
for file in indexed_files:
dated = file.split('_')[-1].split('.')[0]
dated = dated[4:] + dated[:4]
dateList.append(dated)
indexed_files_dict[dated] = file
dataframes = {}
for dated, file in indexed_files_dict.items():
file_name = indexed_files_dir + '\\' + file
dataframes[dated] = pd.read_excel(file_name, sheet_name=0)
dataframes[dated]['file_date'] = dated
dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in
dataframes[dated]['manual_id']]
merged_df = pd.concat([dataframes[dated] for dated in dateList],
ignore_index=True)
merged_df = merged_df.sort_values('file_date', ascending=False)
zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')
pd.set_option('mode.chained_assignment', None)
for col in zeta0.columns:
zeta0[col] = zeta0[col].astype('str')
zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else
x)
zeta0 = zeta0.sort_values('mid', ascending=True)
if 'manual_id' not in merge_columns:
merge_columns.append('manual_id')
zeta0 = zeta0[merge_columns]
return zeta0
<|reserved_special_token_0|>
def selectionAfterJoin(self, df, cols, common_cols):
for col in common_cols:
if col != 'manual_id':
df[col] = np.where(df['{}_left'.format(col)].isnull() | df[
'{}_right'.format(col)].notnull() & (df['{}_right'.
format(col)] != '') & (df['{}_left'.format(col)] != df[
'{}_right'.format(col)]), df['{}_right'.format(col)],
df['{}_left'.format(col)])
drop_list = ['{}_left'.format(col) for col in common_cols if col !=
'manual_id']
drop_list.extend(['{}_right'.format(col) for col in common_cols if
col != 'manual_id'])
df.drop(drop_list, axis=1, inplace=True)
return df[cols]
def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):
wb = load_workbook(filename=self.dest_file)
ws = wb[sheets[0]]
ws.title = sheets[0].replace('ACRONYM', acronym)
try:
curr_df = pd.read_excel(src)
except:
curr_df = pd.read_csv(src)
if zeta0_df is not None:
curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',
right_on='manual_id', how='left', suffixes=('_left', '_right'))
common_columns = [col for col in curr_df.columns if col in
zeta0_df.columns]
self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,
common_columns)
else:
self.source_df = curr_df
session_list = self.source_df.fillna('').values.tolist()
for row_iter in range(len(session_list)):
print(row_iter)
for col_iter in range(len(session_list[row_iter])):
print(col_iter)
ws.cell(row=row_iter + 2, column=col_iter + 1
).value = self.affiliation_cleaner(session_list[
row_iter][col_iter])
wb.save(self.dest_file)
def process_merger(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.copy_larvol_xlsx(template, acronym)
if merge.upper() == 'YES':
zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)
self.update_larvol_xlsx(source_file, acronym, sheets, columns,
zeta0)
else:
self.update_larvol_xlsx(source_file, acronym, sheets, columns)
def separated_by_number(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
affiliations_dict = {}
prev_affiliation = None
for affiliation in affiliations_list:
if affiliation != '':
group = re.findall('\\d+', affiliation)
if group != []:
num = list(map(int, group))[0]
affiliations_dict[str(num)] = str(num).join(affiliation
.split(str(num))[1:]).strip(',. ')
prev_affiliation = num
elif prev_affiliation is not None:
num = prev_affiliation
affiliations_dict[str(num)] = affiliations_dict[str(num)
] + '; ' + affiliation.strip(',. ')
prev_affiliation = num
for author in authors_list:
group = re.findall('\\d+', author)
num_list = list(map(int, group))
if num_list != []:
author_name = author.split(str(num_list[0]))[0].strip(',.-; ')
else:
author_name = author.strip(',.-; ')
for num in num_list:
try:
elem = affiliations_dict[str(num)]
except:
affiliations_dict[str(num)] = ''
cprint(
"Exception for manual_id: {} as affiliation index {} wasn't found"
.format(manual_id, str(num)), 'yellow', attrs=['bold'])
affiliation_name = '; '.join([affiliations_dict[str(num)].strip
(',.- ') for num in num_list])
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def separated_by_semicolon(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
try:
affiliation_name = affiliations_list[iter].strip(',.- ')
except:
affiliation_name = ''
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
<|reserved_special_token_0|>
def process_pairtron(self, sheet):
source_df = self.source_df
source_df = source_df[source_df['authors'].notnull()]
source_id_list = source_df['source_id'].fillna('').tolist()
manual_id_list = source_df['manual_id'].fillna('').tolist()
authors_list = source_df['authors'].tolist()
affiliation_list = source_df['author_affiliation'].fillna('').tolist()
pairtron_list = []
for iter in range(len(authors_list)):
author_tokens = [elem.strip() for elem in authors_list[iter].
split(';')]
affiliation_tokens = [elem.strip() for elem in affiliation_list
[iter].split(';')]
try:
if author_tokens[0][-1].isdigit() and '1' in affiliation_list[
iter]:
pairtron_list.extend(self.separated_by_number(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
elif len(author_tokens) == len(affiliation_tokens):
pairtron_list.extend(self.separated_by_semicolon(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
elif author_tokens[0][-1].isdigit(
) and '1' not in affiliation_list[iter]:
cprint('ALERT: manual_id: {} has missing affiliations.'
.format(manual_id_list[iter]), 'red', attrs=['bold'])
else:
pairtron_list.extend(self.common_affiliation(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
except:
pass
df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',
'authors', 'author_affiliation'])
df.drop_duplicates(inplace=True)
authorsInfo_list = df.values.tolist()
wb = load_workbook(filename=self.dest_file)
ws = wb[sheet]
for row_iter in range(len(authorsInfo_list)):
for col_iter in range(len(authorsInfo_list[row_iter])):
ws.cell(row=row_iter + 2, column=col_iter + 1
).value = authorsInfo_list[row_iter][col_iter]
wb.save(self.dest_file)
def processData(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.process_merger(source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns)
self.process_pairtron(sheets[1])
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class pairtron:
def affiliation_cleaner(self, affiliation):
affiliation = str(affiliation)
affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',
' ')
while ' ;' in affiliation:
affiliation = affiliation.replace(' ;', ';')
while ';;' in affiliation:
affiliation = affiliation.replace(';;', ';')
return affiliation
def zeta0_creation(self, indexed_files_dir, merge_columns):
""" Returns pandas dataframe which has latest record for each manual id after merging all "sheet_name"
in the previously indexed_files which are present in "indexed_files_dir"
"""
indexed_files = [file for file in os.listdir(indexed_files_dir) if
not file.startswith('~')]
indexed_files_dict = {}
indexed_files_dict.clear()
dateList = []
del dateList[:]
for file in indexed_files:
dated = file.split('_')[-1].split('.')[0]
dated = dated[4:] + dated[:4]
dateList.append(dated)
indexed_files_dict[dated] = file
dataframes = {}
for dated, file in indexed_files_dict.items():
file_name = indexed_files_dir + '\\' + file
dataframes[dated] = pd.read_excel(file_name, sheet_name=0)
dataframes[dated]['file_date'] = dated
dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in
dataframes[dated]['manual_id']]
merged_df = pd.concat([dataframes[dated] for dated in dateList],
ignore_index=True)
merged_df = merged_df.sort_values('file_date', ascending=False)
zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')
pd.set_option('mode.chained_assignment', None)
for col in zeta0.columns:
zeta0[col] = zeta0[col].astype('str')
zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else
x)
zeta0 = zeta0.sort_values('mid', ascending=True)
if 'manual_id' not in merge_columns:
merge_columns.append('manual_id')
zeta0 = zeta0[merge_columns]
return zeta0
def copy_larvol_xlsx(self, template, acronym):
date = datetime.now().date().strftime('%m%d%Y')
self.dest_file = os.path.basename(template).replace('ACRONYM', acronym
).replace('MMDDYYYY', date + '_Pairtron')
shutil.copy2(template, self.dest_file)
def selectionAfterJoin(self, df, cols, common_cols):
for col in common_cols:
if col != 'manual_id':
df[col] = np.where(df['{}_left'.format(col)].isnull() | df[
'{}_right'.format(col)].notnull() & (df['{}_right'.
format(col)] != '') & (df['{}_left'.format(col)] != df[
'{}_right'.format(col)]), df['{}_right'.format(col)],
df['{}_left'.format(col)])
drop_list = ['{}_left'.format(col) for col in common_cols if col !=
'manual_id']
drop_list.extend(['{}_right'.format(col) for col in common_cols if
col != 'manual_id'])
df.drop(drop_list, axis=1, inplace=True)
return df[cols]
def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):
wb = load_workbook(filename=self.dest_file)
ws = wb[sheets[0]]
ws.title = sheets[0].replace('ACRONYM', acronym)
try:
curr_df = pd.read_excel(src)
except:
curr_df = pd.read_csv(src)
if zeta0_df is not None:
curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',
right_on='manual_id', how='left', suffixes=('_left', '_right'))
common_columns = [col for col in curr_df.columns if col in
zeta0_df.columns]
self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,
common_columns)
else:
self.source_df = curr_df
session_list = self.source_df.fillna('').values.tolist()
for row_iter in range(len(session_list)):
print(row_iter)
for col_iter in range(len(session_list[row_iter])):
print(col_iter)
ws.cell(row=row_iter + 2, column=col_iter + 1
).value = self.affiliation_cleaner(session_list[
row_iter][col_iter])
wb.save(self.dest_file)
def process_merger(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.copy_larvol_xlsx(template, acronym)
if merge.upper() == 'YES':
zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)
self.update_larvol_xlsx(source_file, acronym, sheets, columns,
zeta0)
else:
self.update_larvol_xlsx(source_file, acronym, sheets, columns)
def separated_by_number(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
affiliations_dict = {}
prev_affiliation = None
for affiliation in affiliations_list:
if affiliation != '':
group = re.findall('\\d+', affiliation)
if group != []:
num = list(map(int, group))[0]
affiliations_dict[str(num)] = str(num).join(affiliation
.split(str(num))[1:]).strip(',. ')
prev_affiliation = num
elif prev_affiliation is not None:
num = prev_affiliation
affiliations_dict[str(num)] = affiliations_dict[str(num)
] + '; ' + affiliation.strip(',. ')
prev_affiliation = num
for author in authors_list:
group = re.findall('\\d+', author)
num_list = list(map(int, group))
if num_list != []:
author_name = author.split(str(num_list[0]))[0].strip(',.-; ')
else:
author_name = author.strip(',.-; ')
for num in num_list:
try:
elem = affiliations_dict[str(num)]
except:
affiliations_dict[str(num)] = ''
cprint(
"Exception for manual_id: {} as affiliation index {} wasn't found"
.format(manual_id, str(num)), 'yellow', attrs=['bold'])
affiliation_name = '; '.join([affiliations_dict[str(num)].strip
(',.- ') for num in num_list])
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def separated_by_semicolon(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
try:
affiliation_name = affiliations_list[iter].strip(',.- ')
except:
affiliation_name = ''
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def common_affiliation(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
affiliation_name = affiliations_list[0].strip(',.- ')
print(affiliation_name)
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def process_pairtron(self, sheet):
source_df = self.source_df
source_df = source_df[source_df['authors'].notnull()]
source_id_list = source_df['source_id'].fillna('').tolist()
manual_id_list = source_df['manual_id'].fillna('').tolist()
authors_list = source_df['authors'].tolist()
affiliation_list = source_df['author_affiliation'].fillna('').tolist()
pairtron_list = []
for iter in range(len(authors_list)):
author_tokens = [elem.strip() for elem in authors_list[iter].
split(';')]
affiliation_tokens = [elem.strip() for elem in affiliation_list
[iter].split(';')]
try:
if author_tokens[0][-1].isdigit() and '1' in affiliation_list[
iter]:
pairtron_list.extend(self.separated_by_number(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
elif len(author_tokens) == len(affiliation_tokens):
pairtron_list.extend(self.separated_by_semicolon(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
elif author_tokens[0][-1].isdigit(
) and '1' not in affiliation_list[iter]:
cprint('ALERT: manual_id: {} has missing affiliations.'
.format(manual_id_list[iter]), 'red', attrs=['bold'])
else:
pairtron_list.extend(self.common_affiliation(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
except:
pass
df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',
'authors', 'author_affiliation'])
df.drop_duplicates(inplace=True)
authorsInfo_list = df.values.tolist()
wb = load_workbook(filename=self.dest_file)
ws = wb[sheet]
for row_iter in range(len(authorsInfo_list)):
for col_iter in range(len(authorsInfo_list[row_iter])):
ws.cell(row=row_iter + 2, column=col_iter + 1
).value = authorsInfo_list[row_iter][col_iter]
wb.save(self.dest_file)
def processData(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.process_merger(source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns)
self.process_pairtron(sheets[1])
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class pairtron:
def affiliation_cleaner(self, affiliation):
affiliation = str(affiliation)
affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',
' ')
while ' ;' in affiliation:
affiliation = affiliation.replace(' ;', ';')
while ';;' in affiliation:
affiliation = affiliation.replace(';;', ';')
return affiliation
def zeta0_creation(self, indexed_files_dir, merge_columns):
""" Returns pandas dataframe which has latest record for each manual id after merging all "sheet_name"
in the previously indexed_files which are present in "indexed_files_dir"
"""
indexed_files = [file for file in os.listdir(indexed_files_dir) if
not file.startswith('~')]
indexed_files_dict = {}
indexed_files_dict.clear()
dateList = []
del dateList[:]
for file in indexed_files:
dated = file.split('_')[-1].split('.')[0]
dated = dated[4:] + dated[:4]
dateList.append(dated)
indexed_files_dict[dated] = file
dataframes = {}
for dated, file in indexed_files_dict.items():
file_name = indexed_files_dir + '\\' + file
dataframes[dated] = pd.read_excel(file_name, sheet_name=0)
dataframes[dated]['file_date'] = dated
dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in
dataframes[dated]['manual_id']]
merged_df = pd.concat([dataframes[dated] for dated in dateList],
ignore_index=True)
merged_df = merged_df.sort_values('file_date', ascending=False)
zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')
pd.set_option('mode.chained_assignment', None)
for col in zeta0.columns:
zeta0[col] = zeta0[col].astype('str')
zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else
x)
zeta0 = zeta0.sort_values('mid', ascending=True)
if 'manual_id' not in merge_columns:
merge_columns.append('manual_id')
zeta0 = zeta0[merge_columns]
return zeta0
def copy_larvol_xlsx(self, template, acronym):
date = datetime.now().date().strftime('%m%d%Y')
self.dest_file = os.path.basename(template).replace('ACRONYM', acronym
).replace('MMDDYYYY', date + '_Pairtron')
shutil.copy2(template, self.dest_file)
def selectionAfterJoin(self, df, cols, common_cols):
for col in common_cols:
if col != 'manual_id':
df[col] = np.where(df['{}_left'.format(col)].isnull() | df[
'{}_right'.format(col)].notnull() & (df['{}_right'.
format(col)] != '') & (df['{}_left'.format(col)] != df[
'{}_right'.format(col)]), df['{}_right'.format(col)],
df['{}_left'.format(col)])
drop_list = ['{}_left'.format(col) for col in common_cols if col !=
'manual_id']
drop_list.extend(['{}_right'.format(col) for col in common_cols if
col != 'manual_id'])
df.drop(drop_list, axis=1, inplace=True)
return df[cols]
def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):
wb = load_workbook(filename=self.dest_file)
ws = wb[sheets[0]]
ws.title = sheets[0].replace('ACRONYM', acronym)
try:
curr_df = pd.read_excel(src)
except:
curr_df = pd.read_csv(src)
if zeta0_df is not None:
curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',
right_on='manual_id', how='left', suffixes=('_left', '_right'))
common_columns = [col for col in curr_df.columns if col in
zeta0_df.columns]
self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,
common_columns)
else:
self.source_df = curr_df
session_list = self.source_df.fillna('').values.tolist()
for row_iter in range(len(session_list)):
print(row_iter)
for col_iter in range(len(session_list[row_iter])):
print(col_iter)
ws.cell(row=row_iter + 2, column=col_iter + 1
).value = self.affiliation_cleaner(session_list[
row_iter][col_iter])
wb.save(self.dest_file)
def process_merger(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.copy_larvol_xlsx(template, acronym)
if merge.upper() == 'YES':
zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)
self.update_larvol_xlsx(source_file, acronym, sheets, columns,
zeta0)
else:
self.update_larvol_xlsx(source_file, acronym, sheets, columns)
def separated_by_number(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
affiliations_dict = {}
prev_affiliation = None
for affiliation in affiliations_list:
if affiliation != '':
group = re.findall('\\d+', affiliation)
if group != []:
num = list(map(int, group))[0]
affiliations_dict[str(num)] = str(num).join(affiliation
.split(str(num))[1:]).strip(',. ')
prev_affiliation = num
elif prev_affiliation is not None:
num = prev_affiliation
affiliations_dict[str(num)] = affiliations_dict[str(num)
] + '; ' + affiliation.strip(',. ')
prev_affiliation = num
for author in authors_list:
group = re.findall('\\d+', author)
num_list = list(map(int, group))
if num_list != []:
author_name = author.split(str(num_list[0]))[0].strip(',.-; ')
else:
author_name = author.strip(',.-; ')
for num in num_list:
try:
elem = affiliations_dict[str(num)]
except:
affiliations_dict[str(num)] = ''
cprint(
"Exception for manual_id: {} as affiliation index {} wasn't found"
.format(manual_id, str(num)), 'yellow', attrs=['bold'])
affiliation_name = '; '.join([affiliations_dict[str(num)].strip
(',.- ') for num in num_list])
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def separated_by_semicolon(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
try:
affiliation_name = affiliations_list[iter].strip(',.- ')
except:
affiliation_name = ''
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def common_affiliation(self, source_id, manual_id, authors_list,
affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
affiliation_name = affiliations_list[0].strip(',.- ')
print(affiliation_name)
separated_authors_list.append([source_id, manual_id,
author_name, affiliation_name])
return separated_authors_list
def process_pairtron(self, sheet):
source_df = self.source_df
source_df = source_df[source_df['authors'].notnull()]
source_id_list = source_df['source_id'].fillna('').tolist()
manual_id_list = source_df['manual_id'].fillna('').tolist()
authors_list = source_df['authors'].tolist()
affiliation_list = source_df['author_affiliation'].fillna('').tolist()
pairtron_list = []
for iter in range(len(authors_list)):
author_tokens = [elem.strip() for elem in authors_list[iter].
split(';')]
affiliation_tokens = [elem.strip() for elem in affiliation_list
[iter].split(';')]
try:
if author_tokens[0][-1].isdigit() and '1' in affiliation_list[
iter]:
pairtron_list.extend(self.separated_by_number(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
elif len(author_tokens) == len(affiliation_tokens):
pairtron_list.extend(self.separated_by_semicolon(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
elif author_tokens[0][-1].isdigit(
) and '1' not in affiliation_list[iter]:
cprint('ALERT: manual_id: {} has missing affiliations.'
.format(manual_id_list[iter]), 'red', attrs=['bold'])
else:
pairtron_list.extend(self.common_affiliation(
source_id_list[iter], manual_id_list[iter],
author_tokens, affiliation_tokens))
except:
pass
df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',
'authors', 'author_affiliation'])
df.drop_duplicates(inplace=True)
authorsInfo_list = df.values.tolist()
wb = load_workbook(filename=self.dest_file)
ws = wb[sheet]
for row_iter in range(len(authorsInfo_list)):
for col_iter in range(len(authorsInfo_list[row_iter])):
ws.cell(row=row_iter + 2, column=col_iter + 1
).value = authorsInfo_list[row_iter][col_iter]
wb.save(self.dest_file)
def processData(self, source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns):
self.process_merger(source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns)
self.process_pairtron(sheets[1])
if __name__ == '__main__':
start = datetime.now()
print('Script Start Time ', start)
print('Script Running.....\n')
parser = ConfigParser()
parser.read('pairtron_config.ini')
source_file = parser.get('dynamic_fields', 'source_file')
acronym = parser.get('dynamic_fields', 'ACRONYM')
merge = parser.get('dynamic_fields', 'merge')
merge_columns = [elem.strip() for elem in parser.get('dynamic_fields',
'merge_columns').split(',')]
template = parser.get('static_fields', 'template')
sheets = parser.get('static_fields', 'sheets').split(',')
indexed_files_dir = parser.get('static_fields', 'indexed_files_dir')
columns = parser.get('static_fields', 'columns').split(',')
obj = pairtron()
obj.processData(source_file, acronym, merge, template, sheets,
indexed_files_dir, columns, merge_columns)
total_time = datetime.now() - start
print('\nScript End Time ', datetime.now())
print('Execution Time', total_time)
<|reserved_special_token_1|>
import re
import pandas as pd
import pandas.io.formats.excel
from configparser import ConfigParser
from datetime import datetime
from termcolor import cprint
import os
import shutil
from openpyxl import load_workbook
import numpy as np
class pairtron():
def affiliation_cleaner(self, affiliation):
# print(affiliation)
affiliation = str(affiliation)
affiliation = affiliation.strip(" ;").replace(" ", " ").replace(" "," ")
while ' ;' in affiliation:
affiliation = affiliation.replace(" ;", ";")
while ';;' in affiliation:
affiliation = affiliation.replace(";;", ";")
return affiliation
def zeta0_creation(self, indexed_files_dir, merge_columns):
""" Returns pandas dataframe which has latest record for each manual id after merging all "sheet_name"
in the previously indexed_files which are present in "indexed_files_dir"
"""
indexed_files = [file for file in os.listdir(indexed_files_dir) if not file.startswith("~")]
indexed_files_dict = {}
indexed_files_dict.clear()
dateList = []
del dateList[:]
for file in indexed_files:
dated = file.split('_')[-1].split('.')[0]
dated = dated[4:] + dated[:4]
dateList.append(dated)
indexed_files_dict[dated] = file
dataframes = {}
for dated, file in indexed_files_dict.items():
file_name = indexed_files_dir + '\\' + file
dataframes[dated] = pd.read_excel(file_name, sheet_name=0)
dataframes[dated]['file_date'] = dated
dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in dataframes[dated]['manual_id']]
merged_df = pd.concat([dataframes[dated] for dated in dateList], ignore_index=True)
merged_df = merged_df.sort_values('file_date', ascending=False)
zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')
pd.set_option('mode.chained_assignment', None)
for col in zeta0.columns:
zeta0[col] = zeta0[col].astype('str')
zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == "object" else x)
zeta0 = zeta0.sort_values('mid', ascending=True)
if "manual_id" not in merge_columns:
merge_columns.append("manual_id")
zeta0 = zeta0[merge_columns]
# print(zeta0)
return zeta0
def copy_larvol_xlsx(self, template, acronym):
date = datetime.now().date().strftime('%m%d%Y')
self.dest_file = os.path.basename(template).replace('ACRONYM',acronym).replace('MMDDYYYY', date + '_Pairtron')
shutil.copy2(template, self.dest_file)
def selectionAfterJoin(self, df, cols, common_cols):
for col in common_cols:
if col != 'manual_id':
df[col] = np.where(df['{}_left'.format(col)].isnull() | ((df['{}_right'.format(col)].notnull()) & (df['{}_right'.format(col)] != '') & (df['{}_left'.format(col)] != df['{}_right'.format(col)])), df['{}_right'.format(col)], df['{}_left'.format(col)])
drop_list = ['{}_left'.format(col) for col in common_cols if col != 'manual_id']
drop_list.extend(['{}_right'.format(col) for col in common_cols if col != 'manual_id'])
df.drop(drop_list, axis=1, inplace=True)
return df[cols]
def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):
wb = load_workbook(filename=self.dest_file)
ws = wb[sheets[0]]
ws.title = sheets[0].replace('ACRONYM',acronym)
try:
curr_df = pd.read_excel(src)
except:
curr_df = pd.read_csv(src)
if zeta0_df is not None:
curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id', right_on='manual_id', how='left', suffixes=('_left', '_right'))
common_columns = [col for col in curr_df.columns if col in zeta0_df.columns]
self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns, common_columns)
else:
self.source_df = curr_df
session_list = self.source_df.fillna('').values.tolist()
for row_iter in range(len(session_list)):
print(row_iter)
for col_iter in range(len(session_list[row_iter])):
print(col_iter)
ws.cell(row=row_iter+2, column=col_iter+1).value = self.affiliation_cleaner(session_list[row_iter][col_iter])
wb.save(self.dest_file)
def process_merger(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns):
self.copy_larvol_xlsx(template, acronym)
if merge.upper() == 'YES':
zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)
self.update_larvol_xlsx(source_file, acronym, sheets, columns, zeta0)
else:
self.update_larvol_xlsx(source_file, acronym, sheets, columns)
def separated_by_number(self, source_id, manual_id, authors_list, affiliations_list):
separated_authors_list = []
affiliations_dict = {}
prev_affiliation = None
for affiliation in affiliations_list:
#print(manual_id)
#print(affiliation)
if affiliation != '':
group = re.findall(r'\d+', affiliation)
#print(group)
if group != []:
num = list(map(int, group))[0]
affiliations_dict[str(num)] = str(num).join(affiliation.split(str(num))[1:]).strip(',. ')
prev_affiliation = num
elif prev_affiliation is not None:
num = prev_affiliation
affiliations_dict[str(num)] = affiliations_dict[str(num)] + '; ' + affiliation.strip(',. ')
prev_affiliation = num
for author in authors_list:
#print(author)
group = re.findall(r'\d+', author)
num_list = list(map(int, group))
#print(num_list)
if num_list != []:
author_name = author.split(str(num_list[0]))[0].strip(',.-; ')
else:
author_name = author.strip(',.-; ')
#print(author_name)
for num in num_list:
try:
elem = affiliations_dict[str(num)]
except:
affiliations_dict[str(num)] = ''
cprint("Exception for manual_id: {} as affiliation index {} wasn't found".format(manual_id, str(num)), 'yellow', attrs=['bold'])
affiliation_name = '; '.join([affiliations_dict[str(num)].strip(',.- ') for num in num_list])
#print(affiliation_name)
separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])
return separated_authors_list
def separated_by_semicolon(self, source_id, manual_id, authors_list, affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
try:
affiliation_name = affiliations_list[iter].strip(',.- ')
except:
affiliation_name = ''
separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])
return separated_authors_list
def common_affiliation(self, source_id, manual_id, authors_list, affiliations_list):
separated_authors_list = []
for iter in range(len(authors_list)):
author_name = authors_list[iter].strip(',.-; ')
affiliation_name = affiliations_list[0].strip(',.- ')
print(affiliation_name)
separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])
return separated_authors_list
def process_pairtron(self, sheet):
source_df = self.source_df
source_df = source_df[source_df['authors'].notnull()]
source_id_list = source_df['source_id'].fillna('').tolist()
manual_id_list = source_df['manual_id'].fillna('').tolist()
authors_list = source_df['authors'].tolist()
affiliation_list = source_df['author_affiliation'].fillna('').tolist()
pairtron_list = []
for iter in range(len(authors_list)):
#print(iter, manual_id_list[iter])
author_tokens = [elem.strip() for elem in authors_list[iter].split(';')]
affiliation_tokens = [elem.strip() for elem in affiliation_list[iter].split(';')]
try:
if author_tokens[0][-1].isdigit() and '1' in affiliation_list[iter]:
pairtron_list.extend(self.separated_by_number(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))
elif len(author_tokens) == len(affiliation_tokens):
pairtron_list.extend(self.separated_by_semicolon(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))
elif author_tokens[0][-1].isdigit() and '1' not in affiliation_list[iter]:
cprint("ALERT: manual_id: {} has missing affiliations.".format(manual_id_list[iter]), 'red', attrs=['bold'])
else:
pairtron_list.extend(self.common_affiliation(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))
except:
pass
df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id', 'authors', 'author_affiliation'])
df.drop_duplicates(inplace = True)
authorsInfo_list = df.values.tolist()
wb = load_workbook(filename=self.dest_file)
ws = wb[sheet]
for row_iter in range(len(authorsInfo_list)):
for col_iter in range(len(authorsInfo_list[row_iter])):
ws.cell(row=row_iter+2, column=col_iter+1).value = authorsInfo_list[row_iter][col_iter]
wb.save(self.dest_file)
def processData(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns):
self.process_merger(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns)
self.process_pairtron(sheets[1])
if __name__ == "__main__":
start = datetime.now()
print ("Script Start Time ",start)
print ("Script Running.....\n")
parser = ConfigParser()
parser.read('pairtron_config.ini')
source_file = parser.get('dynamic_fields', 'source_file')
acronym = parser.get('dynamic_fields', 'ACRONYM')
merge = parser.get('dynamic_fields', 'merge')
merge_columns = [elem.strip() for elem in parser.get('dynamic_fields', 'merge_columns').split(',')]
template = parser.get('static_fields', 'template')
sheets = parser.get('static_fields', 'sheets').split(',')
indexed_files_dir = parser.get('static_fields', 'indexed_files_dir')
columns = parser.get('static_fields', 'columns').split(',')
obj = pairtron()
obj.processData(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns)
total_time = datetime.now() - start
print ("\nScript End Time ",datetime.now())
print ("Execution Time", total_time)
|
flexible
|
{
"blob_id": "fbab5826f47163cf82b534d311eae572c5fcd128",
"index": 3287,
"step-1": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n <mask token>\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n <mask token>\n <mask token>\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n <mask token>\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n <mask token>\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n for iter in range(len(authors_list)):\n author_tokens = [elem.strip() for elem in authors_list[iter].\n split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list\n [iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[\n iter]:\n pairtron_list.extend(self.separated_by_number(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit(\n ) and '1' not in affiliation_list[iter]:\n cprint('ALERT: manual_id: {} has missing affiliations.'\n .format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',\n 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace=True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n\n def copy_larvol_xlsx(self, template, acronym):\n date = datetime.now().date().strftime('%m%d%Y')\n self.dest_file = os.path.basename(template).replace('ACRONYM', acronym\n ).replace('MMDDYYYY', date + '_Pairtron')\n shutil.copy2(template, self.dest_file)\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def common_affiliation(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n affiliation_name = affiliations_list[0].strip(',.- ')\n print(affiliation_name)\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n for iter in range(len(authors_list)):\n author_tokens = [elem.strip() for elem in authors_list[iter].\n split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list\n [iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[\n iter]:\n pairtron_list.extend(self.separated_by_number(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit(\n ) and '1' not in affiliation_list[iter]:\n cprint('ALERT: manual_id: {} has missing affiliations.'\n .format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',\n 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace=True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n\n def copy_larvol_xlsx(self, template, acronym):\n date = datetime.now().date().strftime('%m%d%Y')\n self.dest_file = os.path.basename(template).replace('ACRONYM', acronym\n ).replace('MMDDYYYY', date + '_Pairtron')\n shutil.copy2(template, self.dest_file)\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def common_affiliation(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n affiliation_name = affiliations_list[0].strip(',.- ')\n print(affiliation_name)\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n for iter in range(len(authors_list)):\n author_tokens = [elem.strip() for elem in authors_list[iter].\n split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list\n [iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[\n iter]:\n pairtron_list.extend(self.separated_by_number(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit(\n ) and '1' not in affiliation_list[iter]:\n cprint('ALERT: manual_id: {} has missing affiliations.'\n .format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',\n 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace=True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\nif __name__ == '__main__':\n start = datetime.now()\n print('Script Start Time ', start)\n print('Script Running.....\\n')\n parser = ConfigParser()\n parser.read('pairtron_config.ini')\n source_file = parser.get('dynamic_fields', 'source_file')\n acronym = parser.get('dynamic_fields', 'ACRONYM')\n merge = parser.get('dynamic_fields', 'merge')\n merge_columns = [elem.strip() for elem in parser.get('dynamic_fields',\n 'merge_columns').split(',')]\n template = parser.get('static_fields', 'template')\n sheets = parser.get('static_fields', 'sheets').split(',')\n indexed_files_dir = parser.get('static_fields', 'indexed_files_dir')\n columns = parser.get('static_fields', 'columns').split(',')\n obj = pairtron()\n obj.processData(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n total_time = datetime.now() - start\n print('\\nScript End Time ', datetime.now())\n print('Execution Time', total_time)\n",
"step-5": "import re\nimport pandas as pd\nimport pandas.io.formats.excel\nfrom configparser import ConfigParser\nfrom datetime import datetime\nfrom termcolor import cprint\nimport os\nimport shutil\nfrom openpyxl import load_workbook\nimport numpy as np\n\nclass pairtron():\n\n def affiliation_cleaner(self, affiliation):\n # print(affiliation)\n affiliation = str(affiliation)\n affiliation = affiliation.strip(\" ;\").replace(\" \", \" \").replace(\" \",\" \")\n while ' ;' in affiliation:\n affiliation = affiliation.replace(\" ;\", \";\")\n while ';;' in affiliation:\n affiliation = affiliation.replace(\";;\", \";\")\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if not file.startswith(\"~\")]\n\n indexed_files_dict = {}\n indexed_files_dict.clear()\n\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n\n dataframes = {}\n\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in dataframes[dated]['manual_id']]\n\n merged_df = pd.concat([dataframes[dated] for dated in dateList], ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == \"object\" else x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if \"manual_id\" not in merge_columns:\n merge_columns.append(\"manual_id\")\n zeta0 = zeta0[merge_columns]\n # print(zeta0)\n return zeta0\n\n def copy_larvol_xlsx(self, template, acronym):\n date = datetime.now().date().strftime('%m%d%Y')\n self.dest_file = os.path.basename(template).replace('ACRONYM',acronym).replace('MMDDYYYY', date + '_Pairtron')\n shutil.copy2(template, self.dest_file)\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | ((df['{}_right'.format(col)].notnull()) & (df['{}_right'.format(col)] != '') & (df['{}_left'.format(col)] != df['{}_right'.format(col)])), df['{}_right'.format(col)], df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col != 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM',acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id', right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns, common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter+2, column=col_iter+1).value = self.affiliation_cleaner(session_list[row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns, zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list, affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n\n for affiliation in affiliations_list:\n #print(manual_id)\n #print(affiliation)\n if affiliation != '':\n group = re.findall(r'\\d+', affiliation)\n #print(group)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation.split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n\n for author in authors_list:\n #print(author)\n group = re.findall(r'\\d+', author)\n num_list = list(map(int, group))\n #print(num_list)\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n #print(author_name)\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\"Exception for manual_id: {} as affiliation index {} wasn't found\".format(manual_id, str(num)), 'yellow', attrs=['bold'])\n\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip(',.- ') for num in num_list])\n #print(affiliation_name)\n separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])\n\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list, affiliations_list):\n separated_authors_list = []\n\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])\n\n return separated_authors_list\n\n\n def common_affiliation(self, source_id, manual_id, authors_list, affiliations_list):\n separated_authors_list = []\n\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n affiliation_name = affiliations_list[0].strip(',.- ')\n print(affiliation_name)\n separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])\n\n return separated_authors_list\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n\n for iter in range(len(authors_list)):\n #print(iter, manual_id_list[iter])\n author_tokens = [elem.strip() for elem in authors_list[iter].split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list[iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[iter]:\n pairtron_list.extend(self.separated_by_number(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit() and '1' not in affiliation_list[iter]:\n cprint(\"ALERT: manual_id: {} has missing affiliations.\".format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id', 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace = True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter+2, column=col_iter+1).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\nif __name__ == \"__main__\":\n\n start = datetime.now()\n print (\"Script Start Time \",start)\n print (\"Script Running.....\\n\")\n\n parser = ConfigParser()\n parser.read('pairtron_config.ini')\n\n source_file = parser.get('dynamic_fields', 'source_file')\n acronym = parser.get('dynamic_fields', 'ACRONYM')\n merge = parser.get('dynamic_fields', 'merge')\n merge_columns = [elem.strip() for elem in parser.get('dynamic_fields', 'merge_columns').split(',')]\n template = parser.get('static_fields', 'template')\n sheets = parser.get('static_fields', 'sheets').split(',')\n indexed_files_dir = parser.get('static_fields', 'indexed_files_dir')\n columns = parser.get('static_fields', 'columns').split(',')\n\n obj = pairtron()\n obj.processData(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns)\n\n total_time = datetime.now() - start\n print (\"\\nScript End Time \",datetime.now())\n print (\"Execution Time\", total_time)",
"step-ids": [
9,
10,
12,
13,
15
]
}
|
[
9,
10,
12,
13,
15
] |
# ********************************************************************************** #
# #
# Project: Data Frame Explorer #
# Author: Pawel Rosikiewicz #
# Contact: prosikiewicz(a)gmail.com #
# #
# License: MIT License #
# Copyright (C) 2021.01.30 Pawel Rosikiewicz #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in all #
# copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #
# SOFTWARE. #
# #
# ********************************************************************************** #
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
import random
import glob
import re
import os
import seaborn as sns
from IPython.display import display
from pandas.api.types import is_numeric_dtype
from pandas.api.types import is_string_dtype
# Function, ............................................................................
def find_and_display_patter_in_series(*, series, pattern):
"I used that function when i don't remeber full name of a given column"
res = series.loc[series.str.contains(pattern)]
return res
# Function, ...........................................................................................
def load_csv(*, path, filename, sep="\t", verbose=True):
"""
Loads csv into pandas df, based on pandas.read_scv(),
Returns error, if file or directoy not found
Parameters/Input
_________________ _______________________________________________________________________________
* path full path to directory
* csv_name. full csv file name
* separator "\t", by default
* display_head bool, True, by default, display df.head(),
irrespectively when the futions was called.
Returns
_________________ _______________________________________________________________________________
* DataFrame by Pandas
"""
os.chdir(path)
if len(glob.glob(filename))==1:
df = pd.read_csv(filename, sep=sep, low_memory=False)
# display example,
if verbose==True:
display(df.head(3))
print(df.shape)
else:
pass
# return,
return df
else:
if verbose==True:
print(f"""ERROR :csv file {filename}, was not found in: \n {path}""")
else:
pass
# Function, ............................................................................
def find_patter_in_series(*, s, pat, tolist=True):
'''
I used that function when i don't remeber full name of a given column
'''
res = s.loc[s.str.contains(pat)]
if tolist==True:
return res.values.tolist()
else:
return res
# Function, ...........................................................................................
def format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):
'''
formats columns in df into datetime dtype, and set all times to UTC
work with unix time units, ie. second number since 1970
columns in df, are find using full comlumn name or keywords in column name
'''
assert type(data)==pd.DataFrame, "please provide data in pandas dataframe format"
if isinstance(pattern_list, str):
pattern_list = [pattern_list]
else:
pass
for pat in pattern_list:
# find column names using provided patterns or their full names,
columns_with_potential_datetime_obj = list(find_and_display_patter_in_series(series=pd.Series(data.columns), pattern=pat))
# replace
for i in columns_with_potential_datetime_obj:
# keep example of old cell
before_formatting = str(data.loc[0, i])
# convert to one format
if unixtime==True:
s = pd.to_datetime(data.loc[:, i], errors="coerce", unit='s').copy()#,format cannot be used with unit="s", but it will be the same
data.loc[:, i] = s
if timezone!=None:
data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)
else:
pass
else:
s = pd.to_datetime(data.loc[:, i], errors="coerce",format=dt_format).copy()
data.loc[:, i] = s
if timezone!=None:
data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)
else:
pass
# info
if verbose==True:
print(f"date time formatted in: {i}")
print(f" - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce")
print(f" - Example: {before_formatting} -->> {str(data.loc[0, i])}", end="\n")
else:
pass
return data
# Function, ...........................................................................................
def replace_text(*,df ,pat="", colnames="all", fillna=np.nan, verbose=True):
"""
searches string with a given pattern and replace it with a new patter (fillna), eg: nan,
Parameters/Input
_________________ _______________________________________________________________________________
* df Pandas Dataframe
* searched_pattern "", str literal, used by pd.Series.str.contains()
* colnames default, "all", or list with selected colnames in df
* fillna default numpy.nan, or str literal
- what do you want to place instead of searched pattern in df
Returns
_________________ _______________________________________________________________________________
* DataFrame DataFramne.copy() with new values,
* display messages. number of replaced straings in each column, and examples of replcaced values
"""
# for older version,
searched_pattern = pat
col_names = colnames
# check col_names with values to replace,
if col_names=="all":
sel_col_names = list(df.columns)
else:
sel_col_names = col_names
# display message header,
if verbose==True:
print(f"""\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\n""")
if verbose==False:
pass
# exchnage searched pattern in each column separately,
for i, col_name in enumerate(sel_col_names):
# .. test if you really have string values in that column, otherwise it masy be float for all NaN in a column, and no action will be taken
if is_string_dtype(df[col_name]):
try:
# .... find postions with a given pattern and select three examples to display for the user,
positions_to_replace = df[col_name].str.contains(searched_pattern, na=False).values# arr
examples_to_display = [str(x) for x in list(df.loc[list(positions_to_replace), col_name].str[0:20].values.tolist()[0:3])]
# .... replace postions, and find examples of unchnaged postions,
df.loc[list(positions_to_replace), col_name] = [fillna]*positions_to_replace.sum()
examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace==False), col_name].str[0:20].values.tolist()[0:3])]
# .... diplay info,
if verbose==True:
perc_of_replaced_pos_in_col = "".join([str(positions_to_replace.sum()/df.shape[0]*100),"%"])
print(f"{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}")
print(f" - three examples of replaced postions: {'; '.join(examples_to_display)}", end="\n")
print(f" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}", end="\n\n")
# the second print returns three first examples of exchanged values, just to see what i did,
else:
pass
except:
if verbose==True:
print(f"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n")
else:
pass
else:
if verbose==True:
print(f"{i} - {col_name} - - is not of string type, Values were not replaced! \n")
else:
pass
return df.copy()
# Function, ...........................................................................................
def replace_numeric_values(*, df, colnames="all", lower_limit="none", upper_limit="none", equal=False, replace_with=np.nan, verbose=True):
"""
Replace numerical values that are outside of range of a values
prediced with a theoretical limits of a given variable,
eg less then 0 in weight of a product,
Provide examples and numbers of replaced instances
Parameters/Input
_________________ _______________________________________________________________________________
* df : Pandas DataFrame
* cols_in_df : list, exact colnames of selected or all columns in df
* lower_limit : int,float,"none", if "none" no action is taken
* upper_limit : int,float,"none", if "none" no action is taken
* replace_with : str, np.nan, int, float
* equal : bool, if True, >= and <= values then limits will be replaced,
if False (default), > and < values then limits will be replaced,
Returns
_________________ _______________________________________________________________________________
* DataFrame DataFramne.copy() with new values,
* display messages. number of replaced straings in each column, and examples of replcaced values
"""
cols_names = colnames
# .. check provided col_names,
if cols_names=="all":
cols = list(df.columns)
else:
cols = cols_names
# .. info, header,
if verbose==True:
print(f"""\n{"".join(["-"]*80)} \n Replacing Numerical Values in {len(cols)} columns""")
print(f" lower filter={lower_limit}, upper filter ={upper_limit}")
if equal==True:
print(f" Caution, equal=True, ie. values >= and <= then requested limits will be replaced")
print(f'{"".join(["-"]*80)}\n')
if verbose==False:
pass
# .. intelligent info,
total_count=[]
# .. count, to limit the number of displayed messages,
count = 0
# .. replace values and collect examples,
for i, j in enumerate(cols):
# ..... assume no values were replaced, so the messages work later,
info_lower_filter = 0
info_upper_filter = 0
# ..... test if the column is of the numeric type:
# from pandas.api.types import is_numeric_dtype
if is_numeric_dtype(df[j]):
# * replace values < or <= lower limit,
# - ----------------------------------
if lower_limit!="none":
if equal == True:
lower_filter = df.loc[:,j]<=lower_limit
if equal == False:
lower_filter = df.loc[:,j]<lower_limit
# info,
info_lower_filter=lower_filter.sum()
df.loc[list(lower_filter),j]=replace_with
# * replace values > or >= upper limit,
# - ----------------------------------
if upper_limit!="none":
if equal == True:
upper_filter = df.loc[:,j]>=upper_limit
if equal == False:
upper_filter = df.loc[:,j]>upper_limit
# info,
info_upper_filter=upper_filter.sum()
df.loc[list(upper_filter),j]=replace_with
# * find how many values were replaced, and add that to the total_count list
total_count.append(info_upper_filter+info_lower_filter)
# * display examples for 3 first columns with replaced values,
if verbose==True:
if info_upper_filter+info_lower_filter>0 and count <4:
print(f"eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}")
else:
pass
# * add 1 to count, to limit the number of displayed examples,
count += 1
else:
if verbose==True:
print(f"{i, j} is not of numeric type, values were not replaced !")
else:
pass
# .. additional message, if more then 2 columns had replaced values,
if verbose==True:
if len(total_count)>3 and pd.Series(total_count).sum()>0:
print(f". and {len(total_count)-3} other columns had in total {pd.Series(total_count).sum()} replaced values \n")
# .. message in case no values vere replaced at all,
if pd.Series(total_count).sum()==0:
print("No values were replaced in requested columns....")
else:
pass
# .. return,
return df.copy()
# function, ...................................................
def drop_nan(df, method="any", row=True, verbose=True):
'''
function to dropna with thresholds from rows and columns
. method
. any : row/column wiht any missing data are removed
. all : row/column only wiht missing data are removed
. int, >0 : keeps row/clumns wiht this or larger number of non missing data
. float, >0 : as in the above, as fraction
'''
assert type(df)==pd.DataFrame, "incorrect df dtype"
df = df.copy()
if verbose==True:
print(df.shape)
else:
pass
# set funtion for rows or columns,
if row==True:
shapeidx, dfaxis = 1, 0
else:
shapeidx, dfaxis = 0, 1
# use threshold or "all", or None for do nothing,
if method==None:
pass
elif isinstance(method, str):
df = df.dropna(how=method, axis=dfaxis) # removes rows with NaN in all columns
elif isinstance(method, int):
tr = method
if tr==0:
pass
else:
if tr>=df.shape[shapeidx]:
tr=df.shape[shapeidx]
else:
pass
df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value
elif isinstance(method, float):
tr = int(np.ceil(df.shape[shapeidx]*(method)))
if tr==0:
pass
else:
if tr>=df.shape[shapeidx]:
tr=df.shape[shapeidx]
else:
pass
df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value
else:
pass
# info and return
if verbose==True:
print(df.shape)
else:
pass
return df
# Function, ...........................................................................................
def drop_columns(*, df, columns_to_drop, verbose=True):
"""
Small function to quickly remove columns from,
by column names stored in the list
- created to give info on removed columns and whether I am chnaging df in proper way,
- the function allows for column name duplicates,
"""
assert type(df)==pd.DataFrame, "please provide df in pandas dataframe format"
df = df.copy()
# find unique values in a list, just in case I made the mistake,
columns_to_drop = list(pd.Series(columns_to_drop).unique())
# .. info, header,
if verbose==True:
print(f"""Removing {len(columns_to_drop)} columns from df""")
else:
pass
# remove columns one by one,
for i,j in enumerate(columns_to_drop):
try:
df.drop(columns=[j], axis=1, inplace=True)
if verbose==True:
print(f"{i} removing: {j}, ==> new df.shape: {df.shape}")
else:
pass
except:
if verbose==True:
print(f"{i} .... column: {j}, was not found in df, check if name is correct....")
else:
pass
return df
|
normal
|
{
"blob_id": "5f50b20bd044471ebb8e1350d1a75a250b255d8f",
"index": 8854,
"step-1": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n<mask token>\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n<mask token>\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\n<mask token>\n\n\ndef drop_nan(df, method='any', row=True, verbose=True):\n \"\"\"\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n \"\"\"\n assert type(df) == pd.DataFrame, 'incorrect df dtype'\n df = df.copy()\n if verbose == True:\n print(df.shape)\n else:\n pass\n if row == True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n if method == None:\n pass\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis)\n elif isinstance(method, int):\n tr = method\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx] * method))\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n else:\n pass\n if verbose == True:\n print(df.shape)\n else:\n pass\n return df\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n<mask token>\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\ndef replace_numeric_values(*, df, colnames='all', lower_limit='none',\n upper_limit='none', equal=False, replace_with=np.nan, verbose=True):\n \"\"\" \n\n Replace numerical values that are outside of range of a values \n prediced with a theoretical limits of a given variable, \n eg less then 0 in weight of a product, \n Provide examples and numbers of replaced instances\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df : Pandas DataFrame\n * cols_in_df : list, exact colnames of selected or all columns in df\n * lower_limit : int,float,\"none\", if \"none\" no action is taken\n * upper_limit : int,float,\"none\", if \"none\" no action is taken\n * replace_with : str, np.nan, int, float\n * equal : bool, if True, >= and <= values then limits will be replaced,\n if False (default), > and < values then limits will be replaced,\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n cols_names = colnames\n if cols_names == 'all':\n cols = list(df.columns)\n else:\n cols = cols_names\n if verbose == True:\n print(\n f\"\\n{''.join(['-'] * 80)} \\n Replacing Numerical Values in {len(cols)} columns\"\n )\n print(\n f' lower filter={lower_limit}, upper filter ={upper_limit}')\n if equal == True:\n print(\n f' Caution, equal=True, ie. values >= and <= then requested limits will be replaced'\n )\n print(f\"{''.join(['-'] * 80)}\\n\")\n if verbose == False:\n pass\n total_count = []\n count = 0\n for i, j in enumerate(cols):\n info_lower_filter = 0\n info_upper_filter = 0\n if is_numeric_dtype(df[j]):\n if lower_limit != 'none':\n if equal == True:\n lower_filter = df.loc[:, j] <= lower_limit\n if equal == False:\n lower_filter = df.loc[:, j] < lower_limit\n info_lower_filter = lower_filter.sum()\n df.loc[list(lower_filter), j] = replace_with\n if upper_limit != 'none':\n if equal == True:\n upper_filter = df.loc[:, j] >= upper_limit\n if equal == False:\n upper_filter = df.loc[:, j] > upper_limit\n info_upper_filter = upper_filter.sum()\n df.loc[list(upper_filter), j] = replace_with\n total_count.append(info_upper_filter + info_lower_filter)\n if verbose == True:\n if info_upper_filter + info_lower_filter > 0 and count < 4:\n print(\n f'eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}'\n )\n else:\n pass\n count += 1\n elif verbose == True:\n print(f'{i, j} is not of numeric type, values were not replaced !')\n else:\n pass\n if verbose == True:\n if len(total_count) > 3 and pd.Series(total_count).sum() > 0:\n print(\n f\"\"\". and {len(total_count) - 3} other columns had in total {pd.Series(total_count).sum()} replaced values \n\"\"\"\n )\n if pd.Series(total_count).sum() == 0:\n print('No values were replaced in requested columns....')\n else:\n pass\n return df.copy()\n\n\ndef drop_nan(df, method='any', row=True, verbose=True):\n \"\"\"\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n \"\"\"\n assert type(df) == pd.DataFrame, 'incorrect df dtype'\n df = df.copy()\n if verbose == True:\n print(df.shape)\n else:\n pass\n if row == True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n if method == None:\n pass\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis)\n elif isinstance(method, int):\n tr = method\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx] * method))\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n else:\n pass\n if verbose == True:\n print(df.shape)\n else:\n pass\n return df\n\n\ndef drop_columns(*, df, columns_to_drop, verbose=True):\n \"\"\"\n Small function to quickly remove columns from, \n by column names stored in the list\n - created to give info on removed columns and whether I am chnaging df in proper way,\n - the function allows for column name duplicates, \n \"\"\"\n assert type(df\n ) == pd.DataFrame, 'please provide df in pandas dataframe format'\n df = df.copy()\n columns_to_drop = list(pd.Series(columns_to_drop).unique())\n if verbose == True:\n print(f'Removing {len(columns_to_drop)} columns from df')\n else:\n pass\n for i, j in enumerate(columns_to_drop):\n try:\n df.drop(columns=[j], axis=1, inplace=True)\n if verbose == True:\n print(f'{i} removing: {j}, ==> new df.shape: {df.shape}')\n else:\n pass\n except:\n if verbose == True:\n print(\n f'{i} .... column: {j}, was not found in df, check if name is correct....'\n )\n else:\n pass\n return df\n",
"step-4": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\ndef load_csv(*, path, filename, sep='\\t', verbose=True):\n \"\"\" \n Loads csv into pandas df, based on pandas.read_scv(), \n Returns error, if file or directoy not found\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * path full path to directory\n * csv_name. full csv file name\n * separator \"\t\", by default\n * display_head bool, True, by default, display df.head(), \n irrespectively when the futions was called. \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame by Pandas\n\n \"\"\"\n os.chdir(path)\n if len(glob.glob(filename)) == 1:\n df = pd.read_csv(filename, sep=sep, low_memory=False)\n if verbose == True:\n display(df.head(3))\n print(df.shape)\n else:\n pass\n return df\n elif verbose == True:\n print(f'ERROR :csv file {filename}, was not found in: \\n {path}')\n else:\n pass\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\ndef replace_numeric_values(*, df, colnames='all', lower_limit='none',\n upper_limit='none', equal=False, replace_with=np.nan, verbose=True):\n \"\"\" \n\n Replace numerical values that are outside of range of a values \n prediced with a theoretical limits of a given variable, \n eg less then 0 in weight of a product, \n Provide examples and numbers of replaced instances\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df : Pandas DataFrame\n * cols_in_df : list, exact colnames of selected or all columns in df\n * lower_limit : int,float,\"none\", if \"none\" no action is taken\n * upper_limit : int,float,\"none\", if \"none\" no action is taken\n * replace_with : str, np.nan, int, float\n * equal : bool, if True, >= and <= values then limits will be replaced,\n if False (default), > and < values then limits will be replaced,\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n cols_names = colnames\n if cols_names == 'all':\n cols = list(df.columns)\n else:\n cols = cols_names\n if verbose == True:\n print(\n f\"\\n{''.join(['-'] * 80)} \\n Replacing Numerical Values in {len(cols)} columns\"\n )\n print(\n f' lower filter={lower_limit}, upper filter ={upper_limit}')\n if equal == True:\n print(\n f' Caution, equal=True, ie. values >= and <= then requested limits will be replaced'\n )\n print(f\"{''.join(['-'] * 80)}\\n\")\n if verbose == False:\n pass\n total_count = []\n count = 0\n for i, j in enumerate(cols):\n info_lower_filter = 0\n info_upper_filter = 0\n if is_numeric_dtype(df[j]):\n if lower_limit != 'none':\n if equal == True:\n lower_filter = df.loc[:, j] <= lower_limit\n if equal == False:\n lower_filter = df.loc[:, j] < lower_limit\n info_lower_filter = lower_filter.sum()\n df.loc[list(lower_filter), j] = replace_with\n if upper_limit != 'none':\n if equal == True:\n upper_filter = df.loc[:, j] >= upper_limit\n if equal == False:\n upper_filter = df.loc[:, j] > upper_limit\n info_upper_filter = upper_filter.sum()\n df.loc[list(upper_filter), j] = replace_with\n total_count.append(info_upper_filter + info_lower_filter)\n if verbose == True:\n if info_upper_filter + info_lower_filter > 0 and count < 4:\n print(\n f'eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}'\n )\n else:\n pass\n count += 1\n elif verbose == True:\n print(f'{i, j} is not of numeric type, values were not replaced !')\n else:\n pass\n if verbose == True:\n if len(total_count) > 3 and pd.Series(total_count).sum() > 0:\n print(\n f\"\"\". and {len(total_count) - 3} other columns had in total {pd.Series(total_count).sum()} replaced values \n\"\"\"\n )\n if pd.Series(total_count).sum() == 0:\n print('No values were replaced in requested columns....')\n else:\n pass\n return df.copy()\n\n\ndef drop_nan(df, method='any', row=True, verbose=True):\n \"\"\"\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n \"\"\"\n assert type(df) == pd.DataFrame, 'incorrect df dtype'\n df = df.copy()\n if verbose == True:\n print(df.shape)\n else:\n pass\n if row == True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n if method == None:\n pass\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis)\n elif isinstance(method, int):\n tr = method\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx] * method))\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n else:\n pass\n if verbose == True:\n print(df.shape)\n else:\n pass\n return df\n\n\ndef drop_columns(*, df, columns_to_drop, verbose=True):\n \"\"\"\n Small function to quickly remove columns from, \n by column names stored in the list\n - created to give info on removed columns and whether I am chnaging df in proper way,\n - the function allows for column name duplicates, \n \"\"\"\n assert type(df\n ) == pd.DataFrame, 'please provide df in pandas dataframe format'\n df = df.copy()\n columns_to_drop = list(pd.Series(columns_to_drop).unique())\n if verbose == True:\n print(f'Removing {len(columns_to_drop)} columns from df')\n else:\n pass\n for i, j in enumerate(columns_to_drop):\n try:\n df.drop(columns=[j], axis=1, inplace=True)\n if verbose == True:\n print(f'{i} removing: {j}, ==> new df.shape: {df.shape}')\n else:\n pass\n except:\n if verbose == True:\n print(\n f'{i} .... column: {j}, was not found in df, check if name is correct....'\n )\n else:\n pass\n return df\n",
"step-5": "# ********************************************************************************** #\n# #\n# Project: Data Frame Explorer # \n# Author: Pawel Rosikiewicz #\n# Contact: prosikiewicz(a)gmail.com #\n# #\n# License: MIT License #\n# Copyright (C) 2021.01.30 Pawel Rosikiewicz #\n# #\n# Permission is hereby granted, free of charge, to any person obtaining a copy #\n# of this software and associated documentation files (the \"Software\"), to deal #\n# in the Software without restriction, including without limitation the rights #\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #\n# copies of the Software, and to permit persons to whom the Software is #\n# furnished to do so, subject to the following conditions: #\n# # \n# The above copyright notice and this permission notice shall be included in all #\n# copies or substantial portions of the Software. #\n# #\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #\n# SOFTWARE. #\n# #\n# ********************************************************************************** #\n\n\n# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nimport pandas as pd\nimport random\nimport glob\nimport re\nimport os\nimport seaborn as sns\n\nfrom IPython.display import display\nfrom pandas.api.types import is_numeric_dtype\nfrom pandas.api.types import is_string_dtype\n\n\n\n\n\n\n# Function, ............................................................................\ndef find_and_display_patter_in_series(*, series, pattern):\n \"I used that function when i don't remeber full name of a given column\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n\n# Function, ...........................................................................................\ndef load_csv(*, path, filename, sep=\"\\t\", verbose=True):\n \"\"\" \n Loads csv into pandas df, based on pandas.read_scv(), \n Returns error, if file or directoy not found\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * path full path to directory\n * csv_name. full csv file name\n * separator \"\\t\", by default\n * display_head bool, True, by default, display df.head(), \n irrespectively when the futions was called. \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame by Pandas\n\n \"\"\"\n \n os.chdir(path)\n if len(glob.glob(filename))==1: \n df = pd.read_csv(filename, sep=sep, low_memory=False)\n \n # display example,\n if verbose==True:\n display(df.head(3))\n print(df.shape)\n else:\n pass\n \n # return,\n return df\n \n else:\n if verbose==True:\n print(f\"\"\"ERROR :csv file {filename}, was not found in: \\n {path}\"\"\")\n else:\n pass\n\n\n \n \n \n \n# Function, ............................................................................\ndef find_patter_in_series(*, s, pat, tolist=True):\n '''\n I used that function when i don't remeber full name of a given column\n '''\n res = s.loc[s.str.contains(pat)]\n \n if tolist==True:\n return res.values.tolist()\n else:\n return res \n \n \n \n \n\n \n# Function, ........................................................................................... \ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n '''\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n '''\n assert type(data)==pd.DataFrame, \"please provide data in pandas dataframe format\"\n \n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else: \n pass\n \n for pat in pattern_list: \n # find column names using provided patterns or their full names, \n columns_with_potential_datetime_obj = list(find_and_display_patter_in_series(series=pd.Series(data.columns), pattern=pat))\n \n # replace \n for i in columns_with_potential_datetime_obj:\n # keep example of old cell \n before_formatting = str(data.loc[0, i])\n \n # convert to one format\n if unixtime==True:\n s = pd.to_datetime(data.loc[:, i], errors=\"coerce\", unit='s').copy()#,format cannot be used with unit=\"s\", but it will be the same\n data.loc[:, i] = s\n if timezone!=None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n \n else: \n s = pd.to_datetime(data.loc[:, i], errors=\"coerce\",format=dt_format).copy()\n data.loc[:, i] = s\n if timezone!=None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n \n # info\n if verbose==True:\n print(f\"date time formatted in: {i}\") \n print(f\" - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce\")\n print(f\" - Example: {before_formatting} -->> {str(data.loc[0, i])}\", end=\"\\n\")\n else:\n pass\n\n return data \n \n \n \n \n \n \n \n# Function, ...........................................................................................\ndef replace_text(*,df ,pat=\"\", colnames=\"all\", fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n \n # for older version, \n searched_pattern = pat\n col_names = colnames\n \n # check col_names with values to replace, \n if col_names==\"all\": \n sel_col_names = list(df.columns)\n else: \n sel_col_names = col_names \n\n # display message header, \n if verbose==True:\n print(f\"\"\"\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n\"\"\") \n \n if verbose==False:\n pass\n\n # exchnage searched pattern in each column separately, \n for i, col_name in enumerate(sel_col_names):\n \n # .. test if you really have string values in that column, otherwise it masy be float for all NaN in a column, and no action will be taken \n if is_string_dtype(df[col_name]):\n \n try:\n # .... find postions with a given pattern and select three examples to display for the user, \n positions_to_replace = df[col_name].str.contains(searched_pattern, na=False).values# arr\n examples_to_display = [str(x) for x in list(df.loc[list(positions_to_replace), col_name].str[0:20].values.tolist()[0:3])]\n\n # .... replace postions, and find examples of unchnaged postions,\n df.loc[list(positions_to_replace), col_name] = [fillna]*positions_to_replace.sum() \n examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace==False), col_name].str[0:20].values.tolist()[0:3])]\n\n # .... diplay info,\n if verbose==True:\n perc_of_replaced_pos_in_col = \"\".join([str(positions_to_replace.sum()/df.shape[0]*100),\"%\"])\n print(f\"{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}\")\n print(f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\", end=\"\\n\")\n print(f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\", end=\"\\n\\n\")\n # the second print returns three first examples of exchanged values, just to see what i did,\n else:\n pass\n \n except:\n if verbose==True:\n print(f\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \\n\") \n else:\n pass\n \n else:\n if verbose==True:\n print(f\"{i} - {col_name} - - is not of string type, Values were not replaced! \\n\") \n else:\n pass\n \n return df.copy()\n\n\n \n \n \n\n\n\n# Function, ...........................................................................................\ndef replace_numeric_values(*, df, colnames=\"all\", lower_limit=\"none\", upper_limit=\"none\", equal=False, replace_with=np.nan, verbose=True):\n \"\"\" \n\n Replace numerical values that are outside of range of a values \n prediced with a theoretical limits of a given variable, \n eg less then 0 in weight of a product, \n Provide examples and numbers of replaced instances\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df : Pandas DataFrame\n * cols_in_df : list, exact colnames of selected or all columns in df\n * lower_limit : int,float,\"none\", if \"none\" no action is taken\n * upper_limit : int,float,\"none\", if \"none\" no action is taken\n * replace_with : str, np.nan, int, float\n * equal : bool, if True, >= and <= values then limits will be replaced,\n if False (default), > and < values then limits will be replaced,\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\" \n\n \n cols_names = colnames\n \n # .. check provided col_names,\n if cols_names==\"all\": \n cols = list(df.columns)\n else: \n cols = cols_names \n\n # .. info, header, \n if verbose==True:\n print(f\"\"\"\\n{\"\".join([\"-\"]*80)} \\n Replacing Numerical Values in {len(cols)} columns\"\"\") \n print(f\" lower filter={lower_limit}, upper filter ={upper_limit}\")\n if equal==True:\n print(f\" Caution, equal=True, ie. values >= and <= then requested limits will be replaced\")\n print(f'{\"\".join([\"-\"]*80)}\\n') \n \n if verbose==False:\n pass\n \n \n # .. intelligent info,\n total_count=[]\n\n # .. count, to limit the number of displayed messages,\n count = 0\n\n # .. replace values and collect examples, \n for i, j in enumerate(cols):\n\n # ..... assume no values were replaced, so the messages work later, \n info_lower_filter = 0\n info_upper_filter = 0 \n \n # ..... test if the column is of the numeric type:\n # from pandas.api.types import is_numeric_dtype\n if is_numeric_dtype(df[j]):\n \n \n # * replace values < or <= lower limit,\n # - ----------------------------------\n if lower_limit!=\"none\": \n if equal == True:\n lower_filter = df.loc[:,j]<=lower_limit\n if equal == False:\n lower_filter = df.loc[:,j]<lower_limit\n \n # info,\n info_lower_filter=lower_filter.sum()\n df.loc[list(lower_filter),j]=replace_with\n \n \n # * replace values > or >= upper limit,\n # - ----------------------------------\n if upper_limit!=\"none\": \n if equal == True:\n upper_filter = df.loc[:,j]>=upper_limit\n if equal == False:\n upper_filter = df.loc[:,j]>upper_limit\n \n # info,\n info_upper_filter=upper_filter.sum()\n df.loc[list(upper_filter),j]=replace_with \n \n # * find how many values were replaced, and add that to the total_count list \n total_count.append(info_upper_filter+info_lower_filter)\n \n # * display examples for 3 first columns with replaced values,\n if verbose==True:\n if info_upper_filter+info_lower_filter>0 and count <4:\n print(f\"eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}\")\n else:\n pass\n\n # * add 1 to count, to limit the number of displayed examples,\n count += 1 \n \n else:\n if verbose==True:\n print(f\"{i, j} is not of numeric type, values were not replaced !\")\n else:\n pass\n \n # .. additional message, if more then 2 columns had replaced values, \n if verbose==True:\n if len(total_count)>3 and pd.Series(total_count).sum()>0:\n print(f\". and {len(total_count)-3} other columns had in total {pd.Series(total_count).sum()} replaced values \\n\")\n\n # .. message in case no values vere replaced at all, \n if pd.Series(total_count).sum()==0:\n print(\"No values were replaced in requested columns....\")\n \n else:\n pass\n \n # .. return, \n return df.copy()\n \n \n \n \n\n \n \n# function, ...................................................\ndef drop_nan(df, method=\"any\", row=True, verbose=True): \n '''\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n '''\n \n assert type(df)==pd.DataFrame, \"incorrect df dtype\"\n df = df.copy()\n \n if verbose==True:\n print(df.shape)\n else:\n pass\n \n # set funtion for rows or columns, \n if row==True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n \n # use threshold or \"all\", or None for do nothing, \n if method==None:\n pass\n\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis) # removes rows with NaN in all columns \n\n elif isinstance(method, int):\n tr = method\n if tr==0:\n pass\n else:\n if tr>=df.shape[shapeidx]:\n tr=df.shape[shapeidx]\n else:\n pass \n df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value\n\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx]*(method)))\n if tr==0:\n pass\n else:\n if tr>=df.shape[shapeidx]:\n tr=df.shape[shapeidx]\n else:\n pass \n df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value\n else:\n pass\n \n # info and return\n if verbose==True:\n print(df.shape)\n else:\n pass\n return df\n \n \n \n \n \n \n \n \n# Function, ...........................................................................................\ndef drop_columns(*, df, columns_to_drop, verbose=True):\n \"\"\"\n Small function to quickly remove columns from, \n by column names stored in the list\n - created to give info on removed columns and whether I am chnaging df in proper way,\n - the function allows for column name duplicates, \n \"\"\"\n \n assert type(df)==pd.DataFrame, \"please provide df in pandas dataframe format\"\n df = df.copy()\n \n # find unique values in a list, just in case I made the mistake, \n columns_to_drop = list(pd.Series(columns_to_drop).unique())\n\n # .. info, header, \n if verbose==True:\n print(f\"\"\"Removing {len(columns_to_drop)} columns from df\"\"\") \n else:\n pass\n\n \n # remove columns one by one, \n for i,j in enumerate(columns_to_drop):\n try:\n df.drop(columns=[j], axis=1, inplace=True)\n if verbose==True:\n print(f\"{i} removing: {j}, ==> new df.shape: {df.shape}\")\n else:\n pass\n \n except:\n if verbose==True:\n print(f\"{i} .... column: {j}, was not found in df, check if name is correct....\")\n else:\n pass\n \n return df\n\n",
"step-ids": [
4,
5,
7,
8,
10
]
}
|
[
4,
5,
7,
8,
10
] |
<|reserved_special_token_0|>
@juju.requires_login
def list_models(user='user-admin'):
""" Lists Juju Models
Arguments:
user: Name of user to list models for.
Returns:
Dictionary of known Juju Models (default: user-admin)
"""
models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':
user})
return models['UserModels']
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@juju.requires_login
def list_models(user='user-admin'):
""" Lists Juju Models
Arguments:
user: Name of user to list models for.
Returns:
Dictionary of known Juju Models (default: user-admin)
"""
models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':
user})
return models['UserModels']
@juju.requires_login
def model_info(model):
""" Returns information on select model
Arguments:
model: name of model to inspect
Returns:
Dictionary of model attributes
"""
return juju.CLIENT.Client(request='ModelInfo', params={'Name': model})
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@juju.requires_login
def list_models(user='user-admin'):
""" Lists Juju Models
Arguments:
user: Name of user to list models for.
Returns:
Dictionary of known Juju Models (default: user-admin)
"""
models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':
user})
return models['UserModels']
@juju.requires_login
def model_info(model):
""" Returns information on select model
Arguments:
model: name of model to inspect
Returns:
Dictionary of model attributes
"""
return juju.CLIENT.Client(request='ModelInfo', params={'Name': model})
@juju.requires_login
def model_status():
""" Returns the FullStatus output of a model
Returns:
Dictionary of model status
"""
return juju.CLIENT.Client(request='FullStatus')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from conjureup import juju
@juju.requires_login
def list_models(user='user-admin'):
""" Lists Juju Models
Arguments:
user: Name of user to list models for.
Returns:
Dictionary of known Juju Models (default: user-admin)
"""
models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':
user})
return models['UserModels']
@juju.requires_login
def model_info(model):
""" Returns information on select model
Arguments:
model: name of model to inspect
Returns:
Dictionary of model attributes
"""
return juju.CLIENT.Client(request='ModelInfo', params={'Name': model})
@juju.requires_login
def model_status():
""" Returns the FullStatus output of a model
Returns:
Dictionary of model status
"""
return juju.CLIENT.Client(request='FullStatus')
<|reserved_special_token_1|>
""" Interfaces to Juju API ModelManager """
from conjureup import juju
@juju.requires_login
def list_models(user='user-admin'):
""" Lists Juju Models
Arguments:
user: Name of user to list models for.
Returns:
Dictionary of known Juju Models (default: user-admin)
"""
models = juju.CLIENT.ModelManager(request="ListModels",
params={'Tag': user})
return models['UserModels']
@juju.requires_login
def model_info(model):
""" Returns information on select model
Arguments:
model: name of model to inspect
Returns:
Dictionary of model attributes
"""
return juju.CLIENT.Client(request="ModelInfo",
params={"Name": model})
@juju.requires_login
def model_status():
""" Returns the FullStatus output of a model
Returns:
Dictionary of model status
"""
return juju.CLIENT.Client(request="FullStatus")
|
flexible
|
{
"blob_id": "11045cffc6d47902be7236e1d684422317f2c5f9",
"index": 1444,
"step-1": "<mask token>\n\n\n@juju.requires_login\ndef list_models(user='user-admin'):\n \"\"\" Lists Juju Models\n\n Arguments:\n user: Name of user to list models for.\n\n Returns:\n Dictionary of known Juju Models (default: user-admin)\n \"\"\"\n models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':\n user})\n return models['UserModels']\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@juju.requires_login\ndef list_models(user='user-admin'):\n \"\"\" Lists Juju Models\n\n Arguments:\n user: Name of user to list models for.\n\n Returns:\n Dictionary of known Juju Models (default: user-admin)\n \"\"\"\n models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':\n user})\n return models['UserModels']\n\n\n@juju.requires_login\ndef model_info(model):\n \"\"\" Returns information on select model\n\n Arguments:\n model: name of model to inspect\n\n Returns:\n Dictionary of model attributes\n \"\"\"\n return juju.CLIENT.Client(request='ModelInfo', params={'Name': model})\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\n@juju.requires_login\ndef list_models(user='user-admin'):\n \"\"\" Lists Juju Models\n\n Arguments:\n user: Name of user to list models for.\n\n Returns:\n Dictionary of known Juju Models (default: user-admin)\n \"\"\"\n models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':\n user})\n return models['UserModels']\n\n\n@juju.requires_login\ndef model_info(model):\n \"\"\" Returns information on select model\n\n Arguments:\n model: name of model to inspect\n\n Returns:\n Dictionary of model attributes\n \"\"\"\n return juju.CLIENT.Client(request='ModelInfo', params={'Name': model})\n\n\n@juju.requires_login\ndef model_status():\n \"\"\" Returns the FullStatus output of a model\n\n Returns:\n Dictionary of model status\n \"\"\"\n return juju.CLIENT.Client(request='FullStatus')\n",
"step-4": "<mask token>\nfrom conjureup import juju\n\n\n@juju.requires_login\ndef list_models(user='user-admin'):\n \"\"\" Lists Juju Models\n\n Arguments:\n user: Name of user to list models for.\n\n Returns:\n Dictionary of known Juju Models (default: user-admin)\n \"\"\"\n models = juju.CLIENT.ModelManager(request='ListModels', params={'Tag':\n user})\n return models['UserModels']\n\n\n@juju.requires_login\ndef model_info(model):\n \"\"\" Returns information on select model\n\n Arguments:\n model: name of model to inspect\n\n Returns:\n Dictionary of model attributes\n \"\"\"\n return juju.CLIENT.Client(request='ModelInfo', params={'Name': model})\n\n\n@juju.requires_login\ndef model_status():\n \"\"\" Returns the FullStatus output of a model\n\n Returns:\n Dictionary of model status\n \"\"\"\n return juju.CLIENT.Client(request='FullStatus')\n",
"step-5": "\"\"\" Interfaces to Juju API ModelManager \"\"\"\n\nfrom conjureup import juju\n\n\n@juju.requires_login\ndef list_models(user='user-admin'):\n \"\"\" Lists Juju Models\n\n Arguments:\n user: Name of user to list models for.\n\n Returns:\n Dictionary of known Juju Models (default: user-admin)\n \"\"\"\n models = juju.CLIENT.ModelManager(request=\"ListModels\",\n params={'Tag': user})\n return models['UserModels']\n\n\n@juju.requires_login\ndef model_info(model):\n \"\"\" Returns information on select model\n\n Arguments:\n model: name of model to inspect\n\n Returns:\n Dictionary of model attributes\n \"\"\"\n return juju.CLIENT.Client(request=\"ModelInfo\",\n params={\"Name\": model})\n\n\n@juju.requires_login\ndef model_status():\n \"\"\" Returns the FullStatus output of a model\n\n Returns:\n Dictionary of model status\n \"\"\"\n return juju.CLIENT.Client(request=\"FullStatus\")\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#Get roll numbers, name & marks of the students of a class(get from user) and store these details in a file- marks.txt
count = int(input("How many students are there in class? "))
fileObj = open('marks.txt',"w")
for i in range(count):
print("Enter details for student",(i+1),"below:")
rollNo = int(input("Rollno: "))
name = input("Name: ")
marks = float(input("Marks: "))
records = str(rollNo) + "," + name + "," + str(marks) + '\n'
fileObj.write(records)
fileObj.close()
|
normal
|
{
"blob_id": "74cb06ffa41748af431b46c9ff98eb91771a5015",
"index": 537,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(count):\n print('Enter details for student', i + 1, 'below:')\n rollNo = int(input('Rollno: '))\n name = input('Name: ')\n marks = float(input('Marks: '))\n records = str(rollNo) + ',' + name + ',' + str(marks) + '\\n'\n fileObj.write(records)\nfileObj.close()\n",
"step-3": "count = int(input('How many students are there in class? '))\nfileObj = open('marks.txt', 'w')\nfor i in range(count):\n print('Enter details for student', i + 1, 'below:')\n rollNo = int(input('Rollno: '))\n name = input('Name: ')\n marks = float(input('Marks: '))\n records = str(rollNo) + ',' + name + ',' + str(marks) + '\\n'\n fileObj.write(records)\nfileObj.close()\n",
"step-4": "#Get roll numbers, name & marks of the students of a class(get from user) and store these details in a file- marks.txt\n\ncount = int(input(\"How many students are there in class? \"))\nfileObj = open('marks.txt',\"w\")\n\nfor i in range(count):\n print(\"Enter details for student\",(i+1),\"below:\")\n rollNo = int(input(\"Rollno: \"))\n name = input(\"Name: \")\n marks = float(input(\"Marks: \"))\n records = str(rollNo) + \",\" + name + \",\" + str(marks) + '\\n'\n fileObj.write(records)\nfileObj.close()",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def jwt_error_handler(error):
code = 401
messages = list(getattr(error, 'args', []))
return mk_errors(code, messages)
<|reserved_special_token_0|>
def validation_error_handler(error):
code = getattr(error, 'status_code', 500)
messages = getattr(error, 'messages', [])
return mk_errors(code, messages)
def generic_error_handler(error):
code = getattr(error, 'status_code', 500)
if config.debug:
messages = [str(error)]
else:
messages = ['something went wrong!']
return mk_errors(code, messages)
def error_handler(error):
try:
if isinstance(error, JWTExtendedException):
return jwt_error_handler(error)
elif isinstance(error, HTTPException):
return http_error_handler(error)
elif isinstance(error, ValidationError):
return validation_error_handler(error)
else:
return generic_error_handler(error)
except:
return mk_errors(500, 'something went wrong!')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def jwt_error_handler(error):
code = 401
messages = list(getattr(error, 'args', []))
return mk_errors(code, messages)
<|reserved_special_token_0|>
def validation_error_handler(error):
code = getattr(error, 'status_code', 500)
messages = getattr(error, 'messages', [])
return mk_errors(code, messages)
def generic_error_handler(error):
code = getattr(error, 'status_code', 500)
if config.debug:
messages = [str(error)]
else:
messages = ['something went wrong!']
return mk_errors(code, messages)
def error_handler(error):
try:
if isinstance(error, JWTExtendedException):
return jwt_error_handler(error)
elif isinstance(error, HTTPException):
return http_error_handler(error)
elif isinstance(error, ValidationError):
return validation_error_handler(error)
else:
return generic_error_handler(error)
except:
return mk_errors(500, 'something went wrong!')
def register_handlers(app):
app.errorhandler(Exception)(error_handler)
app.errorhandler(HTTPException)(error_handler)
app.handle_user_exception = error_handler
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def jwt_error_handler(error):
code = 401
messages = list(getattr(error, 'args', []))
return mk_errors(code, messages)
def http_error_handler(error):
resp = error.response
if resp is None:
code = error.code
messages = [error.description]
else:
code = getattr(resp, 'status_code', 500)
json = resp.get_json()
if 'errors' in json and json['errors']:
messages = [e['message'] for e in json['errors'] if 'message' in e]
else:
messages = [str(resp.status)]
return mk_errors(code, messages)
def validation_error_handler(error):
code = getattr(error, 'status_code', 500)
messages = getattr(error, 'messages', [])
return mk_errors(code, messages)
def generic_error_handler(error):
code = getattr(error, 'status_code', 500)
if config.debug:
messages = [str(error)]
else:
messages = ['something went wrong!']
return mk_errors(code, messages)
def error_handler(error):
try:
if isinstance(error, JWTExtendedException):
return jwt_error_handler(error)
elif isinstance(error, HTTPException):
return http_error_handler(error)
elif isinstance(error, ValidationError):
return validation_error_handler(error)
else:
return generic_error_handler(error)
except:
return mk_errors(500, 'something went wrong!')
def register_handlers(app):
app.errorhandler(Exception)(error_handler)
app.errorhandler(HTTPException)(error_handler)
app.handle_user_exception = error_handler
<|reserved_special_token_1|>
from marshmallow import ValidationError
from werkzeug.exceptions import HTTPException
from flask_jwt_extended.exceptions import JWTExtendedException
from memedata.util import mk_errors
from memedata import config
def jwt_error_handler(error):
code = 401
messages = list(getattr(error, 'args', []))
return mk_errors(code, messages)
def http_error_handler(error):
resp = error.response
if resp is None:
code = error.code
messages = [error.description]
else:
code = getattr(resp, 'status_code', 500)
json = resp.get_json()
if 'errors' in json and json['errors']:
messages = [e['message'] for e in json['errors'] if 'message' in e]
else:
messages = [str(resp.status)]
return mk_errors(code, messages)
def validation_error_handler(error):
code = getattr(error, 'status_code', 500)
messages = getattr(error, 'messages', [])
return mk_errors(code, messages)
def generic_error_handler(error):
code = getattr(error, 'status_code', 500)
if config.debug:
messages = [str(error)]
else:
messages = ['something went wrong!']
return mk_errors(code, messages)
def error_handler(error):
try:
if isinstance(error, JWTExtendedException):
return jwt_error_handler(error)
elif isinstance(error, HTTPException):
return http_error_handler(error)
elif isinstance(error, ValidationError):
return validation_error_handler(error)
else:
return generic_error_handler(error)
except:
return mk_errors(500, 'something went wrong!')
def register_handlers(app):
app.errorhandler(Exception)(error_handler)
app.errorhandler(HTTPException)(error_handler)
app.handle_user_exception = error_handler
|
flexible
|
{
"blob_id": "e1da3255668999c3b77aa8c9332b197a9203478e",
"index": 8992,
"step-1": "<mask token>\n\n\ndef jwt_error_handler(error):\n code = 401\n messages = list(getattr(error, 'args', []))\n return mk_errors(code, messages)\n\n\n<mask token>\n\n\ndef validation_error_handler(error):\n code = getattr(error, 'status_code', 500)\n messages = getattr(error, 'messages', [])\n return mk_errors(code, messages)\n\n\ndef generic_error_handler(error):\n code = getattr(error, 'status_code', 500)\n if config.debug:\n messages = [str(error)]\n else:\n messages = ['something went wrong!']\n return mk_errors(code, messages)\n\n\ndef error_handler(error):\n try:\n if isinstance(error, JWTExtendedException):\n return jwt_error_handler(error)\n elif isinstance(error, HTTPException):\n return http_error_handler(error)\n elif isinstance(error, ValidationError):\n return validation_error_handler(error)\n else:\n return generic_error_handler(error)\n except:\n return mk_errors(500, 'something went wrong!')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef jwt_error_handler(error):\n code = 401\n messages = list(getattr(error, 'args', []))\n return mk_errors(code, messages)\n\n\n<mask token>\n\n\ndef validation_error_handler(error):\n code = getattr(error, 'status_code', 500)\n messages = getattr(error, 'messages', [])\n return mk_errors(code, messages)\n\n\ndef generic_error_handler(error):\n code = getattr(error, 'status_code', 500)\n if config.debug:\n messages = [str(error)]\n else:\n messages = ['something went wrong!']\n return mk_errors(code, messages)\n\n\ndef error_handler(error):\n try:\n if isinstance(error, JWTExtendedException):\n return jwt_error_handler(error)\n elif isinstance(error, HTTPException):\n return http_error_handler(error)\n elif isinstance(error, ValidationError):\n return validation_error_handler(error)\n else:\n return generic_error_handler(error)\n except:\n return mk_errors(500, 'something went wrong!')\n\n\ndef register_handlers(app):\n app.errorhandler(Exception)(error_handler)\n app.errorhandler(HTTPException)(error_handler)\n app.handle_user_exception = error_handler\n",
"step-3": "<mask token>\n\n\ndef jwt_error_handler(error):\n code = 401\n messages = list(getattr(error, 'args', []))\n return mk_errors(code, messages)\n\n\ndef http_error_handler(error):\n resp = error.response\n if resp is None:\n code = error.code\n messages = [error.description]\n else:\n code = getattr(resp, 'status_code', 500)\n json = resp.get_json()\n if 'errors' in json and json['errors']:\n messages = [e['message'] for e in json['errors'] if 'message' in e]\n else:\n messages = [str(resp.status)]\n return mk_errors(code, messages)\n\n\ndef validation_error_handler(error):\n code = getattr(error, 'status_code', 500)\n messages = getattr(error, 'messages', [])\n return mk_errors(code, messages)\n\n\ndef generic_error_handler(error):\n code = getattr(error, 'status_code', 500)\n if config.debug:\n messages = [str(error)]\n else:\n messages = ['something went wrong!']\n return mk_errors(code, messages)\n\n\ndef error_handler(error):\n try:\n if isinstance(error, JWTExtendedException):\n return jwt_error_handler(error)\n elif isinstance(error, HTTPException):\n return http_error_handler(error)\n elif isinstance(error, ValidationError):\n return validation_error_handler(error)\n else:\n return generic_error_handler(error)\n except:\n return mk_errors(500, 'something went wrong!')\n\n\ndef register_handlers(app):\n app.errorhandler(Exception)(error_handler)\n app.errorhandler(HTTPException)(error_handler)\n app.handle_user_exception = error_handler\n",
"step-4": "from marshmallow import ValidationError\nfrom werkzeug.exceptions import HTTPException\nfrom flask_jwt_extended.exceptions import JWTExtendedException\nfrom memedata.util import mk_errors\nfrom memedata import config\n\n\ndef jwt_error_handler(error):\n code = 401\n messages = list(getattr(error, 'args', []))\n return mk_errors(code, messages)\n\n\ndef http_error_handler(error):\n resp = error.response\n if resp is None:\n code = error.code\n messages = [error.description]\n else:\n code = getattr(resp, 'status_code', 500)\n json = resp.get_json()\n if 'errors' in json and json['errors']:\n messages = [e['message'] for e in json['errors'] if 'message' in e]\n else:\n messages = [str(resp.status)]\n return mk_errors(code, messages)\n\n\ndef validation_error_handler(error):\n code = getattr(error, 'status_code', 500)\n messages = getattr(error, 'messages', [])\n return mk_errors(code, messages)\n\n\ndef generic_error_handler(error):\n code = getattr(error, 'status_code', 500)\n if config.debug:\n messages = [str(error)]\n else:\n messages = ['something went wrong!']\n return mk_errors(code, messages)\n\n\ndef error_handler(error):\n try:\n if isinstance(error, JWTExtendedException):\n return jwt_error_handler(error)\n elif isinstance(error, HTTPException):\n return http_error_handler(error)\n elif isinstance(error, ValidationError):\n return validation_error_handler(error)\n else:\n return generic_error_handler(error)\n except:\n return mk_errors(500, 'something went wrong!')\n\n\ndef register_handlers(app):\n app.errorhandler(Exception)(error_handler)\n app.errorhandler(HTTPException)(error_handler)\n app.handle_user_exception = error_handler\n",
"step-5": null,
"step-ids": [
4,
5,
6,
7
]
}
|
[
4,
5,
6,
7
] |
import graphene
import f1hub.drivers.schema
import f1hub.results.schema
import f1hub.constructors.schema
import f1hub.races.schema
import f1hub.status.schema
import f1hub.circuits.schema
import f1hub.constructorresults.schema
import f1hub.constructorstandings.schema
import f1hub.driverstandings.schema
import f1hub.laptimes.schema
import f1hub.pitstops.schema
import f1hub.qualifying.schema
import f1hub.seasons.schema
class Query(f1hub.drivers.schema.Query, f1hub.results.schema.Query, f1hub.constructors.schema.Query, f1hub.races.schema.Query, f1hub.status.schema.Query, f1hub.circuits.schema.Query,\
f1hub.constructorresults.schema.Query, f1hub.constructorstandings.schema.Query, f1hub.driverstandings.schema.Query, f1hub.laptimes.schema.Query, f1hub.pitstops.schema.Query,\
f1hub.qualifying.schema.Query, f1hub.seasons.schema.Query, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query)
|
normal
|
{
"blob_id": "05e4bcc7323b908a7b45d766ada463ce172e25c4",
"index": 378,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Query(f1hub.drivers.schema.Query, f1hub.results.schema.Query, f1hub.\n constructors.schema.Query, f1hub.races.schema.Query, f1hub.status.\n schema.Query, f1hub.circuits.schema.Query, f1hub.constructorresults.\n schema.Query, f1hub.constructorstandings.schema.Query, f1hub.\n driverstandings.schema.Query, f1hub.laptimes.schema.Query, f1hub.\n pitstops.schema.Query, f1hub.qualifying.schema.Query, f1hub.seasons.\n schema.Query, graphene.ObjectType):\n pass\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Query(f1hub.drivers.schema.Query, f1hub.results.schema.Query, f1hub.\n constructors.schema.Query, f1hub.races.schema.Query, f1hub.status.\n schema.Query, f1hub.circuits.schema.Query, f1hub.constructorresults.\n schema.Query, f1hub.constructorstandings.schema.Query, f1hub.\n driverstandings.schema.Query, f1hub.laptimes.schema.Query, f1hub.\n pitstops.schema.Query, f1hub.qualifying.schema.Query, f1hub.seasons.\n schema.Query, graphene.ObjectType):\n pass\n\n\nschema = graphene.Schema(query=Query)\n",
"step-4": "import graphene\nimport f1hub.drivers.schema\nimport f1hub.results.schema\nimport f1hub.constructors.schema\nimport f1hub.races.schema\nimport f1hub.status.schema\nimport f1hub.circuits.schema\nimport f1hub.constructorresults.schema\nimport f1hub.constructorstandings.schema\nimport f1hub.driverstandings.schema\nimport f1hub.laptimes.schema\nimport f1hub.pitstops.schema\nimport f1hub.qualifying.schema\nimport f1hub.seasons.schema\n\n\nclass Query(f1hub.drivers.schema.Query, f1hub.results.schema.Query, f1hub.\n constructors.schema.Query, f1hub.races.schema.Query, f1hub.status.\n schema.Query, f1hub.circuits.schema.Query, f1hub.constructorresults.\n schema.Query, f1hub.constructorstandings.schema.Query, f1hub.\n driverstandings.schema.Query, f1hub.laptimes.schema.Query, f1hub.\n pitstops.schema.Query, f1hub.qualifying.schema.Query, f1hub.seasons.\n schema.Query, graphene.ObjectType):\n pass\n\n\nschema = graphene.Schema(query=Query)\n",
"step-5": "import graphene\n\nimport f1hub.drivers.schema\nimport f1hub.results.schema\nimport f1hub.constructors.schema\nimport f1hub.races.schema\nimport f1hub.status.schema\nimport f1hub.circuits.schema\nimport f1hub.constructorresults.schema\nimport f1hub.constructorstandings.schema\nimport f1hub.driverstandings.schema\nimport f1hub.laptimes.schema\nimport f1hub.pitstops.schema\nimport f1hub.qualifying.schema\nimport f1hub.seasons.schema\n\n\nclass Query(f1hub.drivers.schema.Query, f1hub.results.schema.Query, f1hub.constructors.schema.Query, f1hub.races.schema.Query, f1hub.status.schema.Query, f1hub.circuits.schema.Query,\\\n f1hub.constructorresults.schema.Query, f1hub.constructorstandings.schema.Query, f1hub.driverstandings.schema.Query, f1hub.laptimes.schema.Query, f1hub.pitstops.schema.Query,\\\n f1hub.qualifying.schema.Query, f1hub.seasons.schema.Query, graphene.ObjectType):\n pass\n\n\nschema = graphene.Schema(query=Query)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class RandomTest:
def __init__(self, seed=42, deterministic=False):
self.seed = seed
self.deterministic = deterministic
@fixed_random
def test_function(self, i):
return [random.randint(0, 10) for x in range(10)]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def fixed_random(func):
"""Create the data"""
def _func(self, i):
state = random.getstate()
if self.deterministic or self.seed is not None:
random.seed(self.seed + i)
results = func(self, i)
random.setstate(state)
else:
results = func(self, i)
return results
return _func
class RandomTest:
def __init__(self, seed=42, deterministic=False):
self.seed = seed
self.deterministic = deterministic
@fixed_random
def test_function(self, i):
return [random.randint(0, 10) for x in range(10)]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def fixed_random(func):
"""Create the data"""
def _func(self, i):
state = random.getstate()
if self.deterministic or self.seed is not None:
random.seed(self.seed + i)
results = func(self, i)
random.setstate(state)
else:
results = func(self, i)
return results
return _func
class RandomTest:
def __init__(self, seed=42, deterministic=False):
self.seed = seed
self.deterministic = deterministic
@fixed_random
def test_function(self, i):
return [random.randint(0, 10) for x in range(10)]
rt = RandomTest(0)
print(rt.test_function(0))
print(rt.test_function(0))
rt.seed = 1
print(rt.test_function(0))
print(rt.test_function(0))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import random
def fixed_random(func):
"""Create the data"""
def _func(self, i):
state = random.getstate()
if self.deterministic or self.seed is not None:
random.seed(self.seed + i)
results = func(self, i)
random.setstate(state)
else:
results = func(self, i)
return results
return _func
class RandomTest:
def __init__(self, seed=42, deterministic=False):
self.seed = seed
self.deterministic = deterministic
@fixed_random
def test_function(self, i):
return [random.randint(0, 10) for x in range(10)]
rt = RandomTest(0)
print(rt.test_function(0))
print(rt.test_function(0))
rt.seed = 1
print(rt.test_function(0))
print(rt.test_function(0))
<|reserved_special_token_1|>
#/usr/bin/env python3
"""Demonstrates how to do deterministic task generation using l2l"""
import random
def fixed_random(func):
"""Create the data"""
def _func(self, i):
state = random.getstate()
if self.deterministic or self.seed is not None:
random.seed(self.seed + i)
results = func(self, i)
random.setstate(state)
else:
results = func(self, i)
return results
return _func
class RandomTest:
def __init__(self, seed=42, deterministic=False):
self.seed = seed
self.deterministic = deterministic
@fixed_random
def test_function(self, i):
return [random.randint(0, 10) for x in range(10)]
rt = RandomTest(0)
print(rt.test_function(0))
print(rt.test_function(0))
rt.seed = 1
print(rt.test_function(0))
print(rt.test_function(0))
|
flexible
|
{
"blob_id": "7ee5779625d53ff1e18f73b20ba5849666f89b55",
"index": 2111,
"step-1": "<mask token>\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\nrt = RandomTest(0)\nprint(rt.test_function(0))\nprint(rt.test_function(0))\nrt.seed = 1\nprint(rt.test_function(0))\nprint(rt.test_function(0))\n",
"step-4": "<mask token>\nimport random\n\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\nrt = RandomTest(0)\nprint(rt.test_function(0))\nprint(rt.test_function(0))\nrt.seed = 1\nprint(rt.test_function(0))\nprint(rt.test_function(0))\n",
"step-5": "#/usr/bin/env python3\n\n\"\"\"Demonstrates how to do deterministic task generation using l2l\"\"\"\nimport random\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\nrt = RandomTest(0)\nprint(rt.test_function(0))\nprint(rt.test_function(0))\nrt.seed = 1\nprint(rt.test_function(0))\nprint(rt.test_function(0))\n",
"step-ids": [
3,
4,
6,
7,
8
]
}
|
[
3,
4,
6,
7,
8
] |
<|reserved_special_token_0|>
class Tags(models.Model):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Meta:
ordering = '-created_at',
class Newsletter(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=10000)
image = models.ImageField()
target = models.IntegerField()
frequency = models.CharField(max_length=10, choices=FREQUENCY, default=
'monthly')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
tag = models.ManyToManyField(Tags)
@property
def subscribed(self):
return 10
def __str__(self):
return self.name
class Meta:
ordering = '-created_at',
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Tags(models.Model):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __str__(self):
return self.name
def save(self, *arg, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Tags, self).save(*arg, **kwargs)
class Meta:
ordering = '-created_at',
class Newsletter(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=10000)
image = models.ImageField()
target = models.IntegerField()
frequency = models.CharField(max_length=10, choices=FREQUENCY, default=
'monthly')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
tag = models.ManyToManyField(Tags)
@property
def subscribed(self):
return 10
def __str__(self):
return self.name
class Meta:
ordering = '-created_at',
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Tags(models.Model):
name = models.CharField(max_length=100)
slug = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
def save(self, *arg, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Tags, self).save(*arg, **kwargs)
class Meta:
ordering = '-created_at',
class Newsletter(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=10000)
image = models.ImageField()
target = models.IntegerField()
frequency = models.CharField(max_length=10, choices=FREQUENCY, default=
'monthly')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
tag = models.ManyToManyField(Tags)
@property
def subscribed(self):
return 10
def __str__(self):
return self.name
class Meta:
ordering = '-created_at',
<|reserved_special_token_1|>
from django.utils.text import slugify
from pyexpat import model
from django.db import models
from rest_framework_simplejwt.state import User
FREQUENCY = ('daily', 'Diario'), ('weekly', 'Semanal'), ('monthly', 'Mensual')
class Tags(models.Model):
name = models.CharField(max_length=100)
slug = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
def save(self, *arg, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Tags, self).save(*arg, **kwargs)
class Meta:
ordering = '-created_at',
class Newsletter(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=10000)
image = models.ImageField()
target = models.IntegerField()
frequency = models.CharField(max_length=10, choices=FREQUENCY, default=
'monthly')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
tag = models.ManyToManyField(Tags)
@property
def subscribed(self):
return 10
def __str__(self):
return self.name
class Meta:
ordering = '-created_at',
<|reserved_special_token_1|>
from django.utils.text import slugify
from pyexpat import model
from django.db import models
# Create your models here.
from rest_framework_simplejwt.state import User
FREQUENCY = (
('daily', 'Diario'),
('weekly', 'Semanal'),
('monthly', 'Mensual')
)
class Tags(models.Model):
name = models.CharField(max_length=100)
slug = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
def save(self, *arg, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Tags, self).save(*arg, **kwargs)
class Meta:
ordering = ('-created_at',)
class Newsletter(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=10000)
image = models.ImageField()
target = models.IntegerField()
frequency = models.CharField(max_length=10, choices=FREQUENCY, default='monthly')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
tag = models.ManyToManyField(Tags)
@property
def subscribed(self):
return 10
def __str__(self):
return self.name
class Meta:
ordering = ('-created_at',)
|
flexible
|
{
"blob_id": "71503282e58f60e0936a5236edc094f1da937422",
"index": 6565,
"step-1": "<mask token>\n\n\nclass Tags(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n ordering = '-created_at',\n\n\nclass Newsletter(models.Model):\n name = models.CharField(max_length=200)\n description = models.CharField(max_length=10000)\n image = models.ImageField()\n target = models.IntegerField()\n frequency = models.CharField(max_length=10, choices=FREQUENCY, default=\n 'monthly')\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n tag = models.ManyToManyField(Tags)\n\n @property\n def subscribed(self):\n return 10\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n ordering = '-created_at',\n",
"step-2": "<mask token>\n\n\nclass Tags(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.name\n\n def save(self, *arg, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n super(Tags, self).save(*arg, **kwargs)\n\n\n class Meta:\n ordering = '-created_at',\n\n\nclass Newsletter(models.Model):\n name = models.CharField(max_length=200)\n description = models.CharField(max_length=10000)\n image = models.ImageField()\n target = models.IntegerField()\n frequency = models.CharField(max_length=10, choices=FREQUENCY, default=\n 'monthly')\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n tag = models.ManyToManyField(Tags)\n\n @property\n def subscribed(self):\n return 10\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n ordering = '-created_at',\n",
"step-3": "<mask token>\n\n\nclass Tags(models.Model):\n name = models.CharField(max_length=100)\n slug = models.CharField(max_length=150)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.name\n\n def save(self, *arg, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n super(Tags, self).save(*arg, **kwargs)\n\n\n class Meta:\n ordering = '-created_at',\n\n\nclass Newsletter(models.Model):\n name = models.CharField(max_length=200)\n description = models.CharField(max_length=10000)\n image = models.ImageField()\n target = models.IntegerField()\n frequency = models.CharField(max_length=10, choices=FREQUENCY, default=\n 'monthly')\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n tag = models.ManyToManyField(Tags)\n\n @property\n def subscribed(self):\n return 10\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n ordering = '-created_at',\n",
"step-4": "from django.utils.text import slugify\nfrom pyexpat import model\nfrom django.db import models\nfrom rest_framework_simplejwt.state import User\nFREQUENCY = ('daily', 'Diario'), ('weekly', 'Semanal'), ('monthly', 'Mensual')\n\n\nclass Tags(models.Model):\n name = models.CharField(max_length=100)\n slug = models.CharField(max_length=150)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.name\n\n def save(self, *arg, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n super(Tags, self).save(*arg, **kwargs)\n\n\n class Meta:\n ordering = '-created_at',\n\n\nclass Newsletter(models.Model):\n name = models.CharField(max_length=200)\n description = models.CharField(max_length=10000)\n image = models.ImageField()\n target = models.IntegerField()\n frequency = models.CharField(max_length=10, choices=FREQUENCY, default=\n 'monthly')\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n tag = models.ManyToManyField(Tags)\n\n @property\n def subscribed(self):\n return 10\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n ordering = '-created_at',\n",
"step-5": "from django.utils.text import slugify\nfrom pyexpat import model\nfrom django.db import models\n# Create your models here.\nfrom rest_framework_simplejwt.state import User\n\nFREQUENCY = (\n ('daily', 'Diario'),\n ('weekly', 'Semanal'),\n ('monthly', 'Mensual')\n)\n\nclass Tags(models.Model):\n name = models.CharField(max_length=100)\n slug = models.CharField(max_length=150)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.name\n\n def save(self, *arg, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n super(Tags, self).save(*arg, **kwargs)\n\n class Meta:\n ordering = ('-created_at',)\n\nclass Newsletter(models.Model):\n name = models.CharField(max_length=200)\n description = models.CharField(max_length=10000)\n image = models.ImageField()\n target = models.IntegerField()\n frequency = models.CharField(max_length=10, choices=FREQUENCY, default='monthly')\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n tag = models.ManyToManyField(Tags)\n @property\n def subscribed(self):\n return 10\n\n def __str__(self):\n return self.name\n\n class Meta:\n ordering = ('-created_at',)\n\n",
"step-ids": [
5,
7,
8,
10,
11
]
}
|
[
5,
7,
8,
10,
11
] |
n = input()
n = list(n)
n.sort()
alph = []
num = []
for i in range(n):
if i.isalpha():
alpa.append(i)
else:
num.append(i)
result.append(str(alpa))
result.append(str(num))
print(n)
|
normal
|
{
"blob_id": "e364a4e6e1c4e0fd6805515a1149adaf92e9c8fb",
"index": 5584,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nn.sort()\n<mask token>\nfor i in range(n):\n if i.isalpha():\n alpa.append(i)\n else:\n num.append(i)\nresult.append(str(alpa))\nresult.append(str(num))\nprint(n)\n",
"step-3": "n = input()\nn = list(n)\nn.sort()\nalph = []\nnum = []\nfor i in range(n):\n if i.isalpha():\n alpa.append(i)\n else:\n num.append(i)\nresult.append(str(alpa))\nresult.append(str(num))\nprint(n)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
class PredictionRequest(BaseModel):
feature_vector: List[float]
score: Optional[bool] = False
@app.post('/prediction')
def predict(req: PredictionRequest):
prediction = clf.predict([req.feature_vector])
response = {'is_inlier': int(prediction[0])}
score = clf.score_samples([req.feature_vector])
response['anomaly_score'] = score[0]
return response
@app.get('/model_infomation')
def model_infomation():
return clf.get_params()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class PredictionRequest(BaseModel):
feature_vector: List[float]
score: Optional[bool] = False
@app.post('/prediction')
def predict(req: PredictionRequest):
prediction = clf.predict([req.feature_vector])
response = {'is_inlier': int(prediction[0])}
score = clf.score_samples([req.feature_vector])
response['anomaly_score'] = score[0]
return response
@app.get('/model_infomation')
def model_infomation():
return clf.get_params()
if __name__ == '__main__':
print('Running')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
app = FastAPI()
clf = load('model.joblib')
class PredictionRequest(BaseModel):
feature_vector: List[float]
score: Optional[bool] = False
@app.post('/prediction')
def predict(req: PredictionRequest):
prediction = clf.predict([req.feature_vector])
response = {'is_inlier': int(prediction[0])}
score = clf.score_samples([req.feature_vector])
response['anomaly_score'] = score[0]
return response
@app.get('/model_infomation')
def model_infomation():
return clf.get_params()
if __name__ == '__main__':
print('Running')
<|reserved_special_token_1|>
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional
from joblib import load
app = FastAPI()
clf = load('model.joblib')
class PredictionRequest(BaseModel):
feature_vector: List[float]
score: Optional[bool] = False
@app.post('/prediction')
def predict(req: PredictionRequest):
prediction = clf.predict([req.feature_vector])
response = {'is_inlier': int(prediction[0])}
score = clf.score_samples([req.feature_vector])
response['anomaly_score'] = score[0]
return response
@app.get('/model_infomation')
def model_infomation():
return clf.get_params()
if __name__ == '__main__':
print('Running')
<|reserved_special_token_1|>
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional
from joblib import load
app = FastAPI()
clf = load("model.joblib")
class PredictionRequest(BaseModel):
feature_vector: List[float]
score: Optional[bool] = False
@app.post("/prediction")
def predict(req: PredictionRequest):
prediction = clf.predict([req.feature_vector])
response = {"is_inlier": int(prediction[0])}
score = clf.score_samples([req.feature_vector])
response["anomaly_score"] = score[0]
return response
@app.get("/model_infomation")
def model_infomation():
return clf.get_params()
if __name__ == "__main__":
print("Running")
|
flexible
|
{
"blob_id": "d6fa3039c0987bf556c5bd78b66eb43543fd00fe",
"index": 6343,
"step-1": "<mask token>\n\n\nclass PredictionRequest(BaseModel):\n feature_vector: List[float]\n score: Optional[bool] = False\n\n\n@app.post('/prediction')\ndef predict(req: PredictionRequest):\n prediction = clf.predict([req.feature_vector])\n response = {'is_inlier': int(prediction[0])}\n score = clf.score_samples([req.feature_vector])\n response['anomaly_score'] = score[0]\n return response\n\n\n@app.get('/model_infomation')\ndef model_infomation():\n return clf.get_params()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass PredictionRequest(BaseModel):\n feature_vector: List[float]\n score: Optional[bool] = False\n\n\n@app.post('/prediction')\ndef predict(req: PredictionRequest):\n prediction = clf.predict([req.feature_vector])\n response = {'is_inlier': int(prediction[0])}\n score = clf.score_samples([req.feature_vector])\n response['anomaly_score'] = score[0]\n return response\n\n\n@app.get('/model_infomation')\ndef model_infomation():\n return clf.get_params()\n\n\nif __name__ == '__main__':\n print('Running')\n",
"step-3": "<mask token>\napp = FastAPI()\nclf = load('model.joblib')\n\n\nclass PredictionRequest(BaseModel):\n feature_vector: List[float]\n score: Optional[bool] = False\n\n\n@app.post('/prediction')\ndef predict(req: PredictionRequest):\n prediction = clf.predict([req.feature_vector])\n response = {'is_inlier': int(prediction[0])}\n score = clf.score_samples([req.feature_vector])\n response['anomaly_score'] = score[0]\n return response\n\n\n@app.get('/model_infomation')\ndef model_infomation():\n return clf.get_params()\n\n\nif __name__ == '__main__':\n print('Running')\n",
"step-4": "from fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom typing import List, Optional\nfrom joblib import load\napp = FastAPI()\nclf = load('model.joblib')\n\n\nclass PredictionRequest(BaseModel):\n feature_vector: List[float]\n score: Optional[bool] = False\n\n\n@app.post('/prediction')\ndef predict(req: PredictionRequest):\n prediction = clf.predict([req.feature_vector])\n response = {'is_inlier': int(prediction[0])}\n score = clf.score_samples([req.feature_vector])\n response['anomaly_score'] = score[0]\n return response\n\n\n@app.get('/model_infomation')\ndef model_infomation():\n return clf.get_params()\n\n\nif __name__ == '__main__':\n print('Running')\n",
"step-5": "from fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom typing import List, Optional\nfrom joblib import load\n\napp = FastAPI()\nclf = load(\"model.joblib\")\n\nclass PredictionRequest(BaseModel):\n feature_vector: List[float]\n score: Optional[bool] = False\n\n@app.post(\"/prediction\")\ndef predict(req: PredictionRequest):\n prediction = clf.predict([req.feature_vector])\n response = {\"is_inlier\": int(prediction[0])}\n score = clf.score_samples([req.feature_vector])\n response[\"anomaly_score\"] = score[0]\n\n return response\n\n@app.get(\"/model_infomation\")\ndef model_infomation():\n return clf.get_params()\n\nif __name__ == \"__main__\":\n print(\"Running\")\n ",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
@spotify.route('/callback')
def callback():
auth_code = request.args['code']
code_payload = {'grant_type': 'authorization_code', 'code': str(
auth_code), 'redirect_uri': REDIRECT_URI}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
access_token = response_data['access_token']
print(access_token)
refresh_token = response_data['refresh_token']
token_type = response_data['token_type']
expires_in = response_data['expires_in']
redirect_to_index = redirect('http://localhost:3000/')
response = make_response(redirect_to_index)
response.set_cookie('access_token', value=access_token)
response.set_cookie('refresh_token', value=refresh_token)
return response
@spotify.route('/refresh_token', methods=['POST'])
def refresh_token():
r = request.get_json()
refresh_token = r['refresh_token']
code_payload = {'grant_type': 'refresh_token', 'refresh_token':
refresh_token}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
return jsonify(response_data)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@spotify.route('/login')
def login():
url_args = urlencode(auth_query_parameters)
print(url_args)
auth_url = '{}/?{}'.format(SPOTIFY_AUTH_URL, url_args)
return redirect(auth_url)
@spotify.route('/callback')
def callback():
auth_code = request.args['code']
code_payload = {'grant_type': 'authorization_code', 'code': str(
auth_code), 'redirect_uri': REDIRECT_URI}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
access_token = response_data['access_token']
print(access_token)
refresh_token = response_data['refresh_token']
token_type = response_data['token_type']
expires_in = response_data['expires_in']
redirect_to_index = redirect('http://localhost:3000/')
response = make_response(redirect_to_index)
response.set_cookie('access_token', value=access_token)
response.set_cookie('refresh_token', value=refresh_token)
return response
@spotify.route('/refresh_token', methods=['POST'])
def refresh_token():
r = request.get_json()
refresh_token = r['refresh_token']
code_payload = {'grant_type': 'refresh_token', 'refresh_token':
refresh_token}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
return jsonify(response_data)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
spotify = Blueprint('spotify', __name__)
SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')
SPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')
SPOTIFY_AUTH_URL = 'https://accounts.spotify.com/authorize'
SPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token'
SPOTIFY_API_BASE_URL = 'https://api.spotify.com'
API_VERSION = 'v1'
SPOTIFY_API_URL = '{}/{}'.format(SPOTIFY_API_BASE_URL, API_VERSION)
CLIENT_SIDE_URL = 'http://localhost'
PORT = 8888
REDIRECT_URI = '{}:{}/callback'.format(CLIENT_SIDE_URL, PORT)
SCOPE = (
'playlist-modify-public playlist-modify-private user-read-currently-playing'
)
STATE = ''
SHOW_DIALOG_BOOL = True
SHOW_DIALOG_STR = str(SHOW_DIALOG_BOOL).lower()
auth_query_parameters = {'response_type': 'code', 'redirect_uri':
REDIRECT_URI, 'scope': SCOPE, 'client_id': SPOTIFY_CLIENT_ID}
@spotify.route('/login')
def login():
url_args = urlencode(auth_query_parameters)
print(url_args)
auth_url = '{}/?{}'.format(SPOTIFY_AUTH_URL, url_args)
return redirect(auth_url)
@spotify.route('/callback')
def callback():
auth_code = request.args['code']
code_payload = {'grant_type': 'authorization_code', 'code': str(
auth_code), 'redirect_uri': REDIRECT_URI}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
access_token = response_data['access_token']
print(access_token)
refresh_token = response_data['refresh_token']
token_type = response_data['token_type']
expires_in = response_data['expires_in']
redirect_to_index = redirect('http://localhost:3000/')
response = make_response(redirect_to_index)
response.set_cookie('access_token', value=access_token)
response.set_cookie('refresh_token', value=refresh_token)
return response
@spotify.route('/refresh_token', methods=['POST'])
def refresh_token():
r = request.get_json()
refresh_token = r['refresh_token']
code_payload = {'grant_type': 'refresh_token', 'refresh_token':
refresh_token}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
return jsonify(response_data)
<|reserved_special_token_1|>
import os
import base64
from urllib.parse import urlencode
import json
from flask import Blueprint, request, redirect, jsonify, make_response
import requests
spotify = Blueprint('spotify', __name__)
SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')
SPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')
SPOTIFY_AUTH_URL = 'https://accounts.spotify.com/authorize'
SPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token'
SPOTIFY_API_BASE_URL = 'https://api.spotify.com'
API_VERSION = 'v1'
SPOTIFY_API_URL = '{}/{}'.format(SPOTIFY_API_BASE_URL, API_VERSION)
CLIENT_SIDE_URL = 'http://localhost'
PORT = 8888
REDIRECT_URI = '{}:{}/callback'.format(CLIENT_SIDE_URL, PORT)
SCOPE = (
'playlist-modify-public playlist-modify-private user-read-currently-playing'
)
STATE = ''
SHOW_DIALOG_BOOL = True
SHOW_DIALOG_STR = str(SHOW_DIALOG_BOOL).lower()
auth_query_parameters = {'response_type': 'code', 'redirect_uri':
REDIRECT_URI, 'scope': SCOPE, 'client_id': SPOTIFY_CLIENT_ID}
@spotify.route('/login')
def login():
url_args = urlencode(auth_query_parameters)
print(url_args)
auth_url = '{}/?{}'.format(SPOTIFY_AUTH_URL, url_args)
return redirect(auth_url)
@spotify.route('/callback')
def callback():
auth_code = request.args['code']
code_payload = {'grant_type': 'authorization_code', 'code': str(
auth_code), 'redirect_uri': REDIRECT_URI}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
access_token = response_data['access_token']
print(access_token)
refresh_token = response_data['refresh_token']
token_type = response_data['token_type']
expires_in = response_data['expires_in']
redirect_to_index = redirect('http://localhost:3000/')
response = make_response(redirect_to_index)
response.set_cookie('access_token', value=access_token)
response.set_cookie('refresh_token', value=refresh_token)
return response
@spotify.route('/refresh_token', methods=['POST'])
def refresh_token():
r = request.get_json()
refresh_token = r['refresh_token']
code_payload = {'grant_type': 'refresh_token', 'refresh_token':
refresh_token}
base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(
'utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
response_data = json.loads(post_request.text)
return jsonify(response_data)
<|reserved_special_token_1|>
import os
import base64
from urllib.parse import urlencode
import json
from flask import Blueprint, request, redirect, jsonify, make_response
import requests
spotify = Blueprint('spotify', __name__)
# Client Keys
SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')
SPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')
# Spotify URLS
SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
SPOTIFY_API_BASE_URL = "https://api.spotify.com"
API_VERSION = "v1"
SPOTIFY_API_URL = "{}/{}".format(SPOTIFY_API_BASE_URL, API_VERSION)
# Server-side Parameters
CLIENT_SIDE_URL = "http://localhost"
PORT = 8888
REDIRECT_URI = "{}:{}/callback".format(CLIENT_SIDE_URL, PORT)
SCOPE = "playlist-modify-public playlist-modify-private user-read-currently-playing"
STATE = ""
SHOW_DIALOG_BOOL = True
SHOW_DIALOG_STR = str(SHOW_DIALOG_BOOL).lower()
auth_query_parameters = {
"response_type": "code",
"redirect_uri": REDIRECT_URI,
"scope": SCOPE,
# "state": STATE,
# "show_dialog": SHOW_DIALOG_str,
"client_id": SPOTIFY_CLIENT_ID
}
@spotify.route("/login")
def login():
# Auth Step 1: Authorization
url_args = urlencode(auth_query_parameters)
print(url_args)
auth_url = "{}/?{}".format(SPOTIFY_AUTH_URL, url_args)
return redirect(auth_url)
@spotify.route("/callback")
def callback():
# Auth Step 4: Requests refresh and access tokens
auth_code = request.args['code']
code_payload = {
"grant_type": "authorization_code",
"code": str(auth_code),
"redirect_uri": REDIRECT_URI
}
base64encoded = base64.b64encode(bytes("{}:{}".format(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {"Authorization": "Basic {}".format(base64encoded.decode('utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
# Auth Step 5: Tokens are Returned to Application
response_data = json.loads(post_request.text)
access_token = response_data["access_token"]
print(access_token)
refresh_token = response_data["refresh_token"]
token_type = response_data["token_type"]
expires_in = response_data["expires_in"]
redirect_to_index = redirect("http://localhost:3000/")
response = make_response(redirect_to_index)
response.set_cookie('access_token', value=access_token)
response.set_cookie('refresh_token', value=refresh_token)
return response
@spotify.route("/refresh_token", methods=['POST'])
def refresh_token():
# 7. Requesting access token from refresh token
r = request.get_json()
refresh_token = r['refresh_token']
code_payload = {
"grant_type": "refresh_token",
"refresh_token": refresh_token
}
base64encoded = base64.b64encode(bytes("{}:{}".format(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET), 'utf-8'))
headers = {"Authorization": "Basic {}".format(base64encoded.decode('utf-8'))}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
response_data = json.loads(post_request.text)
return jsonify(response_data)
|
flexible
|
{
"blob_id": "f080191fec4e56adc4013da74c840817e88caf56",
"index": 869,
"step-1": "<mask token>\n\n\n@spotify.route('/callback')\ndef callback():\n auth_code = request.args['code']\n code_payload = {'grant_type': 'authorization_code', 'code': str(\n auth_code), 'redirect_uri': REDIRECT_URI}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n access_token = response_data['access_token']\n print(access_token)\n refresh_token = response_data['refresh_token']\n token_type = response_data['token_type']\n expires_in = response_data['expires_in']\n redirect_to_index = redirect('http://localhost:3000/')\n response = make_response(redirect_to_index)\n response.set_cookie('access_token', value=access_token)\n response.set_cookie('refresh_token', value=refresh_token)\n return response\n\n\n@spotify.route('/refresh_token', methods=['POST'])\ndef refresh_token():\n r = request.get_json()\n refresh_token = r['refresh_token']\n code_payload = {'grant_type': 'refresh_token', 'refresh_token':\n refresh_token}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n return jsonify(response_data)\n",
"step-2": "<mask token>\n\n\n@spotify.route('/login')\ndef login():\n url_args = urlencode(auth_query_parameters)\n print(url_args)\n auth_url = '{}/?{}'.format(SPOTIFY_AUTH_URL, url_args)\n return redirect(auth_url)\n\n\n@spotify.route('/callback')\ndef callback():\n auth_code = request.args['code']\n code_payload = {'grant_type': 'authorization_code', 'code': str(\n auth_code), 'redirect_uri': REDIRECT_URI}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n access_token = response_data['access_token']\n print(access_token)\n refresh_token = response_data['refresh_token']\n token_type = response_data['token_type']\n expires_in = response_data['expires_in']\n redirect_to_index = redirect('http://localhost:3000/')\n response = make_response(redirect_to_index)\n response.set_cookie('access_token', value=access_token)\n response.set_cookie('refresh_token', value=refresh_token)\n return response\n\n\n@spotify.route('/refresh_token', methods=['POST'])\ndef refresh_token():\n r = request.get_json()\n refresh_token = r['refresh_token']\n code_payload = {'grant_type': 'refresh_token', 'refresh_token':\n refresh_token}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n return jsonify(response_data)\n",
"step-3": "<mask token>\nspotify = Blueprint('spotify', __name__)\nSPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')\nSPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')\nSPOTIFY_AUTH_URL = 'https://accounts.spotify.com/authorize'\nSPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token'\nSPOTIFY_API_BASE_URL = 'https://api.spotify.com'\nAPI_VERSION = 'v1'\nSPOTIFY_API_URL = '{}/{}'.format(SPOTIFY_API_BASE_URL, API_VERSION)\nCLIENT_SIDE_URL = 'http://localhost'\nPORT = 8888\nREDIRECT_URI = '{}:{}/callback'.format(CLIENT_SIDE_URL, PORT)\nSCOPE = (\n 'playlist-modify-public playlist-modify-private user-read-currently-playing'\n )\nSTATE = ''\nSHOW_DIALOG_BOOL = True\nSHOW_DIALOG_STR = str(SHOW_DIALOG_BOOL).lower()\nauth_query_parameters = {'response_type': 'code', 'redirect_uri':\n REDIRECT_URI, 'scope': SCOPE, 'client_id': SPOTIFY_CLIENT_ID}\n\n\n@spotify.route('/login')\ndef login():\n url_args = urlencode(auth_query_parameters)\n print(url_args)\n auth_url = '{}/?{}'.format(SPOTIFY_AUTH_URL, url_args)\n return redirect(auth_url)\n\n\n@spotify.route('/callback')\ndef callback():\n auth_code = request.args['code']\n code_payload = {'grant_type': 'authorization_code', 'code': str(\n auth_code), 'redirect_uri': REDIRECT_URI}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n access_token = response_data['access_token']\n print(access_token)\n refresh_token = response_data['refresh_token']\n token_type = response_data['token_type']\n expires_in = response_data['expires_in']\n redirect_to_index = redirect('http://localhost:3000/')\n response = make_response(redirect_to_index)\n response.set_cookie('access_token', value=access_token)\n response.set_cookie('refresh_token', value=refresh_token)\n return response\n\n\n@spotify.route('/refresh_token', methods=['POST'])\ndef refresh_token():\n r = request.get_json()\n refresh_token = r['refresh_token']\n code_payload = {'grant_type': 'refresh_token', 'refresh_token':\n refresh_token}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n return jsonify(response_data)\n",
"step-4": "import os\nimport base64\nfrom urllib.parse import urlencode\nimport json\nfrom flask import Blueprint, request, redirect, jsonify, make_response\nimport requests\nspotify = Blueprint('spotify', __name__)\nSPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')\nSPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')\nSPOTIFY_AUTH_URL = 'https://accounts.spotify.com/authorize'\nSPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token'\nSPOTIFY_API_BASE_URL = 'https://api.spotify.com'\nAPI_VERSION = 'v1'\nSPOTIFY_API_URL = '{}/{}'.format(SPOTIFY_API_BASE_URL, API_VERSION)\nCLIENT_SIDE_URL = 'http://localhost'\nPORT = 8888\nREDIRECT_URI = '{}:{}/callback'.format(CLIENT_SIDE_URL, PORT)\nSCOPE = (\n 'playlist-modify-public playlist-modify-private user-read-currently-playing'\n )\nSTATE = ''\nSHOW_DIALOG_BOOL = True\nSHOW_DIALOG_STR = str(SHOW_DIALOG_BOOL).lower()\nauth_query_parameters = {'response_type': 'code', 'redirect_uri':\n REDIRECT_URI, 'scope': SCOPE, 'client_id': SPOTIFY_CLIENT_ID}\n\n\n@spotify.route('/login')\ndef login():\n url_args = urlencode(auth_query_parameters)\n print(url_args)\n auth_url = '{}/?{}'.format(SPOTIFY_AUTH_URL, url_args)\n return redirect(auth_url)\n\n\n@spotify.route('/callback')\ndef callback():\n auth_code = request.args['code']\n code_payload = {'grant_type': 'authorization_code', 'code': str(\n auth_code), 'redirect_uri': REDIRECT_URI}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n access_token = response_data['access_token']\n print(access_token)\n refresh_token = response_data['refresh_token']\n token_type = response_data['token_type']\n expires_in = response_data['expires_in']\n redirect_to_index = redirect('http://localhost:3000/')\n response = make_response(redirect_to_index)\n response.set_cookie('access_token', value=access_token)\n response.set_cookie('refresh_token', value=refresh_token)\n return response\n\n\n@spotify.route('/refresh_token', methods=['POST'])\ndef refresh_token():\n r = request.get_json()\n refresh_token = r['refresh_token']\n code_payload = {'grant_type': 'refresh_token', 'refresh_token':\n refresh_token}\n base64encoded = base64.b64encode(bytes('{}:{}'.format(SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {'Authorization': 'Basic {}'.format(base64encoded.decode(\n 'utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,\n headers=headers)\n response_data = json.loads(post_request.text)\n return jsonify(response_data)\n",
"step-5": "import os\nimport base64\nfrom urllib.parse import urlencode\nimport json\n\nfrom flask import Blueprint, request, redirect, jsonify, make_response\nimport requests\n\nspotify = Blueprint('spotify', __name__)\n\n# Client Keys\nSPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')\nSPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')\n\n# Spotify URLS\nSPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\"\nSPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\"\nSPOTIFY_API_BASE_URL = \"https://api.spotify.com\"\nAPI_VERSION = \"v1\"\nSPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION)\n\n# Server-side Parameters\nCLIENT_SIDE_URL = \"http://localhost\"\nPORT = 8888\nREDIRECT_URI = \"{}:{}/callback\".format(CLIENT_SIDE_URL, PORT)\nSCOPE = \"playlist-modify-public playlist-modify-private user-read-currently-playing\"\nSTATE = \"\"\nSHOW_DIALOG_BOOL = True\nSHOW_DIALOG_STR = str(SHOW_DIALOG_BOOL).lower()\n\n\nauth_query_parameters = {\n \"response_type\": \"code\",\n \"redirect_uri\": REDIRECT_URI,\n \"scope\": SCOPE,\n # \"state\": STATE,\n # \"show_dialog\": SHOW_DIALOG_str,\n \"client_id\": SPOTIFY_CLIENT_ID\n}\n\n\n@spotify.route(\"/login\")\ndef login():\n # Auth Step 1: Authorization\n url_args = urlencode(auth_query_parameters)\n print(url_args)\n auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args)\n return redirect(auth_url)\n\n\n@spotify.route(\"/callback\")\ndef callback():\n # Auth Step 4: Requests refresh and access tokens\n auth_code = request.args['code']\n code_payload = {\n \"grant_type\": \"authorization_code\",\n \"code\": str(auth_code),\n \"redirect_uri\": REDIRECT_URI\n }\n\n base64encoded = base64.b64encode(bytes(\"{}:{}\".format(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {\"Authorization\": \"Basic {}\".format(base64encoded.decode('utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)\n\n # Auth Step 5: Tokens are Returned to Application\n response_data = json.loads(post_request.text)\n access_token = response_data[\"access_token\"]\n print(access_token)\n refresh_token = response_data[\"refresh_token\"]\n token_type = response_data[\"token_type\"]\n expires_in = response_data[\"expires_in\"]\n\n redirect_to_index = redirect(\"http://localhost:3000/\")\n response = make_response(redirect_to_index)\n response.set_cookie('access_token', value=access_token)\n response.set_cookie('refresh_token', value=refresh_token)\n return response\n\n\n@spotify.route(\"/refresh_token\", methods=['POST'])\ndef refresh_token():\n # 7. Requesting access token from refresh token\n r = request.get_json()\n refresh_token = r['refresh_token']\n code_payload = {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": refresh_token\n }\n base64encoded = base64.b64encode(bytes(\"{}:{}\".format(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET), 'utf-8'))\n headers = {\"Authorization\": \"Basic {}\".format(base64encoded.decode('utf-8'))}\n post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)\n response_data = json.loads(post_request.text)\n return jsonify(response_data)\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
import FWCore.ParameterSet.Config as cms
maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
readFiles = cms.untracked.vstring()
secFiles = cms.untracked.vstring()
source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles)
readFiles.extend( [
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FE26AAB2-D90B-E211-AD0F-0025902009B8.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FCB6A333-C70B-E211-8C99-001E67396D51.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FA9CB2B5-D90B-E211-82B1-001E67397B07.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F8F81697-E90B-E211-9A48-002590200834.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F88B7838-C70B-E211-8971-001E673968F1.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F6481280-E90B-E211-8349-002590200B34.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F4DAB680-B90B-E211-BE7E-003048D47A6C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F2F3F436-C70B-E211-A3A4-002481E1511E.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F03693B3-D90B-E211-8CFB-001E67398633.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEF20E3B-C70B-E211-953A-002590200970.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEA69380-E90B-E211-833A-002590200970.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EE92E708-A90B-E211-BE6A-001E67397B07.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EC8A6530-C70B-E211-9D59-002590200840.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EAE34E85-B90B-E211-B5AD-003048673F3A.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EACF738F-E90B-E211-8D44-00259020081C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/E43E9F40-C70B-E211-8CFE-001E67396644.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DEF585B4-D90B-E211-AD4B-002590200B38.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE991237-C70B-E211-A065-001E67397003.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE69B13F-B90B-E211-A320-002481E1511E.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DCDE4B42-C70B-E211-9F88-003048D4602A.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DC7EDE05-A90B-E211-B465-0025902008F4.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DAFF741D-A90B-E211-B24E-001E673969D2.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D865D241-B90B-E211-A391-003048673F26.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D6C4A74C-C70B-E211-B449-003048D45F78.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D4EB5C31-C70B-E211-AC1B-002590200AD0.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D49F4B34-C70B-E211-99F4-0025B3E06400.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D2C6963C-C70B-E211-9D24-002590200908.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D26CAF3C-C70B-E211-A812-002590200930.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D026AE93-B90B-E211-9E76-002481E14D76.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CCD8F139-C70B-E211-B2E8-003048D47A4C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA85ABB8-D90B-E211-A2BB-001E67397E13.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA63512E-C70B-E211-8DDF-001E672CC1E7.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C480E406-A90B-E211-8B58-001E67397D00.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D5E949-9C0B-E211-A208-001E673967C5.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D100AE-D90B-E211-8962-001E67396DBA.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/BCF27C36-C70B-E211-876B-002590200A6C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B4E711BB-D90B-E211-A42C-001E67396E3C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B2A005DE-D90B-E211-94B3-001E67397D91.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AC3D508B-B90B-E211-AB8D-003048D45F2C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAC74E91-B90B-E211-A9FF-002590200A98.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAAE1D0A-A90B-E211-907D-001E67398CB9.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A89EA633-C70B-E211-AF12-0025902009A4.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A836D251-C70B-E211-BFDD-0025902008E4.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A448E095-E90B-E211-8CED-001E673969D2.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9EBE5A69-C70B-E211-A36E-001E67398E12.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9C84FAB1-D90B-E211-8EDF-001E67396874.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9AFA54C5-D90B-E211-9C13-001E67396568.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9A4A0F32-C70B-E211-A372-002590200898.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/94BE773D-C70B-E211-836F-001E67398CE1.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/944B6544-B90B-E211-920A-002481E1511E.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/90CBB57E-E90B-E211-AB2F-0025902009C0.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8E16A8F3-D90B-E211-83D6-002590200B0C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ACD8F9C-B90B-E211-8F86-002590200B4C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ABCBFC1-D90B-E211-9C77-002590200B68.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8AAE9A07-A90B-E211-ABCF-001E673967C5.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8A5DE24C-C70B-E211-9271-002590200988.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/88CA0942-C70B-E211-A894-0025B31E3CC0.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7EFFEF3A-C70B-E211-A78B-001E67396A63.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7CDD1A9C-B90B-E211-99CE-003048D45FD8.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7A951BB1-D90B-E211-B97A-003048D476B4.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/78C1620C-A90B-E211-AF89-001E67396761.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/748AA33D-C70B-E211-AA21-001E67398390.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/74013EE7-D90B-E211-B929-001E673970C1.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/726A8A0A-A90B-E211-86C8-001E67397094.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/70698A49-C70B-E211-BE12-002590200A28.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E05B863-C70B-E211-B476-002590200938.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E03CAFF-D90B-E211-96B9-001E67396C52.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6CB7A769-C70B-E211-A569-002590200A80.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6C3E469D-B90B-E211-93ED-003048D45FE8.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/68D8E30B-A90B-E211-9884-003048673F24.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6644544A-C70B-E211-B9D8-001E67398E49.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/60FAAC62-9C0B-E211-B091-002590200B00.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E932B7F-F60B-E211-A37C-001E67398C05.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E2DFB9D-B90B-E211-8767-0025B31E3C3C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5C9369BA-D90B-E211-AB39-001E67397396.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5485BB36-C70B-E211-A62A-002590200A98.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/54439593-B90B-E211-AF3D-001E67398011.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/540D144A-9C0B-E211-BE2D-001E67396C9D.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5087B43E-B90B-E211-834E-003048D45FB6.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/50119B4C-C70B-E211-BC7A-00259020083C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4EBF2B87-B90B-E211-8020-003048D476C4.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E90C544-B90B-E211-92CF-001E67396DCE.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E42EA41-C70B-E211-89E7-002590200900.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E24ECEB-D90B-E211-B732-001E67397CCE.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4A3C00E2-D90B-E211-81B6-0025902009B0.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/487FA490-B90B-E211-B401-003048D45FE8.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/46C80D32-C70B-E211-ADC0-003048D45F98.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4680304C-B90B-E211-9E05-003048D479F2.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4442750C-A90B-E211-982C-001E67396644.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/428A4E96-B90B-E211-8098-002590200B74.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4048B9E0-D90B-E211-AD88-001E67397B07.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3ECD1D4C-B90B-E211-BCE7-003048D46034.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3EA42648-9C0B-E211-96A1-001E673972F6.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3E5C2DB5-D90B-E211-AFAA-9C8E991A143E.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3C91E824-A90B-E211-A981-001E67397D00.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3AF523B1-D90B-E211-A075-001E67396BB7.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3A3BB131-C70B-E211-AE83-001E67396DB5.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3642D7AF-D90B-E211-A79C-0030486740BA.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30A91F44-9C0B-E211-ABA7-001E6739811A.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30897650-C70B-E211-9F69-0025902008D8.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/304AEF43-C70B-E211-8856-003048D45F98.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2E24DE3A-B90B-E211-ACC7-0025B3E06556.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2CE679E6-D90B-E211-B835-002590200B0C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2C7439E9-D90B-E211-8919-002590200930.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2AFB4848-B90B-E211-A519-001E673965FE.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2A854B08-A90B-E211-9851-001E67397701.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2817039C-B90B-E211-9F8D-0025B31E3C58.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/241AF10A-A90B-E211-BB12-001E67397CCE.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/240A3B43-B90B-E211-BA5F-002481E14FFC.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/20986287-B90B-E211-942A-003048D47A4C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1EB30D07-DA0B-E211-BE8F-001E67398E62.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1E2DEC38-B90B-E211-B323-003048D476C2.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1C490588-B90B-E211-99B7-003048D45FAE.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0E69E144-B90B-E211-AFD2-0025B3E05DB6.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CF5EAB8-D90B-E211-AD4B-002590200AD0.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CBE6239-B90B-E211-8155-001E67396A18.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/08A93150-9C0B-E211-9BF5-001E67396EAA.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0639D68C-B90B-E211-953D-003048D4609E.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/060DDA6A-C70B-E211-BF0C-001E67396D4C.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/02C8D108-DA0B-E211-8141-001E67397396.root',
'/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0078C0C1-D90B-E211-83A4-001E67396E32.root' ] );
secFiles.extend( [
] )
|
normal
|
{
"blob_id": "965bb4c8e7d6650dab7f002645dceacab59a0c5c",
"index": 7298,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nreadFiles.extend([\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FE26AAB2-D90B-E211-AD0F-0025902009B8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FCB6A333-C70B-E211-8C99-001E67396D51.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FA9CB2B5-D90B-E211-82B1-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F8F81697-E90B-E211-9A48-002590200834.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F88B7838-C70B-E211-8971-001E673968F1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F6481280-E90B-E211-8349-002590200B34.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F4DAB680-B90B-E211-BE7E-003048D47A6C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F2F3F436-C70B-E211-A3A4-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F03693B3-D90B-E211-8CFB-001E67398633.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEF20E3B-C70B-E211-953A-002590200970.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEA69380-E90B-E211-833A-002590200970.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EE92E708-A90B-E211-BE6A-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EC8A6530-C70B-E211-9D59-002590200840.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EAE34E85-B90B-E211-B5AD-003048673F3A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EACF738F-E90B-E211-8D44-00259020081C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/E43E9F40-C70B-E211-8CFE-001E67396644.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DEF585B4-D90B-E211-AD4B-002590200B38.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE991237-C70B-E211-A065-001E67397003.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE69B13F-B90B-E211-A320-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DCDE4B42-C70B-E211-9F88-003048D4602A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DC7EDE05-A90B-E211-B465-0025902008F4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DAFF741D-A90B-E211-B24E-001E673969D2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D865D241-B90B-E211-A391-003048673F26.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D6C4A74C-C70B-E211-B449-003048D45F78.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D4EB5C31-C70B-E211-AC1B-002590200AD0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D49F4B34-C70B-E211-99F4-0025B3E06400.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D2C6963C-C70B-E211-9D24-002590200908.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D26CAF3C-C70B-E211-A812-002590200930.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D026AE93-B90B-E211-9E76-002481E14D76.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CCD8F139-C70B-E211-B2E8-003048D47A4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA85ABB8-D90B-E211-A2BB-001E67397E13.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA63512E-C70B-E211-8DDF-001E672CC1E7.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C480E406-A90B-E211-8B58-001E67397D00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D5E949-9C0B-E211-A208-001E673967C5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D100AE-D90B-E211-8962-001E67396DBA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/BCF27C36-C70B-E211-876B-002590200A6C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B4E711BB-D90B-E211-A42C-001E67396E3C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B2A005DE-D90B-E211-94B3-001E67397D91.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AC3D508B-B90B-E211-AB8D-003048D45F2C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAC74E91-B90B-E211-A9FF-002590200A98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAAE1D0A-A90B-E211-907D-001E67398CB9.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A89EA633-C70B-E211-AF12-0025902009A4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A836D251-C70B-E211-BFDD-0025902008E4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A448E095-E90B-E211-8CED-001E673969D2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9EBE5A69-C70B-E211-A36E-001E67398E12.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9C84FAB1-D90B-E211-8EDF-001E67396874.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9AFA54C5-D90B-E211-9C13-001E67396568.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9A4A0F32-C70B-E211-A372-002590200898.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/94BE773D-C70B-E211-836F-001E67398CE1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/944B6544-B90B-E211-920A-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/90CBB57E-E90B-E211-AB2F-0025902009C0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8E16A8F3-D90B-E211-83D6-002590200B0C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ACD8F9C-B90B-E211-8F86-002590200B4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ABCBFC1-D90B-E211-9C77-002590200B68.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8AAE9A07-A90B-E211-ABCF-001E673967C5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8A5DE24C-C70B-E211-9271-002590200988.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/88CA0942-C70B-E211-A894-0025B31E3CC0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7EFFEF3A-C70B-E211-A78B-001E67396A63.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7CDD1A9C-B90B-E211-99CE-003048D45FD8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7A951BB1-D90B-E211-B97A-003048D476B4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/78C1620C-A90B-E211-AF89-001E67396761.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/748AA33D-C70B-E211-AA21-001E67398390.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/74013EE7-D90B-E211-B929-001E673970C1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/726A8A0A-A90B-E211-86C8-001E67397094.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/70698A49-C70B-E211-BE12-002590200A28.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E05B863-C70B-E211-B476-002590200938.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E03CAFF-D90B-E211-96B9-001E67396C52.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6CB7A769-C70B-E211-A569-002590200A80.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6C3E469D-B90B-E211-93ED-003048D45FE8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/68D8E30B-A90B-E211-9884-003048673F24.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6644544A-C70B-E211-B9D8-001E67398E49.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/60FAAC62-9C0B-E211-B091-002590200B00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E932B7F-F60B-E211-A37C-001E67398C05.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E2DFB9D-B90B-E211-8767-0025B31E3C3C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5C9369BA-D90B-E211-AB39-001E67397396.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5485BB36-C70B-E211-A62A-002590200A98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/54439593-B90B-E211-AF3D-001E67398011.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/540D144A-9C0B-E211-BE2D-001E67396C9D.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5087B43E-B90B-E211-834E-003048D45FB6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/50119B4C-C70B-E211-BC7A-00259020083C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4EBF2B87-B90B-E211-8020-003048D476C4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E90C544-B90B-E211-92CF-001E67396DCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E42EA41-C70B-E211-89E7-002590200900.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E24ECEB-D90B-E211-B732-001E67397CCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4A3C00E2-D90B-E211-81B6-0025902009B0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/487FA490-B90B-E211-B401-003048D45FE8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/46C80D32-C70B-E211-ADC0-003048D45F98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4680304C-B90B-E211-9E05-003048D479F2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4442750C-A90B-E211-982C-001E67396644.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/428A4E96-B90B-E211-8098-002590200B74.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4048B9E0-D90B-E211-AD88-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3ECD1D4C-B90B-E211-BCE7-003048D46034.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3EA42648-9C0B-E211-96A1-001E673972F6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3E5C2DB5-D90B-E211-AFAA-9C8E991A143E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3C91E824-A90B-E211-A981-001E67397D00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3AF523B1-D90B-E211-A075-001E67396BB7.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3A3BB131-C70B-E211-AE83-001E67396DB5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3642D7AF-D90B-E211-A79C-0030486740BA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30A91F44-9C0B-E211-ABA7-001E6739811A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30897650-C70B-E211-9F69-0025902008D8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/304AEF43-C70B-E211-8856-003048D45F98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2E24DE3A-B90B-E211-ACC7-0025B3E06556.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2CE679E6-D90B-E211-B835-002590200B0C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2C7439E9-D90B-E211-8919-002590200930.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2AFB4848-B90B-E211-A519-001E673965FE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2A854B08-A90B-E211-9851-001E67397701.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2817039C-B90B-E211-9F8D-0025B31E3C58.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/241AF10A-A90B-E211-BB12-001E67397CCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/240A3B43-B90B-E211-BA5F-002481E14FFC.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/20986287-B90B-E211-942A-003048D47A4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1EB30D07-DA0B-E211-BE8F-001E67398E62.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1E2DEC38-B90B-E211-B323-003048D476C2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1C490588-B90B-E211-99B7-003048D45FAE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0E69E144-B90B-E211-AFD2-0025B3E05DB6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CF5EAB8-D90B-E211-AD4B-002590200AD0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CBE6239-B90B-E211-8155-001E67396A18.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/08A93150-9C0B-E211-9BF5-001E67396EAA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0639D68C-B90B-E211-953D-003048D4609E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/060DDA6A-C70B-E211-BF0C-001E67396D4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/02C8D108-DA0B-E211-8141-001E67397396.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0078C0C1-D90B-E211-83A4-001E67396E32.root'\n ])\nsecFiles.extend([])\n",
"step-3": "<mask token>\nmaxEvents = cms.untracked.PSet(input=cms.untracked.int32(-1))\nreadFiles = cms.untracked.vstring()\nsecFiles = cms.untracked.vstring()\nsource = cms.Source('PoolSource', fileNames=readFiles, secondaryFileNames=\n secFiles)\nreadFiles.extend([\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FE26AAB2-D90B-E211-AD0F-0025902009B8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FCB6A333-C70B-E211-8C99-001E67396D51.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FA9CB2B5-D90B-E211-82B1-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F8F81697-E90B-E211-9A48-002590200834.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F88B7838-C70B-E211-8971-001E673968F1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F6481280-E90B-E211-8349-002590200B34.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F4DAB680-B90B-E211-BE7E-003048D47A6C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F2F3F436-C70B-E211-A3A4-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F03693B3-D90B-E211-8CFB-001E67398633.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEF20E3B-C70B-E211-953A-002590200970.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEA69380-E90B-E211-833A-002590200970.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EE92E708-A90B-E211-BE6A-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EC8A6530-C70B-E211-9D59-002590200840.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EAE34E85-B90B-E211-B5AD-003048673F3A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EACF738F-E90B-E211-8D44-00259020081C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/E43E9F40-C70B-E211-8CFE-001E67396644.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DEF585B4-D90B-E211-AD4B-002590200B38.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE991237-C70B-E211-A065-001E67397003.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE69B13F-B90B-E211-A320-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DCDE4B42-C70B-E211-9F88-003048D4602A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DC7EDE05-A90B-E211-B465-0025902008F4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DAFF741D-A90B-E211-B24E-001E673969D2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D865D241-B90B-E211-A391-003048673F26.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D6C4A74C-C70B-E211-B449-003048D45F78.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D4EB5C31-C70B-E211-AC1B-002590200AD0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D49F4B34-C70B-E211-99F4-0025B3E06400.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D2C6963C-C70B-E211-9D24-002590200908.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D26CAF3C-C70B-E211-A812-002590200930.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D026AE93-B90B-E211-9E76-002481E14D76.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CCD8F139-C70B-E211-B2E8-003048D47A4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA85ABB8-D90B-E211-A2BB-001E67397E13.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA63512E-C70B-E211-8DDF-001E672CC1E7.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C480E406-A90B-E211-8B58-001E67397D00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D5E949-9C0B-E211-A208-001E673967C5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D100AE-D90B-E211-8962-001E67396DBA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/BCF27C36-C70B-E211-876B-002590200A6C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B4E711BB-D90B-E211-A42C-001E67396E3C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B2A005DE-D90B-E211-94B3-001E67397D91.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AC3D508B-B90B-E211-AB8D-003048D45F2C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAC74E91-B90B-E211-A9FF-002590200A98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAAE1D0A-A90B-E211-907D-001E67398CB9.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A89EA633-C70B-E211-AF12-0025902009A4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A836D251-C70B-E211-BFDD-0025902008E4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A448E095-E90B-E211-8CED-001E673969D2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9EBE5A69-C70B-E211-A36E-001E67398E12.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9C84FAB1-D90B-E211-8EDF-001E67396874.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9AFA54C5-D90B-E211-9C13-001E67396568.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9A4A0F32-C70B-E211-A372-002590200898.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/94BE773D-C70B-E211-836F-001E67398CE1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/944B6544-B90B-E211-920A-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/90CBB57E-E90B-E211-AB2F-0025902009C0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8E16A8F3-D90B-E211-83D6-002590200B0C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ACD8F9C-B90B-E211-8F86-002590200B4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ABCBFC1-D90B-E211-9C77-002590200B68.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8AAE9A07-A90B-E211-ABCF-001E673967C5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8A5DE24C-C70B-E211-9271-002590200988.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/88CA0942-C70B-E211-A894-0025B31E3CC0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7EFFEF3A-C70B-E211-A78B-001E67396A63.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7CDD1A9C-B90B-E211-99CE-003048D45FD8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7A951BB1-D90B-E211-B97A-003048D476B4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/78C1620C-A90B-E211-AF89-001E67396761.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/748AA33D-C70B-E211-AA21-001E67398390.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/74013EE7-D90B-E211-B929-001E673970C1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/726A8A0A-A90B-E211-86C8-001E67397094.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/70698A49-C70B-E211-BE12-002590200A28.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E05B863-C70B-E211-B476-002590200938.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E03CAFF-D90B-E211-96B9-001E67396C52.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6CB7A769-C70B-E211-A569-002590200A80.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6C3E469D-B90B-E211-93ED-003048D45FE8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/68D8E30B-A90B-E211-9884-003048673F24.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6644544A-C70B-E211-B9D8-001E67398E49.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/60FAAC62-9C0B-E211-B091-002590200B00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E932B7F-F60B-E211-A37C-001E67398C05.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E2DFB9D-B90B-E211-8767-0025B31E3C3C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5C9369BA-D90B-E211-AB39-001E67397396.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5485BB36-C70B-E211-A62A-002590200A98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/54439593-B90B-E211-AF3D-001E67398011.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/540D144A-9C0B-E211-BE2D-001E67396C9D.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5087B43E-B90B-E211-834E-003048D45FB6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/50119B4C-C70B-E211-BC7A-00259020083C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4EBF2B87-B90B-E211-8020-003048D476C4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E90C544-B90B-E211-92CF-001E67396DCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E42EA41-C70B-E211-89E7-002590200900.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E24ECEB-D90B-E211-B732-001E67397CCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4A3C00E2-D90B-E211-81B6-0025902009B0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/487FA490-B90B-E211-B401-003048D45FE8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/46C80D32-C70B-E211-ADC0-003048D45F98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4680304C-B90B-E211-9E05-003048D479F2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4442750C-A90B-E211-982C-001E67396644.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/428A4E96-B90B-E211-8098-002590200B74.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4048B9E0-D90B-E211-AD88-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3ECD1D4C-B90B-E211-BCE7-003048D46034.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3EA42648-9C0B-E211-96A1-001E673972F6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3E5C2DB5-D90B-E211-AFAA-9C8E991A143E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3C91E824-A90B-E211-A981-001E67397D00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3AF523B1-D90B-E211-A075-001E67396BB7.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3A3BB131-C70B-E211-AE83-001E67396DB5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3642D7AF-D90B-E211-A79C-0030486740BA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30A91F44-9C0B-E211-ABA7-001E6739811A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30897650-C70B-E211-9F69-0025902008D8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/304AEF43-C70B-E211-8856-003048D45F98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2E24DE3A-B90B-E211-ACC7-0025B3E06556.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2CE679E6-D90B-E211-B835-002590200B0C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2C7439E9-D90B-E211-8919-002590200930.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2AFB4848-B90B-E211-A519-001E673965FE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2A854B08-A90B-E211-9851-001E67397701.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2817039C-B90B-E211-9F8D-0025B31E3C58.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/241AF10A-A90B-E211-BB12-001E67397CCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/240A3B43-B90B-E211-BA5F-002481E14FFC.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/20986287-B90B-E211-942A-003048D47A4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1EB30D07-DA0B-E211-BE8F-001E67398E62.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1E2DEC38-B90B-E211-B323-003048D476C2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1C490588-B90B-E211-99B7-003048D45FAE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0E69E144-B90B-E211-AFD2-0025B3E05DB6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CF5EAB8-D90B-E211-AD4B-002590200AD0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CBE6239-B90B-E211-8155-001E67396A18.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/08A93150-9C0B-E211-9BF5-001E67396EAA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0639D68C-B90B-E211-953D-003048D4609E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/060DDA6A-C70B-E211-BF0C-001E67396D4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/02C8D108-DA0B-E211-8141-001E67397396.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0078C0C1-D90B-E211-83A4-001E67396E32.root'\n ])\nsecFiles.extend([])\n",
"step-4": "import FWCore.ParameterSet.Config as cms\nmaxEvents = cms.untracked.PSet(input=cms.untracked.int32(-1))\nreadFiles = cms.untracked.vstring()\nsecFiles = cms.untracked.vstring()\nsource = cms.Source('PoolSource', fileNames=readFiles, secondaryFileNames=\n secFiles)\nreadFiles.extend([\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FE26AAB2-D90B-E211-AD0F-0025902009B8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FCB6A333-C70B-E211-8C99-001E67396D51.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FA9CB2B5-D90B-E211-82B1-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F8F81697-E90B-E211-9A48-002590200834.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F88B7838-C70B-E211-8971-001E673968F1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F6481280-E90B-E211-8349-002590200B34.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F4DAB680-B90B-E211-BE7E-003048D47A6C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F2F3F436-C70B-E211-A3A4-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F03693B3-D90B-E211-8CFB-001E67398633.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEF20E3B-C70B-E211-953A-002590200970.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEA69380-E90B-E211-833A-002590200970.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EE92E708-A90B-E211-BE6A-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EC8A6530-C70B-E211-9D59-002590200840.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EAE34E85-B90B-E211-B5AD-003048673F3A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EACF738F-E90B-E211-8D44-00259020081C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/E43E9F40-C70B-E211-8CFE-001E67396644.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DEF585B4-D90B-E211-AD4B-002590200B38.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE991237-C70B-E211-A065-001E67397003.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE69B13F-B90B-E211-A320-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DCDE4B42-C70B-E211-9F88-003048D4602A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DC7EDE05-A90B-E211-B465-0025902008F4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DAFF741D-A90B-E211-B24E-001E673969D2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D865D241-B90B-E211-A391-003048673F26.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D6C4A74C-C70B-E211-B449-003048D45F78.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D4EB5C31-C70B-E211-AC1B-002590200AD0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D49F4B34-C70B-E211-99F4-0025B3E06400.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D2C6963C-C70B-E211-9D24-002590200908.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D26CAF3C-C70B-E211-A812-002590200930.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D026AE93-B90B-E211-9E76-002481E14D76.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CCD8F139-C70B-E211-B2E8-003048D47A4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA85ABB8-D90B-E211-A2BB-001E67397E13.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA63512E-C70B-E211-8DDF-001E672CC1E7.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C480E406-A90B-E211-8B58-001E67397D00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D5E949-9C0B-E211-A208-001E673967C5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D100AE-D90B-E211-8962-001E67396DBA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/BCF27C36-C70B-E211-876B-002590200A6C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B4E711BB-D90B-E211-A42C-001E67396E3C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B2A005DE-D90B-E211-94B3-001E67397D91.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AC3D508B-B90B-E211-AB8D-003048D45F2C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAC74E91-B90B-E211-A9FF-002590200A98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAAE1D0A-A90B-E211-907D-001E67398CB9.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A89EA633-C70B-E211-AF12-0025902009A4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A836D251-C70B-E211-BFDD-0025902008E4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A448E095-E90B-E211-8CED-001E673969D2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9EBE5A69-C70B-E211-A36E-001E67398E12.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9C84FAB1-D90B-E211-8EDF-001E67396874.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9AFA54C5-D90B-E211-9C13-001E67396568.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9A4A0F32-C70B-E211-A372-002590200898.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/94BE773D-C70B-E211-836F-001E67398CE1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/944B6544-B90B-E211-920A-002481E1511E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/90CBB57E-E90B-E211-AB2F-0025902009C0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8E16A8F3-D90B-E211-83D6-002590200B0C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ACD8F9C-B90B-E211-8F86-002590200B4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ABCBFC1-D90B-E211-9C77-002590200B68.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8AAE9A07-A90B-E211-ABCF-001E673967C5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8A5DE24C-C70B-E211-9271-002590200988.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/88CA0942-C70B-E211-A894-0025B31E3CC0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7EFFEF3A-C70B-E211-A78B-001E67396A63.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7CDD1A9C-B90B-E211-99CE-003048D45FD8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7A951BB1-D90B-E211-B97A-003048D476B4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/78C1620C-A90B-E211-AF89-001E67396761.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/748AA33D-C70B-E211-AA21-001E67398390.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/74013EE7-D90B-E211-B929-001E673970C1.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/726A8A0A-A90B-E211-86C8-001E67397094.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/70698A49-C70B-E211-BE12-002590200A28.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E05B863-C70B-E211-B476-002590200938.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E03CAFF-D90B-E211-96B9-001E67396C52.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6CB7A769-C70B-E211-A569-002590200A80.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6C3E469D-B90B-E211-93ED-003048D45FE8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/68D8E30B-A90B-E211-9884-003048673F24.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6644544A-C70B-E211-B9D8-001E67398E49.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/60FAAC62-9C0B-E211-B091-002590200B00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E932B7F-F60B-E211-A37C-001E67398C05.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E2DFB9D-B90B-E211-8767-0025B31E3C3C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5C9369BA-D90B-E211-AB39-001E67397396.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5485BB36-C70B-E211-A62A-002590200A98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/54439593-B90B-E211-AF3D-001E67398011.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/540D144A-9C0B-E211-BE2D-001E67396C9D.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5087B43E-B90B-E211-834E-003048D45FB6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/50119B4C-C70B-E211-BC7A-00259020083C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4EBF2B87-B90B-E211-8020-003048D476C4.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E90C544-B90B-E211-92CF-001E67396DCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E42EA41-C70B-E211-89E7-002590200900.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E24ECEB-D90B-E211-B732-001E67397CCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4A3C00E2-D90B-E211-81B6-0025902009B0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/487FA490-B90B-E211-B401-003048D45FE8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/46C80D32-C70B-E211-ADC0-003048D45F98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4680304C-B90B-E211-9E05-003048D479F2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4442750C-A90B-E211-982C-001E67396644.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/428A4E96-B90B-E211-8098-002590200B74.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4048B9E0-D90B-E211-AD88-001E67397B07.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3ECD1D4C-B90B-E211-BCE7-003048D46034.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3EA42648-9C0B-E211-96A1-001E673972F6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3E5C2DB5-D90B-E211-AFAA-9C8E991A143E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3C91E824-A90B-E211-A981-001E67397D00.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3AF523B1-D90B-E211-A075-001E67396BB7.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3A3BB131-C70B-E211-AE83-001E67396DB5.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3642D7AF-D90B-E211-A79C-0030486740BA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30A91F44-9C0B-E211-ABA7-001E6739811A.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30897650-C70B-E211-9F69-0025902008D8.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/304AEF43-C70B-E211-8856-003048D45F98.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2E24DE3A-B90B-E211-ACC7-0025B3E06556.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2CE679E6-D90B-E211-B835-002590200B0C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2C7439E9-D90B-E211-8919-002590200930.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2AFB4848-B90B-E211-A519-001E673965FE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2A854B08-A90B-E211-9851-001E67397701.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2817039C-B90B-E211-9F8D-0025B31E3C58.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/241AF10A-A90B-E211-BB12-001E67397CCE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/240A3B43-B90B-E211-BA5F-002481E14FFC.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/20986287-B90B-E211-942A-003048D47A4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1EB30D07-DA0B-E211-BE8F-001E67398E62.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1E2DEC38-B90B-E211-B323-003048D476C2.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1C490588-B90B-E211-99B7-003048D45FAE.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0E69E144-B90B-E211-AFD2-0025B3E05DB6.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CF5EAB8-D90B-E211-AD4B-002590200AD0.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CBE6239-B90B-E211-8155-001E67396A18.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/08A93150-9C0B-E211-9BF5-001E67396EAA.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0639D68C-B90B-E211-953D-003048D4609E.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/060DDA6A-C70B-E211-BF0C-001E67396D4C.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/02C8D108-DA0B-E211-8141-001E67397396.root'\n ,\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0078C0C1-D90B-E211-83A4-001E67396E32.root'\n ])\nsecFiles.extend([])\n",
"step-5": "import FWCore.ParameterSet.Config as cms\n\nmaxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nreadFiles = cms.untracked.vstring()\nsecFiles = cms.untracked.vstring() \nsource = cms.Source (\"PoolSource\",fileNames = readFiles, secondaryFileNames = secFiles)\nreadFiles.extend( [\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FE26AAB2-D90B-E211-AD0F-0025902009B8.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FCB6A333-C70B-E211-8C99-001E67396D51.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FA9CB2B5-D90B-E211-82B1-001E67397B07.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F8F81697-E90B-E211-9A48-002590200834.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F88B7838-C70B-E211-8971-001E673968F1.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F6481280-E90B-E211-8349-002590200B34.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F4DAB680-B90B-E211-BE7E-003048D47A6C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F2F3F436-C70B-E211-A3A4-002481E1511E.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/F03693B3-D90B-E211-8CFB-001E67398633.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEF20E3B-C70B-E211-953A-002590200970.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EEA69380-E90B-E211-833A-002590200970.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EE92E708-A90B-E211-BE6A-001E67397B07.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EC8A6530-C70B-E211-9D59-002590200840.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EAE34E85-B90B-E211-B5AD-003048673F3A.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/EACF738F-E90B-E211-8D44-00259020081C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/E43E9F40-C70B-E211-8CFE-001E67396644.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DEF585B4-D90B-E211-AD4B-002590200B38.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE991237-C70B-E211-A065-001E67397003.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DE69B13F-B90B-E211-A320-002481E1511E.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DCDE4B42-C70B-E211-9F88-003048D4602A.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DC7EDE05-A90B-E211-B465-0025902008F4.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/DAFF741D-A90B-E211-B24E-001E673969D2.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D865D241-B90B-E211-A391-003048673F26.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D6C4A74C-C70B-E211-B449-003048D45F78.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D4EB5C31-C70B-E211-AC1B-002590200AD0.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D49F4B34-C70B-E211-99F4-0025B3E06400.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D2C6963C-C70B-E211-9D24-002590200908.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D26CAF3C-C70B-E211-A812-002590200930.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/D026AE93-B90B-E211-9E76-002481E14D76.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CCD8F139-C70B-E211-B2E8-003048D47A4C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA85ABB8-D90B-E211-A2BB-001E67397E13.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/CA63512E-C70B-E211-8DDF-001E672CC1E7.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C480E406-A90B-E211-8B58-001E67397D00.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D5E949-9C0B-E211-A208-001E673967C5.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/C0D100AE-D90B-E211-8962-001E67396DBA.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/BCF27C36-C70B-E211-876B-002590200A6C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B4E711BB-D90B-E211-A42C-001E67396E3C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/B2A005DE-D90B-E211-94B3-001E67397D91.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AC3D508B-B90B-E211-AB8D-003048D45F2C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAC74E91-B90B-E211-A9FF-002590200A98.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/AAAE1D0A-A90B-E211-907D-001E67398CB9.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A89EA633-C70B-E211-AF12-0025902009A4.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A836D251-C70B-E211-BFDD-0025902008E4.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/A448E095-E90B-E211-8CED-001E673969D2.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9EBE5A69-C70B-E211-A36E-001E67398E12.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9C84FAB1-D90B-E211-8EDF-001E67396874.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9AFA54C5-D90B-E211-9C13-001E67396568.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/9A4A0F32-C70B-E211-A372-002590200898.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/94BE773D-C70B-E211-836F-001E67398CE1.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/944B6544-B90B-E211-920A-002481E1511E.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/90CBB57E-E90B-E211-AB2F-0025902009C0.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8E16A8F3-D90B-E211-83D6-002590200B0C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ACD8F9C-B90B-E211-8F86-002590200B4C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8ABCBFC1-D90B-E211-9C77-002590200B68.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8AAE9A07-A90B-E211-ABCF-001E673967C5.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/8A5DE24C-C70B-E211-9271-002590200988.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/88CA0942-C70B-E211-A894-0025B31E3CC0.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7EFFEF3A-C70B-E211-A78B-001E67396A63.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7CDD1A9C-B90B-E211-99CE-003048D45FD8.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/7A951BB1-D90B-E211-B97A-003048D476B4.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/78C1620C-A90B-E211-AF89-001E67396761.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/748AA33D-C70B-E211-AA21-001E67398390.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/74013EE7-D90B-E211-B929-001E673970C1.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/726A8A0A-A90B-E211-86C8-001E67397094.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/70698A49-C70B-E211-BE12-002590200A28.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E05B863-C70B-E211-B476-002590200938.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6E03CAFF-D90B-E211-96B9-001E67396C52.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6CB7A769-C70B-E211-A569-002590200A80.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6C3E469D-B90B-E211-93ED-003048D45FE8.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/68D8E30B-A90B-E211-9884-003048673F24.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/6644544A-C70B-E211-B9D8-001E67398E49.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/60FAAC62-9C0B-E211-B091-002590200B00.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E932B7F-F60B-E211-A37C-001E67398C05.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5E2DFB9D-B90B-E211-8767-0025B31E3C3C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5C9369BA-D90B-E211-AB39-001E67397396.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5485BB36-C70B-E211-A62A-002590200A98.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/54439593-B90B-E211-AF3D-001E67398011.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/540D144A-9C0B-E211-BE2D-001E67396C9D.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/5087B43E-B90B-E211-834E-003048D45FB6.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/50119B4C-C70B-E211-BC7A-00259020083C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4EBF2B87-B90B-E211-8020-003048D476C4.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E90C544-B90B-E211-92CF-001E67396DCE.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E42EA41-C70B-E211-89E7-002590200900.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4E24ECEB-D90B-E211-B732-001E67397CCE.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4A3C00E2-D90B-E211-81B6-0025902009B0.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/487FA490-B90B-E211-B401-003048D45FE8.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/46C80D32-C70B-E211-ADC0-003048D45F98.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4680304C-B90B-E211-9E05-003048D479F2.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4442750C-A90B-E211-982C-001E67396644.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/428A4E96-B90B-E211-8098-002590200B74.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/4048B9E0-D90B-E211-AD88-001E67397B07.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3ECD1D4C-B90B-E211-BCE7-003048D46034.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3EA42648-9C0B-E211-96A1-001E673972F6.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3E5C2DB5-D90B-E211-AFAA-9C8E991A143E.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3C91E824-A90B-E211-A981-001E67397D00.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3AF523B1-D90B-E211-A075-001E67396BB7.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3A3BB131-C70B-E211-AE83-001E67396DB5.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/3642D7AF-D90B-E211-A79C-0030486740BA.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30A91F44-9C0B-E211-ABA7-001E6739811A.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/30897650-C70B-E211-9F69-0025902008D8.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/304AEF43-C70B-E211-8856-003048D45F98.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2E24DE3A-B90B-E211-ACC7-0025B3E06556.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2CE679E6-D90B-E211-B835-002590200B0C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2C7439E9-D90B-E211-8919-002590200930.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2AFB4848-B90B-E211-A519-001E673965FE.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2A854B08-A90B-E211-9851-001E67397701.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/2817039C-B90B-E211-9F8D-0025B31E3C58.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/241AF10A-A90B-E211-BB12-001E67397CCE.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/240A3B43-B90B-E211-BA5F-002481E14FFC.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/20986287-B90B-E211-942A-003048D47A4C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1EB30D07-DA0B-E211-BE8F-001E67398E62.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1E2DEC38-B90B-E211-B323-003048D476C2.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/1C490588-B90B-E211-99B7-003048D45FAE.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0E69E144-B90B-E211-AFD2-0025B3E05DB6.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CF5EAB8-D90B-E211-AD4B-002590200AD0.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0CBE6239-B90B-E211-8155-001E67396A18.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/08A93150-9C0B-E211-9BF5-001E67396EAA.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0639D68C-B90B-E211-953D-003048D4609E.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/060DDA6A-C70B-E211-BF0C-001E67396D4C.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/02C8D108-DA0B-E211-8141-001E67397396.root',\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/0078C0C1-D90B-E211-83A4-001E67396E32.root' ] );\n\n\nsecFiles.extend( [\n ] )\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python/motorcycle.py Author "Nathan Wycoff <nathanbrwycoff@gmail.com>" 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")
|
normal
|
{
"blob_id": "aba3e0907e59bc5125759e90d3c784ceb97fca80",
"index": 9941,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nnp.random.seed(123)\n<mask token>\ntf.enable_eager_execution()\ntf.set_random_seed(123)\n<mask 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<mask 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<mask 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<mask token>\nplt.scatter(x, y)\n<mask token>\nplt.scatter(x, preds)\nplt.savefig('temp.pdf')\n",
"step-3": "<mask token>\nnp.random.seed(123)\n<mask 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",
"step-4": "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",
"step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# python/motorcycle.py Author \"Nathan Wycoff <nathanbrwycoff@gmail.com>\" 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",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import random
a = input('Nome do primeiro aluno: ')
b = input('Nome do segundo aluno: ')
c = input('Nome do terceiro aluno: ')
d = input('Nome do quarto aluno: ')
names = [a, b, c, d]
print('O aluno escolhido é {}.'.format(random.choice(names)))
|
normal
|
{
"blob_id": "bac3cee5e6d129fcf345d92000cb2a257c303dd5",
"index": 9805,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('O aluno escolhido é {}.'.format(random.choice(names)))\n",
"step-3": "<mask token>\na = input('Nome do primeiro aluno: ')\nb = input('Nome do segundo aluno: ')\nc = input('Nome do terceiro aluno: ')\nd = input('Nome do quarto aluno: ')\nnames = [a, b, c, d]\nprint('O aluno escolhido é {}.'.format(random.choice(names)))\n",
"step-4": "import random\na = input('Nome do primeiro aluno: ')\nb = input('Nome do segundo aluno: ')\nc = input('Nome do terceiro aluno: ')\nd = input('Nome do quarto aluno: ')\nnames = [a, b, c, d]\nprint('O aluno escolhido é {}.'.format(random.choice(names)))\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import random
s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=-/.,;'[]{}:<>?"
i = 0
fin = ""
while i == 0:
num = int(input("What length do you want? "))
password = "".join(random.sample(s, num))
print(password)
j = 0
while(j ==0):
want = input("Do you this password? (yes or no) ")
want.lower()
if want == "yes":
print("Your Password is " + password)
break
elif want == "no":
break
if want == "yes":
fin = input("Do you want a new password. yes or no? ")
fin.lower()
while j == 0:
if fin == "yes":
break
elif fin == "no":
break
if fin == "no":
print("This is your final password " + password)
break
|
normal
|
{
"blob_id": "3089dba0956151bd43e443b679ec0b24da644d08",
"index": 3701,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile i == 0:\n num = int(input('What length do you want? '))\n password = ''.join(random.sample(s, num))\n print(password)\n j = 0\n while j == 0:\n want = input('Do you this password? (yes or no) ')\n want.lower()\n if want == 'yes':\n print('Your Password is ' + password)\n break\n elif want == 'no':\n break\n if want == 'yes':\n fin = input('Do you want a new password. yes or no? ')\n fin.lower()\n while j == 0:\n if fin == 'yes':\n break\n elif fin == 'no':\n break\n if fin == 'no':\n print('This is your final password ' + password)\n break\n",
"step-3": "<mask token>\ns = (\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=-/.,;'[]{}:<>?\"\n )\ni = 0\nfin = ''\nwhile i == 0:\n num = int(input('What length do you want? '))\n password = ''.join(random.sample(s, num))\n print(password)\n j = 0\n while j == 0:\n want = input('Do you this password? (yes or no) ')\n want.lower()\n if want == 'yes':\n print('Your Password is ' + password)\n break\n elif want == 'no':\n break\n if want == 'yes':\n fin = input('Do you want a new password. yes or no? ')\n fin.lower()\n while j == 0:\n if fin == 'yes':\n break\n elif fin == 'no':\n break\n if fin == 'no':\n print('This is your final password ' + password)\n break\n",
"step-4": "import random\ns = (\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=-/.,;'[]{}:<>?\"\n )\ni = 0\nfin = ''\nwhile i == 0:\n num = int(input('What length do you want? '))\n password = ''.join(random.sample(s, num))\n print(password)\n j = 0\n while j == 0:\n want = input('Do you this password? (yes or no) ')\n want.lower()\n if want == 'yes':\n print('Your Password is ' + password)\n break\n elif want == 'no':\n break\n if want == 'yes':\n fin = input('Do you want a new password. yes or no? ')\n fin.lower()\n while j == 0:\n if fin == 'yes':\n break\n elif fin == 'no':\n break\n if fin == 'no':\n print('This is your final password ' + password)\n break\n",
"step-5": "import random\n\ns = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=-/.,;'[]{}:<>?\"\ni = 0\nfin = \"\"\nwhile i == 0:\n num = int(input(\"What length do you want? \"))\n\n password = \"\".join(random.sample(s, num))\n\n print(password)\n j = 0\n while(j ==0):\n want = input(\"Do you this password? (yes or no) \")\n want.lower()\n if want == \"yes\":\n print(\"Your Password is \" + password)\n break\n elif want == \"no\":\n break\n if want == \"yes\":\n fin = input(\"Do you want a new password. yes or no? \")\n fin.lower()\n while j == 0:\n if fin == \"yes\":\n break\n elif fin == \"no\":\n break\n if fin == \"no\":\n print(\"This is your final password \" + password)\n break",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
urlpatterns = patterns('accounts.views', url('^$', 'home', name='home'),
url('^login/$', 'login', name='login'), url('^logout/$', 'logout', name
='logout'), url('^register/$', 'register', name='register'), url(
'^dashboard/', 'dashboard', name='dashboard'), url('^rewards/',
'rewards', name='rewards'), url('get_all_data/', 'get_all_data', name=
'get_all_data'))
<|reserved_special_token_1|>
from django.conf.urls import patterns, include, url
urlpatterns = patterns('accounts.views', url('^$', 'home', name='home'),
url('^login/$', 'login', name='login'), url('^logout/$', 'logout', name
='logout'), url('^register/$', 'register', name='register'), url(
'^dashboard/', 'dashboard', name='dashboard'), url('^rewards/',
'rewards', name='rewards'), url('get_all_data/', 'get_all_data', name=
'get_all_data'))
<|reserved_special_token_1|>
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('accounts.views',
url(r'^$', 'home', name='home'),
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^register/$', 'register', name='register'),
url(r'^dashboard/', 'dashboard', name='dashboard'),
url(r'^rewards/', 'rewards', name='rewards'),
url(r'get_all_data/', 'get_all_data', name='get_all_data'),
)
|
flexible
|
{
"blob_id": "798ddd4a6e4febb4664bf1c973877628d1a45c71",
"index": 368,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = patterns('accounts.views', url('^$', 'home', name='home'),\n url('^login/$', 'login', name='login'), url('^logout/$', 'logout', name\n ='logout'), url('^register/$', 'register', name='register'), url(\n '^dashboard/', 'dashboard', name='dashboard'), url('^rewards/',\n 'rewards', name='rewards'), url('get_all_data/', 'get_all_data', name=\n 'get_all_data'))\n",
"step-3": "from django.conf.urls import patterns, include, url\nurlpatterns = patterns('accounts.views', url('^$', 'home', name='home'),\n url('^login/$', 'login', name='login'), url('^logout/$', 'logout', name\n ='logout'), url('^register/$', 'register', name='register'), url(\n '^dashboard/', 'dashboard', name='dashboard'), url('^rewards/',\n 'rewards', name='rewards'), url('get_all_data/', 'get_all_data', name=\n 'get_all_data'))\n",
"step-4": "from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('accounts.views',\n url(r'^$', 'home', name='home'),\n url(r'^login/$', 'login', name='login'),\n url(r'^logout/$', 'logout', name='logout'),\n url(r'^register/$', 'register', name='register'),\n url(r'^dashboard/', 'dashboard', name='dashboard'),\n url(r'^rewards/', 'rewards', name='rewards'),\n url(r'get_all_data/', 'get_all_data', name='get_all_data'),\n)\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
"""
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
"""
# O(n) TC and SC
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
cnt = {}
for num in nums:
cnt[num] = cnt.get(num, 0) + 1
res = []
for k, v in cnt.items():
if v > 1:
res.append(k)
return res
# O(n) TC and O(1) SC
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
res = []
for num in nums:
if nums[abs(num)-1] < 0:
res.append(abs(num))
else:
nums[abs(num)-1] *= -1
return res
|
normal
|
{
"blob_id": "5cfd7744f98c80483cb4dd318c17a7cd83ed3ae3",
"index": 758,
"step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n res = []\n for num in nums:\n if nums[abs(num) - 1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num) - 1] *= -1\n return res\n",
"step-3": "<mask token>\n\n\nclass Solution:\n <mask token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n res = []\n for num in nums:\n if nums[abs(num) - 1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num) - 1] *= -1\n return res\n",
"step-4": "<mask token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n cnt = {}\n for num in nums:\n cnt[num] = cnt.get(num, 0) + 1\n res = []\n for k, v in cnt.items():\n if v > 1:\n res.append(k)\n return res\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n res = []\n for num in nums:\n if nums[abs(num) - 1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num) - 1] *= -1\n return res\n",
"step-5": "\"\"\"\nGiven an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.\nFind all the elements that appear twice in this array.\nCould you do it without extra space and in O(n) runtime?\n\nExample:\nInput:\n[4,3,2,7,8,2,3,1]\n\nOutput:\n[2,3]\n\"\"\"\n\n# O(n) TC and SC\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n cnt = {}\n\n for num in nums:\n cnt[num] = cnt.get(num, 0) + 1\n\n res = []\n\n for k, v in cnt.items():\n if v > 1:\n res.append(k)\n\n return res\n\n\n# O(n) TC and O(1) SC\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n res = []\n \n for num in nums:\n if nums[abs(num)-1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num)-1] *= -1\n \n return res\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
import requests
from bs4 import BeautifulSoup
import re
# if no using some headers, wikiloc answers HTML error 503, probably they protect their servers against scrapping
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0',}
def main():
print("##############################")
response=requests.get("http://www.muenchen.de/rathaus/Serviceangebote/familie/kinderbetreuung/corona.html#geschlossene-kitas-oder-kitagruppen-_6", headers=headers)
soup=BeautifulSoup(response.text, "lxml")
p = soup.find("p", text =re.compile("geschlossen"))
if p != None:
kitaUl = p.findNext("ul")
kitaList = kitaUl.find_all("li")
# for kita in kitaList:
# print("KITA: " + kita.text)
print("TOTAL closed Kitas=", len(kitaList))
else:
print("Error, Kita list not found")
print("##############################")
response=requests.get("http://www.lgl.bayern.de/gesundheit/infektionsschutz/infektionskrankheiten_a_z/coronavirus/karte_coronavirus/", headers=headers)
soup2=BeautifulSoup(response.text, "lxml")
munich = soup2.find("td", text =re.compile("München Stadt"))
if munich != None:
change = munich.findNext("td").findNext("td")
average=change.findNext("td").findNext("td").findNext("td")
print("Munich 7-day average %s, today´s increase %s" %(re.sub(r"\s+", "", average.text), re.sub(r"\s+", "", change.text)))
else:
print("Error, Munich row not found")
print("##############################")
exit
if __name__ == "__main__":
main()
|
normal
|
{
"blob_id": "5a4a014d07cf312f148e089ea43484f663ce32bc",
"index": 8586,
"step-1": "<mask token>\n\n\ndef main():\n print('##############################')\n response = requests.get(\n 'http://www.muenchen.de/rathaus/Serviceangebote/familie/kinderbetreuung/corona.html#geschlossene-kitas-oder-kitagruppen-_6'\n , headers=headers)\n soup = BeautifulSoup(response.text, 'lxml')\n p = soup.find('p', text=re.compile('geschlossen'))\n if p != None:\n kitaUl = p.findNext('ul')\n kitaList = kitaUl.find_all('li')\n print('TOTAL closed Kitas=', len(kitaList))\n else:\n print('Error, Kita list not found')\n print('##############################')\n response = requests.get(\n 'http://www.lgl.bayern.de/gesundheit/infektionsschutz/infektionskrankheiten_a_z/coronavirus/karte_coronavirus/'\n , headers=headers)\n soup2 = BeautifulSoup(response.text, 'lxml')\n munich = soup2.find('td', text=re.compile('München Stadt'))\n if munich != None:\n change = munich.findNext('td').findNext('td')\n average = change.findNext('td').findNext('td').findNext('td')\n print('Munich 7-day average %s, today´s increase %s' % (re.sub(\n '\\\\s+', '', average.text), re.sub('\\\\s+', '', change.text)))\n else:\n print('Error, Munich row not found')\n print('##############################')\n exit\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n print('##############################')\n response = requests.get(\n 'http://www.muenchen.de/rathaus/Serviceangebote/familie/kinderbetreuung/corona.html#geschlossene-kitas-oder-kitagruppen-_6'\n , headers=headers)\n soup = BeautifulSoup(response.text, 'lxml')\n p = soup.find('p', text=re.compile('geschlossen'))\n if p != None:\n kitaUl = p.findNext('ul')\n kitaList = kitaUl.find_all('li')\n print('TOTAL closed Kitas=', len(kitaList))\n else:\n print('Error, Kita list not found')\n print('##############################')\n response = requests.get(\n 'http://www.lgl.bayern.de/gesundheit/infektionsschutz/infektionskrankheiten_a_z/coronavirus/karte_coronavirus/'\n , headers=headers)\n soup2 = BeautifulSoup(response.text, 'lxml')\n munich = soup2.find('td', text=re.compile('München Stadt'))\n if munich != None:\n change = munich.findNext('td').findNext('td')\n average = change.findNext('td').findNext('td').findNext('td')\n print('Munich 7-day average %s, today´s increase %s' % (re.sub(\n '\\\\s+', '', average.text), re.sub('\\\\s+', '', change.text)))\n else:\n print('Error, Munich row not found')\n print('##############################')\n exit\n\n\nif __name__ == '__main__':\n main()\n",
"step-3": "<mask token>\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0'\n }\n\n\ndef main():\n print('##############################')\n response = requests.get(\n 'http://www.muenchen.de/rathaus/Serviceangebote/familie/kinderbetreuung/corona.html#geschlossene-kitas-oder-kitagruppen-_6'\n , headers=headers)\n soup = BeautifulSoup(response.text, 'lxml')\n p = soup.find('p', text=re.compile('geschlossen'))\n if p != None:\n kitaUl = p.findNext('ul')\n kitaList = kitaUl.find_all('li')\n print('TOTAL closed Kitas=', len(kitaList))\n else:\n print('Error, Kita list not found')\n print('##############################')\n response = requests.get(\n 'http://www.lgl.bayern.de/gesundheit/infektionsschutz/infektionskrankheiten_a_z/coronavirus/karte_coronavirus/'\n , headers=headers)\n soup2 = BeautifulSoup(response.text, 'lxml')\n munich = soup2.find('td', text=re.compile('München Stadt'))\n if munich != None:\n change = munich.findNext('td').findNext('td')\n average = change.findNext('td').findNext('td').findNext('td')\n print('Munich 7-day average %s, today´s increase %s' % (re.sub(\n '\\\\s+', '', average.text), re.sub('\\\\s+', '', change.text)))\n else:\n print('Error, Munich row not found')\n print('##############################')\n exit\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "import requests\nfrom bs4 import BeautifulSoup\nimport re\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0'\n }\n\n\ndef main():\n print('##############################')\n response = requests.get(\n 'http://www.muenchen.de/rathaus/Serviceangebote/familie/kinderbetreuung/corona.html#geschlossene-kitas-oder-kitagruppen-_6'\n , headers=headers)\n soup = BeautifulSoup(response.text, 'lxml')\n p = soup.find('p', text=re.compile('geschlossen'))\n if p != None:\n kitaUl = p.findNext('ul')\n kitaList = kitaUl.find_all('li')\n print('TOTAL closed Kitas=', len(kitaList))\n else:\n print('Error, Kita list not found')\n print('##############################')\n response = requests.get(\n 'http://www.lgl.bayern.de/gesundheit/infektionsschutz/infektionskrankheiten_a_z/coronavirus/karte_coronavirus/'\n , headers=headers)\n soup2 = BeautifulSoup(response.text, 'lxml')\n munich = soup2.find('td', text=re.compile('München Stadt'))\n if munich != None:\n change = munich.findNext('td').findNext('td')\n average = change.findNext('td').findNext('td').findNext('td')\n print('Munich 7-day average %s, today´s increase %s' % (re.sub(\n '\\\\s+', '', average.text), re.sub('\\\\s+', '', change.text)))\n else:\n print('Error, Munich row not found')\n print('##############################')\n exit\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "import requests\nfrom bs4 import BeautifulSoup\nimport re\n\n# if no using some headers, wikiloc answers HTML error 503, probably they protect their servers against scrapping\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0',}\n\n\ndef main():\n print(\"##############################\")\n response=requests.get(\"http://www.muenchen.de/rathaus/Serviceangebote/familie/kinderbetreuung/corona.html#geschlossene-kitas-oder-kitagruppen-_6\", headers=headers)\n soup=BeautifulSoup(response.text, \"lxml\")\n p = soup.find(\"p\", text =re.compile(\"geschlossen\"))\n if p != None:\n kitaUl = p.findNext(\"ul\")\n kitaList = kitaUl.find_all(\"li\")\n # for kita in kitaList:\n # print(\"KITA: \" + kita.text)\n print(\"TOTAL closed Kitas=\", len(kitaList))\n else: \n print(\"Error, Kita list not found\")\n \n print(\"##############################\")\n response=requests.get(\"http://www.lgl.bayern.de/gesundheit/infektionsschutz/infektionskrankheiten_a_z/coronavirus/karte_coronavirus/\", headers=headers)\n soup2=BeautifulSoup(response.text, \"lxml\")\n munich = soup2.find(\"td\", text =re.compile(\"München Stadt\"))\n if munich != None:\n change = munich.findNext(\"td\").findNext(\"td\")\n average=change.findNext(\"td\").findNext(\"td\").findNext(\"td\")\n print(\"Munich 7-day average %s, today´s increase %s\" %(re.sub(r\"\\s+\", \"\", average.text), re.sub(r\"\\s+\", \"\", change.text)))\n else: \n print(\"Error, Munich row not found\")\n print(\"##############################\")\n exit\n\n\nif __name__ == \"__main__\":\n main()",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#!/usr/bin/python
import math
def Main():
try:
radius = float(input("Please enter the radius: "))
area = math.pi * radius**2
print("Area =", area)
except:
print("You did not enter a number")
if __name__ == "__main__":
Main()
|
normal
|
{
"blob_id": "33c4e0504425c5d22cefb9b4c798c3fd56a63771",
"index": 3641,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef Main():\n try:\n radius = float(input('Please enter the radius: '))\n area = math.pi * radius ** 2\n print('Area =', area)\n except:\n print('You did not enter a number')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef Main():\n try:\n radius = float(input('Please enter the radius: '))\n area = math.pi * radius ** 2\n print('Area =', area)\n except:\n print('You did not enter a number')\n\n\nif __name__ == '__main__':\n Main()\n",
"step-4": "import math\n\n\ndef Main():\n try:\n radius = float(input('Please enter the radius: '))\n area = math.pi * radius ** 2\n print('Area =', area)\n except:\n print('You did not enter a number')\n\n\nif __name__ == '__main__':\n Main()\n",
"step-5": "#!/usr/bin/python\nimport math\n\ndef Main():\n\ttry:\n\t\tradius = float(input(\"Please enter the radius: \"))\n\t\tarea = math.pi * radius**2\n\t\tprint(\"Area =\", area)\n\texcept:\n\t\tprint(\"You did not enter a number\")\n\nif __name__ == \"__main__\":\n\tMain()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class BackgroundCheck(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def predict_proba(self, x):
return self.prob_background(x)
class GaussianEstimation(object):
def __init__(self):
self.mu = None
self.cov = None
self.N = 0
def fit(self, x):
N = x.shape[1]
mu = np.mean(x, axis=0)
cov = np.cov(x, rowvar=False)
if self.N is 0:
self.N = N
self.mu = mu
self.k = len(mu)
self.cov = cov
else:
self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)
self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)
self.N += N
def likelihood(self, x):
return np.exp(self.log_likelihood(x))
def log_likelihood(self, x):
x_mu = x - self.mu
inverse = np.linalg.inv(self.cov)
exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])
return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.
log(2 * np.pi))
@property
def max(self):
return self.likelihood(self.mu.reshape(1, -1))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class BackgroundCheck(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def prob_foreground(self, x):
l = self.model.likelihood(x)
l_max = self.model.max
return np.true_divide(l, l_max)
def prob_background(self, x):
return 1 - self.prob_foreground(x)
def predict_proba(self, x):
return self.prob_background(x)
class GaussianEstimation(object):
def __init__(self):
self.mu = None
self.cov = None
self.N = 0
def fit(self, x):
N = x.shape[1]
mu = np.mean(x, axis=0)
cov = np.cov(x, rowvar=False)
if self.N is 0:
self.N = N
self.mu = mu
self.k = len(mu)
self.cov = cov
else:
self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)
self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)
self.N += N
def likelihood(self, x):
return np.exp(self.log_likelihood(x))
def log_likelihood(self, x):
x_mu = x - self.mu
inverse = np.linalg.inv(self.cov)
exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])
return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.
log(2 * np.pi))
@property
def max(self):
return self.likelihood(self.mu.reshape(1, -1))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class BackgroundCheck(object):
def __init__(self, model):
self.model = model
def fit(self, x):
self.model.fit(x)
def prob_foreground(self, x):
l = self.model.likelihood(x)
l_max = self.model.max
return np.true_divide(l, l_max)
def prob_background(self, x):
return 1 - self.prob_foreground(x)
def predict_proba(self, x):
return self.prob_background(x)
class GaussianEstimation(object):
def __init__(self):
self.mu = None
self.cov = None
self.N = 0
def fit(self, x):
N = x.shape[1]
mu = np.mean(x, axis=0)
cov = np.cov(x, rowvar=False)
if self.N is 0:
self.N = N
self.mu = mu
self.k = len(mu)
self.cov = cov
else:
self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)
self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)
self.N += N
def likelihood(self, x):
return np.exp(self.log_likelihood(x))
def log_likelihood(self, x):
x_mu = x - self.mu
inverse = np.linalg.inv(self.cov)
exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])
return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.
log(2 * np.pi))
@property
def max(self):
return self.likelihood(self.mu.reshape(1, -1))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def get_samples(n):
return np.random.multivariate_normal(mean=MU, cov=COV, size=n)
class BackgroundCheck(object):
def __init__(self, model):
self.model = model
def fit(self, x):
self.model.fit(x)
def prob_foreground(self, x):
l = self.model.likelihood(x)
l_max = self.model.max
return np.true_divide(l, l_max)
def prob_background(self, x):
return 1 - self.prob_foreground(x)
def predict_proba(self, x):
return self.prob_background(x)
class GaussianEstimation(object):
def __init__(self):
self.mu = None
self.cov = None
self.N = 0
def fit(self, x):
N = x.shape[1]
mu = np.mean(x, axis=0)
cov = np.cov(x, rowvar=False)
if self.N is 0:
self.N = N
self.mu = mu
self.k = len(mu)
self.cov = cov
else:
self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)
self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)
self.N += N
def likelihood(self, x):
return np.exp(self.log_likelihood(x))
def log_likelihood(self, x):
x_mu = x - self.mu
inverse = np.linalg.inv(self.cov)
exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])
return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.
log(2 * np.pi))
@property
def max(self):
return self.likelihood(self.mu.reshape(1, -1))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.lines import Line2D
np.random.seed(42)
n_samples = 5000
MU = np.array([0.5, 1.5])
COV = np.array([[1., 0.7], [0.7, 2.]])
def get_samples(n):
return np.random.multivariate_normal(mean=MU, cov=COV, size=n)
class BackgroundCheck(object):
def __init__(self, model):
self.model = model
def fit(self, x):
self.model.fit(x)
def prob_foreground(self, x):
l = self.model.likelihood(x)
l_max = self.model.max
return np.true_divide(l, l_max)
def prob_background(self, x):
return 1 - self.prob_foreground(x)
def predict_proba(self, x):
return self.prob_background(x)
class GaussianEstimation(object):
def __init__(self):
self.mu = None
self.cov = None
self.N = 0
def fit(self, x):
N = x.shape[1]
mu = np.mean(x, axis=0)
cov = np.cov(x, rowvar=False)
if self.N is 0:
self.N = N
self.mu = mu
self.k = len(mu)
self.cov = cov
else:
self.mu = np.true_divide((self.mu * self.N) + (mu * N), self.N + N)
self.cov = np.true_divide((self.cov * self.N) + (cov * N), self.N + N)
self.N += N
def likelihood(self, x):
return np.exp(self.log_likelihood(x))
def log_likelihood(self, x):
x_mu = x - self.mu
# a = np.array([[1, 2]])
# b = np.array([[1, 2],[3,4]])
# np.inner(np.inner(a, b.T), a)
inverse = np.linalg.inv(self.cov)
exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])
return - 0.5 * (
np.log(np.linalg.det(self.cov))
+ exp \
+ self.k * np.log(2*np.pi)
)
@property
def max(self):
return self.likelihood(self.mu.reshape(1,-1))
model = BackgroundCheck(GaussianEstimation())
for i in range(n_samples/2):
x = get_samples(2)
model.fit(x)
x = get_samples(n_samples)
p_foreground = 1 - model.predict_proba(x)
fig = plt.figure('scatter')
fig.clf()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x[:,0], x[:,1], p_foreground)
ax.set_xlabel('$x_0$')
ax.set_ylabel('$x_1$')
ax.set_zlabel('p_foreground')
fig.savefig('p_foreground_x.svg')
X = np.linspace(min(x[:,0]), max(x[:,0]), 30)
Y = np.linspace(min(x[:,1]), max(x[:,1]), 30)
X, Y = np.meshgrid(X, Y)
grid = np.concatenate((X.reshape(-1,1), Y.reshape(-1,1)), axis=1)
p_foreground = 1 - model.predict_proba(grid).reshape(X.shape[0], X.shape[1])
fig = plt.figure('surface')
fig.clf()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, p_foreground, cmap=cm.coolwarm)
ax.set_xlabel('$x_0$')
ax.set_ylabel('$x_1$')
ax.set_zlabel('p_foreground')
fig.savefig('p_foreground_grid.svg')
|
flexible
|
{
"blob_id": "d61b04539295f6b25e7f6589d32f313e3c6df82f",
"index": 1180,
"step-1": "<mask token>\n\n\nclass BackgroundCheck(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def predict_proba(self, x):\n return self.prob_background(x)\n\n\nclass GaussianEstimation(object):\n\n def __init__(self):\n self.mu = None\n self.cov = None\n self.N = 0\n\n def fit(self, x):\n N = x.shape[1]\n mu = np.mean(x, axis=0)\n cov = np.cov(x, rowvar=False)\n if self.N is 0:\n self.N = N\n self.mu = mu\n self.k = len(mu)\n self.cov = cov\n else:\n self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)\n self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)\n self.N += N\n\n def likelihood(self, x):\n return np.exp(self.log_likelihood(x))\n\n def log_likelihood(self, x):\n x_mu = x - self.mu\n inverse = np.linalg.inv(self.cov)\n exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])\n return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.\n log(2 * np.pi))\n\n @property\n def max(self):\n return self.likelihood(self.mu.reshape(1, -1))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass BackgroundCheck(object):\n <mask token>\n <mask token>\n\n def prob_foreground(self, x):\n l = self.model.likelihood(x)\n l_max = self.model.max\n return np.true_divide(l, l_max)\n\n def prob_background(self, x):\n return 1 - self.prob_foreground(x)\n\n def predict_proba(self, x):\n return self.prob_background(x)\n\n\nclass GaussianEstimation(object):\n\n def __init__(self):\n self.mu = None\n self.cov = None\n self.N = 0\n\n def fit(self, x):\n N = x.shape[1]\n mu = np.mean(x, axis=0)\n cov = np.cov(x, rowvar=False)\n if self.N is 0:\n self.N = N\n self.mu = mu\n self.k = len(mu)\n self.cov = cov\n else:\n self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)\n self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)\n self.N += N\n\n def likelihood(self, x):\n return np.exp(self.log_likelihood(x))\n\n def log_likelihood(self, x):\n x_mu = x - self.mu\n inverse = np.linalg.inv(self.cov)\n exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])\n return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.\n log(2 * np.pi))\n\n @property\n def max(self):\n return self.likelihood(self.mu.reshape(1, -1))\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass BackgroundCheck(object):\n\n def __init__(self, model):\n self.model = model\n\n def fit(self, x):\n self.model.fit(x)\n\n def prob_foreground(self, x):\n l = self.model.likelihood(x)\n l_max = self.model.max\n return np.true_divide(l, l_max)\n\n def prob_background(self, x):\n return 1 - self.prob_foreground(x)\n\n def predict_proba(self, x):\n return self.prob_background(x)\n\n\nclass GaussianEstimation(object):\n\n def __init__(self):\n self.mu = None\n self.cov = None\n self.N = 0\n\n def fit(self, x):\n N = x.shape[1]\n mu = np.mean(x, axis=0)\n cov = np.cov(x, rowvar=False)\n if self.N is 0:\n self.N = N\n self.mu = mu\n self.k = len(mu)\n self.cov = cov\n else:\n self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)\n self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)\n self.N += N\n\n def likelihood(self, x):\n return np.exp(self.log_likelihood(x))\n\n def log_likelihood(self, x):\n x_mu = x - self.mu\n inverse = np.linalg.inv(self.cov)\n exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])\n return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.\n log(2 * np.pi))\n\n @property\n def max(self):\n return self.likelihood(self.mu.reshape(1, -1))\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\ndef get_samples(n):\n return np.random.multivariate_normal(mean=MU, cov=COV, size=n)\n\n\nclass BackgroundCheck(object):\n\n def __init__(self, model):\n self.model = model\n\n def fit(self, x):\n self.model.fit(x)\n\n def prob_foreground(self, x):\n l = self.model.likelihood(x)\n l_max = self.model.max\n return np.true_divide(l, l_max)\n\n def prob_background(self, x):\n return 1 - self.prob_foreground(x)\n\n def predict_proba(self, x):\n return self.prob_background(x)\n\n\nclass GaussianEstimation(object):\n\n def __init__(self):\n self.mu = None\n self.cov = None\n self.N = 0\n\n def fit(self, x):\n N = x.shape[1]\n mu = np.mean(x, axis=0)\n cov = np.cov(x, rowvar=False)\n if self.N is 0:\n self.N = N\n self.mu = mu\n self.k = len(mu)\n self.cov = cov\n else:\n self.mu = np.true_divide(self.mu * self.N + mu * N, self.N + N)\n self.cov = np.true_divide(self.cov * self.N + cov * N, self.N + N)\n self.N += N\n\n def likelihood(self, x):\n return np.exp(self.log_likelihood(x))\n\n def log_likelihood(self, x):\n x_mu = x - self.mu\n inverse = np.linalg.inv(self.cov)\n exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])\n return -0.5 * (np.log(np.linalg.det(self.cov)) + exp + self.k * np.\n log(2 * np.pi))\n\n @property\n def max(self):\n return self.likelihood(self.mu.reshape(1, -1))\n\n\n<mask token>\n",
"step-5": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.lines import Line2D\n\nnp.random.seed(42)\n\nn_samples = 5000\nMU = np.array([0.5, 1.5])\nCOV = np.array([[1., 0.7], [0.7, 2.]])\n\ndef get_samples(n):\n return np.random.multivariate_normal(mean=MU, cov=COV, size=n)\n\nclass BackgroundCheck(object):\n def __init__(self, model):\n self.model = model\n\n def fit(self, x):\n self.model.fit(x)\n\n def prob_foreground(self, x):\n l = self.model.likelihood(x)\n l_max = self.model.max\n return np.true_divide(l, l_max)\n\n def prob_background(self, x):\n return 1 - self.prob_foreground(x)\n\n def predict_proba(self, x):\n return self.prob_background(x)\n\n\nclass GaussianEstimation(object):\n def __init__(self):\n self.mu = None\n self.cov = None\n self.N = 0\n\n def fit(self, x):\n N = x.shape[1]\n mu = np.mean(x, axis=0)\n cov = np.cov(x, rowvar=False)\n\n if self.N is 0:\n self.N = N\n self.mu = mu\n self.k = len(mu)\n self.cov = cov\n else:\n self.mu = np.true_divide((self.mu * self.N) + (mu * N), self.N + N)\n self.cov = np.true_divide((self.cov * self.N) + (cov * N), self.N + N)\n self.N += N\n\n def likelihood(self, x):\n return np.exp(self.log_likelihood(x))\n\n def log_likelihood(self, x):\n x_mu = x - self.mu\n # a = np.array([[1, 2]])\n # b = np.array([[1, 2],[3,4]])\n # np.inner(np.inner(a, b.T), a)\n inverse = np.linalg.inv(self.cov)\n exp = np.array([np.inner(np.inner(a, inverse.T), a) for a in x_mu])\n return - 0.5 * (\n np.log(np.linalg.det(self.cov))\n + exp \\\n + self.k * np.log(2*np.pi)\n )\n\n @property\n def max(self):\n return self.likelihood(self.mu.reshape(1,-1))\n\n\nmodel = BackgroundCheck(GaussianEstimation())\nfor i in range(n_samples/2):\n x = get_samples(2)\n model.fit(x)\n\nx = get_samples(n_samples)\n\np_foreground = 1 - model.predict_proba(x)\nfig = plt.figure('scatter')\nfig.clf()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x[:,0], x[:,1], p_foreground)\nax.set_xlabel('$x_0$')\nax.set_ylabel('$x_1$')\nax.set_zlabel('p_foreground')\nfig.savefig('p_foreground_x.svg')\n\n\nX = np.linspace(min(x[:,0]), max(x[:,0]), 30)\nY = np.linspace(min(x[:,1]), max(x[:,1]), 30)\nX, Y = np.meshgrid(X, Y)\n\ngrid = np.concatenate((X.reshape(-1,1), Y.reshape(-1,1)), axis=1)\np_foreground = 1 - model.predict_proba(grid).reshape(X.shape[0], X.shape[1])\n\nfig = plt.figure('surface')\nfig.clf()\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(X, Y, p_foreground, cmap=cm.coolwarm)\nax.set_xlabel('$x_0$')\nax.set_ylabel('$x_1$')\nax.set_zlabel('p_foreground')\nfig.savefig('p_foreground_grid.svg')\n",
"step-ids": [
8,
10,
12,
13,
17
]
}
|
[
8,
10,
12,
13,
17
] |
import sys
import array
import random
import math
import gameduino2.prep
import zlib
import struct
import gameduino as GD
from eve import align4
from PIL import Image
import numpy as np
import wave
import common
GLOWR = (128, 256)
GLOWR = (160, 400)
sys.path.append("/home/jamesb/git/gd2-asset/examples/nightstrike")
import night0
class Renderer(common.Branded):
def __init__(self, eve):
self.eve = eve
self.t = 0
def load(self):
eve = self.eve
eve.cc(open("/home/jamesb/git/gd2-asset/examples/nightstrike/night0.gd3", "rb").read())
def draw(self):
eve = self.eve
eve.VertexFormat(3)
eve.ClearColorRGB(0, 0, 100)
eve.Clear()
eve.Begin(GD.BITMAPS)
eve.BlendFunc(GD.SRC_ALPHA, 0)
night0.missile_a.draw(eve, 640, 360, 2, angle = self.t)
self.t += 1
|
normal
|
{
"blob_id": "2471daad5969da29a20417a099a3ecd92fa036b4",
"index": 6393,
"step-1": "<mask token>\n\n\nclass Renderer(common.Branded):\n\n def __init__(self, eve):\n self.eve = eve\n self.t = 0\n\n def load(self):\n eve = self.eve\n eve.cc(open(\n '/home/jamesb/git/gd2-asset/examples/nightstrike/night0.gd3',\n 'rb').read())\n\n def draw(self):\n eve = self.eve\n eve.VertexFormat(3)\n eve.ClearColorRGB(0, 0, 100)\n eve.Clear()\n eve.Begin(GD.BITMAPS)\n eve.BlendFunc(GD.SRC_ALPHA, 0)\n night0.missile_a.draw(eve, 640, 360, 2, angle=self.t)\n self.t += 1\n",
"step-2": "<mask token>\nsys.path.append('/home/jamesb/git/gd2-asset/examples/nightstrike')\n<mask token>\n\n\nclass Renderer(common.Branded):\n\n def __init__(self, eve):\n self.eve = eve\n self.t = 0\n\n def load(self):\n eve = self.eve\n eve.cc(open(\n '/home/jamesb/git/gd2-asset/examples/nightstrike/night0.gd3',\n 'rb').read())\n\n def draw(self):\n eve = self.eve\n eve.VertexFormat(3)\n eve.ClearColorRGB(0, 0, 100)\n eve.Clear()\n eve.Begin(GD.BITMAPS)\n eve.BlendFunc(GD.SRC_ALPHA, 0)\n night0.missile_a.draw(eve, 640, 360, 2, angle=self.t)\n self.t += 1\n",
"step-3": "<mask token>\nGLOWR = 128, 256\nGLOWR = 160, 400\nsys.path.append('/home/jamesb/git/gd2-asset/examples/nightstrike')\n<mask token>\n\n\nclass Renderer(common.Branded):\n\n def __init__(self, eve):\n self.eve = eve\n self.t = 0\n\n def load(self):\n eve = self.eve\n eve.cc(open(\n '/home/jamesb/git/gd2-asset/examples/nightstrike/night0.gd3',\n 'rb').read())\n\n def draw(self):\n eve = self.eve\n eve.VertexFormat(3)\n eve.ClearColorRGB(0, 0, 100)\n eve.Clear()\n eve.Begin(GD.BITMAPS)\n eve.BlendFunc(GD.SRC_ALPHA, 0)\n night0.missile_a.draw(eve, 640, 360, 2, angle=self.t)\n self.t += 1\n",
"step-4": "import sys\nimport array\nimport random\nimport math\nimport gameduino2.prep\nimport zlib\nimport struct\nimport gameduino as GD\nfrom eve import align4\nfrom PIL import Image\nimport numpy as np\nimport wave\nimport common\nGLOWR = 128, 256\nGLOWR = 160, 400\nsys.path.append('/home/jamesb/git/gd2-asset/examples/nightstrike')\nimport night0\n\n\nclass Renderer(common.Branded):\n\n def __init__(self, eve):\n self.eve = eve\n self.t = 0\n\n def load(self):\n eve = self.eve\n eve.cc(open(\n '/home/jamesb/git/gd2-asset/examples/nightstrike/night0.gd3',\n 'rb').read())\n\n def draw(self):\n eve = self.eve\n eve.VertexFormat(3)\n eve.ClearColorRGB(0, 0, 100)\n eve.Clear()\n eve.Begin(GD.BITMAPS)\n eve.BlendFunc(GD.SRC_ALPHA, 0)\n night0.missile_a.draw(eve, 640, 360, 2, angle=self.t)\n self.t += 1\n",
"step-5": "import sys\nimport array\nimport random\nimport math\nimport gameduino2.prep\nimport zlib\nimport struct\nimport gameduino as GD\nfrom eve import align4\n\nfrom PIL import Image\nimport numpy as np\nimport wave\nimport common\n\nGLOWR = (128, 256)\nGLOWR = (160, 400)\n\nsys.path.append(\"/home/jamesb/git/gd2-asset/examples/nightstrike\")\nimport night0\n\nclass Renderer(common.Branded):\n def __init__(self, eve):\n self.eve = eve\n self.t = 0\n\n def load(self):\n eve = self.eve\n\n eve.cc(open(\"/home/jamesb/git/gd2-asset/examples/nightstrike/night0.gd3\", \"rb\").read())\n\n def draw(self):\n eve = self.eve\n\n eve.VertexFormat(3)\n eve.ClearColorRGB(0, 0, 100)\n eve.Clear()\n\n eve.Begin(GD.BITMAPS)\n eve.BlendFunc(GD.SRC_ALPHA, 0)\n\n night0.missile_a.draw(eve, 640, 360, 2, angle = self.t)\n self.t += 1\n",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
'''
* @file IntQueue.py
* @author (original JAVA) William Fiset, william.alexandre.fiset@gmail.com
* liujingkun, liujkon@gmail.com
* (conversion to Python) Armin Zare Zadeh, ali.a.zarezadeh@gmail.com
* @date 23 Jun 2020
* @version 0.1
* @brief This file contains an implementation of an integer only queue.
*
'''
import time
from array import array as arr
from collections import deque
from Queue import Queue
class IntQueue(Queue):
'''
An integer only implementation of a queue
'''
def __init__(self, maxSize):
"""
maxSize is the maximum number of items
that can be in the queue at any given time
"""
self.front = 0
self.end = 0
self.qSize = 0
self.data = arr('i', (0 for i in range(maxSize)))
def isEmpty(self):
"""
Return true/false on whether the queue is empty
"""
return self.qSize == 0
def size(self):
"""
Return the number of elements inside the queue
"""
return self.qSize
def peek(self):
if self.isEmpty():
raise Exception('Queue is empty')
self.front = self.front % len(self.data)
return self.data[self.front]
def isFull(self):
return self.qSize == len(self.data)
def offer(self, value):
"""
Add an element to the queue
"""
if self.isFull():
raise Exception("Queue too small!")
self.data[self.end] = value
self.end += 1
self.qSize += 1
self.end = self.end % len(self.data)
def poll(self):
"""
Make sure you check is the queue is not empty before calling poll!
"""
if self.isEmpty():
raise Exception('Queue is empty')
self.qSize -= 1
self.front = self.front % len(self.data)
d = self.data[self.front]
self.front += 1
return d
def benchMarkTest():
"""
BenchMark IntQueue vs ArrayDeque.
"""
n = 10000000
intQ = IntQueue(n)
# IntQueue times at around 12.109375 seconds
start = time.process_time()
for i in range(0, n):
intQ.offer(i)
for i in range(0, n):
intQ.poll()
end = time.process_time()
print("IntQueue Time: ", (end - start))
# ArrayDeque times at around 1.1875 seconds
arrayDeque = deque()
start = time.process_time()
for i in range(0, n):
arrayDeque.append(i)
for i in range(0, n):
arrayDeque.popleft()
end = time.process_time()
print("ArrayDeque Time: ", (end - start))
if __name__ == '__main__':
"""
Example usage
"""
q = IntQueue(5)
q.offer(1)
q.offer(2)
q.offer(3)
q.offer(4)
q.offer(5)
print(q.poll()) # 1
print(q.poll()) # 2
print(q.poll()) # 3
print(q.poll()) # 4
print(q.isEmpty()) # false
q.offer(1);
q.offer(2);
q.offer(3);
print(q.poll()) # 5
print(q.poll()) # 1
print(q.poll()) # 2
print(q.poll()) # 3
print(q.isEmpty()) # true
benchMarkTest()
|
normal
|
{
"blob_id": "0ed99037d7ff708b7931fbc3553b1aeb19a20f53",
"index": 810,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass IntQueue(Queue):\n <mask token>\n\n def __init__(self, maxSize):\n \"\"\"\n maxSize is the maximum number of items\n that can be in the queue at any given time\n \"\"\"\n self.front = 0\n self.end = 0\n self.qSize = 0\n self.data = arr('i', (0 for i in range(maxSize)))\n\n def isEmpty(self):\n \"\"\"\n Return true/false on whether the queue is empty\n \"\"\"\n return self.qSize == 0\n\n def size(self):\n \"\"\"\n Return the number of elements inside the queue\n \"\"\"\n return self.qSize\n\n def peek(self):\n if self.isEmpty():\n raise Exception('Queue is empty')\n self.front = self.front % len(self.data)\n return self.data[self.front]\n\n def isFull(self):\n return self.qSize == len(self.data)\n\n def offer(self, value):\n \"\"\"\n Add an element to the queue\n \"\"\"\n if self.isFull():\n raise Exception('Queue too small!')\n self.data[self.end] = value\n self.end += 1\n self.qSize += 1\n self.end = self.end % len(self.data)\n\n def poll(self):\n \"\"\"\n Make sure you check is the queue is not empty before calling poll!\n \"\"\"\n if self.isEmpty():\n raise Exception('Queue is empty')\n self.qSize -= 1\n self.front = self.front % len(self.data)\n d = self.data[self.front]\n self.front += 1\n return d\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass IntQueue(Queue):\n \"\"\" \n An integer only implementation of a queue\n \"\"\"\n\n def __init__(self, maxSize):\n \"\"\"\n maxSize is the maximum number of items\n that can be in the queue at any given time\n \"\"\"\n self.front = 0\n self.end = 0\n self.qSize = 0\n self.data = arr('i', (0 for i in range(maxSize)))\n\n def isEmpty(self):\n \"\"\"\n Return true/false on whether the queue is empty\n \"\"\"\n return self.qSize == 0\n\n def size(self):\n \"\"\"\n Return the number of elements inside the queue\n \"\"\"\n return self.qSize\n\n def peek(self):\n if self.isEmpty():\n raise Exception('Queue is empty')\n self.front = self.front % len(self.data)\n return self.data[self.front]\n\n def isFull(self):\n return self.qSize == len(self.data)\n\n def offer(self, value):\n \"\"\"\n Add an element to the queue\n \"\"\"\n if self.isFull():\n raise Exception('Queue too small!')\n self.data[self.end] = value\n self.end += 1\n self.qSize += 1\n self.end = self.end % len(self.data)\n\n def poll(self):\n \"\"\"\n Make sure you check is the queue is not empty before calling poll!\n \"\"\"\n if self.isEmpty():\n raise Exception('Queue is empty')\n self.qSize -= 1\n self.front = self.front % len(self.data)\n d = self.data[self.front]\n self.front += 1\n return d\n\n\ndef benchMarkTest():\n \"\"\"\n BenchMark IntQueue vs ArrayDeque.\n \"\"\"\n n = 10000000\n intQ = IntQueue(n)\n start = time.process_time()\n for i in range(0, n):\n intQ.offer(i)\n for i in range(0, n):\n intQ.poll()\n end = time.process_time()\n print('IntQueue Time: ', end - start)\n arrayDeque = deque()\n start = time.process_time()\n for i in range(0, n):\n arrayDeque.append(i)\n for i in range(0, n):\n arrayDeque.popleft()\n end = time.process_time()\n print('ArrayDeque Time: ', end - start)\n\n\nif __name__ == '__main__':\n \"\"\"\n Example usage\n \"\"\"\n q = IntQueue(5)\n q.offer(1)\n q.offer(2)\n q.offer(3)\n q.offer(4)\n q.offer(5)\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.isEmpty())\n q.offer(1)\n q.offer(2)\n q.offer(3)\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.isEmpty())\n benchMarkTest()\n",
"step-4": "<mask token>\nimport time\nfrom array import array as arr\nfrom collections import deque\nfrom Queue import Queue\n\n\nclass IntQueue(Queue):\n \"\"\" \n An integer only implementation of a queue\n \"\"\"\n\n def __init__(self, maxSize):\n \"\"\"\n maxSize is the maximum number of items\n that can be in the queue at any given time\n \"\"\"\n self.front = 0\n self.end = 0\n self.qSize = 0\n self.data = arr('i', (0 for i in range(maxSize)))\n\n def isEmpty(self):\n \"\"\"\n Return true/false on whether the queue is empty\n \"\"\"\n return self.qSize == 0\n\n def size(self):\n \"\"\"\n Return the number of elements inside the queue\n \"\"\"\n return self.qSize\n\n def peek(self):\n if self.isEmpty():\n raise Exception('Queue is empty')\n self.front = self.front % len(self.data)\n return self.data[self.front]\n\n def isFull(self):\n return self.qSize == len(self.data)\n\n def offer(self, value):\n \"\"\"\n Add an element to the queue\n \"\"\"\n if self.isFull():\n raise Exception('Queue too small!')\n self.data[self.end] = value\n self.end += 1\n self.qSize += 1\n self.end = self.end % len(self.data)\n\n def poll(self):\n \"\"\"\n Make sure you check is the queue is not empty before calling poll!\n \"\"\"\n if self.isEmpty():\n raise Exception('Queue is empty')\n self.qSize -= 1\n self.front = self.front % len(self.data)\n d = self.data[self.front]\n self.front += 1\n return d\n\n\ndef benchMarkTest():\n \"\"\"\n BenchMark IntQueue vs ArrayDeque.\n \"\"\"\n n = 10000000\n intQ = IntQueue(n)\n start = time.process_time()\n for i in range(0, n):\n intQ.offer(i)\n for i in range(0, n):\n intQ.poll()\n end = time.process_time()\n print('IntQueue Time: ', end - start)\n arrayDeque = deque()\n start = time.process_time()\n for i in range(0, n):\n arrayDeque.append(i)\n for i in range(0, n):\n arrayDeque.popleft()\n end = time.process_time()\n print('ArrayDeque Time: ', end - start)\n\n\nif __name__ == '__main__':\n \"\"\"\n Example usage\n \"\"\"\n q = IntQueue(5)\n q.offer(1)\n q.offer(2)\n q.offer(3)\n q.offer(4)\n q.offer(5)\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.isEmpty())\n q.offer(1)\n q.offer(2)\n q.offer(3)\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.poll())\n print(q.isEmpty())\n benchMarkTest()\n",
"step-5": "'''\n * @file IntQueue.py\n * @author (original JAVA) William Fiset, william.alexandre.fiset@gmail.com\n * liujingkun, liujkon@gmail.com\n * (conversion to Python) Armin Zare Zadeh, ali.a.zarezadeh@gmail.com\n * @date 23 Jun 2020\n * @version 0.1\n * @brief This file contains an implementation of an integer only queue.\n * \n'''\n\nimport time\nfrom array import array as arr\nfrom collections import deque\nfrom Queue import Queue\n\n\nclass IntQueue(Queue):\n ''' \n An integer only implementation of a queue\n '''\n def __init__(self, maxSize):\n \"\"\"\n maxSize is the maximum number of items\n that can be in the queue at any given time\n \"\"\" \n self.front = 0\n self.end = 0\n self.qSize = 0\n self.data = arr('i', (0 for i in range(maxSize)))\n\n\n def isEmpty(self):\n \"\"\"\n Return true/false on whether the queue is empty\n \"\"\"\n return self.qSize == 0\n\n\n def size(self):\n \"\"\"\n Return the number of elements inside the queue\n \"\"\" \n return self.qSize\n\n\n def peek(self):\n if self.isEmpty():\n raise Exception('Queue is empty')\n \n self.front = self.front % len(self.data)\n return self.data[self.front]\n\n\n def isFull(self):\n return self.qSize == len(self.data)\n\n\n def offer(self, value):\n \"\"\"\n Add an element to the queue\n \"\"\"\n if self.isFull():\n raise Exception(\"Queue too small!\")\n \n self.data[self.end] = value\n self.end += 1\n self.qSize += 1\n self.end = self.end % len(self.data)\n\n\n def poll(self):\n \"\"\"\n Make sure you check is the queue is not empty before calling poll!\n \"\"\"\n if self.isEmpty():\n raise Exception('Queue is empty')\n \n self.qSize -= 1\n self.front = self.front % len(self.data)\n d = self.data[self.front]\n self.front += 1\n return d\n\n\n\ndef benchMarkTest():\n \"\"\"\n BenchMark IntQueue vs ArrayDeque.\n \"\"\" \n\n n = 10000000\n intQ = IntQueue(n)\n\n # IntQueue times at around 12.109375 seconds\n start = time.process_time()\n for i in range(0, n):\n intQ.offer(i)\n for i in range(0, n):\n intQ.poll()\n end = time.process_time()\n print(\"IntQueue Time: \", (end - start))\n\n # ArrayDeque times at around 1.1875 seconds\n arrayDeque = deque()\n start = time.process_time()\n for i in range(0, n):\n arrayDeque.append(i)\n for i in range(0, n):\n arrayDeque.popleft()\n end = time.process_time()\n print(\"ArrayDeque Time: \", (end - start))\n\n\n\nif __name__ == '__main__':\n \"\"\"\n Example usage\n \"\"\"\n\n q = IntQueue(5)\n\n q.offer(1)\n q.offer(2)\n q.offer(3)\n q.offer(4)\n q.offer(5)\n\n print(q.poll()) # 1\n print(q.poll()) # 2\n print(q.poll()) # 3\n print(q.poll()) # 4\n\n print(q.isEmpty()) # false\n\n q.offer(1);\n q.offer(2);\n q.offer(3);\n\n print(q.poll()) # 5\n print(q.poll()) # 1\n print(q.poll()) # 2\n print(q.poll()) # 3\n\n print(q.isEmpty()) # true\n\n benchMarkTest()\n",
"step-ids": [
0,
8,
11,
12,
13
]
}
|
[
0,
8,
11,
12,
13
] |
'''
Author: Iris Peng. Date: Feb 21, 2016
Usage: Scrape Weibo posts from Zhongsou for the first time for a query
In the terminal, type
$ python3 scrape_weibo.py
and follow the prompts
'''
import requests
from bs4 import BeautifulSoup
from pandas import DataFrame
import time
import pandas
import glob, os
global QUERY_LINK
QUERY_LINK = 'http://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%B1%C6'#link
global OUTPUT_FILE_NAME
OUTPUT_FILE_NAME = 'scrape' # Name of your output file
global WORKING_DIR
WORKING_DIR = '~/Corpora/'
global OLD_MASTER_FILE
OLD_MASTER_FILE = '{}Text_data/'.format(WORKING_DIR) + 'yeshizuile.txt' #Feed the new output
class NewScrape():
def scrape_main(self):
'''
Top-level function.
Use links from below, scrape a page, sleep for 5s, and restart on the next link.
'''
for i in self.gen_links():
index = str(self.gen_links().index(i))
link = i
self.get_weibo(link,index)
time.sleep(5)
self.retrieve_posts(OUTPUT_FILE_NAME)
#self.clean_temp()
print('='*10)
print('Congratulations! Your data is stored')
return None
def gen_links(self):
links = []
for i in range(1,51):
i = str(i)
links.append('{}&b={}'.format(QUERY_LINK,i))
return links
def get_weibo(self,link,index):
'''
Scrape a certain weibio search result page on 'zhongsou' and store it in locally.
'''
html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR),'w', encoding = 'utf8')
r = requests.get(link)
print ('accessing web data.')
html_doc.write(r.text)
html_doc.close()
# Write into a csv file
outfile_name = 'zhongsou_results_page_' + index + '.csv'
outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name,'w', encoding = 'utf8') #change path
# Turn the text into a BeautifulSoup object and strip down the text.
html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR),'r', encoding = 'utf8')#change path
soup = BeautifulSoup(html_doc)
user_link = []
post_txt = []
post_link = []
post_time = []
weibo_items = soup.find_all('div', class_='weibo_item')
for item in weibo_items:
for link in item.find_all('a', target='_blank', class_='sina_weibo'):
url = link.get('href')
post_link.append(url)
for post in item.find_all('h3', class_='weibo_title'):
for a in post.find_all('a'):
url = a.get('href')
user_link.append(url)
for time in item.find_all('div', class_='weibo_time'):
txt = time.get_text()
post_time.append(txt)
for post in item.find_all('p', class_='weibo_txt'):
txt = post.get_text()
post_txt.append(txt)
data = {'post_text':post_txt,'post_link':post_link,'user':user_link, 'time':post_time}
frame = DataFrame(data)
frame.to_csv(outfile, encoding='utf-8')
print (outfile_name,'processed complete.')
outfile.close()
html_doc.close()
return None
def clean_temp(self):
filelist = glob.glob('{}Temp/*'.format(WORKING_DIR))
for f in filelist:
os.remove(f)
print('Temp files removed')
return None
def retrieve_posts(self,outfile_name):
'''(str)->a file
'''
post_text = []
for i in range(50):
frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'.format(WORKING_DIR, str(i)))#change directory
df2 = DataFrame(frame_2)
for i in df2.post_text:#the column'post_text'
post_text.append(i)
data = {'post_text':post_text}
frame = DataFrame(data)
frame.to_csv('{}Text_data/{}.txt'.format(WORKING_DIR, outfile_name), encoding = 'utf-8')#change saved path
frame.to_excel('{}Text_data/{}.xlsx'.format(WORKING_DIR, outfile_name), encoding = 'utf-8')#change saved path
print("Done")
return None
class ContinueScrape():
def scrape_main(self):
'''
Top-level function.
Use links from below, scrape a page, sleep for 5s, and restart on the next link.
'''
for i in self.gen_links():
index = str(self.gen_links().index(i))
link = i
cmd = self.get_weibo(link,index)
if cmd == 'STOP':
break
else:
time.sleep(10)
continue
print('='*10)
print('Scrape is now complete. Help me to organize them.')
print ('View your temp folder, what is the biggest number of the files? \n')
fn = int(input())
self.retrieve_posts(fn)
print('='*10)
print('Congratulations! Your data is stored')
return
def gen_links(self):
links = []
for i in range(1,51):
i = str(i)
links.append('{}&b={}'.format(QUERY_LINK,i))
return links
def get_weibo(self,link,index):
'''
Scrape a certain weibio search result page on 'zhongsou' and store it in locally.
'''
html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w', encoding='utf8')
r = requests.get(link)
print ('Accessing web data.')
html_doc.write(r.text)
html_doc.close()
# Retrieve scrape history
h_post_text = []
h_frame = pandas.read_csv(OLD_MASTER_FILE)
h_df = DataFrame(h_frame)
for i in h_df.post_text:
h_post_text.append(i)
# Write into a csv file
outfile_name = 'zhongsou_results_page_' + index + '.csv'
outfile = open('{}Temp/'.format(WORKING_DIR)+ outfile_name,'w', encoding = 'utf8') #change path
# Turn the text into a BeautifulSoup object and strip down the text.
html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r', encoding='utf8')
soup = BeautifulSoup(html_doc)
user_link = []
post_txt = []
post_link = []
post_time = []
cmd = None
weibo_items = soup.find_all('div', class_='weibo_item')
for item in weibo_items:
for link in item.find_all('a', target='_blank', class_='sina_weibo'):
url = link.get('href')
post_link.append(url)
for post in item.find_all('h3', class_='weibo_title'):
for a in post.find_all('a'):
url = a.get('href')
user_link.append(url)
for time in item.find_all('div', class_='weibo_time'):
txt = time.get_text()
post_time.append(txt)
for post in item.find_all('p', class_='weibo_txt'):
txt = post.get_text()
post_txt.append(txt)
#has bugs!
#if txt in h_post_text:
if txt == h_post_text[0]:
print (txt)
print(' ___ exists')
print ('End of new data.') #Doesn't affect main function, break should be in main function
del post_link[-1]
del user_link[-1]
del post_time[-1]
del post_txt[-1]
cmd = 'STOP'
break
data = {'post_text':post_txt,'post_link':post_link,'user':user_link, 'time':post_time}
frame = DataFrame(data)
frame.to_csv(outfile, encoding='utf-8')
print (outfile_name,'processed complete.')
outfile.close()
html_doc.close()
return cmd
def retrieve_posts(self,file_number_total):
'''(int)->a file
'''
post_text = []
for i in range(file_number_total+1):
frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'.format(WORKING_DIR, str(i)))
df2 = DataFrame(frame_2)
for i in df2.post_text:#the column'post_text'
post_text.append(i)
frame_1 = pandas.read_csv(OLD_MASTER_FILE)
df1 = DataFrame(frame_1)
for i in df1.post_text:
post_text.append(i)
data = {'post_text':post_text}
frame = DataFrame(data)
frame.to_csv('{}Text_data/{}_2.txt'.format(WORKING_DIR, OUTPUT_FILE_NAME), encoding = 'utf-8')#saved path
frame.to_excel('{}Text_data/{}_2.xlsx'.format(WORKING_DIR, OUTPUT_FILE_NAME), encoding = 'utf-8')#saved path
print("Data gathered.")
## filelist = glob.glob('{}Temp/*'.format(WORKING_DIR))
## for f in filelist:
## os.remove(f)
#os.remove(OLD_MASTER_FILE)
print('Temp files removed')
return None
print('='*10)
print('This program will help you collect Weibo language data as generated by the 中搜 search results.\n')
print('Use this page to generate a link for your query item:\n\nhttp://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%CD%F8%D3%EF')
QUERY_LINK = input('\nPaste your query link \n> ')
OUTPUT_FILE_NAME = input('\nWhat\'s your query term? (This will be used as file name)\n> ')
resp = input('\nIs this your first time running this query? Y/N\n> ').upper()
if resp == 'Y':
print()
print('='*10)
print('Initialize scraping now.')
print('='*10)
NewScrape().scrape_main()
elif resp == 'N':
OLD_MASTER_FILE = input('\nWhere is the old txt file you want to merge later? Please paste full path. \n> ')
print()
print('='*10)
print('WARNING: FURTHER ACTIONS NEEDED AT THE END OF SCRAPING.')
print('Initialize scraping now.')
print('='*10)
ContinueScrape().scrape_main()
else:
print('Invalid command. Try again.')
|
normal
|
{
"blob_id": "ed3fbae19c88100690dd5c558c0dc6d36a4849c8",
"index": 1451,
"step-1": "<mask token>\n\n\nclass NewScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n self.get_weibo(link, index)\n time.sleep(5)\n self.retrieve_posts(OUTPUT_FILE_NAME)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return None\n <mask token>\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return None\n <mask token>\n\n def retrieve_posts(self, outfile_name):\n \"\"\"(str)->a file\n \"\"\"\n post_text = []\n for i in range(50):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}.txt'.format(WORKING_DIR, outfile_name),\n encoding='utf-8')\n frame.to_excel('{}Text_data/{}.xlsx'.format(WORKING_DIR,\n outfile_name), encoding='utf-8')\n print('Done')\n return None\n\n\nclass ContinueScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n cmd = self.get_weibo(link, index)\n if cmd == 'STOP':\n break\n else:\n time.sleep(10)\n continue\n print('=' * 10)\n print('Scrape is now complete. Help me to organize them.')\n print(\n 'View your temp folder, what is the biggest number of the files? \\n'\n )\n fn = int(input())\n self.retrieve_posts(fn)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return\n\n def gen_links(self):\n links = []\n for i in range(1, 51):\n i = str(i)\n links.append('{}&b={}'.format(QUERY_LINK, i))\n return links\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('Accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n h_post_text = []\n h_frame = pandas.read_csv(OLD_MASTER_FILE)\n h_df = DataFrame(h_frame)\n for i in h_df.post_text:\n h_post_text.append(i)\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n cmd = None\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n if txt == h_post_text[0]:\n print(txt)\n print(' ___ exists')\n print('End of new data.')\n del post_link[-1]\n del user_link[-1]\n del post_time[-1]\n del post_txt[-1]\n cmd = 'STOP'\n break\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return cmd\n\n def retrieve_posts(self, file_number_total):\n \"\"\"(int)->a file\n \"\"\"\n post_text = []\n for i in range(file_number_total + 1):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n frame_1 = pandas.read_csv(OLD_MASTER_FILE)\n df1 = DataFrame(frame_1)\n for i in df1.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}_2.txt'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n frame.to_excel('{}Text_data/{}_2.xlsx'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n print('Data gathered.')\n print('Temp files removed')\n return None\n\n\n<mask token>\n",
"step-2": "<mask token>\nglobal QUERY_LINK\n<mask token>\nglobal OUTPUT_FILE_NAME\n<mask token>\nglobal WORKING_DIR\n<mask token>\nglobal OLD_MASTER_FILE\n<mask token>\n\n\nclass NewScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n self.get_weibo(link, index)\n time.sleep(5)\n self.retrieve_posts(OUTPUT_FILE_NAME)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return None\n\n def gen_links(self):\n links = []\n for i in range(1, 51):\n i = str(i)\n links.append('{}&b={}'.format(QUERY_LINK, i))\n return links\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return None\n\n def clean_temp(self):\n filelist = glob.glob('{}Temp/*'.format(WORKING_DIR))\n for f in filelist:\n os.remove(f)\n print('Temp files removed')\n return None\n\n def retrieve_posts(self, outfile_name):\n \"\"\"(str)->a file\n \"\"\"\n post_text = []\n for i in range(50):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}.txt'.format(WORKING_DIR, outfile_name),\n encoding='utf-8')\n frame.to_excel('{}Text_data/{}.xlsx'.format(WORKING_DIR,\n outfile_name), encoding='utf-8')\n print('Done')\n return None\n\n\nclass ContinueScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n cmd = self.get_weibo(link, index)\n if cmd == 'STOP':\n break\n else:\n time.sleep(10)\n continue\n print('=' * 10)\n print('Scrape is now complete. Help me to organize them.')\n print(\n 'View your temp folder, what is the biggest number of the files? \\n'\n )\n fn = int(input())\n self.retrieve_posts(fn)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return\n\n def gen_links(self):\n links = []\n for i in range(1, 51):\n i = str(i)\n links.append('{}&b={}'.format(QUERY_LINK, i))\n return links\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('Accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n h_post_text = []\n h_frame = pandas.read_csv(OLD_MASTER_FILE)\n h_df = DataFrame(h_frame)\n for i in h_df.post_text:\n h_post_text.append(i)\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n cmd = None\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n if txt == h_post_text[0]:\n print(txt)\n print(' ___ exists')\n print('End of new data.')\n del post_link[-1]\n del user_link[-1]\n del post_time[-1]\n del post_txt[-1]\n cmd = 'STOP'\n break\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return cmd\n\n def retrieve_posts(self, file_number_total):\n \"\"\"(int)->a file\n \"\"\"\n post_text = []\n for i in range(file_number_total + 1):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n frame_1 = pandas.read_csv(OLD_MASTER_FILE)\n df1 = DataFrame(frame_1)\n for i in df1.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}_2.txt'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n frame.to_excel('{}Text_data/{}_2.xlsx'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n print('Data gathered.')\n print('Temp files removed')\n return None\n\n\nprint('=' * 10)\nprint(\n \"\"\"This program will help you collect Weibo language data as generated by the 中搜 search results.\n\"\"\"\n )\nprint(\n \"\"\"Use this page to generate a link for your query item:\n\nhttp://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%CD%F8%D3%EF\"\"\"\n )\n<mask token>\nif resp == 'Y':\n print()\n print('=' * 10)\n print('Initialize scraping now.')\n print('=' * 10)\n NewScrape().scrape_main()\nelif resp == 'N':\n OLD_MASTER_FILE = input(\n \"\"\"\nWhere is the old txt file you want to merge later? Please paste full path. \n> \"\"\"\n )\n print()\n print('=' * 10)\n print('WARNING: FURTHER ACTIONS NEEDED AT THE END OF SCRAPING.')\n print('Initialize scraping now.')\n print('=' * 10)\n ContinueScrape().scrape_main()\nelse:\n print('Invalid command. Try again.')\n",
"step-3": "<mask token>\nglobal QUERY_LINK\nQUERY_LINK = (\n 'http://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%B1%C6'\n )\nglobal OUTPUT_FILE_NAME\nOUTPUT_FILE_NAME = 'scrape'\nglobal WORKING_DIR\nWORKING_DIR = '~/Corpora/'\nglobal OLD_MASTER_FILE\nOLD_MASTER_FILE = '{}Text_data/'.format(WORKING_DIR) + 'yeshizuile.txt'\n\n\nclass NewScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n self.get_weibo(link, index)\n time.sleep(5)\n self.retrieve_posts(OUTPUT_FILE_NAME)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return None\n\n def gen_links(self):\n links = []\n for i in range(1, 51):\n i = str(i)\n links.append('{}&b={}'.format(QUERY_LINK, i))\n return links\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return None\n\n def clean_temp(self):\n filelist = glob.glob('{}Temp/*'.format(WORKING_DIR))\n for f in filelist:\n os.remove(f)\n print('Temp files removed')\n return None\n\n def retrieve_posts(self, outfile_name):\n \"\"\"(str)->a file\n \"\"\"\n post_text = []\n for i in range(50):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}.txt'.format(WORKING_DIR, outfile_name),\n encoding='utf-8')\n frame.to_excel('{}Text_data/{}.xlsx'.format(WORKING_DIR,\n outfile_name), encoding='utf-8')\n print('Done')\n return None\n\n\nclass ContinueScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n cmd = self.get_weibo(link, index)\n if cmd == 'STOP':\n break\n else:\n time.sleep(10)\n continue\n print('=' * 10)\n print('Scrape is now complete. Help me to organize them.')\n print(\n 'View your temp folder, what is the biggest number of the files? \\n'\n )\n fn = int(input())\n self.retrieve_posts(fn)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return\n\n def gen_links(self):\n links = []\n for i in range(1, 51):\n i = str(i)\n links.append('{}&b={}'.format(QUERY_LINK, i))\n return links\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('Accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n h_post_text = []\n h_frame = pandas.read_csv(OLD_MASTER_FILE)\n h_df = DataFrame(h_frame)\n for i in h_df.post_text:\n h_post_text.append(i)\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n cmd = None\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n if txt == h_post_text[0]:\n print(txt)\n print(' ___ exists')\n print('End of new data.')\n del post_link[-1]\n del user_link[-1]\n del post_time[-1]\n del post_txt[-1]\n cmd = 'STOP'\n break\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return cmd\n\n def retrieve_posts(self, file_number_total):\n \"\"\"(int)->a file\n \"\"\"\n post_text = []\n for i in range(file_number_total + 1):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n frame_1 = pandas.read_csv(OLD_MASTER_FILE)\n df1 = DataFrame(frame_1)\n for i in df1.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}_2.txt'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n frame.to_excel('{}Text_data/{}_2.xlsx'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n print('Data gathered.')\n print('Temp files removed')\n return None\n\n\nprint('=' * 10)\nprint(\n \"\"\"This program will help you collect Weibo language data as generated by the 中搜 search results.\n\"\"\"\n )\nprint(\n \"\"\"Use this page to generate a link for your query item:\n\nhttp://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%CD%F8%D3%EF\"\"\"\n )\nQUERY_LINK = input(\"\"\"\nPaste your query link \n> \"\"\")\nOUTPUT_FILE_NAME = input(\n \"\"\"\nWhat's your query term? (This will be used as file name)\n> \"\"\")\nresp = input(\"\"\"\nIs this your first time running this query? Y/N\n> \"\"\").upper()\nif resp == 'Y':\n print()\n print('=' * 10)\n print('Initialize scraping now.')\n print('=' * 10)\n NewScrape().scrape_main()\nelif resp == 'N':\n OLD_MASTER_FILE = input(\n \"\"\"\nWhere is the old txt file you want to merge later? Please paste full path. \n> \"\"\"\n )\n print()\n print('=' * 10)\n print('WARNING: FURTHER ACTIONS NEEDED AT THE END OF SCRAPING.')\n print('Initialize scraping now.')\n print('=' * 10)\n ContinueScrape().scrape_main()\nelse:\n print('Invalid command. Try again.')\n",
"step-4": "<mask token>\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pandas import DataFrame\nimport time\nimport pandas\nimport glob, os\nglobal QUERY_LINK\nQUERY_LINK = (\n 'http://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%B1%C6'\n )\nglobal OUTPUT_FILE_NAME\nOUTPUT_FILE_NAME = 'scrape'\nglobal WORKING_DIR\nWORKING_DIR = '~/Corpora/'\nglobal OLD_MASTER_FILE\nOLD_MASTER_FILE = '{}Text_data/'.format(WORKING_DIR) + 'yeshizuile.txt'\n\n\nclass NewScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n self.get_weibo(link, index)\n time.sleep(5)\n self.retrieve_posts(OUTPUT_FILE_NAME)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return None\n\n def gen_links(self):\n links = []\n for i in range(1, 51):\n i = str(i)\n links.append('{}&b={}'.format(QUERY_LINK, i))\n return links\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return None\n\n def clean_temp(self):\n filelist = glob.glob('{}Temp/*'.format(WORKING_DIR))\n for f in filelist:\n os.remove(f)\n print('Temp files removed')\n return None\n\n def retrieve_posts(self, outfile_name):\n \"\"\"(str)->a file\n \"\"\"\n post_text = []\n for i in range(50):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}.txt'.format(WORKING_DIR, outfile_name),\n encoding='utf-8')\n frame.to_excel('{}Text_data/{}.xlsx'.format(WORKING_DIR,\n outfile_name), encoding='utf-8')\n print('Done')\n return None\n\n\nclass ContinueScrape:\n\n def scrape_main(self):\n \"\"\"\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n \"\"\"\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n cmd = self.get_weibo(link, index)\n if cmd == 'STOP':\n break\n else:\n time.sleep(10)\n continue\n print('=' * 10)\n print('Scrape is now complete. Help me to organize them.')\n print(\n 'View your temp folder, what is the biggest number of the files? \\n'\n )\n fn = int(input())\n self.retrieve_posts(fn)\n print('=' * 10)\n print('Congratulations! Your data is stored')\n return\n\n def gen_links(self):\n links = []\n for i in range(1, 51):\n i = str(i)\n links.append('{}&b={}'.format(QUERY_LINK, i))\n return links\n\n def get_weibo(self, link, index):\n \"\"\"\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n \"\"\"\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w',\n encoding='utf8')\n r = requests.get(link)\n print('Accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n h_post_text = []\n h_frame = pandas.read_csv(OLD_MASTER_FILE)\n h_df = DataFrame(h_frame)\n for i in h_df.post_text:\n h_post_text.append(i)\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name, 'w',\n encoding='utf8')\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r',\n encoding='utf8')\n soup = BeautifulSoup(html_doc)\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n cmd = None\n weibo_items = soup.find_all('div', class_='weibo_item')\n for item in weibo_items:\n for link in item.find_all('a', target='_blank', class_='sina_weibo'\n ):\n url = link.get('href')\n post_link.append(url)\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n if txt == h_post_text[0]:\n print(txt)\n print(' ___ exists')\n print('End of new data.')\n del post_link[-1]\n del user_link[-1]\n del post_time[-1]\n del post_txt[-1]\n cmd = 'STOP'\n break\n data = {'post_text': post_txt, 'post_link': post_link, 'user':\n user_link, 'time': post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print(outfile_name, 'processed complete.')\n outfile.close()\n html_doc.close()\n return cmd\n\n def retrieve_posts(self, file_number_total):\n \"\"\"(int)->a file\n \"\"\"\n post_text = []\n for i in range(file_number_total + 1):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'\n .format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:\n post_text.append(i)\n frame_1 = pandas.read_csv(OLD_MASTER_FILE)\n df1 = DataFrame(frame_1)\n for i in df1.post_text:\n post_text.append(i)\n data = {'post_text': post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}_2.txt'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n frame.to_excel('{}Text_data/{}_2.xlsx'.format(WORKING_DIR,\n OUTPUT_FILE_NAME), encoding='utf-8')\n print('Data gathered.')\n print('Temp files removed')\n return None\n\n\nprint('=' * 10)\nprint(\n \"\"\"This program will help you collect Weibo language data as generated by the 中搜 search results.\n\"\"\"\n )\nprint(\n \"\"\"Use this page to generate a link for your query item:\n\nhttp://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%CD%F8%D3%EF\"\"\"\n )\nQUERY_LINK = input(\"\"\"\nPaste your query link \n> \"\"\")\nOUTPUT_FILE_NAME = input(\n \"\"\"\nWhat's your query term? (This will be used as file name)\n> \"\"\")\nresp = input(\"\"\"\nIs this your first time running this query? Y/N\n> \"\"\").upper()\nif resp == 'Y':\n print()\n print('=' * 10)\n print('Initialize scraping now.')\n print('=' * 10)\n NewScrape().scrape_main()\nelif resp == 'N':\n OLD_MASTER_FILE = input(\n \"\"\"\nWhere is the old txt file you want to merge later? Please paste full path. \n> \"\"\"\n )\n print()\n print('=' * 10)\n print('WARNING: FURTHER ACTIONS NEEDED AT THE END OF SCRAPING.')\n print('Initialize scraping now.')\n print('=' * 10)\n ContinueScrape().scrape_main()\nelse:\n print('Invalid command. Try again.')\n",
"step-5": "'''\nAuthor: Iris Peng. Date: Feb 21, 2016\nUsage: Scrape Weibo posts from Zhongsou for the first time for a query\n\nIn the terminal, type\n$ python3 scrape_weibo.py\n\nand follow the prompts\n\n'''\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pandas import DataFrame\nimport time\nimport pandas\nimport glob, os\n\n\nglobal QUERY_LINK\nQUERY_LINK = 'http://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%B1%C6'#link\n\nglobal OUTPUT_FILE_NAME\nOUTPUT_FILE_NAME = 'scrape' # Name of your output file\n\nglobal WORKING_DIR\nWORKING_DIR = '~/Corpora/'\n\nglobal OLD_MASTER_FILE\nOLD_MASTER_FILE = '{}Text_data/'.format(WORKING_DIR) + 'yeshizuile.txt' #Feed the new output\n \n\nclass NewScrape():\n \n def scrape_main(self):\n '''\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n '''\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n self.get_weibo(link,index)\n time.sleep(5)\n \n self.retrieve_posts(OUTPUT_FILE_NAME)\n #self.clean_temp()\n print('='*10)\n print('Congratulations! Your data is stored')\n return None\n\n def gen_links(self):\n links = []\n for i in range(1,51):\n i = str(i) \n links.append('{}&b={}'.format(QUERY_LINK,i))\n return links\n\n def get_weibo(self,link,index):\n \n '''\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n '''\n\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR),'w', encoding = 'utf8')\n \n r = requests.get(link)\n print ('accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n \n # Write into a csv file\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR) + outfile_name,'w', encoding = 'utf8') #change path\n \n # Turn the text into a BeautifulSoup object and strip down the text.\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR),'r', encoding = 'utf8')#change path\n soup = BeautifulSoup(html_doc)\n\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n \n weibo_items = soup.find_all('div', class_='weibo_item')\n \n for item in weibo_items: \n \n for link in item.find_all('a', target='_blank', class_='sina_weibo'):\n url = link.get('href')\n post_link.append(url)\n\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n \n data = {'post_text':post_txt,'post_link':post_link,'user':user_link, 'time':post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print (outfile_name,'processed complete.')\n \n outfile.close()\n html_doc.close()\n return None\n\n def clean_temp(self):\n filelist = glob.glob('{}Temp/*'.format(WORKING_DIR))\n for f in filelist:\n os.remove(f)\n print('Temp files removed')\n return None\n\n \n def retrieve_posts(self,outfile_name):\n '''(str)->a file\n ''' \n post_text = []\n \n for i in range(50):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'.format(WORKING_DIR, str(i)))#change directory\n df2 = DataFrame(frame_2)\n for i in df2.post_text:#the column'post_text'\n post_text.append(i)\n\n data = {'post_text':post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}.txt'.format(WORKING_DIR, outfile_name), encoding = 'utf-8')#change saved path\n frame.to_excel('{}Text_data/{}.xlsx'.format(WORKING_DIR, outfile_name), encoding = 'utf-8')#change saved path\n print(\"Done\")\n return None \n\nclass ContinueScrape():\n \n def scrape_main(self):\n '''\n Top-level function.\n Use links from below, scrape a page, sleep for 5s, and restart on the next link.\n '''\n for i in self.gen_links():\n index = str(self.gen_links().index(i))\n link = i\n cmd = self.get_weibo(link,index)\n if cmd == 'STOP':\n break\n else:\n time.sleep(10)\n continue\n \n print('='*10)\n print('Scrape is now complete. Help me to organize them.')\n print ('View your temp folder, what is the biggest number of the files? \\n')\n fn = int(input())\n self.retrieve_posts(fn)\n print('='*10)\n print('Congratulations! Your data is stored')\n return \n\n def gen_links(self):\n links = []\n for i in range(1,51):\n i = str(i) \n links.append('{}&b={}'.format(QUERY_LINK,i))\n return links\n\n def get_weibo(self,link,index):\n \n '''\n Scrape a certain weibio search result page on 'zhongsou' and store it in locally.\n '''\n\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'w', encoding='utf8')\n\n r = requests.get(link)\n print ('Accessing web data.')\n html_doc.write(r.text)\n html_doc.close()\n\n # Retrieve scrape history\n h_post_text = [] \n h_frame = pandas.read_csv(OLD_MASTER_FILE) \n h_df = DataFrame(h_frame)\n for i in h_df.post_text:\n h_post_text.append(i)\n \n # Write into a csv file\n outfile_name = 'zhongsou_results_page_' + index + '.csv'\n outfile = open('{}Temp/'.format(WORKING_DIR)+ outfile_name,'w', encoding = 'utf8') #change path\n \n # Turn the text into a BeautifulSoup object and strip down the text.\n html_doc = open('{}Temp/weibo.txt'.format(WORKING_DIR), 'r', encoding='utf8')\n soup = BeautifulSoup(html_doc)\n\n user_link = []\n post_txt = []\n post_link = []\n post_time = []\n cmd = None\n \n weibo_items = soup.find_all('div', class_='weibo_item')\n \n for item in weibo_items: \n \n for link in item.find_all('a', target='_blank', class_='sina_weibo'):\n url = link.get('href')\n post_link.append(url)\n\n for post in item.find_all('h3', class_='weibo_title'):\n for a in post.find_all('a'):\n url = a.get('href')\n user_link.append(url)\n\n for time in item.find_all('div', class_='weibo_time'):\n txt = time.get_text()\n post_time.append(txt)\n\n for post in item.find_all('p', class_='weibo_txt'):\n txt = post.get_text()\n post_txt.append(txt)\n\n #has bugs!\n #if txt in h_post_text:\n if txt == h_post_text[0]: \n print (txt)\n print(' ___ exists')\n print ('End of new data.') #Doesn't affect main function, break should be in main function\n del post_link[-1]\n del user_link[-1]\n del post_time[-1]\n del post_txt[-1]\n cmd = 'STOP'\n break\n \n data = {'post_text':post_txt,'post_link':post_link,'user':user_link, 'time':post_time}\n frame = DataFrame(data)\n frame.to_csv(outfile, encoding='utf-8')\n print (outfile_name,'processed complete.')\n \n outfile.close()\n html_doc.close()\n return cmd\n\n def retrieve_posts(self,file_number_total):\n '''(int)->a file\n '''\n post_text = []\n \n \n for i in range(file_number_total+1):\n frame_2 = pandas.read_csv('{}Temp/zhongsou_results_page_{}.csv'.format(WORKING_DIR, str(i)))\n df2 = DataFrame(frame_2)\n for i in df2.post_text:#the column'post_text'\n post_text.append(i)\n\n frame_1 = pandas.read_csv(OLD_MASTER_FILE)\n df1 = DataFrame(frame_1)\n for i in df1.post_text:\n post_text.append(i)\n\n data = {'post_text':post_text}\n frame = DataFrame(data)\n frame.to_csv('{}Text_data/{}_2.txt'.format(WORKING_DIR, OUTPUT_FILE_NAME), encoding = 'utf-8')#saved path\n frame.to_excel('{}Text_data/{}_2.xlsx'.format(WORKING_DIR, OUTPUT_FILE_NAME), encoding = 'utf-8')#saved path\n\n\n print(\"Data gathered.\")\n\n## filelist = glob.glob('{}Temp/*'.format(WORKING_DIR))\n## for f in filelist:\n## os.remove(f)\n\n #os.remove(OLD_MASTER_FILE)\n\n print('Temp files removed')\n\n return None \n\nprint('='*10)\nprint('This program will help you collect Weibo language data as generated by the 中搜 search results.\\n')\nprint('Use this page to generate a link for your query item:\\n\\nhttp://t.zhongsou.com/wb?form_id=1&org=1&sel=0&so=1&v=%D6%D0%CB%D1&w=%CD%F8%D3%EF')\nQUERY_LINK = input('\\nPaste your query link \\n> ')\nOUTPUT_FILE_NAME = input('\\nWhat\\'s your query term? (This will be used as file name)\\n> ')\nresp = input('\\nIs this your first time running this query? Y/N\\n> ').upper()\nif resp == 'Y':\n print()\n print('='*10)\n print('Initialize scraping now.')\n print('='*10)\n NewScrape().scrape_main()\nelif resp == 'N':\n OLD_MASTER_FILE = input('\\nWhere is the old txt file you want to merge later? Please paste full path. \\n> ')\n print()\n print('='*10)\n print('WARNING: FURTHER ACTIONS NEEDED AT THE END OF SCRAPING.')\n print('Initialize scraping now.')\n print('='*10)\n ContinueScrape().scrape_main()\n \nelse:\n print('Invalid command. Try again.')\n",
"step-ids": [
9,
12,
13,
14,
15
]
}
|
[
9,
12,
13,
14,
15
] |
from django.contrib import admin
# from .models import Product, Client
from .models import Board
admin.site.register(Board)
# admin.site.register(Product)
# # admin.site.register(Price)
# admin.site.register(Client)
# # Register your models here.
|
normal
|
{
"blob_id": "ea323a8398ceff8496e7f8d0f365d50f3115e954",
"index": 5228,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nadmin.site.register(Board)\n",
"step-3": "from django.contrib import admin\nfrom .models import Board\nadmin.site.register(Board)\n",
"step-4": "from django.contrib import admin\n# from .models import Product, Client\nfrom .models import Board\n\nadmin.site.register(Board)\n\n# admin.site.register(Product)\n# # admin.site.register(Price)\n# admin.site.register(Client)\n# # Register your models here.\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class Song(Base):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class File(Base):
__tablename__ = 'files'
id = Column(Integer, primary_key=True)
filename = Column(String, nullable=False)
song = relationship('Song', uselist=False, backref='song')
def as_dictionary(self):
file_dict = {'id': self.id, 'filename': self.filename}
return file_dict
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Song(Base):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def as_dictionary(self):
file_data = session.query(File).get(self.file_id)
song_dict = {'id': self.id, 'file': {'id': file_data.id, 'filename':
file_data.filename}}
return song_dict
class File(Base):
__tablename__ = 'files'
id = Column(Integer, primary_key=True)
filename = Column(String, nullable=False)
song = relationship('Song', uselist=False, backref='song')
def as_dictionary(self):
file_dict = {'id': self.id, 'filename': self.filename}
return file_dict
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Song(Base):
__tablename__ = 'songs'
id = Column(Integer, primary_key=True)
file_id = Column(Integer, ForeignKey('files.id'), nullable=False)
def as_dictionary(self):
file_data = session.query(File).get(self.file_id)
song_dict = {'id': self.id, 'file': {'id': file_data.id, 'filename':
file_data.filename}}
return song_dict
class File(Base):
__tablename__ = 'files'
id = Column(Integer, primary_key=True)
filename = Column(String, nullable=False)
song = relationship('Song', uselist=False, backref='song')
def as_dictionary(self):
file_dict = {'id': self.id, 'filename': self.filename}
return file_dict
<|reserved_special_token_1|>
import os.path
from flask import url_for
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey
from sqlalchemy.orm import relationship
from tuneful import app
from .database import Base, engine, session
class Song(Base):
__tablename__ = 'songs'
id = Column(Integer, primary_key=True)
file_id = Column(Integer, ForeignKey('files.id'), nullable=False)
def as_dictionary(self):
file_data = session.query(File).get(self.file_id)
song_dict = {'id': self.id, 'file': {'id': file_data.id, 'filename':
file_data.filename}}
return song_dict
class File(Base):
__tablename__ = 'files'
id = Column(Integer, primary_key=True)
filename = Column(String, nullable=False)
song = relationship('Song', uselist=False, backref='song')
def as_dictionary(self):
file_dict = {'id': self.id, 'filename': self.filename}
return file_dict
<|reserved_special_token_1|>
import os.path
from flask import url_for
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey
from sqlalchemy.orm import relationship
from tuneful import app
from .database import Base, engine, session
class Song(Base):
__tablename__ = 'songs'
id = Column(Integer, primary_key=True)
file_id = Column(Integer, ForeignKey('files.id'), nullable=False)
def as_dictionary(self):
file_data = session.query(File).get(self.file_id)
song_dict = {
"id": self.id,
"file": {
"id": file_data.id,
"filename": file_data.filename
}
}
return song_dict
class File(Base):
__tablename__ = 'files'
id = Column(Integer, primary_key=True)
filename = Column(String, nullable=False)
song = relationship("Song", uselist=False, backref="song")
def as_dictionary(self):
file_dict = {
"id": self.id,
"filename": self.filename
}
return file_dict
|
flexible
|
{
"blob_id": "d5c2b73c202c9944cd64798ef5ddc08ce68a4a9a",
"index": 3446,
"step-1": "<mask token>\n\n\nclass Song(Base):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass File(Base):\n __tablename__ = 'files'\n id = Column(Integer, primary_key=True)\n filename = Column(String, nullable=False)\n song = relationship('Song', uselist=False, backref='song')\n\n def as_dictionary(self):\n file_dict = {'id': self.id, 'filename': self.filename}\n return file_dict\n",
"step-2": "<mask token>\n\n\nclass Song(Base):\n <mask token>\n <mask token>\n <mask token>\n\n def as_dictionary(self):\n file_data = session.query(File).get(self.file_id)\n song_dict = {'id': self.id, 'file': {'id': file_data.id, 'filename':\n file_data.filename}}\n return song_dict\n\n\nclass File(Base):\n __tablename__ = 'files'\n id = Column(Integer, primary_key=True)\n filename = Column(String, nullable=False)\n song = relationship('Song', uselist=False, backref='song')\n\n def as_dictionary(self):\n file_dict = {'id': self.id, 'filename': self.filename}\n return file_dict\n",
"step-3": "<mask token>\n\n\nclass Song(Base):\n __tablename__ = 'songs'\n id = Column(Integer, primary_key=True)\n file_id = Column(Integer, ForeignKey('files.id'), nullable=False)\n\n def as_dictionary(self):\n file_data = session.query(File).get(self.file_id)\n song_dict = {'id': self.id, 'file': {'id': file_data.id, 'filename':\n file_data.filename}}\n return song_dict\n\n\nclass File(Base):\n __tablename__ = 'files'\n id = Column(Integer, primary_key=True)\n filename = Column(String, nullable=False)\n song = relationship('Song', uselist=False, backref='song')\n\n def as_dictionary(self):\n file_dict = {'id': self.id, 'filename': self.filename}\n return file_dict\n",
"step-4": "import os.path\nfrom flask import url_for\nfrom sqlalchemy import Column, Integer, String, Sequence, ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom tuneful import app\nfrom .database import Base, engine, session\n\n\nclass Song(Base):\n __tablename__ = 'songs'\n id = Column(Integer, primary_key=True)\n file_id = Column(Integer, ForeignKey('files.id'), nullable=False)\n\n def as_dictionary(self):\n file_data = session.query(File).get(self.file_id)\n song_dict = {'id': self.id, 'file': {'id': file_data.id, 'filename':\n file_data.filename}}\n return song_dict\n\n\nclass File(Base):\n __tablename__ = 'files'\n id = Column(Integer, primary_key=True)\n filename = Column(String, nullable=False)\n song = relationship('Song', uselist=False, backref='song')\n\n def as_dictionary(self):\n file_dict = {'id': self.id, 'filename': self.filename}\n return file_dict\n",
"step-5": "import os.path\n\nfrom flask import url_for\nfrom sqlalchemy import Column, Integer, String, Sequence, ForeignKey\nfrom sqlalchemy.orm import relationship\n\nfrom tuneful import app\nfrom .database import Base, engine, session\n\nclass Song(Base):\n __tablename__ = 'songs'\n id = Column(Integer, primary_key=True)\n file_id = Column(Integer, ForeignKey('files.id'), nullable=False)\n \n def as_dictionary(self):\n file_data = session.query(File).get(self.file_id)\n song_dict = {\n \"id\": self.id,\n \"file\": {\n \"id\": file_data.id,\n \"filename\": file_data.filename\n }\n }\n return song_dict\n\nclass File(Base):\n __tablename__ = 'files'\n id = Column(Integer, primary_key=True)\n filename = Column(String, nullable=False)\n song = relationship(\"Song\", uselist=False, backref=\"song\")\n\n def as_dictionary(self):\n file_dict = {\n \"id\": self.id,\n \"filename\": self.filename\n }\n return file_dict",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
myDict = {'Friends': ['AP', 'Soham', 'Baba'], 'Likes': ['Math',
'Programming'], 'languages': ['C++', 'Python', 'Java']}
myInt = 123
myFloat = 12.3333
myName = 'Somesh Thakur'
|
flexible
|
{
"blob_id": "345967e2aeafda6ce30cbbbbacf976c97b17def7",
"index": 515,
"step-1": "<mask token>\n",
"step-2": "myDict = {'Friends': ['AP', 'Soham', 'Baba'], 'Likes': ['Math',\n 'Programming'], 'languages': ['C++', 'Python', 'Java']}\nmyInt = 123\nmyFloat = 12.3333\nmyName = 'Somesh Thakur'\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
from src.secStructure import *
from suffix_trees import STree
import math
import re
def test_processData():
# Test1: ignoring peak position
data = ['example/example1.fa', 'example/example2.fa']
struct_data = ['example/exampleStrucData/exampleStructuralData1.fa',
'example/exampleStrucData/exampleStructuralData2.fa']
k = 3
top = 10
peak = None
feature = None
cmd = False
no_sec_peak = 1 # True
# Executing
process = SecStructure(data, data, k, peak, top, feature, cmd, struct_data, no_sec_peak)
alphabet1 = process.getStructProfile1().getAlphabet()
alphabet2 = process.getStructProfile2().getAlphabet()
kmer_counts1 = process.getStructProfile1().getProfile()
kmer_counts2 = process.getStructProfile2().getProfile()
results = SecStructure.processData(process)
template1 = results[0][0]
template2 = results[1][0]
dotbracket_string1 = results[0][1]
dotbracket_string2 = results[1][1]
# Testing
assert len(alphabet1) == 6
for e in ["S", "H", "B", "I", "M", "E"]:
assert e in alphabet1
assert len(alphabet2) == 2
assert "S" in alphabet2
assert "E" in alphabet2
assert kmer_counts1 == {'EE': 4, 'ES': 1, 'SS': 11, 'SH': 1, 'HH': 3, 'II': 4, 'IS': 1, 'SM': 1, 'MM': 1, 'BB': 4,
'BS': 1}
assert kmer_counts2 == {'SS': 20, 'EE': 7, 'ES': 3, 'SE': 2}
assert template1 == "EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSMMMSSSHHHSSSEEE"
assert dotbracket_string1 == "...(((...(((...(((...))))))...)))...(((...)))..."
assert template2 == "EEESSSSSSEEE"
assert dotbracket_string2 == "...((()))..."
# Test2: with peak position
no_sec_peak = 0 # True
# Executing
process2 = SecStructure(data, data, k, peak, top, feature, cmd, struct_data, no_sec_peak)
alphabet1 = process2.getStructProfile1().getAlphabet()
alphabet2 = process2.getStructProfile2().getAlphabet()
kmer_counts1 = process2.getStructProfile1().getProfile()
kmer_counts2 = process2.getStructProfile2().getProfile()
results = SecStructure.processData(process2)
template1 = results[0][0]
template2 = results[1][0]
dotbracket_string1 = results[0][1]
dotbracket_string2 = results[1][1]
# Testing
assert len(alphabet1) == 10
for e in ["s", "h", "b", "i", "m", "E", "S", "B", "I", "E"]:
assert e in alphabet1
assert len(alphabet2) == 4
for e in ["s", "S", "e", "E"]:
assert e in alphabet2
assert kmer_counts1 == {'eE': 1, 'Es': 1, 'sS': 1, 'Sh': 1, 'iI': 1, 'Is': 1, 'bB': 1, 'Bs': 1}
assert kmer_counts2 == {'sS': 3, 'Ss': 2, 'sE': 1, 'Ee': 1, 'Se': 1}
assert template1 == "EEESSSIIISSSBBBSSSSSSSSSIIISSSEEE"
assert dotbracket_string1 == "...(((...(((...((())))))...)))..."
assert template2 == "EEESSSSSSEEE"
assert dotbracket_string2 == "...((()))..."
# Test3: different alphabets
sProfile1 = process.getStructProfile1()
sProfile2 = process.getStructProfile2()
# Test3a: alphabets with no multiloop
alphabet3 = ["S", "B", "E"]
alphabet4 = ["S", "I", "E"]
sProfile1.setAlphabet(alphabet3)
sProfile2.setAlphabet(alphabet4)
results = SecStructure.processData(process)
template1 = results[0][0]
template2 = results[1][0]
dotbracket_string1 = results[0][1]
dotbracket_string2 = results[1][1]
assert template1 == "EEESSSBBBSSSSSSSSSEEE"
assert dotbracket_string1 == "...(((...((())))))..."
assert template2 == "EEESSSIIISSSSSSIIISSSEEE"
assert dotbracket_string2 == "...(((...((()))...)))..."
# Test3b: alphabets with only hairpin or hairpin and multiloop
alphabet5 = ["S", "H", "E"]
alphabet6 = ["S", "H", "M", "E"]
sProfile1.setAlphabet(alphabet5)
sProfile2.setAlphabet(alphabet6)
results = SecStructure.processData(process)
template1 = results[0][0]
template2 = results[1][0]
dotbracket_string1 = results[0][1]
dotbracket_string2 = results[1][1]
assert template1 == "EEESSSHHHSSSEEE"
assert dotbracket_string1 == "...(((...)))..."
assert template2 == "EEESSSHHHSSSMMMSSSHHHSSSEEE"
assert dotbracket_string2 == "...(((...)))...(((...)))..."
# Test3c: ('flawed') alphabets with no multiloops
alphabet7 = ["S", "H", "E", "B", "I"]
alphabet8 = ["S", "M", "E"] # should be equal to ["S","E"]
sProfile1.setAlphabet(alphabet7)
sProfile2.setAlphabet(alphabet8)
results = SecStructure.processData(process)
template1 = results[0][0]
template2 = results[1][0]
dotbracket_string1 = results[0][1]
dotbracket_string2 = results[1][1]
assert template1 == "EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE"
assert dotbracket_string1 == "...(((...(((...(((...))))))...)))..."
assert template2 == "EEESSSSSSEEE"
assert dotbracket_string2 == "...((()))..."
def test_createColorVector():
# Test1: no normalization vector wanted
k = 2
no_sec_peak = 1
template = "EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE"
kmer_counts = {"EE": 5, "ES": 7, "SS": 20, "SI": 10, "II": 15, "IS": 11, "SB": 5, "BB": 6, "BS": 5, "SH": 4,
"HH": 5, "HS": 4, "SE": 7}
template_sTree = STree.STree(template)
normalization_vector1 = None
color_hm = {str(i): 0 for i in range(1, len(template) + 1)}
# Executing
new_color_hm1, not_matched1, color_domain_max1 = createColorVector(k, template_sTree, kmer_counts, color_hm,
no_sec_peak, normalization_vector1)
assert len(color_hm) == len(new_color_hm1)
for i in color_hm.keys():
x = color_hm[i]
if x > 0:
assert new_color_hm1[i] == math.log(x, 2)
else:
assert new_color_hm1[i] == 0
assert len(not_matched1) == 0
assert color_domain_max1 == 4.954196310386876
# Test2: with normalization vector
normalization_vector2 = {"EE": 0, "ES": 0, "SS": 0.7, "SI": 0.1, "II": 0.2, "IS": 0, "SB": 0, "BB": 0, "BS": 0,
"SH": 0, "HH": 0, "HS": 0, "SE": 0}
# Execution
color_hm = {str(i): 0 for i in range(1, len(template) + 1)}
new_color_hm2, not_matched2, color_domain_max2 = createColorVector(k, template_sTree, kmer_counts, color_hm,
no_sec_peak, normalization_vector2)
last_idx = -1
last_kmer = ""
test_color_hm = {str(i): 0 for i in range(1, len(template) + 1)}
for kmer in normalization_vector2:
indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.escape(kmer)), template)]
indices_list.sort()
norm = normalization_vector2[kmer]
if norm == 0:
norm = 1
for idx in indices_list:
for i in range(0, k):
current_idx = str(idx + i + 1)
if last_idx + 2 == int(current_idx) and last_kmer == kmer:
continue
test_color_hm[current_idx] += (kmer_counts[kmer] / norm)
last_idx = idx
last_kmer = kmer
test_color_hm = {x: math.log(y, 2) if y > 0 else y for x, y in test_color_hm.items()}
test_color_domain_max = max(test_color_hm.values())
# Testing
assert new_color_hm1 is not new_color_hm2
assert len(color_hm) == len(new_color_hm2)
assert len(not_matched2) == 0
assert color_domain_max2 == test_color_domain_max
for i in new_color_hm2.keys():
assert new_color_hm2[i] == test_color_hm[i]
# Test3: normalization vector and secondary peak position
kmer_counts2 = {"Ee": 5, "eS": 7, "sS": 20, "Si": 10, "iI": 15, "iS": 11, "Sb": 5, "Bb": 6, "bS": 5, "sH": 4,
"Hh": 5, "hS": 4, "Se": 7}
no_sec_peak2 = 0
# Execution
color_hm = {str(i): 0 for i in range(1, len(template) + 1)}
new_color_hm3, not_matched3, color_domain_max3 = createColorVector(k, template_sTree, kmer_counts2, color_hm,
no_sec_peak2, normalization_vector2)
test_color_hm2 = {str(i): 0 for i in range(1, len(template) + 1)}
for kmer in kmer_counts2.keys():
indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.escape(kmer.upper())), template)]
indices_list.sort()
norm = normalization_vector2[kmer.upper()]
if norm == 0:
norm = 1
for idx in indices_list:
# use only peak-position in 2-mer for visualization
idx = [idx + i for i in range(0, len(kmer)) if kmer[i].isupper()][0]
test_color_hm2[str(idx + 1)] += (kmer_counts2[kmer] / norm)
test_color_hm2 = {x: math.log(y, 2) if y > 0 else y for x, y in test_color_hm2.items()}
test_color_domain_max2 = max(test_color_hm2.values())
# Testing
assert len(not_matched3) == 0
assert new_color_hm2 is not new_color_hm3
assert len(color_hm) == len(new_color_hm3)
for i in test_color_hm2:
assert test_color_hm2[i] == new_color_hm3[i]
assert test_color_domain_max2 == color_domain_max3
def test_helpAddIBloop():
k = 3
# Test 1: forward and all true
template1 = ["EEE"]
internalloop = True
bulge = True
forward = True
# Execution
new_template1 = helpAddIBloop(k, template1, internalloop, bulge, forward)
# Test 2: backward and all true
template2 = ["EEE", "SSS", "III", "SSS", "BBB", "SSS", "HHH"]
internalloop = True
bulge = True
forward = False
# Execution
new_template2 = helpAddIBloop(k, template2, internalloop, bulge, forward)
# Test 3: only internal loops, forward and backward
template3_f = ["EEE"]
template3_b = ["EEE", "SSS", "III", "SSS", "HHH"]
internalloop = True
bulge = False
forward = True
# Execution
new_template3_f = helpAddIBloop(k, template3_f, internalloop, bulge, forward)
forward = False
new_template3_b = helpAddIBloop(k, template3_b, internalloop, bulge, forward)
# Test 4: only bulges, forward and backward
template4_f = ["EEE"]
template4_b = ["EEE", "SSS", "BBB", "SSS", "HHH"]
internalloop = False
bulge = True
forward = True
# Execution
new_template4_f = helpAddIBloop(k, template4_f, internalloop, bulge, forward)
forward = False
new_template4_b = helpAddIBloop(k, template4_b, internalloop, bulge, forward)
# Testing
assert new_template1 == ["EEE", "SSS", "III", "SSS", "BBB"]
assert new_template2 == ["EEE", "SSS", "III", "SSS", "BBB", "SSS", "HHH", "SSS", "SSS", "III"]
assert new_template3_f == ["EEE", "SSS", "III"]
assert new_template3_b == ["EEE", "SSS", "III", "SSS", "HHH", "SSS", "III"]
assert new_template4_f == ["EEE", "SSS", "BBB"]
assert new_template4_b == ["EEE", "SSS", "BBB", "SSS", "HHH", "SSS"]
def test_element2dotbracket():
k3 = 3
k2 = 2
k4 = 4
# Test1 without multiloop
elem_list1 = ["EEE", "SSS", "III", "SSS", "BBB", "SSS", "HHH", "SSS", "SSS", "III", "SSS", "EEE"]
dotbracket_string1 = "...(((...(((...(((...))))))...)))..."
# Test2 with multiloop
elem_list2 = ["EE", "SS", "II", "SS", "HH", "SS", "II", "SS", "MM", "SS", "BB", "SS", "HH", "SS", "SS", "EE"]
dotbracket_string2 = "..((..((..))..))..((..((..)))).."
# Test 3 without loops
elem_list3 = ["EEEE", "SSSS", "SSSS", "EEEE"]
dotbracket_string3 = "....(((())))...."
# Test 5 with everything
elem_list4 = ["EEE", "SSS", "III", "SSS", "BBB", "SSS", "HHH", "SSS", "SSS", "III", "SSS", "MMM", "SSS", "HHH",
"SSS", "EEE"]
dotbracket_string4 = "...(((...(((...(((...))))))...)))...(((...)))..."
# Execution
db1 = []
db1.extend(element2dotbracket(elem_list1, k3, 0, 6, True))
db1.extend(element2dotbracket(elem_list1, k3, 7, len(elem_list1) - 1, False))
db1 = ''.join(db1)
db2 = []
db2.extend(element2dotbracket(elem_list2, k2, 0, 4, True))
db2.extend(element2dotbracket(elem_list2, k2, 5, 8, False))
db2.extend(element2dotbracket(elem_list2, k2, 9, 12, True))
db2.extend(element2dotbracket(elem_list2, k2, 13, len(elem_list2) - 1, False))
db2 = ''.join(db2)
db3 = []
db3.extend(element2dotbracket(elem_list3, k4, 0, 1, True))
db3.extend(element2dotbracket(elem_list3, k4, 2, len(elem_list3) - 1, False))
db3 = ''.join(db3)
db4 = []
db4.extend(element2dotbracket(elem_list4, k3, 0, 6, True))
db4.extend(element2dotbracket(elem_list4, k3, 7, 11, False))
db4.extend(element2dotbracket(elem_list4, k3, 12, 13, True))
db4.extend(element2dotbracket(elem_list4, k3, 14, len(elem_list4) - 1, False))
db4 = ''.join(db4)
# testing
assert db1 == dotbracket_string1
assert db2 == dotbracket_string2
assert db3 == dotbracket_string3
assert db4 == dotbracket_string4
|
normal
|
{
"blob_id": "60b1a77d2de4a52ae9597f88917c4a3996c99923",
"index": 5626,
"step-1": "<mask token>\n\n\ndef test_createColorVector():\n k = 2\n no_sec_peak = 1\n template = 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE'\n kmer_counts = {'EE': 5, 'ES': 7, 'SS': 20, 'SI': 10, 'II': 15, 'IS': 11,\n 'SB': 5, 'BB': 6, 'BS': 5, 'SH': 4, 'HH': 5, 'HS': 4, 'SE': 7}\n template_sTree = STree.STree(template)\n normalization_vector1 = None\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm1, not_matched1, color_domain_max1 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector1)\n assert len(color_hm) == len(new_color_hm1)\n for i in color_hm.keys():\n x = color_hm[i]\n if x > 0:\n assert new_color_hm1[i] == math.log(x, 2)\n else:\n assert new_color_hm1[i] == 0\n assert len(not_matched1) == 0\n assert color_domain_max1 == 4.954196310386876\n normalization_vector2 = {'EE': 0, 'ES': 0, 'SS': 0.7, 'SI': 0.1, 'II': \n 0.2, 'IS': 0, 'SB': 0, 'BB': 0, 'BS': 0, 'SH': 0, 'HH': 0, 'HS': 0,\n 'SE': 0}\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm2, not_matched2, color_domain_max2 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector2)\n last_idx = -1\n last_kmer = ''\n test_color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in normalization_vector2:\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer)), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n for i in range(0, k):\n current_idx = str(idx + i + 1)\n if last_idx + 2 == int(current_idx) and last_kmer == kmer:\n continue\n test_color_hm[current_idx] += kmer_counts[kmer] / norm\n last_idx = idx\n last_kmer = kmer\n test_color_hm = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm.items()}\n test_color_domain_max = max(test_color_hm.values())\n assert new_color_hm1 is not new_color_hm2\n assert len(color_hm) == len(new_color_hm2)\n assert len(not_matched2) == 0\n assert color_domain_max2 == test_color_domain_max\n for i in new_color_hm2.keys():\n assert new_color_hm2[i] == test_color_hm[i]\n kmer_counts2 = {'Ee': 5, 'eS': 7, 'sS': 20, 'Si': 10, 'iI': 15, 'iS': \n 11, 'Sb': 5, 'Bb': 6, 'bS': 5, 'sH': 4, 'Hh': 5, 'hS': 4, 'Se': 7}\n no_sec_peak2 = 0\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm3, not_matched3, color_domain_max3 = createColorVector(k,\n template_sTree, kmer_counts2, color_hm, no_sec_peak2,\n normalization_vector2)\n test_color_hm2 = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in kmer_counts2.keys():\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer.upper())), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer.upper()]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n idx = [(idx + i) for i in range(0, len(kmer)) if kmer[i].isupper()\n ][0]\n test_color_hm2[str(idx + 1)] += kmer_counts2[kmer] / norm\n test_color_hm2 = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm2.items()}\n test_color_domain_max2 = max(test_color_hm2.values())\n assert len(not_matched3) == 0\n assert new_color_hm2 is not new_color_hm3\n assert len(color_hm) == len(new_color_hm3)\n for i in test_color_hm2:\n assert test_color_hm2[i] == new_color_hm3[i]\n assert test_color_domain_max2 == color_domain_max3\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_createColorVector():\n k = 2\n no_sec_peak = 1\n template = 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE'\n kmer_counts = {'EE': 5, 'ES': 7, 'SS': 20, 'SI': 10, 'II': 15, 'IS': 11,\n 'SB': 5, 'BB': 6, 'BS': 5, 'SH': 4, 'HH': 5, 'HS': 4, 'SE': 7}\n template_sTree = STree.STree(template)\n normalization_vector1 = None\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm1, not_matched1, color_domain_max1 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector1)\n assert len(color_hm) == len(new_color_hm1)\n for i in color_hm.keys():\n x = color_hm[i]\n if x > 0:\n assert new_color_hm1[i] == math.log(x, 2)\n else:\n assert new_color_hm1[i] == 0\n assert len(not_matched1) == 0\n assert color_domain_max1 == 4.954196310386876\n normalization_vector2 = {'EE': 0, 'ES': 0, 'SS': 0.7, 'SI': 0.1, 'II': \n 0.2, 'IS': 0, 'SB': 0, 'BB': 0, 'BS': 0, 'SH': 0, 'HH': 0, 'HS': 0,\n 'SE': 0}\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm2, not_matched2, color_domain_max2 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector2)\n last_idx = -1\n last_kmer = ''\n test_color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in normalization_vector2:\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer)), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n for i in range(0, k):\n current_idx = str(idx + i + 1)\n if last_idx + 2 == int(current_idx) and last_kmer == kmer:\n continue\n test_color_hm[current_idx] += kmer_counts[kmer] / norm\n last_idx = idx\n last_kmer = kmer\n test_color_hm = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm.items()}\n test_color_domain_max = max(test_color_hm.values())\n assert new_color_hm1 is not new_color_hm2\n assert len(color_hm) == len(new_color_hm2)\n assert len(not_matched2) == 0\n assert color_domain_max2 == test_color_domain_max\n for i in new_color_hm2.keys():\n assert new_color_hm2[i] == test_color_hm[i]\n kmer_counts2 = {'Ee': 5, 'eS': 7, 'sS': 20, 'Si': 10, 'iI': 15, 'iS': \n 11, 'Sb': 5, 'Bb': 6, 'bS': 5, 'sH': 4, 'Hh': 5, 'hS': 4, 'Se': 7}\n no_sec_peak2 = 0\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm3, not_matched3, color_domain_max3 = createColorVector(k,\n template_sTree, kmer_counts2, color_hm, no_sec_peak2,\n normalization_vector2)\n test_color_hm2 = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in kmer_counts2.keys():\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer.upper())), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer.upper()]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n idx = [(idx + i) for i in range(0, len(kmer)) if kmer[i].isupper()\n ][0]\n test_color_hm2[str(idx + 1)] += kmer_counts2[kmer] / norm\n test_color_hm2 = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm2.items()}\n test_color_domain_max2 = max(test_color_hm2.values())\n assert len(not_matched3) == 0\n assert new_color_hm2 is not new_color_hm3\n assert len(color_hm) == len(new_color_hm3)\n for i in test_color_hm2:\n assert test_color_hm2[i] == new_color_hm3[i]\n assert test_color_domain_max2 == color_domain_max3\n\n\ndef test_helpAddIBloop():\n k = 3\n template1 = ['EEE']\n internalloop = True\n bulge = True\n forward = True\n new_template1 = helpAddIBloop(k, template1, internalloop, bulge, forward)\n template2 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH']\n internalloop = True\n bulge = True\n forward = False\n new_template2 = helpAddIBloop(k, template2, internalloop, bulge, forward)\n template3_f = ['EEE']\n template3_b = ['EEE', 'SSS', 'III', 'SSS', 'HHH']\n internalloop = True\n bulge = False\n forward = True\n new_template3_f = helpAddIBloop(k, template3_f, internalloop, bulge,\n forward)\n forward = False\n new_template3_b = helpAddIBloop(k, template3_b, internalloop, bulge,\n forward)\n template4_f = ['EEE']\n template4_b = ['EEE', 'SSS', 'BBB', 'SSS', 'HHH']\n internalloop = False\n bulge = True\n forward = True\n new_template4_f = helpAddIBloop(k, template4_f, internalloop, bulge,\n forward)\n forward = False\n new_template4_b = helpAddIBloop(k, template4_b, internalloop, bulge,\n forward)\n assert new_template1 == ['EEE', 'SSS', 'III', 'SSS', 'BBB']\n assert new_template2 == ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS',\n 'HHH', 'SSS', 'SSS', 'III']\n assert new_template3_f == ['EEE', 'SSS', 'III']\n assert new_template3_b == ['EEE', 'SSS', 'III', 'SSS', 'HHH', 'SSS', 'III']\n assert new_template4_f == ['EEE', 'SSS', 'BBB']\n assert new_template4_b == ['EEE', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS']\n\n\ndef test_element2dotbracket():\n k3 = 3\n k2 = 2\n k4 = 4\n elem_list1 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS',\n 'SSS', 'III', 'SSS', 'EEE']\n dotbracket_string1 = '...(((...(((...(((...))))))...)))...'\n elem_list2 = ['EE', 'SS', 'II', 'SS', 'HH', 'SS', 'II', 'SS', 'MM',\n 'SS', 'BB', 'SS', 'HH', 'SS', 'SS', 'EE']\n dotbracket_string2 = '..((..((..))..))..((..((..))))..'\n elem_list3 = ['EEEE', 'SSSS', 'SSSS', 'EEEE']\n dotbracket_string3 = '....(((())))....'\n elem_list4 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS',\n 'SSS', 'III', 'SSS', 'MMM', 'SSS', 'HHH', 'SSS', 'EEE']\n dotbracket_string4 = '...(((...(((...(((...))))))...)))...(((...)))...'\n db1 = []\n db1.extend(element2dotbracket(elem_list1, k3, 0, 6, True))\n db1.extend(element2dotbracket(elem_list1, k3, 7, len(elem_list1) - 1, \n False))\n db1 = ''.join(db1)\n db2 = []\n db2.extend(element2dotbracket(elem_list2, k2, 0, 4, True))\n db2.extend(element2dotbracket(elem_list2, k2, 5, 8, False))\n db2.extend(element2dotbracket(elem_list2, k2, 9, 12, True))\n db2.extend(element2dotbracket(elem_list2, k2, 13, len(elem_list2) - 1, \n False))\n db2 = ''.join(db2)\n db3 = []\n db3.extend(element2dotbracket(elem_list3, k4, 0, 1, True))\n db3.extend(element2dotbracket(elem_list3, k4, 2, len(elem_list3) - 1, \n False))\n db3 = ''.join(db3)\n db4 = []\n db4.extend(element2dotbracket(elem_list4, k3, 0, 6, True))\n db4.extend(element2dotbracket(elem_list4, k3, 7, 11, False))\n db4.extend(element2dotbracket(elem_list4, k3, 12, 13, True))\n db4.extend(element2dotbracket(elem_list4, k3, 14, len(elem_list4) - 1, \n False))\n db4 = ''.join(db4)\n assert db1 == dotbracket_string1\n assert db2 == dotbracket_string2\n assert db3 == dotbracket_string3\n assert db4 == dotbracket_string4\n",
"step-3": "<mask token>\n\n\ndef test_processData():\n data = ['example/example1.fa', 'example/example2.fa']\n struct_data = ['example/exampleStrucData/exampleStructuralData1.fa',\n 'example/exampleStrucData/exampleStructuralData2.fa']\n k = 3\n top = 10\n peak = None\n feature = None\n cmd = False\n no_sec_peak = 1\n process = SecStructure(data, data, k, peak, top, feature, cmd,\n struct_data, no_sec_peak)\n alphabet1 = process.getStructProfile1().getAlphabet()\n alphabet2 = process.getStructProfile2().getAlphabet()\n kmer_counts1 = process.getStructProfile1().getProfile()\n kmer_counts2 = process.getStructProfile2().getProfile()\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert len(alphabet1) == 6\n for e in ['S', 'H', 'B', 'I', 'M', 'E']:\n assert e in alphabet1\n assert len(alphabet2) == 2\n assert 'S' in alphabet2\n assert 'E' in alphabet2\n assert kmer_counts1 == {'EE': 4, 'ES': 1, 'SS': 11, 'SH': 1, 'HH': 3,\n 'II': 4, 'IS': 1, 'SM': 1, 'MM': 1, 'BB': 4, 'BS': 1}\n assert kmer_counts2 == {'SS': 20, 'EE': 7, 'ES': 3, 'SE': 2}\n assert template1 == 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSMMMSSSHHHSSSEEE'\n assert dotbracket_string1 == '...(((...(((...(((...))))))...)))...(((...)))...'\n assert template2 == 'EEESSSSSSEEE'\n assert dotbracket_string2 == '...((()))...'\n no_sec_peak = 0\n process2 = SecStructure(data, data, k, peak, top, feature, cmd,\n struct_data, no_sec_peak)\n alphabet1 = process2.getStructProfile1().getAlphabet()\n alphabet2 = process2.getStructProfile2().getAlphabet()\n kmer_counts1 = process2.getStructProfile1().getProfile()\n kmer_counts2 = process2.getStructProfile2().getProfile()\n results = SecStructure.processData(process2)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert len(alphabet1) == 10\n for e in ['s', 'h', 'b', 'i', 'm', 'E', 'S', 'B', 'I', 'E']:\n assert e in alphabet1\n assert len(alphabet2) == 4\n for e in ['s', 'S', 'e', 'E']:\n assert e in alphabet2\n assert kmer_counts1 == {'eE': 1, 'Es': 1, 'sS': 1, 'Sh': 1, 'iI': 1,\n 'Is': 1, 'bB': 1, 'Bs': 1}\n assert kmer_counts2 == {'sS': 3, 'Ss': 2, 'sE': 1, 'Ee': 1, 'Se': 1}\n assert template1 == 'EEESSSIIISSSBBBSSSSSSSSSIIISSSEEE'\n assert dotbracket_string1 == '...(((...(((...((())))))...)))...'\n assert template2 == 'EEESSSSSSEEE'\n assert dotbracket_string2 == '...((()))...'\n sProfile1 = process.getStructProfile1()\n sProfile2 = process.getStructProfile2()\n alphabet3 = ['S', 'B', 'E']\n alphabet4 = ['S', 'I', 'E']\n sProfile1.setAlphabet(alphabet3)\n sProfile2.setAlphabet(alphabet4)\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert template1 == 'EEESSSBBBSSSSSSSSSEEE'\n assert dotbracket_string1 == '...(((...((())))))...'\n assert template2 == 'EEESSSIIISSSSSSIIISSSEEE'\n assert dotbracket_string2 == '...(((...((()))...)))...'\n alphabet5 = ['S', 'H', 'E']\n alphabet6 = ['S', 'H', 'M', 'E']\n sProfile1.setAlphabet(alphabet5)\n sProfile2.setAlphabet(alphabet6)\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert template1 == 'EEESSSHHHSSSEEE'\n assert dotbracket_string1 == '...(((...)))...'\n assert template2 == 'EEESSSHHHSSSMMMSSSHHHSSSEEE'\n assert dotbracket_string2 == '...(((...)))...(((...)))...'\n alphabet7 = ['S', 'H', 'E', 'B', 'I']\n alphabet8 = ['S', 'M', 'E']\n sProfile1.setAlphabet(alphabet7)\n sProfile2.setAlphabet(alphabet8)\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert template1 == 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE'\n assert dotbracket_string1 == '...(((...(((...(((...))))))...)))...'\n assert template2 == 'EEESSSSSSEEE'\n assert dotbracket_string2 == '...((()))...'\n\n\ndef test_createColorVector():\n k = 2\n no_sec_peak = 1\n template = 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE'\n kmer_counts = {'EE': 5, 'ES': 7, 'SS': 20, 'SI': 10, 'II': 15, 'IS': 11,\n 'SB': 5, 'BB': 6, 'BS': 5, 'SH': 4, 'HH': 5, 'HS': 4, 'SE': 7}\n template_sTree = STree.STree(template)\n normalization_vector1 = None\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm1, not_matched1, color_domain_max1 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector1)\n assert len(color_hm) == len(new_color_hm1)\n for i in color_hm.keys():\n x = color_hm[i]\n if x > 0:\n assert new_color_hm1[i] == math.log(x, 2)\n else:\n assert new_color_hm1[i] == 0\n assert len(not_matched1) == 0\n assert color_domain_max1 == 4.954196310386876\n normalization_vector2 = {'EE': 0, 'ES': 0, 'SS': 0.7, 'SI': 0.1, 'II': \n 0.2, 'IS': 0, 'SB': 0, 'BB': 0, 'BS': 0, 'SH': 0, 'HH': 0, 'HS': 0,\n 'SE': 0}\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm2, not_matched2, color_domain_max2 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector2)\n last_idx = -1\n last_kmer = ''\n test_color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in normalization_vector2:\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer)), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n for i in range(0, k):\n current_idx = str(idx + i + 1)\n if last_idx + 2 == int(current_idx) and last_kmer == kmer:\n continue\n test_color_hm[current_idx] += kmer_counts[kmer] / norm\n last_idx = idx\n last_kmer = kmer\n test_color_hm = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm.items()}\n test_color_domain_max = max(test_color_hm.values())\n assert new_color_hm1 is not new_color_hm2\n assert len(color_hm) == len(new_color_hm2)\n assert len(not_matched2) == 0\n assert color_domain_max2 == test_color_domain_max\n for i in new_color_hm2.keys():\n assert new_color_hm2[i] == test_color_hm[i]\n kmer_counts2 = {'Ee': 5, 'eS': 7, 'sS': 20, 'Si': 10, 'iI': 15, 'iS': \n 11, 'Sb': 5, 'Bb': 6, 'bS': 5, 'sH': 4, 'Hh': 5, 'hS': 4, 'Se': 7}\n no_sec_peak2 = 0\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm3, not_matched3, color_domain_max3 = createColorVector(k,\n template_sTree, kmer_counts2, color_hm, no_sec_peak2,\n normalization_vector2)\n test_color_hm2 = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in kmer_counts2.keys():\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer.upper())), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer.upper()]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n idx = [(idx + i) for i in range(0, len(kmer)) if kmer[i].isupper()\n ][0]\n test_color_hm2[str(idx + 1)] += kmer_counts2[kmer] / norm\n test_color_hm2 = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm2.items()}\n test_color_domain_max2 = max(test_color_hm2.values())\n assert len(not_matched3) == 0\n assert new_color_hm2 is not new_color_hm3\n assert len(color_hm) == len(new_color_hm3)\n for i in test_color_hm2:\n assert test_color_hm2[i] == new_color_hm3[i]\n assert test_color_domain_max2 == color_domain_max3\n\n\ndef test_helpAddIBloop():\n k = 3\n template1 = ['EEE']\n internalloop = True\n bulge = True\n forward = True\n new_template1 = helpAddIBloop(k, template1, internalloop, bulge, forward)\n template2 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH']\n internalloop = True\n bulge = True\n forward = False\n new_template2 = helpAddIBloop(k, template2, internalloop, bulge, forward)\n template3_f = ['EEE']\n template3_b = ['EEE', 'SSS', 'III', 'SSS', 'HHH']\n internalloop = True\n bulge = False\n forward = True\n new_template3_f = helpAddIBloop(k, template3_f, internalloop, bulge,\n forward)\n forward = False\n new_template3_b = helpAddIBloop(k, template3_b, internalloop, bulge,\n forward)\n template4_f = ['EEE']\n template4_b = ['EEE', 'SSS', 'BBB', 'SSS', 'HHH']\n internalloop = False\n bulge = True\n forward = True\n new_template4_f = helpAddIBloop(k, template4_f, internalloop, bulge,\n forward)\n forward = False\n new_template4_b = helpAddIBloop(k, template4_b, internalloop, bulge,\n forward)\n assert new_template1 == ['EEE', 'SSS', 'III', 'SSS', 'BBB']\n assert new_template2 == ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS',\n 'HHH', 'SSS', 'SSS', 'III']\n assert new_template3_f == ['EEE', 'SSS', 'III']\n assert new_template3_b == ['EEE', 'SSS', 'III', 'SSS', 'HHH', 'SSS', 'III']\n assert new_template4_f == ['EEE', 'SSS', 'BBB']\n assert new_template4_b == ['EEE', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS']\n\n\ndef test_element2dotbracket():\n k3 = 3\n k2 = 2\n k4 = 4\n elem_list1 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS',\n 'SSS', 'III', 'SSS', 'EEE']\n dotbracket_string1 = '...(((...(((...(((...))))))...)))...'\n elem_list2 = ['EE', 'SS', 'II', 'SS', 'HH', 'SS', 'II', 'SS', 'MM',\n 'SS', 'BB', 'SS', 'HH', 'SS', 'SS', 'EE']\n dotbracket_string2 = '..((..((..))..))..((..((..))))..'\n elem_list3 = ['EEEE', 'SSSS', 'SSSS', 'EEEE']\n dotbracket_string3 = '....(((())))....'\n elem_list4 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS',\n 'SSS', 'III', 'SSS', 'MMM', 'SSS', 'HHH', 'SSS', 'EEE']\n dotbracket_string4 = '...(((...(((...(((...))))))...)))...(((...)))...'\n db1 = []\n db1.extend(element2dotbracket(elem_list1, k3, 0, 6, True))\n db1.extend(element2dotbracket(elem_list1, k3, 7, len(elem_list1) - 1, \n False))\n db1 = ''.join(db1)\n db2 = []\n db2.extend(element2dotbracket(elem_list2, k2, 0, 4, True))\n db2.extend(element2dotbracket(elem_list2, k2, 5, 8, False))\n db2.extend(element2dotbracket(elem_list2, k2, 9, 12, True))\n db2.extend(element2dotbracket(elem_list2, k2, 13, len(elem_list2) - 1, \n False))\n db2 = ''.join(db2)\n db3 = []\n db3.extend(element2dotbracket(elem_list3, k4, 0, 1, True))\n db3.extend(element2dotbracket(elem_list3, k4, 2, len(elem_list3) - 1, \n False))\n db3 = ''.join(db3)\n db4 = []\n db4.extend(element2dotbracket(elem_list4, k3, 0, 6, True))\n db4.extend(element2dotbracket(elem_list4, k3, 7, 11, False))\n db4.extend(element2dotbracket(elem_list4, k3, 12, 13, True))\n db4.extend(element2dotbracket(elem_list4, k3, 14, len(elem_list4) - 1, \n False))\n db4 = ''.join(db4)\n assert db1 == dotbracket_string1\n assert db2 == dotbracket_string2\n assert db3 == dotbracket_string3\n assert db4 == dotbracket_string4\n",
"step-4": "from src.secStructure import *\nfrom suffix_trees import STree\nimport math\nimport re\n\n\ndef test_processData():\n data = ['example/example1.fa', 'example/example2.fa']\n struct_data = ['example/exampleStrucData/exampleStructuralData1.fa',\n 'example/exampleStrucData/exampleStructuralData2.fa']\n k = 3\n top = 10\n peak = None\n feature = None\n cmd = False\n no_sec_peak = 1\n process = SecStructure(data, data, k, peak, top, feature, cmd,\n struct_data, no_sec_peak)\n alphabet1 = process.getStructProfile1().getAlphabet()\n alphabet2 = process.getStructProfile2().getAlphabet()\n kmer_counts1 = process.getStructProfile1().getProfile()\n kmer_counts2 = process.getStructProfile2().getProfile()\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert len(alphabet1) == 6\n for e in ['S', 'H', 'B', 'I', 'M', 'E']:\n assert e in alphabet1\n assert len(alphabet2) == 2\n assert 'S' in alphabet2\n assert 'E' in alphabet2\n assert kmer_counts1 == {'EE': 4, 'ES': 1, 'SS': 11, 'SH': 1, 'HH': 3,\n 'II': 4, 'IS': 1, 'SM': 1, 'MM': 1, 'BB': 4, 'BS': 1}\n assert kmer_counts2 == {'SS': 20, 'EE': 7, 'ES': 3, 'SE': 2}\n assert template1 == 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSMMMSSSHHHSSSEEE'\n assert dotbracket_string1 == '...(((...(((...(((...))))))...)))...(((...)))...'\n assert template2 == 'EEESSSSSSEEE'\n assert dotbracket_string2 == '...((()))...'\n no_sec_peak = 0\n process2 = SecStructure(data, data, k, peak, top, feature, cmd,\n struct_data, no_sec_peak)\n alphabet1 = process2.getStructProfile1().getAlphabet()\n alphabet2 = process2.getStructProfile2().getAlphabet()\n kmer_counts1 = process2.getStructProfile1().getProfile()\n kmer_counts2 = process2.getStructProfile2().getProfile()\n results = SecStructure.processData(process2)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert len(alphabet1) == 10\n for e in ['s', 'h', 'b', 'i', 'm', 'E', 'S', 'B', 'I', 'E']:\n assert e in alphabet1\n assert len(alphabet2) == 4\n for e in ['s', 'S', 'e', 'E']:\n assert e in alphabet2\n assert kmer_counts1 == {'eE': 1, 'Es': 1, 'sS': 1, 'Sh': 1, 'iI': 1,\n 'Is': 1, 'bB': 1, 'Bs': 1}\n assert kmer_counts2 == {'sS': 3, 'Ss': 2, 'sE': 1, 'Ee': 1, 'Se': 1}\n assert template1 == 'EEESSSIIISSSBBBSSSSSSSSSIIISSSEEE'\n assert dotbracket_string1 == '...(((...(((...((())))))...)))...'\n assert template2 == 'EEESSSSSSEEE'\n assert dotbracket_string2 == '...((()))...'\n sProfile1 = process.getStructProfile1()\n sProfile2 = process.getStructProfile2()\n alphabet3 = ['S', 'B', 'E']\n alphabet4 = ['S', 'I', 'E']\n sProfile1.setAlphabet(alphabet3)\n sProfile2.setAlphabet(alphabet4)\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert template1 == 'EEESSSBBBSSSSSSSSSEEE'\n assert dotbracket_string1 == '...(((...((())))))...'\n assert template2 == 'EEESSSIIISSSSSSIIISSSEEE'\n assert dotbracket_string2 == '...(((...((()))...)))...'\n alphabet5 = ['S', 'H', 'E']\n alphabet6 = ['S', 'H', 'M', 'E']\n sProfile1.setAlphabet(alphabet5)\n sProfile2.setAlphabet(alphabet6)\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert template1 == 'EEESSSHHHSSSEEE'\n assert dotbracket_string1 == '...(((...)))...'\n assert template2 == 'EEESSSHHHSSSMMMSSSHHHSSSEEE'\n assert dotbracket_string2 == '...(((...)))...(((...)))...'\n alphabet7 = ['S', 'H', 'E', 'B', 'I']\n alphabet8 = ['S', 'M', 'E']\n sProfile1.setAlphabet(alphabet7)\n sProfile2.setAlphabet(alphabet8)\n results = SecStructure.processData(process)\n template1 = results[0][0]\n template2 = results[1][0]\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n assert template1 == 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE'\n assert dotbracket_string1 == '...(((...(((...(((...))))))...)))...'\n assert template2 == 'EEESSSSSSEEE'\n assert dotbracket_string2 == '...((()))...'\n\n\ndef test_createColorVector():\n k = 2\n no_sec_peak = 1\n template = 'EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE'\n kmer_counts = {'EE': 5, 'ES': 7, 'SS': 20, 'SI': 10, 'II': 15, 'IS': 11,\n 'SB': 5, 'BB': 6, 'BS': 5, 'SH': 4, 'HH': 5, 'HS': 4, 'SE': 7}\n template_sTree = STree.STree(template)\n normalization_vector1 = None\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm1, not_matched1, color_domain_max1 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector1)\n assert len(color_hm) == len(new_color_hm1)\n for i in color_hm.keys():\n x = color_hm[i]\n if x > 0:\n assert new_color_hm1[i] == math.log(x, 2)\n else:\n assert new_color_hm1[i] == 0\n assert len(not_matched1) == 0\n assert color_domain_max1 == 4.954196310386876\n normalization_vector2 = {'EE': 0, 'ES': 0, 'SS': 0.7, 'SI': 0.1, 'II': \n 0.2, 'IS': 0, 'SB': 0, 'BB': 0, 'BS': 0, 'SH': 0, 'HH': 0, 'HS': 0,\n 'SE': 0}\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm2, not_matched2, color_domain_max2 = createColorVector(k,\n template_sTree, kmer_counts, color_hm, no_sec_peak,\n normalization_vector2)\n last_idx = -1\n last_kmer = ''\n test_color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in normalization_vector2:\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer)), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n for i in range(0, k):\n current_idx = str(idx + i + 1)\n if last_idx + 2 == int(current_idx) and last_kmer == kmer:\n continue\n test_color_hm[current_idx] += kmer_counts[kmer] / norm\n last_idx = idx\n last_kmer = kmer\n test_color_hm = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm.items()}\n test_color_domain_max = max(test_color_hm.values())\n assert new_color_hm1 is not new_color_hm2\n assert len(color_hm) == len(new_color_hm2)\n assert len(not_matched2) == 0\n assert color_domain_max2 == test_color_domain_max\n for i in new_color_hm2.keys():\n assert new_color_hm2[i] == test_color_hm[i]\n kmer_counts2 = {'Ee': 5, 'eS': 7, 'sS': 20, 'Si': 10, 'iI': 15, 'iS': \n 11, 'Sb': 5, 'Bb': 6, 'bS': 5, 'sH': 4, 'Hh': 5, 'hS': 4, 'Se': 7}\n no_sec_peak2 = 0\n color_hm = {str(i): (0) for i in range(1, len(template) + 1)}\n new_color_hm3, not_matched3, color_domain_max3 = createColorVector(k,\n template_sTree, kmer_counts2, color_hm, no_sec_peak2,\n normalization_vector2)\n test_color_hm2 = {str(i): (0) for i in range(1, len(template) + 1)}\n for kmer in kmer_counts2.keys():\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.\n escape(kmer.upper())), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer.upper()]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n idx = [(idx + i) for i in range(0, len(kmer)) if kmer[i].isupper()\n ][0]\n test_color_hm2[str(idx + 1)] += kmer_counts2[kmer] / norm\n test_color_hm2 = {x: (math.log(y, 2) if y > 0 else y) for x, y in\n test_color_hm2.items()}\n test_color_domain_max2 = max(test_color_hm2.values())\n assert len(not_matched3) == 0\n assert new_color_hm2 is not new_color_hm3\n assert len(color_hm) == len(new_color_hm3)\n for i in test_color_hm2:\n assert test_color_hm2[i] == new_color_hm3[i]\n assert test_color_domain_max2 == color_domain_max3\n\n\ndef test_helpAddIBloop():\n k = 3\n template1 = ['EEE']\n internalloop = True\n bulge = True\n forward = True\n new_template1 = helpAddIBloop(k, template1, internalloop, bulge, forward)\n template2 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH']\n internalloop = True\n bulge = True\n forward = False\n new_template2 = helpAddIBloop(k, template2, internalloop, bulge, forward)\n template3_f = ['EEE']\n template3_b = ['EEE', 'SSS', 'III', 'SSS', 'HHH']\n internalloop = True\n bulge = False\n forward = True\n new_template3_f = helpAddIBloop(k, template3_f, internalloop, bulge,\n forward)\n forward = False\n new_template3_b = helpAddIBloop(k, template3_b, internalloop, bulge,\n forward)\n template4_f = ['EEE']\n template4_b = ['EEE', 'SSS', 'BBB', 'SSS', 'HHH']\n internalloop = False\n bulge = True\n forward = True\n new_template4_f = helpAddIBloop(k, template4_f, internalloop, bulge,\n forward)\n forward = False\n new_template4_b = helpAddIBloop(k, template4_b, internalloop, bulge,\n forward)\n assert new_template1 == ['EEE', 'SSS', 'III', 'SSS', 'BBB']\n assert new_template2 == ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS',\n 'HHH', 'SSS', 'SSS', 'III']\n assert new_template3_f == ['EEE', 'SSS', 'III']\n assert new_template3_b == ['EEE', 'SSS', 'III', 'SSS', 'HHH', 'SSS', 'III']\n assert new_template4_f == ['EEE', 'SSS', 'BBB']\n assert new_template4_b == ['EEE', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS']\n\n\ndef test_element2dotbracket():\n k3 = 3\n k2 = 2\n k4 = 4\n elem_list1 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS',\n 'SSS', 'III', 'SSS', 'EEE']\n dotbracket_string1 = '...(((...(((...(((...))))))...)))...'\n elem_list2 = ['EE', 'SS', 'II', 'SS', 'HH', 'SS', 'II', 'SS', 'MM',\n 'SS', 'BB', 'SS', 'HH', 'SS', 'SS', 'EE']\n dotbracket_string2 = '..((..((..))..))..((..((..))))..'\n elem_list3 = ['EEEE', 'SSSS', 'SSSS', 'EEEE']\n dotbracket_string3 = '....(((())))....'\n elem_list4 = ['EEE', 'SSS', 'III', 'SSS', 'BBB', 'SSS', 'HHH', 'SSS',\n 'SSS', 'III', 'SSS', 'MMM', 'SSS', 'HHH', 'SSS', 'EEE']\n dotbracket_string4 = '...(((...(((...(((...))))))...)))...(((...)))...'\n db1 = []\n db1.extend(element2dotbracket(elem_list1, k3, 0, 6, True))\n db1.extend(element2dotbracket(elem_list1, k3, 7, len(elem_list1) - 1, \n False))\n db1 = ''.join(db1)\n db2 = []\n db2.extend(element2dotbracket(elem_list2, k2, 0, 4, True))\n db2.extend(element2dotbracket(elem_list2, k2, 5, 8, False))\n db2.extend(element2dotbracket(elem_list2, k2, 9, 12, True))\n db2.extend(element2dotbracket(elem_list2, k2, 13, len(elem_list2) - 1, \n False))\n db2 = ''.join(db2)\n db3 = []\n db3.extend(element2dotbracket(elem_list3, k4, 0, 1, True))\n db3.extend(element2dotbracket(elem_list3, k4, 2, len(elem_list3) - 1, \n False))\n db3 = ''.join(db3)\n db4 = []\n db4.extend(element2dotbracket(elem_list4, k3, 0, 6, True))\n db4.extend(element2dotbracket(elem_list4, k3, 7, 11, False))\n db4.extend(element2dotbracket(elem_list4, k3, 12, 13, True))\n db4.extend(element2dotbracket(elem_list4, k3, 14, len(elem_list4) - 1, \n False))\n db4 = ''.join(db4)\n assert db1 == dotbracket_string1\n assert db2 == dotbracket_string2\n assert db3 == dotbracket_string3\n assert db4 == dotbracket_string4\n",
"step-5": "from src.secStructure import *\nfrom suffix_trees import STree\nimport math\nimport re\n\n\ndef test_processData():\n # Test1: ignoring peak position\n data = ['example/example1.fa', 'example/example2.fa']\n struct_data = ['example/exampleStrucData/exampleStructuralData1.fa',\n 'example/exampleStrucData/exampleStructuralData2.fa']\n k = 3\n top = 10\n peak = None\n feature = None\n cmd = False\n no_sec_peak = 1 # True\n\n # Executing\n\n process = SecStructure(data, data, k, peak, top, feature, cmd, struct_data, no_sec_peak)\n\n alphabet1 = process.getStructProfile1().getAlphabet()\n alphabet2 = process.getStructProfile2().getAlphabet()\n\n kmer_counts1 = process.getStructProfile1().getProfile()\n kmer_counts2 = process.getStructProfile2().getProfile()\n\n results = SecStructure.processData(process)\n\n template1 = results[0][0]\n template2 = results[1][0]\n\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n\n # Testing\n\n assert len(alphabet1) == 6\n for e in [\"S\", \"H\", \"B\", \"I\", \"M\", \"E\"]:\n assert e in alphabet1\n\n assert len(alphabet2) == 2\n assert \"S\" in alphabet2\n assert \"E\" in alphabet2\n\n assert kmer_counts1 == {'EE': 4, 'ES': 1, 'SS': 11, 'SH': 1, 'HH': 3, 'II': 4, 'IS': 1, 'SM': 1, 'MM': 1, 'BB': 4,\n 'BS': 1}\n assert kmer_counts2 == {'SS': 20, 'EE': 7, 'ES': 3, 'SE': 2}\n\n assert template1 == \"EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSMMMSSSHHHSSSEEE\"\n assert dotbracket_string1 == \"...(((...(((...(((...))))))...)))...(((...)))...\"\n\n assert template2 == \"EEESSSSSSEEE\"\n assert dotbracket_string2 == \"...((()))...\"\n\n # Test2: with peak position\n no_sec_peak = 0 # True\n\n # Executing\n\n process2 = SecStructure(data, data, k, peak, top, feature, cmd, struct_data, no_sec_peak)\n\n alphabet1 = process2.getStructProfile1().getAlphabet()\n alphabet2 = process2.getStructProfile2().getAlphabet()\n\n kmer_counts1 = process2.getStructProfile1().getProfile()\n kmer_counts2 = process2.getStructProfile2().getProfile()\n\n results = SecStructure.processData(process2)\n\n template1 = results[0][0]\n template2 = results[1][0]\n\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n\n # Testing\n\n assert len(alphabet1) == 10\n for e in [\"s\", \"h\", \"b\", \"i\", \"m\", \"E\", \"S\", \"B\", \"I\", \"E\"]:\n assert e in alphabet1\n\n assert len(alphabet2) == 4\n for e in [\"s\", \"S\", \"e\", \"E\"]:\n assert e in alphabet2\n\n assert kmer_counts1 == {'eE': 1, 'Es': 1, 'sS': 1, 'Sh': 1, 'iI': 1, 'Is': 1, 'bB': 1, 'Bs': 1}\n assert kmer_counts2 == {'sS': 3, 'Ss': 2, 'sE': 1, 'Ee': 1, 'Se': 1}\n\n assert template1 == \"EEESSSIIISSSBBBSSSSSSSSSIIISSSEEE\"\n assert dotbracket_string1 == \"...(((...(((...((())))))...)))...\"\n\n assert template2 == \"EEESSSSSSEEE\"\n assert dotbracket_string2 == \"...((()))...\"\n\n # Test3: different alphabets\n sProfile1 = process.getStructProfile1()\n sProfile2 = process.getStructProfile2()\n\n # Test3a: alphabets with no multiloop\n\n alphabet3 = [\"S\", \"B\", \"E\"]\n alphabet4 = [\"S\", \"I\", \"E\"]\n\n sProfile1.setAlphabet(alphabet3)\n sProfile2.setAlphabet(alphabet4)\n\n results = SecStructure.processData(process)\n\n template1 = results[0][0]\n template2 = results[1][0]\n\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n\n assert template1 == \"EEESSSBBBSSSSSSSSSEEE\"\n assert dotbracket_string1 == \"...(((...((())))))...\"\n\n assert template2 == \"EEESSSIIISSSSSSIIISSSEEE\"\n assert dotbracket_string2 == \"...(((...((()))...)))...\"\n\n # Test3b: alphabets with only hairpin or hairpin and multiloop\n alphabet5 = [\"S\", \"H\", \"E\"]\n alphabet6 = [\"S\", \"H\", \"M\", \"E\"]\n\n sProfile1.setAlphabet(alphabet5)\n sProfile2.setAlphabet(alphabet6)\n\n results = SecStructure.processData(process)\n\n template1 = results[0][0]\n template2 = results[1][0]\n\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n\n assert template1 == \"EEESSSHHHSSSEEE\"\n assert dotbracket_string1 == \"...(((...)))...\"\n\n assert template2 == \"EEESSSHHHSSSMMMSSSHHHSSSEEE\"\n assert dotbracket_string2 == \"...(((...)))...(((...)))...\"\n\n # Test3c: ('flawed') alphabets with no multiloops\n\n alphabet7 = [\"S\", \"H\", \"E\", \"B\", \"I\"]\n alphabet8 = [\"S\", \"M\", \"E\"] # should be equal to [\"S\",\"E\"]\n\n sProfile1.setAlphabet(alphabet7)\n sProfile2.setAlphabet(alphabet8)\n\n results = SecStructure.processData(process)\n\n template1 = results[0][0]\n template2 = results[1][0]\n\n dotbracket_string1 = results[0][1]\n dotbracket_string2 = results[1][1]\n\n assert template1 == \"EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE\"\n assert dotbracket_string1 == \"...(((...(((...(((...))))))...)))...\"\n\n assert template2 == \"EEESSSSSSEEE\"\n assert dotbracket_string2 == \"...((()))...\"\n\n\ndef test_createColorVector():\n # Test1: no normalization vector wanted\n k = 2\n no_sec_peak = 1\n template = \"EEESSSIIISSSBBBSSSHHHSSSSSSIIISSSEEE\"\n kmer_counts = {\"EE\": 5, \"ES\": 7, \"SS\": 20, \"SI\": 10, \"II\": 15, \"IS\": 11, \"SB\": 5, \"BB\": 6, \"BS\": 5, \"SH\": 4,\n \"HH\": 5, \"HS\": 4, \"SE\": 7}\n template_sTree = STree.STree(template)\n normalization_vector1 = None\n\n color_hm = {str(i): 0 for i in range(1, len(template) + 1)}\n\n # Executing\n new_color_hm1, not_matched1, color_domain_max1 = createColorVector(k, template_sTree, kmer_counts, color_hm,\n no_sec_peak, normalization_vector1)\n\n assert len(color_hm) == len(new_color_hm1)\n for i in color_hm.keys():\n x = color_hm[i]\n if x > 0:\n assert new_color_hm1[i] == math.log(x, 2)\n else:\n assert new_color_hm1[i] == 0\n assert len(not_matched1) == 0\n assert color_domain_max1 == 4.954196310386876\n\n # Test2: with normalization vector\n\n normalization_vector2 = {\"EE\": 0, \"ES\": 0, \"SS\": 0.7, \"SI\": 0.1, \"II\": 0.2, \"IS\": 0, \"SB\": 0, \"BB\": 0, \"BS\": 0,\n \"SH\": 0, \"HH\": 0, \"HS\": 0, \"SE\": 0}\n\n # Execution\n\n color_hm = {str(i): 0 for i in range(1, len(template) + 1)}\n new_color_hm2, not_matched2, color_domain_max2 = createColorVector(k, template_sTree, kmer_counts, color_hm,\n no_sec_peak, normalization_vector2)\n\n last_idx = -1\n last_kmer = \"\"\n\n test_color_hm = {str(i): 0 for i in range(1, len(template) + 1)}\n for kmer in normalization_vector2:\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.escape(kmer)), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n for i in range(0, k):\n current_idx = str(idx + i + 1)\n if last_idx + 2 == int(current_idx) and last_kmer == kmer:\n continue\n test_color_hm[current_idx] += (kmer_counts[kmer] / norm)\n last_idx = idx\n last_kmer = kmer\n\n test_color_hm = {x: math.log(y, 2) if y > 0 else y for x, y in test_color_hm.items()}\n test_color_domain_max = max(test_color_hm.values())\n\n # Testing\n\n assert new_color_hm1 is not new_color_hm2\n assert len(color_hm) == len(new_color_hm2)\n assert len(not_matched2) == 0\n assert color_domain_max2 == test_color_domain_max\n for i in new_color_hm2.keys():\n assert new_color_hm2[i] == test_color_hm[i]\n\n # Test3: normalization vector and secondary peak position\n\n kmer_counts2 = {\"Ee\": 5, \"eS\": 7, \"sS\": 20, \"Si\": 10, \"iI\": 15, \"iS\": 11, \"Sb\": 5, \"Bb\": 6, \"bS\": 5, \"sH\": 4,\n \"Hh\": 5, \"hS\": 4, \"Se\": 7}\n no_sec_peak2 = 0\n\n # Execution\n\n color_hm = {str(i): 0 for i in range(1, len(template) + 1)}\n new_color_hm3, not_matched3, color_domain_max3 = createColorVector(k, template_sTree, kmer_counts2, color_hm,\n no_sec_peak2, normalization_vector2)\n\n test_color_hm2 = {str(i): 0 for i in range(1, len(template) + 1)}\n for kmer in kmer_counts2.keys():\n indices_list = [t.start() for t in re.finditer('(?={0})'.format(re.escape(kmer.upper())), template)]\n indices_list.sort()\n norm = normalization_vector2[kmer.upper()]\n if norm == 0:\n norm = 1\n for idx in indices_list:\n # use only peak-position in 2-mer for visualization\n idx = [idx + i for i in range(0, len(kmer)) if kmer[i].isupper()][0]\n test_color_hm2[str(idx + 1)] += (kmer_counts2[kmer] / norm)\n\n test_color_hm2 = {x: math.log(y, 2) if y > 0 else y for x, y in test_color_hm2.items()}\n test_color_domain_max2 = max(test_color_hm2.values())\n\n # Testing\n\n assert len(not_matched3) == 0\n assert new_color_hm2 is not new_color_hm3\n assert len(color_hm) == len(new_color_hm3)\n for i in test_color_hm2:\n assert test_color_hm2[i] == new_color_hm3[i]\n assert test_color_domain_max2 == color_domain_max3\n\n\ndef test_helpAddIBloop():\n k = 3\n\n # Test 1: forward and all true\n template1 = [\"EEE\"]\n internalloop = True\n bulge = True\n forward = True\n\n # Execution\n new_template1 = helpAddIBloop(k, template1, internalloop, bulge, forward)\n\n # Test 2: backward and all true\n template2 = [\"EEE\", \"SSS\", \"III\", \"SSS\", \"BBB\", \"SSS\", \"HHH\"]\n internalloop = True\n bulge = True\n forward = False\n\n # Execution\n new_template2 = helpAddIBloop(k, template2, internalloop, bulge, forward)\n\n # Test 3: only internal loops, forward and backward\n template3_f = [\"EEE\"]\n template3_b = [\"EEE\", \"SSS\", \"III\", \"SSS\", \"HHH\"]\n internalloop = True\n bulge = False\n forward = True\n\n # Execution\n new_template3_f = helpAddIBloop(k, template3_f, internalloop, bulge, forward)\n\n forward = False\n new_template3_b = helpAddIBloop(k, template3_b, internalloop, bulge, forward)\n\n # Test 4: only bulges, forward and backward\n template4_f = [\"EEE\"]\n template4_b = [\"EEE\", \"SSS\", \"BBB\", \"SSS\", \"HHH\"]\n internalloop = False\n bulge = True\n forward = True\n\n # Execution\n new_template4_f = helpAddIBloop(k, template4_f, internalloop, bulge, forward)\n\n forward = False\n new_template4_b = helpAddIBloop(k, template4_b, internalloop, bulge, forward)\n\n # Testing\n assert new_template1 == [\"EEE\", \"SSS\", \"III\", \"SSS\", \"BBB\"]\n assert new_template2 == [\"EEE\", \"SSS\", \"III\", \"SSS\", \"BBB\", \"SSS\", \"HHH\", \"SSS\", \"SSS\", \"III\"]\n assert new_template3_f == [\"EEE\", \"SSS\", \"III\"]\n assert new_template3_b == [\"EEE\", \"SSS\", \"III\", \"SSS\", \"HHH\", \"SSS\", \"III\"]\n assert new_template4_f == [\"EEE\", \"SSS\", \"BBB\"]\n assert new_template4_b == [\"EEE\", \"SSS\", \"BBB\", \"SSS\", \"HHH\", \"SSS\"]\n\n\ndef test_element2dotbracket():\n k3 = 3\n k2 = 2\n k4 = 4\n\n # Test1 without multiloop\n elem_list1 = [\"EEE\", \"SSS\", \"III\", \"SSS\", \"BBB\", \"SSS\", \"HHH\", \"SSS\", \"SSS\", \"III\", \"SSS\", \"EEE\"]\n dotbracket_string1 = \"...(((...(((...(((...))))))...)))...\"\n\n # Test2 with multiloop\n elem_list2 = [\"EE\", \"SS\", \"II\", \"SS\", \"HH\", \"SS\", \"II\", \"SS\", \"MM\", \"SS\", \"BB\", \"SS\", \"HH\", \"SS\", \"SS\", \"EE\"]\n dotbracket_string2 = \"..((..((..))..))..((..((..))))..\"\n\n # Test 3 without loops\n elem_list3 = [\"EEEE\", \"SSSS\", \"SSSS\", \"EEEE\"]\n dotbracket_string3 = \"....(((())))....\"\n\n # Test 5 with everything\n elem_list4 = [\"EEE\", \"SSS\", \"III\", \"SSS\", \"BBB\", \"SSS\", \"HHH\", \"SSS\", \"SSS\", \"III\", \"SSS\", \"MMM\", \"SSS\", \"HHH\",\n \"SSS\", \"EEE\"]\n dotbracket_string4 = \"...(((...(((...(((...))))))...)))...(((...)))...\"\n\n # Execution\n db1 = []\n db1.extend(element2dotbracket(elem_list1, k3, 0, 6, True))\n db1.extend(element2dotbracket(elem_list1, k3, 7, len(elem_list1) - 1, False))\n db1 = ''.join(db1)\n\n db2 = []\n db2.extend(element2dotbracket(elem_list2, k2, 0, 4, True))\n db2.extend(element2dotbracket(elem_list2, k2, 5, 8, False))\n db2.extend(element2dotbracket(elem_list2, k2, 9, 12, True))\n db2.extend(element2dotbracket(elem_list2, k2, 13, len(elem_list2) - 1, False))\n db2 = ''.join(db2)\n\n db3 = []\n db3.extend(element2dotbracket(elem_list3, k4, 0, 1, True))\n db3.extend(element2dotbracket(elem_list3, k4, 2, len(elem_list3) - 1, False))\n db3 = ''.join(db3)\n\n db4 = []\n db4.extend(element2dotbracket(elem_list4, k3, 0, 6, True))\n db4.extend(element2dotbracket(elem_list4, k3, 7, 11, False))\n db4.extend(element2dotbracket(elem_list4, k3, 12, 13, True))\n db4.extend(element2dotbracket(elem_list4, k3, 14, len(elem_list4) - 1, False))\n db4 = ''.join(db4)\n\n # testing\n assert db1 == dotbracket_string1\n assert db2 == dotbracket_string2\n assert db3 == dotbracket_string3\n assert db4 == dotbracket_string4\n",
"step-ids": [
1,
3,
4,
5,
6
]
}
|
[
1,
3,
4,
5,
6
] |
#!/usr/bin/env python
# coding: utf-8
import logging
import config
def get_common_logger(name='common', logfile=None):
'''
args: name (str): logger name
logfile (str): log file, use stream handler (stdout) as default.
return:
logger obj
'''
my_logger = logging.getLogger(name)
my_logger.setLevel(config.LOG_LEVEL)
if logfile:
handler = logging.FileHandler(logfile)
else:
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
handler.setFormatter(formatter)
my_logger.addHandler(handler)
# Stop logger propagate, forbiden duplicate log.
my_logger.propagate = False
return my_logger
COMMON_LOGGER = get_common_logger('common logger')
if __name__ == '__main__':
COMMON_LOGGER.debug('test')
|
normal
|
{
"blob_id": "1754bce54a47cb78dce3b545d3dce835a4e0e69f",
"index": 947,
"step-1": "<mask token>\n\n\ndef get_common_logger(name='common', logfile=None):\n \"\"\"\n args: name (str): logger name\n logfile (str): log file, use stream handler (stdout) as default.\n return:\n logger obj\n \"\"\"\n my_logger = logging.getLogger(name)\n my_logger.setLevel(config.LOG_LEVEL)\n if logfile:\n handler = logging.FileHandler(logfile)\n else:\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s'\n )\n handler.setFormatter(formatter)\n my_logger.addHandler(handler)\n my_logger.propagate = False\n return my_logger\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_common_logger(name='common', logfile=None):\n \"\"\"\n args: name (str): logger name\n logfile (str): log file, use stream handler (stdout) as default.\n return:\n logger obj\n \"\"\"\n my_logger = logging.getLogger(name)\n my_logger.setLevel(config.LOG_LEVEL)\n if logfile:\n handler = logging.FileHandler(logfile)\n else:\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s'\n )\n handler.setFormatter(formatter)\n my_logger.addHandler(handler)\n my_logger.propagate = False\n return my_logger\n\n\n<mask token>\nif __name__ == '__main__':\n COMMON_LOGGER.debug('test')\n",
"step-3": "<mask token>\n\n\ndef get_common_logger(name='common', logfile=None):\n \"\"\"\n args: name (str): logger name\n logfile (str): log file, use stream handler (stdout) as default.\n return:\n logger obj\n \"\"\"\n my_logger = logging.getLogger(name)\n my_logger.setLevel(config.LOG_LEVEL)\n if logfile:\n handler = logging.FileHandler(logfile)\n else:\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s'\n )\n handler.setFormatter(formatter)\n my_logger.addHandler(handler)\n my_logger.propagate = False\n return my_logger\n\n\nCOMMON_LOGGER = get_common_logger('common logger')\nif __name__ == '__main__':\n COMMON_LOGGER.debug('test')\n",
"step-4": "import logging\nimport config\n\n\ndef get_common_logger(name='common', logfile=None):\n \"\"\"\n args: name (str): logger name\n logfile (str): log file, use stream handler (stdout) as default.\n return:\n logger obj\n \"\"\"\n my_logger = logging.getLogger(name)\n my_logger.setLevel(config.LOG_LEVEL)\n if logfile:\n handler = logging.FileHandler(logfile)\n else:\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s'\n )\n handler.setFormatter(formatter)\n my_logger.addHandler(handler)\n my_logger.propagate = False\n return my_logger\n\n\nCOMMON_LOGGER = get_common_logger('common logger')\nif __name__ == '__main__':\n COMMON_LOGGER.debug('test')\n",
"step-5": "#!/usr/bin/env python\n# coding: utf-8\n\nimport logging\n\nimport config\n\n\ndef get_common_logger(name='common', logfile=None):\n '''\n args: name (str): logger name\n logfile (str): log file, use stream handler (stdout) as default.\n return:\n logger obj\n '''\n my_logger = logging.getLogger(name)\n my_logger.setLevel(config.LOG_LEVEL)\n if logfile:\n handler = logging.FileHandler(logfile)\n else:\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\n handler.setFormatter(formatter)\n my_logger.addHandler(handler)\n # Stop logger propagate, forbiden duplicate log.\n my_logger.propagate = False\n return my_logger\n\n\nCOMMON_LOGGER = get_common_logger('common logger')\n\nif __name__ == '__main__':\n COMMON_LOGGER.debug('test')\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
print(1 / 2 * 2)
<|reserved_special_token_1|>
print(1/2 * 2) # division ret
|
flexible
|
{
"blob_id": "2c1e51f2c392e77299463d95a2277b3d2ca7c299",
"index": 4336,
"step-1": "<mask token>\n",
"step-2": "print(1 / 2 * 2)\n",
"step-3": "print(1/2 * 2) # division ret\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
import matplotlib.pyplot as plt
import sys
sys.path.append('coin_flipping_src')
from monte_carlo import monte_carlo
from probability import probability
plt.style.use('bmh')
x_coords = range(10)
probablility_results = [probability(x,10) for x in x_coords]
plt.plot(x_coords,probablility_results,linewidth = 2.5)
# plt.plot([0,1,2,3,4],[0.1, 0.3, 0.5, 0.1, 0.1],linewidth=2.5)
for _ in range(5):
plt.plot(x_coords,[monte_carlo(x,10,100) for x in x_coords],linewidth = 0.75)
# plt.plot([0,1,2,3,4],[0.3, 0.1, 0.4, 0.2, 0.1],linewidth=0.75)
# plt.plot([0,1,2,3,4],[0.2, 0.2, 0.3, 0.3, 0.2],linewidth=0.75)
plt.legend(['True','MC 1','MC 2','MC 3','MC 4','MC 5'])
plt.xlabel('Number of Heads')
plt.ylabel('Probability')
plt.title('True Distribution vs Monte Carlo Simulations for 10 Coin Flips')
plt.savefig('plot.png')
plt.show()
|
normal
|
{
"blob_id": "124d7da330aa7c869320e10f4f89cc1c872f85f2",
"index": 430,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.append('coin_flipping_src')\n<mask token>\nplt.style.use('bmh')\n<mask token>\nplt.plot(x_coords, probablility_results, linewidth=2.5)\nfor _ in range(5):\n plt.plot(x_coords, [monte_carlo(x, 10, 100) for x in x_coords],\n linewidth=0.75)\nplt.legend(['True', 'MC 1', 'MC 2', 'MC 3', 'MC 4', 'MC 5'])\nplt.xlabel('Number of Heads')\nplt.ylabel('Probability')\nplt.title('True Distribution vs Monte Carlo Simulations for 10 Coin Flips')\nplt.savefig('plot.png')\nplt.show()\n",
"step-3": "<mask token>\nsys.path.append('coin_flipping_src')\n<mask token>\nplt.style.use('bmh')\nx_coords = range(10)\nprobablility_results = [probability(x, 10) for x in x_coords]\nplt.plot(x_coords, probablility_results, linewidth=2.5)\nfor _ in range(5):\n plt.plot(x_coords, [monte_carlo(x, 10, 100) for x in x_coords],\n linewidth=0.75)\nplt.legend(['True', 'MC 1', 'MC 2', 'MC 3', 'MC 4', 'MC 5'])\nplt.xlabel('Number of Heads')\nplt.ylabel('Probability')\nplt.title('True Distribution vs Monte Carlo Simulations for 10 Coin Flips')\nplt.savefig('plot.png')\nplt.show()\n",
"step-4": "import matplotlib.pyplot as plt\nimport sys\nsys.path.append('coin_flipping_src')\nfrom monte_carlo import monte_carlo\nfrom probability import probability\nplt.style.use('bmh')\nx_coords = range(10)\nprobablility_results = [probability(x, 10) for x in x_coords]\nplt.plot(x_coords, probablility_results, linewidth=2.5)\nfor _ in range(5):\n plt.plot(x_coords, [monte_carlo(x, 10, 100) for x in x_coords],\n linewidth=0.75)\nplt.legend(['True', 'MC 1', 'MC 2', 'MC 3', 'MC 4', 'MC 5'])\nplt.xlabel('Number of Heads')\nplt.ylabel('Probability')\nplt.title('True Distribution vs Monte Carlo Simulations for 10 Coin Flips')\nplt.savefig('plot.png')\nplt.show()\n",
"step-5": "import matplotlib.pyplot as plt\nimport sys\nsys.path.append('coin_flipping_src')\nfrom monte_carlo import monte_carlo\nfrom probability import probability\nplt.style.use('bmh')\nx_coords = range(10)\nprobablility_results = [probability(x,10) for x in x_coords]\nplt.plot(x_coords,probablility_results,linewidth = 2.5)\n# plt.plot([0,1,2,3,4],[0.1, 0.3, 0.5, 0.1, 0.1],linewidth=2.5)\nfor _ in range(5):\n plt.plot(x_coords,[monte_carlo(x,10,100) for x in x_coords],linewidth = 0.75)\n# plt.plot([0,1,2,3,4],[0.3, 0.1, 0.4, 0.2, 0.1],linewidth=0.75)\n# plt.plot([0,1,2,3,4],[0.2, 0.2, 0.3, 0.3, 0.2],linewidth=0.75)\nplt.legend(['True','MC 1','MC 2','MC 3','MC 4','MC 5'])\nplt.xlabel('Number of Heads')\nplt.ylabel('Probability')\nplt.title('True Distribution vs Monte Carlo Simulations for 10 Coin Flips')\nplt.savefig('plot.png')\nplt.show()",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
myxlobject.convert_sheet_to_dict(file_path='Soul Breaks.xlsx', sheet=
'First Sheet', filter_variables_dict={'User Type': 'Admin',
'Environment': 'Dev'})
<|reserved_special_token_1|>
<|reserved_special_token_0|>
myxlobject = XlToDict()
myxlobject.convert_sheet_to_dict(file_path='Soul Breaks.xlsx', sheet=
'First Sheet', filter_variables_dict={'User Type': 'Admin',
'Environment': 'Dev'})
<|reserved_special_token_1|>
import xl2dict
myxlobject = XlToDict()
myxlobject.convert_sheet_to_dict(file_path='Soul Breaks.xlsx', sheet=
'First Sheet', filter_variables_dict={'User Type': 'Admin',
'Environment': 'Dev'})
<|reserved_special_token_1|>
import xl2dict
myxlobject= XlToDict()
myxlobject.convert_sheet_to_dict(file_path="Soul Breaks.xlsx", sheet="First Sheet",
filter_variables_dict={"User Type" : "Admin", "Environment" : "Dev"})
|
flexible
|
{
"blob_id": "8ec981bf8746e09d3865bc20dcfbf2fbd797c145",
"index": 7511,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmyxlobject.convert_sheet_to_dict(file_path='Soul Breaks.xlsx', sheet=\n 'First Sheet', filter_variables_dict={'User Type': 'Admin',\n 'Environment': 'Dev'})\n",
"step-3": "<mask token>\nmyxlobject = XlToDict()\nmyxlobject.convert_sheet_to_dict(file_path='Soul Breaks.xlsx', sheet=\n 'First Sheet', filter_variables_dict={'User Type': 'Admin',\n 'Environment': 'Dev'})\n",
"step-4": "import xl2dict\nmyxlobject = XlToDict()\nmyxlobject.convert_sheet_to_dict(file_path='Soul Breaks.xlsx', sheet=\n 'First Sheet', filter_variables_dict={'User Type': 'Admin',\n 'Environment': 'Dev'})\n",
"step-5": "import xl2dict\n\nmyxlobject= XlToDict()\nmyxlobject.convert_sheet_to_dict(file_path=\"Soul Breaks.xlsx\", sheet=\"First Sheet\",\n filter_variables_dict={\"User Type\" : \"Admin\", \"Environment\" : \"Dev\"})",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
'''
Handprint module for handling credentials.
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2018-2022 by the California Institute of Technology. This code
is open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more information.
'''
from .base import Credentials
from .amazon_auth import AmazonCredentials
from .google_auth import GoogleCredentials
from .microsoft_auth import MicrosoftCredentials
|
normal
|
{
"blob_id": "7e29220752b4a52be34cdf0c734695d1052d0414",
"index": 9309,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfrom .base import Credentials\nfrom .amazon_auth import AmazonCredentials\nfrom .google_auth import GoogleCredentials\nfrom .microsoft_auth import MicrosoftCredentials\n",
"step-3": "'''\nHandprint module for handling credentials.\n\nAuthors\n-------\n\nMichael Hucka <mhucka@caltech.edu> -- Caltech Library\n\nCopyright\n---------\n\nCopyright (c) 2018-2022 by the California Institute of Technology. This code\nis open-source software released under a 3-clause BSD license. Please see the\nfile \"LICENSE\" for more information.\n'''\n\nfrom .base import Credentials\nfrom .amazon_auth import AmazonCredentials\nfrom .google_auth import GoogleCredentials\nfrom .microsoft_auth import MicrosoftCredentials\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
ALPACA_KEY = 'Enter your apaca key here'
ALPACA_SECRET_KEY = 'Enter your apaca secret key here'
ALPACA_MARKET = 'enter alpaca market link here'
TWILIO_KEY = 'enter your twilio key here'
TWILIO_SECRET_KEY = 'enter your twilio secret key here'
YOUR_PHONE_NUMBER = 'Enter your phone number'
YOUR_TWILIO_NUMBER = 'Enter your twilio phone number'
|
flexible
|
{
"blob_id": "10cb4b59d1e1e823c56ae5ceea0514b1c1904292",
"index": 3769,
"step-1": "<mask token>\n",
"step-2": "ALPACA_KEY = 'Enter your apaca key here'\nALPACA_SECRET_KEY = 'Enter your apaca secret key here'\nALPACA_MARKET = 'enter alpaca market link here'\nTWILIO_KEY = 'enter your twilio key here'\nTWILIO_SECRET_KEY = 'enter your twilio secret key here'\nYOUR_PHONE_NUMBER = 'Enter your phone number'\nYOUR_TWILIO_NUMBER = 'Enter your twilio phone number'\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
with open('file.txt', 'r') as fh:
data = fh.readline()
<|reserved_special_token_0|>
for key in lis:
if key in my_dict.keys():
my_dict[key] += 1
else:
my_dict[key] = 1
print(my_dict)
<|reserved_special_token_1|>
with open('file.txt', 'r') as fh:
data = fh.readline()
lis = data.split(' ')
my_dict = {}
for key in lis:
if key in my_dict.keys():
my_dict[key] += 1
else:
my_dict[key] = 1
print(my_dict)
<|reserved_special_token_1|>
with open("file.txt", 'r') as fh:
data = fh.readline()
lis= data.split(' ')
my_dict={}
for key in lis:
if key in my_dict.keys():
my_dict[key] += 1
else:
my_dict[key] = 1
print(my_dict)
|
flexible
|
{
"blob_id": "8cd582915c5abd96a4ef8a3a5309311f2a73a156",
"index": 460,
"step-1": "<mask token>\n",
"step-2": "with open('file.txt', 'r') as fh:\n data = fh.readline()\n<mask token>\nfor key in lis:\n if key in my_dict.keys():\n my_dict[key] += 1\n else:\n my_dict[key] = 1\nprint(my_dict)\n",
"step-3": "with open('file.txt', 'r') as fh:\n data = fh.readline()\nlis = data.split(' ')\nmy_dict = {}\nfor key in lis:\n if key in my_dict.keys():\n my_dict[key] += 1\n else:\n my_dict[key] = 1\nprint(my_dict)\n",
"step-4": "\n\nwith open(\"file.txt\", 'r') as fh:\n data = fh.readline()\n\nlis= data.split(' ')\nmy_dict={}\n\nfor key in lis:\n if key in my_dict.keys():\n my_dict[key] += 1\n else:\n my_dict[key] = 1\n\nprint(my_dict)\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
admin.site.register(User)
admin.site.register(UserProfile)
admin.site.register(Lead)
admin.site.register(Agent)
admin.site.register(Category)
<|reserved_special_token_1|>
from django.contrib import admin
from .models import User, UserProfile, Lead, Agent, Category
admin.site.register(User)
admin.site.register(UserProfile)
admin.site.register(Lead)
admin.site.register(Agent)
admin.site.register(Category)
|
flexible
|
{
"blob_id": "55d184a9342b40fe027913e46933325bb00e33a6",
"index": 5386,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nadmin.site.register(User)\nadmin.site.register(UserProfile)\nadmin.site.register(Lead)\nadmin.site.register(Agent)\nadmin.site.register(Category)\n",
"step-3": "from django.contrib import admin\nfrom .models import User, UserProfile, Lead, Agent, Category\nadmin.site.register(User)\nadmin.site.register(UserProfile)\nadmin.site.register(Lead)\nadmin.site.register(Agent)\nadmin.site.register(Category)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
import os, subprocess, time
from os.path import isfile, join
import shutil # to move files from af folder to another
import math
def GetListFile(PathFile, FileExtension):
return [os.path.splitext(f)[0] for f in os.listdir(PathFile) if isfile(join(PathFile, f)) and os.path.splitext(f)[1] == '.' + FileExtension]
def openfile(Path):
fileIn = open(Path, "r")
lines = fileIn.readlines()
fileIn.close()
return lines
import re
def parse_Ct_Structure(Path):
lines = openfile(Path)
# Get the initial position of the read and it Series ||||| with mutations
# replace one space in case of multi spaces re.sub( '\s+', ' ', mystring ).strip()
#print Path
#print [int(re.sub( '\s+', ' ', elem ).strip().split(' ')[4]) for elem in lines[1:]]
return [int(re.sub( '\s+', ' ', elem ).strip().split(' ')[4]) for elem in lines[1:]]
def parse_SHAPE(Path):
lines = openfile(Path)
lista=[]
# Get the initial position of the read and it Series ||||| with mutations
# replace one space in case of multi spaces re.sub( '\s+', ' ', mystring ).strip()
Intermediate=[re.sub( '\s+', '\t', elem ).strip().split('\t') for elem in lines]
for elem in Intermediate:
if len(elem)>2 and float(elem[2])!=0:
lista.append(float(elem[2]))
else:
lista.append(-10)
return lista
def Pairing_status(structure):# a line in ct format with a number for the partner if paired and 0 if not
status=[]
for value in structure:
#print value,'lol'
if value== '(' or value== ')':
status.append('P')
if value =='.':
status.append('Un')
if value=='x':
status.append('PK')
return status
def plot2D(x,y,titre):
import matplotlib.pyplot as plt
import numpy as np
plt.plot(x,y,'r.')
plt.xlabel('shape')
plt.ylabel('unpaired probability')
plt.title(titre)
# fitting functions
plt.show()
def distribution_plots(Y,titre):
# plot the x distribution
import matplotlib.pyplot as plt
import numpy as np
'''
d = {x: Y.count(x) for x in Y}
print d
plt.plot(d.keys(),d.values(),'.')
'''
plt.hist(Y, bins=10, color='green')
plt.ylabel('Frequencies')
plt.title(titre)
# fitting functions
#plt.show()
plt.savefig(titre)
def GetbasepairsProb(path_Fasta, fil, FileExtensionFasta,Path_dot_plot):
listProbaPairs=[]
SingleProba=[]
FastaPath=os.path.join(path_Fasta, fil + '.' + FileExtensionFasta)
rna =openfile(FastaPath)[1]
#print rna
os.system("RNAfold -p -d2 --noLP <" + FastaPath+ ">output.txt")
PSPath=os.path.join( Path_dot_plot,fil+"_dp.ps")
shutil.move(fil+"_dp.ps",PSPath)
os.remove(fil+"_ss.ps")
#print fil,'rr'
bpm = loadDotPlotPS(PSPath)
dp = DotPlot(rna, bpm)
for i in range(len(rna)):
for j in range(i, len(rna)):
if dp.getBPProb(i, j) > 0:# get only non null probabilities
listProbaPairs.append((i,j,dp.getBPProb(i, j)))
SingleProba=dp.getUnpairedProbs()
return listProbaPairs, SingleProba
#!!!!!!!!!!!!!!!!!!!!!!!!!!!! loadDotPlotPS(path)
def loadDotPlotPS(path):
res = {}
outTmp = open(path)
for l in outTmp:
data = l[:-1].split()
if len(data) == 4 and data[3]=="ubox":
i = int(data[0])-1
j = int(data[1])-1
p = math.pow(float(data[2]),2.)
res[i,j] = p
outTmp.close()
return res
def parse_rdat(Path):
lines = openfile(Path)
RNA=[]
seq=dict()
struct=dict()
reactivity=dict()
for line in lines:
#print line.split('\t')[0]
if line.split('\t')[0]== 'NAME':
RNA.append(line.split('\t')[1][:-1])
Id= line.split('\t')[1][:-1]
#print 'id',Id
if line.split('\t')[0]=='SEQUENCE':
seq[Id]= line.split('\t')[1][:-2]
if line.split('\t')[0]=='STRUCTURE':
struct[Id]=line.split('\t')[1][:-2]
if line.split('\t')[0]=='REACTIVITY:1':
#print line.split('\t')[1:-1]
reactivity[Id]=line.split('\t')[1:-1]
return RNA,seq, struct,reactivity
def create_fasta_shapeFiles(RNA,seq, struct,reactivity,path_fasta,path_SHAPE):
for Id in RNA:
Outfasta=open(os.path.join(path_fasta, Id+'.fa'),'w')
OutShape=open(os.path.join(path_SHAPE, Id+'.shape'),'w')
Outfasta.write("%s \n" % (">"+ Id))
Outfasta.write("%s \n" % (seq[Id]))
Outfasta.write("%s " % (struct[Id]))
Outfasta.close()
#print Id, len(reactivity[Id]),len(seq[Id])
for i, val in enumerate(reactivity[Id][:-1]):
#print reactivity[Id]
if i <len(seq[Id])and val!=" ":
print Id,i, seq[Id][i],"FF",val
OutShape.write("%i \t %s \t %f \n"%(i+1,seq[Id][i],float(val)))
#print "done"
class DotPlot:
"""Class for holding/producing base-pair probability matrices"""
def __init__(self, rna , bpm = None):
self.rna = rna[:]
if bpm is None:
# we will avoid this case to be sure that rnafold from the min works well
self.bpm = self.runRNAFold()
else:
self.bpm = bpm
def getSeq(self):
return self.rna
def getBPProb(self,i,j):
if (i,j) in self.bpm:
return self.bpm[i,j]
else:
return 0.
def getUnpairedProbs(self):
res = [1. for i in self.rna]
for i,j in self.bpm:
res[i] -= self.bpm[i,j]
res[j] -= self.bpm[i,j]
return res
def Parsefile(Path):
fileIn = open(Path, "r")
lines = fileIn.readlines()
fileIn.close()
return lines
def parseReactivityfile(fileinput):
Reactvities=[]
lines=Parsefile(fileinput)
for it in range(len(lines)):
if (lines[it].split("\t")[2][:-1]):
Reactvities.append(lines[it].split("\t")[2][:-1])
else:
Reactvities.append(-10)
return Reactvities
if __name__ == '__main__':
####################"" To parametrize ##########################
FileExtensionshape ='shape'
react='NMIA'
path_SHAPE='SHAPE_files_NMIA'
path_Fasta = 'fasta_files'
FileExtensionFasta = 'fa'
Shape={}
States={}
BP={}
UNP={}
Quaternary = {}
tertiary = {}
Unpaired2 = {}
lisTIP = []
lisTUn = []
lisHE = []
lisHES = []
lisTIPinterne=[]
lisTIPexterne=[]
SPTIP = []
SPTUn = []
SPHE = []
SPHES = []
SPTIPinterne = []
SPTIPexterne = []
lisIP = [] # shape values for paired Positions
lisUn = [] # shape values for unpaired Positions
SPIP = [] # probability of being unpaired from McCaskill for IP category
SPUn = [] # probability of being unpaired from McCaskill for Un category
RNA=[]
struct=dict()
reactivity=dict()
list3=[]
for filz in GetListFile(path_Fasta, FileExtensionFasta):
#print reactivity
rna = Parsefile(os.path.join(path_Fasta, filz + '.' + FileExtensionFasta))[1]
structure=Parsefile(os.path.join(path_Fasta, filz + '.' + FileExtensionFasta))[2]
States[filz] = Pairing_status(structure)
reactivity[filz]=parseReactivityfile(os.path.join(path_SHAPE, filz + react+'Shape.txt'))
# Get the end-Helix positions
print "GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG",filz, len(States[filz])
print States[filz][-1]
for i,elem in enumerate(States[filz]):
if elem=='Un' or elem=='PK':
list3.append(elem)
if elem=='P':
#print i, elem,i-1,i+1, States[filz][i+1]
if i in range(1,len(rna)-3) and (States[filz][i-1]=='Un' or States[filz][i-1]=='PK' or States[filz][i+1]=='Un' or States[filz][i-1]=='PK' ): # wh should add PK constraint because we are looking for stacked substructures that does not take into account thhe tertiary or pseudoknots extension!!
list3.append('HE')
else:
list3.append(elem)
cum=[]
for filz in GetListFile(path_Fasta, FileExtensionFasta):
if reactivity[filz]==[]:
print "warning!! Empty reactivity",rna
cum=cum+reactivity[filz]
Shape=cum
#print len(Shape)
lIP = [] # shape values for paired Positions
lUn = []
lHE =[]
# for structural_study
#print [elem[:-1] for elem in Shape]
for nucl,shape in zip(list3,Shape):
if shape!=-10 and nucl=='P':
print "la vaaleur", shape
lIP.append( float(shape))
#SPIP.append(UnpPb )
if shape!=-10 and nucl=='Un':
lUn.append( float(shape))
#SPUn.append(UnpPb )
if shape!=-10 and nucl=='HE':
lHE.append( float(shape))
import numpy as np
labels=["Stacked nucleotides","Unpaired nucleotides","Helix-end"]
lists= [lIP,lUn, lHE]
for (data, title) in [(lIP, "P" + str(react)), (lUn, "U"+ str(react)),(lHE,"HE"+ str(react))]:
print title ,'\n' , data
|
normal
|
{
"blob_id": "8b671404228642f7ef96844c33ac3cee402bdb19",
"index": 1279,
"step-1": "import os, subprocess, time\nfrom os.path import isfile, join\nimport shutil # to move files from af folder to another\nimport math\n\ndef GetListFile(PathFile, FileExtension):\n return [os.path.splitext(f)[0] for f in os.listdir(PathFile) if isfile(join(PathFile, f)) and os.path.splitext(f)[1] == '.' + FileExtension]\n\n\ndef openfile(Path):\n fileIn = open(Path, \"r\")\n lines = fileIn.readlines()\n fileIn.close()\n return lines\n\n\nimport re\ndef parse_Ct_Structure(Path):\n lines = openfile(Path)\n # Get the initial position of the read and it Series ||||| with mutations\n # replace one space in case of multi spaces re.sub( '\\s+', ' ', mystring ).strip()\n #print Path\n #print [int(re.sub( '\\s+', ' ', elem ).strip().split(' ')[4]) for elem in lines[1:]]\n return [int(re.sub( '\\s+', ' ', elem ).strip().split(' ')[4]) for elem in lines[1:]]\n\ndef parse_SHAPE(Path):\n lines = openfile(Path)\n lista=[]\n # Get the initial position of the read and it Series ||||| with mutations\n # replace one space in case of multi spaces re.sub( '\\s+', ' ', mystring ).strip()\n\n Intermediate=[re.sub( '\\s+', '\\t', elem ).strip().split('\\t') for elem in lines]\n for elem in Intermediate:\n if len(elem)>2 and float(elem[2])!=0:\n lista.append(float(elem[2])) \n else:\n lista.append(-10)\n return lista\ndef Pairing_status(structure):# a line in ct format with a number for the partner if paired and 0 if not\n status=[]\n for value in structure:\n #print value,'lol'\n if value== '(' or value== ')':\n status.append('P')\n\tif value =='.':\n\t status.append('Un') \n if value=='x':\n status.append('PK')\n return status\n\ndef plot2D(x,y,titre):\n import matplotlib.pyplot as plt\n import numpy as np\n\n plt.plot(x,y,'r.')\n plt.xlabel('shape')\n plt.ylabel('unpaired probability')\n plt.title(titre)\n # fitting functions\n plt.show()\ndef distribution_plots(Y,titre):\n # plot the x distribution\n\n import matplotlib.pyplot as plt\n import numpy as np\n '''\n d = {x: Y.count(x) for x in Y}\n print d\n plt.plot(d.keys(),d.values(),'.')\n '''\n plt.hist(Y, bins=10, color='green')\n plt.ylabel('Frequencies')\n plt.title(titre)\n # fitting functions\n #plt.show()\n plt.savefig(titre)\n\ndef GetbasepairsProb(path_Fasta, fil, FileExtensionFasta,Path_dot_plot):\n\n listProbaPairs=[]\n SingleProba=[]\n FastaPath=os.path.join(path_Fasta, fil + '.' + FileExtensionFasta)\n rna =openfile(FastaPath)[1]\n #print rna\n os.system(\"RNAfold -p -d2 --noLP <\" + FastaPath+ \">output.txt\")\n PSPath=os.path.join( Path_dot_plot,fil+\"_dp.ps\")\n shutil.move(fil+\"_dp.ps\",PSPath)\n os.remove(fil+\"_ss.ps\")\n #print fil,'rr'\n bpm = loadDotPlotPS(PSPath)\n dp = DotPlot(rna, bpm)\n\n for i in range(len(rna)):\n for j in range(i, len(rna)):\n if dp.getBPProb(i, j) > 0:# get only non null probabilities\n listProbaPairs.append((i,j,dp.getBPProb(i, j)))\n\n SingleProba=dp.getUnpairedProbs()\n return listProbaPairs, SingleProba\n#!!!!!!!!!!!!!!!!!!!!!!!!!!!! loadDotPlotPS(path)\ndef loadDotPlotPS(path):\n res = {}\n outTmp = open(path)\n for l in outTmp:\n data = l[:-1].split()\n if len(data) == 4 and data[3]==\"ubox\":\n i = int(data[0])-1\n j = int(data[1])-1\n p = math.pow(float(data[2]),2.)\n res[i,j] = p\n outTmp.close()\n return res\n\ndef parse_rdat(Path):\n\tlines = openfile(Path)\n\tRNA=[]\n\tseq=dict()\n\tstruct=dict()\n\treactivity=dict()\n\tfor line in lines:\n\t\t#print line.split('\\t')[0]\n\t\tif line.split('\\t')[0]== 'NAME':\n\t\t\tRNA.append(line.split('\\t')[1][:-1])\n\t\t Id= line.split('\\t')[1][:-1]\n\t\t #print 'id',Id\n\t\tif line.split('\\t')[0]=='SEQUENCE':\n\t\t\tseq[Id]= line.split('\\t')[1][:-2]\n\t\tif line.split('\\t')[0]=='STRUCTURE':\n\t\t\tstruct[Id]=line.split('\\t')[1][:-2]\n\t\tif line.split('\\t')[0]=='REACTIVITY:1':\n #print line.split('\\t')[1:-1]\n\t\t\treactivity[Id]=line.split('\\t')[1:-1]\n\treturn RNA,seq, struct,reactivity\n\n\ndef create_fasta_shapeFiles(RNA,seq, struct,reactivity,path_fasta,path_SHAPE):\n for Id in RNA:\n\t Outfasta=open(os.path.join(path_fasta, Id+'.fa'),'w')\n\t OutShape=open(os.path.join(path_SHAPE, Id+'.shape'),'w')\n\t Outfasta.write(\"%s \\n\" % (\">\"+ Id))\n\t Outfasta.write(\"%s \\n\" % (seq[Id]))\n\t Outfasta.write(\"%s \" % (struct[Id]))\n\t Outfasta.close()\n #print Id, len(reactivity[Id]),len(seq[Id]) \n\t for i, val in enumerate(reactivity[Id][:-1]):\n #print reactivity[Id]\n if i <len(seq[Id])and val!=\" \": \n print Id,i, seq[Id][i],\"FF\",val\n\t\t\tOutShape.write(\"%i \\t %s \\t %f \\n\"%(i+1,seq[Id][i],float(val)))\n #print \"done\"\nclass DotPlot:\n \"\"\"Class for holding/producing base-pair probability matrices\"\"\"\n def __init__(self, rna , bpm = None):\n self.rna = rna[:]\n if bpm is None:\n # we will avoid this case to be sure that rnafold from the min works well\n self.bpm = self.runRNAFold()\n else:\n self.bpm = bpm\n def getSeq(self):\n return self.rna\n\n def getBPProb(self,i,j):\n if (i,j) in self.bpm:\n return self.bpm[i,j]\n else:\n return 0.\n\n def getUnpairedProbs(self):\n res = [1. for i in self.rna]\n for i,j in self.bpm:\n res[i] -= self.bpm[i,j]\n res[j] -= self.bpm[i,j]\n return res\n\ndef Parsefile(Path):\n fileIn = open(Path, \"r\")\n lines = fileIn.readlines()\n fileIn.close()\n return lines\n\n\ndef parseReactivityfile(fileinput):\n Reactvities=[]\n lines=Parsefile(fileinput)\n for it in range(len(lines)):\n if (lines[it].split(\"\\t\")[2][:-1]):\n \tReactvities.append(lines[it].split(\"\\t\")[2][:-1])\n\t\telse:\n\t\t\tReactvities.append(-10)\n return Reactvities\n\n\n\nif __name__ == '__main__':\n ####################\"\" To parametrize ##########################\n FileExtensionshape ='shape'\n react='NMIA'\n path_SHAPE='SHAPE_files_NMIA'\n path_Fasta = 'fasta_files'\n FileExtensionFasta = 'fa'\n\n\n Shape={}\n States={}\n\n BP={}\n UNP={}\n Quaternary = {}\n tertiary = {}\n Unpaired2 = {}\n lisTIP = []\n lisTUn = []\n lisHE = []\n lisHES = []\n lisTIPinterne=[]\n lisTIPexterne=[]\n SPTIP = []\n SPTUn = []\n SPHE = []\n SPHES = []\n SPTIPinterne = []\n SPTIPexterne = []\n\n lisIP = [] # shape values for paired Positions\n lisUn = [] # shape values for unpaired Positions\n SPIP = [] # probability of being unpaired from McCaskill for IP category\n SPUn = [] # probability of being unpaired from McCaskill for Un category\n RNA=[]\n\n \n struct=dict()\n reactivity=dict()\n\n \n \n\t\n list3=[]\n \n for filz in GetListFile(path_Fasta, FileExtensionFasta):\n #print reactivity\n \n \n rna = Parsefile(os.path.join(path_Fasta, filz + '.' + FileExtensionFasta))[1]\n structure=Parsefile(os.path.join(path_Fasta, filz + '.' + FileExtensionFasta))[2]\n States[filz] = Pairing_status(structure)\n reactivity[filz]=parseReactivityfile(os.path.join(path_SHAPE, filz + react+'Shape.txt'))\n\n # Get the end-Helix positions\n print \"GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG\",filz, len(States[filz])\n print States[filz][-1]\n for i,elem in enumerate(States[filz]):\n \n if elem=='Un' or elem=='PK':\n list3.append(elem)\n if elem=='P':\n #print i, elem,i-1,i+1, States[filz][i+1]\n if i in range(1,len(rna)-3) and (States[filz][i-1]=='Un' or States[filz][i-1]=='PK' or States[filz][i+1]=='Un' or States[filz][i-1]=='PK' ): # wh should add PK constraint because we are looking for stacked substructures that does not take into account thhe tertiary or pseudoknots extension!!\n list3.append('HE')\n else:\n list3.append(elem)\n cum=[]\n for filz in GetListFile(path_Fasta, FileExtensionFasta):\n if reactivity[filz]==[]:\n\t\tprint \"warning!! Empty reactivity\",rna\n\tcum=cum+reactivity[filz]\n Shape=cum\n #print len(Shape)\n lIP = [] # shape values for paired Positions\n lUn = []\n lHE =[]\n # for structural_study \n #print [elem[:-1] for elem in Shape]\n for nucl,shape in zip(list3,Shape):\n\t\tif shape!=-10 and nucl=='P':\n print \"la vaaleur\", shape\n\t\t lIP.append( float(shape))\n\t\t #SPIP.append(UnpPb )\n\t\tif shape!=-10 and nucl=='Un':\n\t\t lUn.append( float(shape))\n\t\t #SPUn.append(UnpPb )\n\t\tif shape!=-10 and nucl=='HE':\n\t\t lHE.append( float(shape))\n import numpy as np\n labels=[\"Stacked nucleotides\",\"Unpaired nucleotides\",\"Helix-end\"]\n lists= [lIP,lUn, lHE]\n for (data, title) in [(lIP, \"P\" + str(react)), (lUn, \"U\"+ str(react)),(lHE,\"HE\"+ str(react))]:\n \tprint title ,'\\n' , data\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
def aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.
parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,
aanderaa_4319a.parse_4319a]):
logger.debug('aanderaa_read_universal()')
with Serial(port, 9600, timeout=2) as ser:
r = None
for _ in range(max_retry):
ser.flush()
ser.write(b'\r\ndo sample\r\n')
try:
line = ser.readline()
line = filter(lambda c: c <= 127, line)
line = bytearray(filter(lambda c: c not in ['\x11', '\x13'],
line))
line = line.decode().strip()
if len(line) <= 0:
logger.debug('(no response)')
continue
elif any([(c in line) for c in '#*']):
logger.debug('(junk)')
logger.debug(line)
logger.debug([ord(c) for c in line])
continue
elif 'SYNTAX ERROR' in line:
logger.debug('(SYNTAX ERROR)')
logger.debug([ord(c) for c in line])
continue
else:
for f in parsers:
logging.debug(f)
try:
r = f(line)
if r is not None and len(r) > 0:
break
except ValueError:
logger.debug('(valueerror)')
else:
time.sleep(1.29)
ser.flush()
except UnicodeDecodeError:
logger.exception('UnicodeDecodeError: {}'.format(line))
ser.flush()
if r is not None and len(r.keys()):
break
time.sleep(1.17)
ser.flush()
return r
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.
parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,
aanderaa_4319a.parse_4319a]):
logger.debug('aanderaa_read_universal()')
with Serial(port, 9600, timeout=2) as ser:
r = None
for _ in range(max_retry):
ser.flush()
ser.write(b'\r\ndo sample\r\n')
try:
line = ser.readline()
line = filter(lambda c: c <= 127, line)
line = bytearray(filter(lambda c: c not in ['\x11', '\x13'],
line))
line = line.decode().strip()
if len(line) <= 0:
logger.debug('(no response)')
continue
elif any([(c in line) for c in '#*']):
logger.debug('(junk)')
logger.debug(line)
logger.debug([ord(c) for c in line])
continue
elif 'SYNTAX ERROR' in line:
logger.debug('(SYNTAX ERROR)')
logger.debug([ord(c) for c in line])
continue
else:
for f in parsers:
logging.debug(f)
try:
r = f(line)
if r is not None and len(r) > 0:
break
except ValueError:
logger.debug('(valueerror)')
else:
time.sleep(1.29)
ser.flush()
except UnicodeDecodeError:
logger.exception('UnicodeDecodeError: {}'.format(line))
ser.flush()
if r is not None and len(r.keys()):
break
time.sleep(1.17)
ser.flush()
return r
if '__main__' == __name__:
logger.setLevel(logging.INFO)
logging.basicConfig(level=logging.INFO)
DEFAULT_PORT = '/dev/ttyS1'
PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()
if len(PORT) <= 0:
PORT = DEFAULT_PORT
while True:
try:
print(aanderaa_read_universal(PORT))
except KeyboardInterrupt:
print('user interrupted')
break
<|reserved_special_token_1|>
<|reserved_special_token_0|>
logger = logging.getLogger(__name__)
def aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.
parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,
aanderaa_4319a.parse_4319a]):
logger.debug('aanderaa_read_universal()')
with Serial(port, 9600, timeout=2) as ser:
r = None
for _ in range(max_retry):
ser.flush()
ser.write(b'\r\ndo sample\r\n')
try:
line = ser.readline()
line = filter(lambda c: c <= 127, line)
line = bytearray(filter(lambda c: c not in ['\x11', '\x13'],
line))
line = line.decode().strip()
if len(line) <= 0:
logger.debug('(no response)')
continue
elif any([(c in line) for c in '#*']):
logger.debug('(junk)')
logger.debug(line)
logger.debug([ord(c) for c in line])
continue
elif 'SYNTAX ERROR' in line:
logger.debug('(SYNTAX ERROR)')
logger.debug([ord(c) for c in line])
continue
else:
for f in parsers:
logging.debug(f)
try:
r = f(line)
if r is not None and len(r) > 0:
break
except ValueError:
logger.debug('(valueerror)')
else:
time.sleep(1.29)
ser.flush()
except UnicodeDecodeError:
logger.exception('UnicodeDecodeError: {}'.format(line))
ser.flush()
if r is not None and len(r.keys()):
break
time.sleep(1.17)
ser.flush()
return r
if '__main__' == __name__:
logger.setLevel(logging.INFO)
logging.basicConfig(level=logging.INFO)
DEFAULT_PORT = '/dev/ttyS1'
PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()
if len(PORT) <= 0:
PORT = DEFAULT_PORT
while True:
try:
print(aanderaa_read_universal(PORT))
except KeyboardInterrupt:
print('user interrupted')
break
<|reserved_special_token_1|>
import logging, time, sys
from serial import Serial
from . import aanderaa_3835
from . import aanderaa_4330f
from . import aanderaa_4531d
from . import aanderaa_4319a
logger = logging.getLogger(__name__)
def aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.
parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,
aanderaa_4319a.parse_4319a]):
logger.debug('aanderaa_read_universal()')
with Serial(port, 9600, timeout=2) as ser:
r = None
for _ in range(max_retry):
ser.flush()
ser.write(b'\r\ndo sample\r\n')
try:
line = ser.readline()
line = filter(lambda c: c <= 127, line)
line = bytearray(filter(lambda c: c not in ['\x11', '\x13'],
line))
line = line.decode().strip()
if len(line) <= 0:
logger.debug('(no response)')
continue
elif any([(c in line) for c in '#*']):
logger.debug('(junk)')
logger.debug(line)
logger.debug([ord(c) for c in line])
continue
elif 'SYNTAX ERROR' in line:
logger.debug('(SYNTAX ERROR)')
logger.debug([ord(c) for c in line])
continue
else:
for f in parsers:
logging.debug(f)
try:
r = f(line)
if r is not None and len(r) > 0:
break
except ValueError:
logger.debug('(valueerror)')
else:
time.sleep(1.29)
ser.flush()
except UnicodeDecodeError:
logger.exception('UnicodeDecodeError: {}'.format(line))
ser.flush()
if r is not None and len(r.keys()):
break
time.sleep(1.17)
ser.flush()
return r
if '__main__' == __name__:
logger.setLevel(logging.INFO)
logging.basicConfig(level=logging.INFO)
DEFAULT_PORT = '/dev/ttyS1'
PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()
if len(PORT) <= 0:
PORT = DEFAULT_PORT
while True:
try:
print(aanderaa_read_universal(PORT))
except KeyboardInterrupt:
print('user interrupted')
break
<|reserved_special_token_1|>
# Stanley H.I. Lio
# hlio@hawaii.edu
# All Rights Reserved. 2018
import logging, time, sys
from serial import Serial
from . import aanderaa_3835
from . import aanderaa_4330f
from . import aanderaa_4531d
from . import aanderaa_4319a
logger = logging.getLogger(__name__)
# works with 3835 (DO), 4330F (DO), 4531D (DO), and 4319A (EC)
def aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835, aanderaa_4319a.parse_4319a]):
logger.debug('aanderaa_read_universal()')
with Serial(port, 9600, timeout=2) as ser:
r = None
for _ in range(max_retry):
ser.flush()
ser.write(b'\r\ndo sample\r\n')
try:
line = ser.readline()
line = filter(lambda c: c <= 0x7f, line)
line = bytearray(filter(lambda c: c not in ['\x11', '\x13'], line)) # the control characters
line = line.decode().strip()
#print([ord(c) for c in line])
if len(line) <= 0:
logger.debug('(no response)')
continue
elif any([c in line for c in '#*']):
logger.debug('(junk)')
logger.debug(line)
logger.debug([ord(c) for c in line])
continue
elif 'SYNTAX ERROR' in line:
logger.debug('(SYNTAX ERROR)')
logger.debug([ord(c) for c in line])
continue
else:
for f in parsers:
logging.debug(f)
try:
r = f(line)
if r is not None and len(r) > 0:
break
except ValueError:
logger.debug('(valueerror)')
else:
time.sleep(1.29)
ser.flush()
except UnicodeDecodeError:
logger.exception('UnicodeDecodeError: {}'.format(line))
ser.flush()
if r is not None and len(r.keys()):
break
time.sleep(1.17)
ser.flush()
return r
if '__main__' == __name__:
logger.setLevel(logging.INFO)
logging.basicConfig(level=logging.INFO)
DEFAULT_PORT = '/dev/ttyS1'
PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()
if len(PORT) <= 0:
PORT = DEFAULT_PORT
while True:
try:
print(aanderaa_read_universal(PORT))
except KeyboardInterrupt:
print('user interrupted')
break
|
flexible
|
{
"blob_id": "c52ad4040c14471319939605c400ff4d4ad982a7",
"index": 5213,
"step-1": "<mask token>\n\n\ndef aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.\n parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,\n aanderaa_4319a.parse_4319a]):\n logger.debug('aanderaa_read_universal()')\n with Serial(port, 9600, timeout=2) as ser:\n r = None\n for _ in range(max_retry):\n ser.flush()\n ser.write(b'\\r\\ndo sample\\r\\n')\n try:\n line = ser.readline()\n line = filter(lambda c: c <= 127, line)\n line = bytearray(filter(lambda c: c not in ['\\x11', '\\x13'],\n line))\n line = line.decode().strip()\n if len(line) <= 0:\n logger.debug('(no response)')\n continue\n elif any([(c in line) for c in '#*']):\n logger.debug('(junk)')\n logger.debug(line)\n logger.debug([ord(c) for c in line])\n continue\n elif 'SYNTAX ERROR' in line:\n logger.debug('(SYNTAX ERROR)')\n logger.debug([ord(c) for c in line])\n continue\n else:\n for f in parsers:\n logging.debug(f)\n try:\n r = f(line)\n if r is not None and len(r) > 0:\n break\n except ValueError:\n logger.debug('(valueerror)')\n else:\n time.sleep(1.29)\n ser.flush()\n except UnicodeDecodeError:\n logger.exception('UnicodeDecodeError: {}'.format(line))\n ser.flush()\n if r is not None and len(r.keys()):\n break\n time.sleep(1.17)\n ser.flush()\n return r\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.\n parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,\n aanderaa_4319a.parse_4319a]):\n logger.debug('aanderaa_read_universal()')\n with Serial(port, 9600, timeout=2) as ser:\n r = None\n for _ in range(max_retry):\n ser.flush()\n ser.write(b'\\r\\ndo sample\\r\\n')\n try:\n line = ser.readline()\n line = filter(lambda c: c <= 127, line)\n line = bytearray(filter(lambda c: c not in ['\\x11', '\\x13'],\n line))\n line = line.decode().strip()\n if len(line) <= 0:\n logger.debug('(no response)')\n continue\n elif any([(c in line) for c in '#*']):\n logger.debug('(junk)')\n logger.debug(line)\n logger.debug([ord(c) for c in line])\n continue\n elif 'SYNTAX ERROR' in line:\n logger.debug('(SYNTAX ERROR)')\n logger.debug([ord(c) for c in line])\n continue\n else:\n for f in parsers:\n logging.debug(f)\n try:\n r = f(line)\n if r is not None and len(r) > 0:\n break\n except ValueError:\n logger.debug('(valueerror)')\n else:\n time.sleep(1.29)\n ser.flush()\n except UnicodeDecodeError:\n logger.exception('UnicodeDecodeError: {}'.format(line))\n ser.flush()\n if r is not None and len(r.keys()):\n break\n time.sleep(1.17)\n ser.flush()\n return r\n\n\nif '__main__' == __name__:\n logger.setLevel(logging.INFO)\n logging.basicConfig(level=logging.INFO)\n DEFAULT_PORT = '/dev/ttyS1'\n PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()\n if len(PORT) <= 0:\n PORT = DEFAULT_PORT\n while True:\n try:\n print(aanderaa_read_universal(PORT))\n except KeyboardInterrupt:\n print('user interrupted')\n break\n",
"step-3": "<mask token>\nlogger = logging.getLogger(__name__)\n\n\ndef aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.\n parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,\n aanderaa_4319a.parse_4319a]):\n logger.debug('aanderaa_read_universal()')\n with Serial(port, 9600, timeout=2) as ser:\n r = None\n for _ in range(max_retry):\n ser.flush()\n ser.write(b'\\r\\ndo sample\\r\\n')\n try:\n line = ser.readline()\n line = filter(lambda c: c <= 127, line)\n line = bytearray(filter(lambda c: c not in ['\\x11', '\\x13'],\n line))\n line = line.decode().strip()\n if len(line) <= 0:\n logger.debug('(no response)')\n continue\n elif any([(c in line) for c in '#*']):\n logger.debug('(junk)')\n logger.debug(line)\n logger.debug([ord(c) for c in line])\n continue\n elif 'SYNTAX ERROR' in line:\n logger.debug('(SYNTAX ERROR)')\n logger.debug([ord(c) for c in line])\n continue\n else:\n for f in parsers:\n logging.debug(f)\n try:\n r = f(line)\n if r is not None and len(r) > 0:\n break\n except ValueError:\n logger.debug('(valueerror)')\n else:\n time.sleep(1.29)\n ser.flush()\n except UnicodeDecodeError:\n logger.exception('UnicodeDecodeError: {}'.format(line))\n ser.flush()\n if r is not None and len(r.keys()):\n break\n time.sleep(1.17)\n ser.flush()\n return r\n\n\nif '__main__' == __name__:\n logger.setLevel(logging.INFO)\n logging.basicConfig(level=logging.INFO)\n DEFAULT_PORT = '/dev/ttyS1'\n PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()\n if len(PORT) <= 0:\n PORT = DEFAULT_PORT\n while True:\n try:\n print(aanderaa_read_universal(PORT))\n except KeyboardInterrupt:\n print('user interrupted')\n break\n",
"step-4": "import logging, time, sys\nfrom serial import Serial\nfrom . import aanderaa_3835\nfrom . import aanderaa_4330f\nfrom . import aanderaa_4531d\nfrom . import aanderaa_4319a\nlogger = logging.getLogger(__name__)\n\n\ndef aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.\n parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835,\n aanderaa_4319a.parse_4319a]):\n logger.debug('aanderaa_read_universal()')\n with Serial(port, 9600, timeout=2) as ser:\n r = None\n for _ in range(max_retry):\n ser.flush()\n ser.write(b'\\r\\ndo sample\\r\\n')\n try:\n line = ser.readline()\n line = filter(lambda c: c <= 127, line)\n line = bytearray(filter(lambda c: c not in ['\\x11', '\\x13'],\n line))\n line = line.decode().strip()\n if len(line) <= 0:\n logger.debug('(no response)')\n continue\n elif any([(c in line) for c in '#*']):\n logger.debug('(junk)')\n logger.debug(line)\n logger.debug([ord(c) for c in line])\n continue\n elif 'SYNTAX ERROR' in line:\n logger.debug('(SYNTAX ERROR)')\n logger.debug([ord(c) for c in line])\n continue\n else:\n for f in parsers:\n logging.debug(f)\n try:\n r = f(line)\n if r is not None and len(r) > 0:\n break\n except ValueError:\n logger.debug('(valueerror)')\n else:\n time.sleep(1.29)\n ser.flush()\n except UnicodeDecodeError:\n logger.exception('UnicodeDecodeError: {}'.format(line))\n ser.flush()\n if r is not None and len(r.keys()):\n break\n time.sleep(1.17)\n ser.flush()\n return r\n\n\nif '__main__' == __name__:\n logger.setLevel(logging.INFO)\n logging.basicConfig(level=logging.INFO)\n DEFAULT_PORT = '/dev/ttyS1'\n PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()\n if len(PORT) <= 0:\n PORT = DEFAULT_PORT\n while True:\n try:\n print(aanderaa_read_universal(PORT))\n except KeyboardInterrupt:\n print('user interrupted')\n break\n",
"step-5": "# Stanley H.I. Lio\n# hlio@hawaii.edu\n# All Rights Reserved. 2018\nimport logging, time, sys\nfrom serial import Serial\nfrom . import aanderaa_3835\nfrom . import aanderaa_4330f\nfrom . import aanderaa_4531d\nfrom . import aanderaa_4319a\n\n\nlogger = logging.getLogger(__name__)\n\n\n# works with 3835 (DO), 4330F (DO), 4531D (DO), and 4319A (EC)\ndef aanderaa_read_universal(port, max_retry=3, parsers=[aanderaa_4531d.parse_4531d, aanderaa_4330f.parse_4330f, aanderaa_3835.parse_3835, aanderaa_4319a.parse_4319a]):\n logger.debug('aanderaa_read_universal()')\n \n with Serial(port, 9600, timeout=2) as ser:\n\n r = None\n for _ in range(max_retry):\n\n ser.flush()\n ser.write(b'\\r\\ndo sample\\r\\n')\n try:\n line = ser.readline()\n line = filter(lambda c: c <= 0x7f, line)\n line = bytearray(filter(lambda c: c not in ['\\x11', '\\x13'], line)) # the control characters\n line = line.decode().strip()\n #print([ord(c) for c in line])\n\n if len(line) <= 0:\n logger.debug('(no response)') \n continue\n elif any([c in line for c in '#*']):\n logger.debug('(junk)')\n logger.debug(line)\n logger.debug([ord(c) for c in line])\n continue\n elif 'SYNTAX ERROR' in line:\n logger.debug('(SYNTAX ERROR)')\n logger.debug([ord(c) for c in line])\n continue\n else:\n for f in parsers:\n logging.debug(f)\n try:\n r = f(line)\n if r is not None and len(r) > 0:\n break\n except ValueError:\n logger.debug('(valueerror)')\n else:\n time.sleep(1.29)\n ser.flush()\n\n except UnicodeDecodeError:\n logger.exception('UnicodeDecodeError: {}'.format(line))\n ser.flush()\n\n if r is not None and len(r.keys()):\n break\n\n time.sleep(1.17)\n\n ser.flush()\n return r\n\n\nif '__main__' == __name__:\n\n logger.setLevel(logging.INFO)\n logging.basicConfig(level=logging.INFO)\n\n DEFAULT_PORT = '/dev/ttyS1'\n PORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()\n if len(PORT) <= 0:\n PORT = DEFAULT_PORT\n\n while True:\n try:\n print(aanderaa_read_universal(PORT))\n except KeyboardInterrupt:\n print('user interrupted')\n break\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
class tlimit:
def __init__(self, name, text):
self.name = name
self.text = text
<|reserved_special_token_0|>
class SensorData:
date = datetime.datetime(1970, 1, 1, 0, 0, 0)
server_room_temperature = 0.0
server_room_humidity = 0.0
def __init__(self, d, t, h):
self.date = d
self.server_room_temperature = t
self.server_room_humidity = h
def __str__(self):
return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.
server_room_temperature, self.server_room_humidity)
<|reserved_special_token_0|>
def smooth_data(data, smooth_width):
"""
smooth the curve plotted by data
:param data: the input data
:param smooth_width: the width of the mobile average
:return: the smoothed data
"""
out = []
for i, dat in enumerate(data):
low = max(0, i - smooth_width)
high = min(len(data) - 1, low + 2 * smooth_width)
n = 0
s_temperature = 0
s_humidity = 0
for d in data[low:high]:
n += 1
s_temperature += d.server_room_temperature
s_humidity += d.server_room_humidity
s_temperature /= float(max(1, n))
s_humidity /= float(max(1, n))
out.append(SensorData(dat.date, s_temperature, s_humidity))
return out
<|reserved_special_token_0|>
class displaydata:
"""
lass to encapsulate the meteo result to display
"""
def __init__(self):
self.temperature = '0'
self.temp_tendance = ''
self.temp_max = '0'
self.temp_min = '0'
self.temp_max_date = '0'
self.temp_min_date = '0'
self.temp_mean = '0'
self.humidity = '0'
self.hum_tendance = ''
self.hum_max = '0'
self.hum_min = '0'
self.hum_max_date = '0'
self.hum_min_date = '0'
self.hum_mean = '0'
def __tendance(self, dt, seuil):
if len(dt) < 3:
return 'mdi-arrow-left-right-bold-outline tgreen'
if len(dt) > 20:
p1 = dt[-20]
p2 = dt[-10]
p3 = dt[-1]
else:
p1 = dt[0]
p2 = dt[len(dt) / 2]
p3 = dt[-1]
if abs(p3 - p2) < seuil:
return 'mdi-arrow-left-right-bold-outline tgreen'
elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2
) < seuil and p2 > p1:
return 'mdi-arrow-top-right-bold-outline torange'
elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2
) < seuil and p2 < p1:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 > p2 > p3:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 < p2 < p3:
return 'mdi-arrow-up-bold-outline tred'
else:
return 'mdi-arrow-left-right-bold-outline tgreen'
def compute_from_data(self, dta, dha, date):
self.temp_max = -2000
self.temp_min = 2000
self.temp_mean = 0
for i, t in enumerate(dta):
self.temp_mean += t
if t > self.temp_max:
self.temp_max = t
self.temp_max_date = date[i]
if t < self.temp_min:
self.temp_min = t
self.temp_min_date = date[i]
if len(dta) > 0:
self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))
self.temp_max = '{:.2f}'.format(self.temp_max)
self.temp_min = '{:.2f}'.format(self.temp_min)
self.temperature = '{:.2f}'.format(dta[-1])
self.temp_tendance = self.__tendance(dta, 0.05)
self.hum_max = -2000
self.hum_min = 2000
self.hum_mean = 0
for i, t in enumerate(dha):
self.hum_mean += t
if t > self.hum_max:
self.hum_max = t
self.hum_max_date = date[i]
if t < self.hum_min:
self.hum_min = t
self.hum_min_date = date[i]
if len(dha) > 0:
self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))
self.hum_max = '{:.2f}'.format(self.hum_max)
self.hum_min = '{:.2f}'.format(self.hum_min)
self.hum_tendance = self.__tendance(dha, 0.05)
self.humidity = '{:.2f}'.format(dha[-1])
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class tlimit:
def __init__(self, name, text):
self.name = name
self.text = text
<|reserved_special_token_0|>
class SensorData:
date = datetime.datetime(1970, 1, 1, 0, 0, 0)
server_room_temperature = 0.0
server_room_humidity = 0.0
def __init__(self, d, t, h):
self.date = d
self.server_room_temperature = t
self.server_room_humidity = h
def __str__(self):
return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.
server_room_temperature, self.server_room_humidity)
<|reserved_special_token_0|>
def smooth_data(data, smooth_width):
"""
smooth the curve plotted by data
:param data: the input data
:param smooth_width: the width of the mobile average
:return: the smoothed data
"""
out = []
for i, dat in enumerate(data):
low = max(0, i - smooth_width)
high = min(len(data) - 1, low + 2 * smooth_width)
n = 0
s_temperature = 0
s_humidity = 0
for d in data[low:high]:
n += 1
s_temperature += d.server_room_temperature
s_humidity += d.server_room_humidity
s_temperature /= float(max(1, n))
s_humidity /= float(max(1, n))
out.append(SensorData(dat.date, s_temperature, s_humidity))
return out
<|reserved_special_token_0|>
class displaydata:
"""
lass to encapsulate the meteo result to display
"""
def __init__(self):
self.temperature = '0'
self.temp_tendance = ''
self.temp_max = '0'
self.temp_min = '0'
self.temp_max_date = '0'
self.temp_min_date = '0'
self.temp_mean = '0'
self.humidity = '0'
self.hum_tendance = ''
self.hum_max = '0'
self.hum_min = '0'
self.hum_max_date = '0'
self.hum_min_date = '0'
self.hum_mean = '0'
def __tendance(self, dt, seuil):
if len(dt) < 3:
return 'mdi-arrow-left-right-bold-outline tgreen'
if len(dt) > 20:
p1 = dt[-20]
p2 = dt[-10]
p3 = dt[-1]
else:
p1 = dt[0]
p2 = dt[len(dt) / 2]
p3 = dt[-1]
if abs(p3 - p2) < seuil:
return 'mdi-arrow-left-right-bold-outline tgreen'
elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2
) < seuil and p2 > p1:
return 'mdi-arrow-top-right-bold-outline torange'
elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2
) < seuil and p2 < p1:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 > p2 > p3:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 < p2 < p3:
return 'mdi-arrow-up-bold-outline tred'
else:
return 'mdi-arrow-left-right-bold-outline tgreen'
def compute_from_data(self, dta, dha, date):
self.temp_max = -2000
self.temp_min = 2000
self.temp_mean = 0
for i, t in enumerate(dta):
self.temp_mean += t
if t > self.temp_max:
self.temp_max = t
self.temp_max_date = date[i]
if t < self.temp_min:
self.temp_min = t
self.temp_min_date = date[i]
if len(dta) > 0:
self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))
self.temp_max = '{:.2f}'.format(self.temp_max)
self.temp_min = '{:.2f}'.format(self.temp_min)
self.temperature = '{:.2f}'.format(dta[-1])
self.temp_tendance = self.__tendance(dta, 0.05)
self.hum_max = -2000
self.hum_min = 2000
self.hum_mean = 0
for i, t in enumerate(dha):
self.hum_mean += t
if t > self.hum_max:
self.hum_max = t
self.hum_max_date = date[i]
if t < self.hum_min:
self.hum_min = t
self.hum_min_date = date[i]
if len(dha) > 0:
self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))
self.hum_max = '{:.2f}'.format(self.hum_max)
self.hum_min = '{:.2f}'.format(self.hum_min)
self.hum_tendance = self.__tendance(dha, 0.05)
self.humidity = '{:.2f}'.format(dha[-1])
def getData(ll, smoo):
data = resample_data(get_data(ll), 1000)
if smoo > 0:
data = smooth_data(data, smoo)
print(len(data))
dates = []
temperatures = []
humidity = []
i = 0
for sset in data:
i += 1
dates.append(sset.date.strftime('%Y-%m-%d %H:%M:%S'))
temperatures.append(sset.server_room_temperature)
humidity.append(sset.server_room_humidity)
d = displaydata()
d.compute_from_data(temperatures, humidity, dates)
return dates, temperatures, humidity, d
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class tlimit:
def __init__(self, name, text):
self.name = name
self.text = text
<|reserved_special_token_0|>
class SensorData:
date = datetime.datetime(1970, 1, 1, 0, 0, 0)
server_room_temperature = 0.0
server_room_humidity = 0.0
def __init__(self, d, t, h):
self.date = d
self.server_room_temperature = t
self.server_room_humidity = h
def __str__(self):
return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.
server_room_temperature, self.server_room_humidity)
def get_data(last):
"""
get the database data on the last period
:param last: duration of the period
:return: the data
"""
Table = 'ServerRoom'
filter = ''
if last == 'lastone':
data = request_meteodata(
'SELECT * from `ServerRoom` ORDER BY id DESC LIMIT 1 ')
if len(data) == 0:
return [SensorData(datetime.datetime.now(), 0, 0)]
res = []
for d in data:
res.append(SensorData(d[1], d[2], d[3]))
return res
if last != 'All':
limit = datetime.datetime.now().astimezone(utz)
if last == '24hours':
limit -= datetime.timedelta(hours=24)
else:
limit = limit.replace(hour=0, minute=0, second=0, microsecond=0)
if last == '3days':
limit -= datetime.timedelta(days=3)
elif last == '7days':
limit -= datetime.timedelta(days=7)
elif last == 'month':
limit = limit.replace(day=1)
elif last == '30days':
limit -= datetime.timedelta(days=30)
elif last == 'year':
limit = limit.replace(day=1, month=1)
filter = " WHERE `date` > '" + str(limit) + "'"
order = ' ORDER BY `date` ASC'
req = 'SELECT * FROM `' + Table + '`' + filter + order
data = request_meteodata(req)
if len(data) == 0:
print('no data: get all')
req = 'SELECT * FROM `' + Table + '`' + order
data = request_meteodata(req)
res = []
for d in data:
res.append(SensorData(d[1], d[2], d[3]))
return res
def smooth_data(data, smooth_width):
"""
smooth the curve plotted by data
:param data: the input data
:param smooth_width: the width of the mobile average
:return: the smoothed data
"""
out = []
for i, dat in enumerate(data):
low = max(0, i - smooth_width)
high = min(len(data) - 1, low + 2 * smooth_width)
n = 0
s_temperature = 0
s_humidity = 0
for d in data[low:high]:
n += 1
s_temperature += d.server_room_temperature
s_humidity += d.server_room_humidity
s_temperature /= float(max(1, n))
s_humidity /= float(max(1, n))
out.append(SensorData(dat.date, s_temperature, s_humidity))
return out
<|reserved_special_token_0|>
class displaydata:
"""
lass to encapsulate the meteo result to display
"""
def __init__(self):
self.temperature = '0'
self.temp_tendance = ''
self.temp_max = '0'
self.temp_min = '0'
self.temp_max_date = '0'
self.temp_min_date = '0'
self.temp_mean = '0'
self.humidity = '0'
self.hum_tendance = ''
self.hum_max = '0'
self.hum_min = '0'
self.hum_max_date = '0'
self.hum_min_date = '0'
self.hum_mean = '0'
def __tendance(self, dt, seuil):
if len(dt) < 3:
return 'mdi-arrow-left-right-bold-outline tgreen'
if len(dt) > 20:
p1 = dt[-20]
p2 = dt[-10]
p3 = dt[-1]
else:
p1 = dt[0]
p2 = dt[len(dt) / 2]
p3 = dt[-1]
if abs(p3 - p2) < seuil:
return 'mdi-arrow-left-right-bold-outline tgreen'
elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2
) < seuil and p2 > p1:
return 'mdi-arrow-top-right-bold-outline torange'
elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2
) < seuil and p2 < p1:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 > p2 > p3:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 < p2 < p3:
return 'mdi-arrow-up-bold-outline tred'
else:
return 'mdi-arrow-left-right-bold-outline tgreen'
def compute_from_data(self, dta, dha, date):
self.temp_max = -2000
self.temp_min = 2000
self.temp_mean = 0
for i, t in enumerate(dta):
self.temp_mean += t
if t > self.temp_max:
self.temp_max = t
self.temp_max_date = date[i]
if t < self.temp_min:
self.temp_min = t
self.temp_min_date = date[i]
if len(dta) > 0:
self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))
self.temp_max = '{:.2f}'.format(self.temp_max)
self.temp_min = '{:.2f}'.format(self.temp_min)
self.temperature = '{:.2f}'.format(dta[-1])
self.temp_tendance = self.__tendance(dta, 0.05)
self.hum_max = -2000
self.hum_min = 2000
self.hum_mean = 0
for i, t in enumerate(dha):
self.hum_mean += t
if t > self.hum_max:
self.hum_max = t
self.hum_max_date = date[i]
if t < self.hum_min:
self.hum_min = t
self.hum_min_date = date[i]
if len(dha) > 0:
self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))
self.hum_max = '{:.2f}'.format(self.hum_max)
self.hum_min = '{:.2f}'.format(self.hum_min)
self.hum_tendance = self.__tendance(dha, 0.05)
self.humidity = '{:.2f}'.format(dha[-1])
def getData(ll, smoo):
data = resample_data(get_data(ll), 1000)
if smoo > 0:
data = smooth_data(data, smoo)
print(len(data))
dates = []
temperatures = []
humidity = []
i = 0
for sset in data:
i += 1
dates.append(sset.date.strftime('%Y-%m-%d %H:%M:%S'))
temperatures.append(sset.server_room_temperature)
humidity.append(sset.server_room_humidity)
d = displaydata()
d.compute_from_data(temperatures, humidity, dates)
return dates, temperatures, humidity, d
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class tlimit:
def __init__(self, name, text):
self.name = name
self.text = text
time_limit = [tlimit('All', 'All Data'), tlimit('day', 'Current day'),
tlimit('24hours', 'Last 24 hours'), tlimit('3days', 'Three last days'),
tlimit('7days', 'Seven last days'), tlimit('month', 'Current month'),
tlimit('30days', 'Last 30 days'), tlimit('year', 'Current year')]
tz = pytz.timezone('Europe/Paris')
utz = pytz.timezone('UTC')
def request_meteodata(request: str):
"""
execute a request in the MeteoData database
:param request: the request to execute
:return: the feteched result
"""
import MySQLdb
import platform
if platform.system() == 'Windows':
MySQLParams = {'host': '192.168.5.1', 'user': 'MeteoRobot',
'passwd': 'robot', 'db': 'MeteoData'}
else:
MySQLParams = {'host': 'localhost', 'user': 'MeteoRobot', 'passwd':
'robot', 'db': 'MeteoData'}
try:
con = MySQLdb.connect(**MySQLParams)
cur = con.cursor()
cur.execute(request)
con.commit()
data = cur.fetchall()
except MySQLdb.Error as err:
print(str(err))
return []
except Exception as err:
print(str(err))
return []
con.close()
return data
class SensorData:
date = datetime.datetime(1970, 1, 1, 0, 0, 0)
server_room_temperature = 0.0
server_room_humidity = 0.0
def __init__(self, d, t, h):
self.date = d
self.server_room_temperature = t
self.server_room_humidity = h
def __str__(self):
return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.
server_room_temperature, self.server_room_humidity)
def get_data(last):
"""
get the database data on the last period
:param last: duration of the period
:return: the data
"""
Table = 'ServerRoom'
filter = ''
if last == 'lastone':
data = request_meteodata(
'SELECT * from `ServerRoom` ORDER BY id DESC LIMIT 1 ')
if len(data) == 0:
return [SensorData(datetime.datetime.now(), 0, 0)]
res = []
for d in data:
res.append(SensorData(d[1], d[2], d[3]))
return res
if last != 'All':
limit = datetime.datetime.now().astimezone(utz)
if last == '24hours':
limit -= datetime.timedelta(hours=24)
else:
limit = limit.replace(hour=0, minute=0, second=0, microsecond=0)
if last == '3days':
limit -= datetime.timedelta(days=3)
elif last == '7days':
limit -= datetime.timedelta(days=7)
elif last == 'month':
limit = limit.replace(day=1)
elif last == '30days':
limit -= datetime.timedelta(days=30)
elif last == 'year':
limit = limit.replace(day=1, month=1)
filter = " WHERE `date` > '" + str(limit) + "'"
order = ' ORDER BY `date` ASC'
req = 'SELECT * FROM `' + Table + '`' + filter + order
data = request_meteodata(req)
if len(data) == 0:
print('no data: get all')
req = 'SELECT * FROM `' + Table + '`' + order
data = request_meteodata(req)
res = []
for d in data:
res.append(SensorData(d[1], d[2], d[3]))
return res
def smooth_data(data, smooth_width):
"""
smooth the curve plotted by data
:param data: the input data
:param smooth_width: the width of the mobile average
:return: the smoothed data
"""
out = []
for i, dat in enumerate(data):
low = max(0, i - smooth_width)
high = min(len(data) - 1, low + 2 * smooth_width)
n = 0
s_temperature = 0
s_humidity = 0
for d in data[low:high]:
n += 1
s_temperature += d.server_room_temperature
s_humidity += d.server_room_humidity
s_temperature /= float(max(1, n))
s_humidity /= float(max(1, n))
out.append(SensorData(dat.date, s_temperature, s_humidity))
return out
def resample_data(data, entity_number):
"""
limit the amount of dat
:param data: input data
:param entity_number: maximum number of entity in output
:return: he resampled data
"""
if len(data) <= entity_number:
return data
interval = int(len(data) / entity_number + 1)
out = []
for i, dat in enumerate(data):
if i % interval == 0:
out.append(dat)
return out
class displaydata:
"""
lass to encapsulate the meteo result to display
"""
def __init__(self):
self.temperature = '0'
self.temp_tendance = ''
self.temp_max = '0'
self.temp_min = '0'
self.temp_max_date = '0'
self.temp_min_date = '0'
self.temp_mean = '0'
self.humidity = '0'
self.hum_tendance = ''
self.hum_max = '0'
self.hum_min = '0'
self.hum_max_date = '0'
self.hum_min_date = '0'
self.hum_mean = '0'
def __tendance(self, dt, seuil):
if len(dt) < 3:
return 'mdi-arrow-left-right-bold-outline tgreen'
if len(dt) > 20:
p1 = dt[-20]
p2 = dt[-10]
p3 = dt[-1]
else:
p1 = dt[0]
p2 = dt[len(dt) / 2]
p3 = dt[-1]
if abs(p3 - p2) < seuil:
return 'mdi-arrow-left-right-bold-outline tgreen'
elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2
) < seuil and p2 > p1:
return 'mdi-arrow-top-right-bold-outline torange'
elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2
) < seuil and p2 < p1:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 > p2 > p3:
return 'mdi-arrow-bottom-right-bold-outline tlightblue'
elif p1 < p2 < p3:
return 'mdi-arrow-up-bold-outline tred'
else:
return 'mdi-arrow-left-right-bold-outline tgreen'
def compute_from_data(self, dta, dha, date):
self.temp_max = -2000
self.temp_min = 2000
self.temp_mean = 0
for i, t in enumerate(dta):
self.temp_mean += t
if t > self.temp_max:
self.temp_max = t
self.temp_max_date = date[i]
if t < self.temp_min:
self.temp_min = t
self.temp_min_date = date[i]
if len(dta) > 0:
self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))
self.temp_max = '{:.2f}'.format(self.temp_max)
self.temp_min = '{:.2f}'.format(self.temp_min)
self.temperature = '{:.2f}'.format(dta[-1])
self.temp_tendance = self.__tendance(dta, 0.05)
self.hum_max = -2000
self.hum_min = 2000
self.hum_mean = 0
for i, t in enumerate(dha):
self.hum_mean += t
if t > self.hum_max:
self.hum_max = t
self.hum_max_date = date[i]
if t < self.hum_min:
self.hum_min = t
self.hum_min_date = date[i]
if len(dha) > 0:
self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))
self.hum_max = '{:.2f}'.format(self.hum_max)
self.hum_min = '{:.2f}'.format(self.hum_min)
self.hum_tendance = self.__tendance(dha, 0.05)
self.humidity = '{:.2f}'.format(dha[-1])
def getData(ll, smoo):
data = resample_data(get_data(ll), 1000)
if smoo > 0:
data = smooth_data(data, smoo)
print(len(data))
dates = []
temperatures = []
humidity = []
i = 0
for sset in data:
i += 1
dates.append(sset.date.strftime('%Y-%m-%d %H:%M:%S'))
temperatures.append(sset.server_room_temperature)
humidity.append(sset.server_room_humidity)
d = displaydata()
d.compute_from_data(temperatures, humidity, dates)
return dates, temperatures, humidity, d
def get_actual_data():
data = get_data('lastone')
return '{:.2f}'.format(data[0].server_room_temperature), '{:.2f}'.format(
data[0].server_room_humidity)
<|reserved_special_token_1|>
"""
definition of a sensor
"""
import datetime
import pytz
class tlimit:
def __init__(self, name, text):
self.name = name
self.text = text
time_limit = [
tlimit("All", "All Data"),
tlimit("day", "Current day"),
tlimit("24hours", "Last 24 hours"),
tlimit("3days", "Three last days"),
tlimit("7days", "Seven last days"),
tlimit("month", "Current month"),
tlimit("30days", "Last 30 days"),
tlimit("year", "Current year"),
]
tz = pytz.timezone("Europe/Paris")
utz = pytz.timezone("UTC")
def request_meteodata(request: str):
"""
execute a request in the MeteoData database
:param request: the request to execute
:return: the feteched result
"""
import MySQLdb
import platform
if platform.system() == "Windows":
MySQLParams = {
'host' : "192.168.5.1",
'user' : "MeteoRobot",
'passwd': "robot",
'db' : "MeteoData"
}
else:
MySQLParams = {
'host' : "localhost",
'user' : "MeteoRobot",
'passwd': "robot",
'db' : "MeteoData"
}
try:
con = MySQLdb.connect(**MySQLParams)
cur = con.cursor()
cur.execute(request)
con.commit()
data = cur.fetchall()
except MySQLdb.Error as err:
print(str(err))
return []
except Exception as err:
print(str(err))
return []
con.close()
return data
class SensorData:
date = datetime.datetime(1970, 1, 1, 0, 0, 0)
server_room_temperature = 0.0
server_room_humidity = 0.0
def __init__(self, d, t, h):
self.date = d
self.server_room_temperature = t
self.server_room_humidity = h
def __str__(self):
return str(self.date) + " {:.2f}°C {:.1f}%".format(self.server_room_temperature, self.server_room_humidity)
def get_data(last):
"""
get the database data on the last period
:param last: duration of the period
:return: the data
"""
Table = "ServerRoom"
filter = ""
if last == "lastone":
data = request_meteodata("SELECT * from `ServerRoom` ORDER BY id DESC LIMIT 1 ")
if len(data) == 0:
return [SensorData(datetime.datetime.now(), 0, 0)]
res = []
for d in data:
res.append(SensorData(d[1], d[2], d[3]))
return res
if last != "All":
limit = datetime.datetime.now().astimezone(utz)
if last == "24hours":
limit -= datetime.timedelta(hours=24)
else:
limit = limit.replace(hour=0, minute=0, second=0, microsecond=0)
if last == "3days":
limit -= datetime.timedelta(days=3)
elif last == "7days":
limit -= datetime.timedelta(days=7)
elif last == "month":
limit = limit.replace(day=1)
elif last == "30days":
limit -= datetime.timedelta(days=30)
elif last == "year":
limit = limit.replace(day=1, month=1)
filter = " WHERE `date` > '" + str(limit) + "'"
order = " ORDER BY `date` ASC"
req = "SELECT * FROM `" + Table + "`" + filter + order
data = request_meteodata(req)
if len(data) == 0:
print("no data: get all")
req = "SELECT * FROM `" + Table + "`" + order
data = request_meteodata(req)
res = []
for d in data:
res.append(SensorData(d[1], d[2], d[3]))
return res
def smooth_data(data, smooth_width):
"""
smooth the curve plotted by data
:param data: the input data
:param smooth_width: the width of the mobile average
:return: the smoothed data
"""
out = []
for i, dat in enumerate(data):
low = max(0, i - smooth_width)
high = min((len(data) - 1), low + 2 * smooth_width)
n = 0
s_temperature = 0
s_humidity = 0
for d in data[low:high]:
n += 1
s_temperature += d.server_room_temperature
s_humidity += d.server_room_humidity
s_temperature /= float(max(1, n))
s_humidity /= float(max(1, n))
out.append(SensorData(dat.date, s_temperature, s_humidity))
return out
def resample_data(data, entity_number):
"""
limit the amount of dat
:param data: input data
:param entity_number: maximum number of entity in output
:return: he resampled data
"""
if len(data) <= entity_number:
# not that many entity: nothing to do
return data
interval = int(len(data)/entity_number + 1)
out = []
for i, dat in enumerate(data):
if i % interval == 0:
out.append(dat)
return out
class displaydata:
"""
lass to encapsulate the meteo result to display
"""
def __init__(self):
self.temperature = "0"
self.temp_tendance = ""
self.temp_max = "0"
self.temp_min = "0"
self.temp_max_date = "0"
self.temp_min_date = "0"
self.temp_mean = "0"
self.humidity = "0"
self.hum_tendance = ""
self.hum_max = "0"
self.hum_min = "0"
self.hum_max_date = "0"
self.hum_min_date = "0"
self.hum_mean = "0"
def __tendance(self, dt, seuil):
if len(dt) < 3:
return "mdi-arrow-left-right-bold-outline tgreen"
if len(dt) > 20:
p1 = dt[-20]
p2 = dt[-10]
p3 = dt[-1]
else:
p1 = dt[0]
p2 = dt[len(dt)/2]
p3 = dt[-1]
if abs(p3 - p2) < seuil:
return "mdi-arrow-left-right-bold-outline tgreen"
elif (abs(p2 - p1) < seuil and p3 > p2) or (abs(p3 - p2) < seuil and p2 > p1):
return "mdi-arrow-top-right-bold-outline torange"
elif (abs(p2 - p1) < seuil and p3 < p2) or (abs(p3 - p2) < seuil and p2 < p1):
return "mdi-arrow-bottom-right-bold-outline tlightblue"
elif p1 > p2 > p3:
return "mdi-arrow-bottom-right-bold-outline tlightblue"
elif p1 < p2 < p3:
return "mdi-arrow-up-bold-outline tred"
else:
return "mdi-arrow-left-right-bold-outline tgreen"
def compute_from_data(self, dta, dha, date):
self.temp_max = -2000
self.temp_min = 2000
self.temp_mean = 0
for i, t in enumerate(dta):
self.temp_mean += t
if t > self.temp_max:
self.temp_max = t
self.temp_max_date = date[i]
if t < self.temp_min:
self.temp_min = t
self.temp_min_date = date[i]
if len(dta) > 0:
self.temp_mean = "{:.2f}".format(self.temp_mean / float(len(dta)))
self.temp_max = "{:.2f}".format(self.temp_max)
self.temp_min = "{:.2f}".format(self.temp_min)
self.temperature = "{:.2f}".format(dta[-1])
self.temp_tendance = self.__tendance(dta, 0.05)
self.hum_max = -2000
self.hum_min = 2000
self.hum_mean = 0
for i, t in enumerate(dha):
self.hum_mean += t
if t > self.hum_max:
self.hum_max = t
self.hum_max_date = date[i]
if t < self.hum_min:
self.hum_min = t
self.hum_min_date = date[i]
if len(dha) > 0:
self.hum_mean = "{:.2f}".format(self.hum_mean / float(len(dha)))
self.hum_max = "{:.2f}".format(self.hum_max)
self.hum_min = "{:.2f}".format(self.hum_min)
self.hum_tendance = self.__tendance(dha, 0.05)
self.humidity = "{:.2f}".format(dha[-1])
def getData(ll, smoo):
data = resample_data(get_data(ll), 1000)
if smoo > 0:
data = smooth_data(data, smoo)
print(len(data))
dates = []
temperatures = []
humidity = []
i = 0
for sset in data:
i += 1
dates.append(sset.date.strftime("%Y-%m-%d %H:%M:%S"))
temperatures.append(sset.server_room_temperature)
humidity.append(sset.server_room_humidity)
d = displaydata()
d.compute_from_data(temperatures, humidity, dates)
return dates, temperatures, humidity, d
def get_actual_data():
data = get_data("lastone")
return "{:.2f}".format(data[0].server_room_temperature), "{:.2f}".format(data[0].server_room_humidity)
|
flexible
|
{
"blob_id": "cb9ea8791009a29a24a76bc2b161e7f8599fec1b",
"index": 5780,
"step-1": "<mask token>\n\n\nclass tlimit:\n\n def __init__(self, name, text):\n self.name = name\n self.text = text\n\n\n<mask token>\n\n\nclass SensorData:\n date = datetime.datetime(1970, 1, 1, 0, 0, 0)\n server_room_temperature = 0.0\n server_room_humidity = 0.0\n\n def __init__(self, d, t, h):\n self.date = d\n self.server_room_temperature = t\n self.server_room_humidity = h\n\n def __str__(self):\n return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.\n server_room_temperature, self.server_room_humidity)\n\n\n<mask token>\n\n\ndef smooth_data(data, smooth_width):\n \"\"\"\n smooth the curve plotted by data\n :param data: the input data\n :param smooth_width: the width of the mobile average\n :return: the smoothed data\n \"\"\"\n out = []\n for i, dat in enumerate(data):\n low = max(0, i - smooth_width)\n high = min(len(data) - 1, low + 2 * smooth_width)\n n = 0\n s_temperature = 0\n s_humidity = 0\n for d in data[low:high]:\n n += 1\n s_temperature += d.server_room_temperature\n s_humidity += d.server_room_humidity\n s_temperature /= float(max(1, n))\n s_humidity /= float(max(1, n))\n out.append(SensorData(dat.date, s_temperature, s_humidity))\n return out\n\n\n<mask token>\n\n\nclass displaydata:\n \"\"\"\n lass to encapsulate the meteo result to display\n \"\"\"\n\n def __init__(self):\n self.temperature = '0'\n self.temp_tendance = ''\n self.temp_max = '0'\n self.temp_min = '0'\n self.temp_max_date = '0'\n self.temp_min_date = '0'\n self.temp_mean = '0'\n self.humidity = '0'\n self.hum_tendance = ''\n self.hum_max = '0'\n self.hum_min = '0'\n self.hum_max_date = '0'\n self.hum_min_date = '0'\n self.hum_mean = '0'\n\n def __tendance(self, dt, seuil):\n if len(dt) < 3:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n if len(dt) > 20:\n p1 = dt[-20]\n p2 = dt[-10]\n p3 = dt[-1]\n else:\n p1 = dt[0]\n p2 = dt[len(dt) / 2]\n p3 = dt[-1]\n if abs(p3 - p2) < seuil:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2\n ) < seuil and p2 > p1:\n return 'mdi-arrow-top-right-bold-outline torange'\n elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2\n ) < seuil and p2 < p1:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 > p2 > p3:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 < p2 < p3:\n return 'mdi-arrow-up-bold-outline tred'\n else:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n\n def compute_from_data(self, dta, dha, date):\n self.temp_max = -2000\n self.temp_min = 2000\n self.temp_mean = 0\n for i, t in enumerate(dta):\n self.temp_mean += t\n if t > self.temp_max:\n self.temp_max = t\n self.temp_max_date = date[i]\n if t < self.temp_min:\n self.temp_min = t\n self.temp_min_date = date[i]\n if len(dta) > 0:\n self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))\n self.temp_max = '{:.2f}'.format(self.temp_max)\n self.temp_min = '{:.2f}'.format(self.temp_min)\n self.temperature = '{:.2f}'.format(dta[-1])\n self.temp_tendance = self.__tendance(dta, 0.05)\n self.hum_max = -2000\n self.hum_min = 2000\n self.hum_mean = 0\n for i, t in enumerate(dha):\n self.hum_mean += t\n if t > self.hum_max:\n self.hum_max = t\n self.hum_max_date = date[i]\n if t < self.hum_min:\n self.hum_min = t\n self.hum_min_date = date[i]\n if len(dha) > 0:\n self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))\n self.hum_max = '{:.2f}'.format(self.hum_max)\n self.hum_min = '{:.2f}'.format(self.hum_min)\n self.hum_tendance = self.__tendance(dha, 0.05)\n self.humidity = '{:.2f}'.format(dha[-1])\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass tlimit:\n\n def __init__(self, name, text):\n self.name = name\n self.text = text\n\n\n<mask token>\n\n\nclass SensorData:\n date = datetime.datetime(1970, 1, 1, 0, 0, 0)\n server_room_temperature = 0.0\n server_room_humidity = 0.0\n\n def __init__(self, d, t, h):\n self.date = d\n self.server_room_temperature = t\n self.server_room_humidity = h\n\n def __str__(self):\n return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.\n server_room_temperature, self.server_room_humidity)\n\n\n<mask token>\n\n\ndef smooth_data(data, smooth_width):\n \"\"\"\n smooth the curve plotted by data\n :param data: the input data\n :param smooth_width: the width of the mobile average\n :return: the smoothed data\n \"\"\"\n out = []\n for i, dat in enumerate(data):\n low = max(0, i - smooth_width)\n high = min(len(data) - 1, low + 2 * smooth_width)\n n = 0\n s_temperature = 0\n s_humidity = 0\n for d in data[low:high]:\n n += 1\n s_temperature += d.server_room_temperature\n s_humidity += d.server_room_humidity\n s_temperature /= float(max(1, n))\n s_humidity /= float(max(1, n))\n out.append(SensorData(dat.date, s_temperature, s_humidity))\n return out\n\n\n<mask token>\n\n\nclass displaydata:\n \"\"\"\n lass to encapsulate the meteo result to display\n \"\"\"\n\n def __init__(self):\n self.temperature = '0'\n self.temp_tendance = ''\n self.temp_max = '0'\n self.temp_min = '0'\n self.temp_max_date = '0'\n self.temp_min_date = '0'\n self.temp_mean = '0'\n self.humidity = '0'\n self.hum_tendance = ''\n self.hum_max = '0'\n self.hum_min = '0'\n self.hum_max_date = '0'\n self.hum_min_date = '0'\n self.hum_mean = '0'\n\n def __tendance(self, dt, seuil):\n if len(dt) < 3:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n if len(dt) > 20:\n p1 = dt[-20]\n p2 = dt[-10]\n p3 = dt[-1]\n else:\n p1 = dt[0]\n p2 = dt[len(dt) / 2]\n p3 = dt[-1]\n if abs(p3 - p2) < seuil:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2\n ) < seuil and p2 > p1:\n return 'mdi-arrow-top-right-bold-outline torange'\n elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2\n ) < seuil and p2 < p1:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 > p2 > p3:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 < p2 < p3:\n return 'mdi-arrow-up-bold-outline tred'\n else:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n\n def compute_from_data(self, dta, dha, date):\n self.temp_max = -2000\n self.temp_min = 2000\n self.temp_mean = 0\n for i, t in enumerate(dta):\n self.temp_mean += t\n if t > self.temp_max:\n self.temp_max = t\n self.temp_max_date = date[i]\n if t < self.temp_min:\n self.temp_min = t\n self.temp_min_date = date[i]\n if len(dta) > 0:\n self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))\n self.temp_max = '{:.2f}'.format(self.temp_max)\n self.temp_min = '{:.2f}'.format(self.temp_min)\n self.temperature = '{:.2f}'.format(dta[-1])\n self.temp_tendance = self.__tendance(dta, 0.05)\n self.hum_max = -2000\n self.hum_min = 2000\n self.hum_mean = 0\n for i, t in enumerate(dha):\n self.hum_mean += t\n if t > self.hum_max:\n self.hum_max = t\n self.hum_max_date = date[i]\n if t < self.hum_min:\n self.hum_min = t\n self.hum_min_date = date[i]\n if len(dha) > 0:\n self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))\n self.hum_max = '{:.2f}'.format(self.hum_max)\n self.hum_min = '{:.2f}'.format(self.hum_min)\n self.hum_tendance = self.__tendance(dha, 0.05)\n self.humidity = '{:.2f}'.format(dha[-1])\n\n\ndef getData(ll, smoo):\n data = resample_data(get_data(ll), 1000)\n if smoo > 0:\n data = smooth_data(data, smoo)\n print(len(data))\n dates = []\n temperatures = []\n humidity = []\n i = 0\n for sset in data:\n i += 1\n dates.append(sset.date.strftime('%Y-%m-%d %H:%M:%S'))\n temperatures.append(sset.server_room_temperature)\n humidity.append(sset.server_room_humidity)\n d = displaydata()\n d.compute_from_data(temperatures, humidity, dates)\n return dates, temperatures, humidity, d\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass tlimit:\n\n def __init__(self, name, text):\n self.name = name\n self.text = text\n\n\n<mask token>\n\n\nclass SensorData:\n date = datetime.datetime(1970, 1, 1, 0, 0, 0)\n server_room_temperature = 0.0\n server_room_humidity = 0.0\n\n def __init__(self, d, t, h):\n self.date = d\n self.server_room_temperature = t\n self.server_room_humidity = h\n\n def __str__(self):\n return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.\n server_room_temperature, self.server_room_humidity)\n\n\ndef get_data(last):\n \"\"\"\n get the database data on the last period\n :param last: duration of the period\n :return: the data\n \"\"\"\n Table = 'ServerRoom'\n filter = ''\n if last == 'lastone':\n data = request_meteodata(\n 'SELECT * from `ServerRoom` ORDER BY id DESC LIMIT 1 ')\n if len(data) == 0:\n return [SensorData(datetime.datetime.now(), 0, 0)]\n res = []\n for d in data:\n res.append(SensorData(d[1], d[2], d[3]))\n return res\n if last != 'All':\n limit = datetime.datetime.now().astimezone(utz)\n if last == '24hours':\n limit -= datetime.timedelta(hours=24)\n else:\n limit = limit.replace(hour=0, minute=0, second=0, microsecond=0)\n if last == '3days':\n limit -= datetime.timedelta(days=3)\n elif last == '7days':\n limit -= datetime.timedelta(days=7)\n elif last == 'month':\n limit = limit.replace(day=1)\n elif last == '30days':\n limit -= datetime.timedelta(days=30)\n elif last == 'year':\n limit = limit.replace(day=1, month=1)\n filter = \" WHERE `date` > '\" + str(limit) + \"'\"\n order = ' ORDER BY `date` ASC'\n req = 'SELECT * FROM `' + Table + '`' + filter + order\n data = request_meteodata(req)\n if len(data) == 0:\n print('no data: get all')\n req = 'SELECT * FROM `' + Table + '`' + order\n data = request_meteodata(req)\n res = []\n for d in data:\n res.append(SensorData(d[1], d[2], d[3]))\n return res\n\n\ndef smooth_data(data, smooth_width):\n \"\"\"\n smooth the curve plotted by data\n :param data: the input data\n :param smooth_width: the width of the mobile average\n :return: the smoothed data\n \"\"\"\n out = []\n for i, dat in enumerate(data):\n low = max(0, i - smooth_width)\n high = min(len(data) - 1, low + 2 * smooth_width)\n n = 0\n s_temperature = 0\n s_humidity = 0\n for d in data[low:high]:\n n += 1\n s_temperature += d.server_room_temperature\n s_humidity += d.server_room_humidity\n s_temperature /= float(max(1, n))\n s_humidity /= float(max(1, n))\n out.append(SensorData(dat.date, s_temperature, s_humidity))\n return out\n\n\n<mask token>\n\n\nclass displaydata:\n \"\"\"\n lass to encapsulate the meteo result to display\n \"\"\"\n\n def __init__(self):\n self.temperature = '0'\n self.temp_tendance = ''\n self.temp_max = '0'\n self.temp_min = '0'\n self.temp_max_date = '0'\n self.temp_min_date = '0'\n self.temp_mean = '0'\n self.humidity = '0'\n self.hum_tendance = ''\n self.hum_max = '0'\n self.hum_min = '0'\n self.hum_max_date = '0'\n self.hum_min_date = '0'\n self.hum_mean = '0'\n\n def __tendance(self, dt, seuil):\n if len(dt) < 3:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n if len(dt) > 20:\n p1 = dt[-20]\n p2 = dt[-10]\n p3 = dt[-1]\n else:\n p1 = dt[0]\n p2 = dt[len(dt) / 2]\n p3 = dt[-1]\n if abs(p3 - p2) < seuil:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2\n ) < seuil and p2 > p1:\n return 'mdi-arrow-top-right-bold-outline torange'\n elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2\n ) < seuil and p2 < p1:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 > p2 > p3:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 < p2 < p3:\n return 'mdi-arrow-up-bold-outline tred'\n else:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n\n def compute_from_data(self, dta, dha, date):\n self.temp_max = -2000\n self.temp_min = 2000\n self.temp_mean = 0\n for i, t in enumerate(dta):\n self.temp_mean += t\n if t > self.temp_max:\n self.temp_max = t\n self.temp_max_date = date[i]\n if t < self.temp_min:\n self.temp_min = t\n self.temp_min_date = date[i]\n if len(dta) > 0:\n self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))\n self.temp_max = '{:.2f}'.format(self.temp_max)\n self.temp_min = '{:.2f}'.format(self.temp_min)\n self.temperature = '{:.2f}'.format(dta[-1])\n self.temp_tendance = self.__tendance(dta, 0.05)\n self.hum_max = -2000\n self.hum_min = 2000\n self.hum_mean = 0\n for i, t in enumerate(dha):\n self.hum_mean += t\n if t > self.hum_max:\n self.hum_max = t\n self.hum_max_date = date[i]\n if t < self.hum_min:\n self.hum_min = t\n self.hum_min_date = date[i]\n if len(dha) > 0:\n self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))\n self.hum_max = '{:.2f}'.format(self.hum_max)\n self.hum_min = '{:.2f}'.format(self.hum_min)\n self.hum_tendance = self.__tendance(dha, 0.05)\n self.humidity = '{:.2f}'.format(dha[-1])\n\n\ndef getData(ll, smoo):\n data = resample_data(get_data(ll), 1000)\n if smoo > 0:\n data = smooth_data(data, smoo)\n print(len(data))\n dates = []\n temperatures = []\n humidity = []\n i = 0\n for sset in data:\n i += 1\n dates.append(sset.date.strftime('%Y-%m-%d %H:%M:%S'))\n temperatures.append(sset.server_room_temperature)\n humidity.append(sset.server_room_humidity)\n d = displaydata()\n d.compute_from_data(temperatures, humidity, dates)\n return dates, temperatures, humidity, d\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass tlimit:\n\n def __init__(self, name, text):\n self.name = name\n self.text = text\n\n\ntime_limit = [tlimit('All', 'All Data'), tlimit('day', 'Current day'),\n tlimit('24hours', 'Last 24 hours'), tlimit('3days', 'Three last days'),\n tlimit('7days', 'Seven last days'), tlimit('month', 'Current month'),\n tlimit('30days', 'Last 30 days'), tlimit('year', 'Current year')]\ntz = pytz.timezone('Europe/Paris')\nutz = pytz.timezone('UTC')\n\n\ndef request_meteodata(request: str):\n \"\"\"\n execute a request in the MeteoData database\n :param request: the request to execute\n :return: the feteched result\n \"\"\"\n import MySQLdb\n import platform\n if platform.system() == 'Windows':\n MySQLParams = {'host': '192.168.5.1', 'user': 'MeteoRobot',\n 'passwd': 'robot', 'db': 'MeteoData'}\n else:\n MySQLParams = {'host': 'localhost', 'user': 'MeteoRobot', 'passwd':\n 'robot', 'db': 'MeteoData'}\n try:\n con = MySQLdb.connect(**MySQLParams)\n cur = con.cursor()\n cur.execute(request)\n con.commit()\n data = cur.fetchall()\n except MySQLdb.Error as err:\n print(str(err))\n return []\n except Exception as err:\n print(str(err))\n return []\n con.close()\n return data\n\n\nclass SensorData:\n date = datetime.datetime(1970, 1, 1, 0, 0, 0)\n server_room_temperature = 0.0\n server_room_humidity = 0.0\n\n def __init__(self, d, t, h):\n self.date = d\n self.server_room_temperature = t\n self.server_room_humidity = h\n\n def __str__(self):\n return str(self.date) + ' {:.2f}°C {:.1f}%'.format(self.\n server_room_temperature, self.server_room_humidity)\n\n\ndef get_data(last):\n \"\"\"\n get the database data on the last period\n :param last: duration of the period\n :return: the data\n \"\"\"\n Table = 'ServerRoom'\n filter = ''\n if last == 'lastone':\n data = request_meteodata(\n 'SELECT * from `ServerRoom` ORDER BY id DESC LIMIT 1 ')\n if len(data) == 0:\n return [SensorData(datetime.datetime.now(), 0, 0)]\n res = []\n for d in data:\n res.append(SensorData(d[1], d[2], d[3]))\n return res\n if last != 'All':\n limit = datetime.datetime.now().astimezone(utz)\n if last == '24hours':\n limit -= datetime.timedelta(hours=24)\n else:\n limit = limit.replace(hour=0, minute=0, second=0, microsecond=0)\n if last == '3days':\n limit -= datetime.timedelta(days=3)\n elif last == '7days':\n limit -= datetime.timedelta(days=7)\n elif last == 'month':\n limit = limit.replace(day=1)\n elif last == '30days':\n limit -= datetime.timedelta(days=30)\n elif last == 'year':\n limit = limit.replace(day=1, month=1)\n filter = \" WHERE `date` > '\" + str(limit) + \"'\"\n order = ' ORDER BY `date` ASC'\n req = 'SELECT * FROM `' + Table + '`' + filter + order\n data = request_meteodata(req)\n if len(data) == 0:\n print('no data: get all')\n req = 'SELECT * FROM `' + Table + '`' + order\n data = request_meteodata(req)\n res = []\n for d in data:\n res.append(SensorData(d[1], d[2], d[3]))\n return res\n\n\ndef smooth_data(data, smooth_width):\n \"\"\"\n smooth the curve plotted by data\n :param data: the input data\n :param smooth_width: the width of the mobile average\n :return: the smoothed data\n \"\"\"\n out = []\n for i, dat in enumerate(data):\n low = max(0, i - smooth_width)\n high = min(len(data) - 1, low + 2 * smooth_width)\n n = 0\n s_temperature = 0\n s_humidity = 0\n for d in data[low:high]:\n n += 1\n s_temperature += d.server_room_temperature\n s_humidity += d.server_room_humidity\n s_temperature /= float(max(1, n))\n s_humidity /= float(max(1, n))\n out.append(SensorData(dat.date, s_temperature, s_humidity))\n return out\n\n\ndef resample_data(data, entity_number):\n \"\"\"\n limit the amount of dat\n :param data: input data\n :param entity_number: maximum number of entity in output\n :return: he resampled data\n \"\"\"\n if len(data) <= entity_number:\n return data\n interval = int(len(data) / entity_number + 1)\n out = []\n for i, dat in enumerate(data):\n if i % interval == 0:\n out.append(dat)\n return out\n\n\nclass displaydata:\n \"\"\"\n lass to encapsulate the meteo result to display\n \"\"\"\n\n def __init__(self):\n self.temperature = '0'\n self.temp_tendance = ''\n self.temp_max = '0'\n self.temp_min = '0'\n self.temp_max_date = '0'\n self.temp_min_date = '0'\n self.temp_mean = '0'\n self.humidity = '0'\n self.hum_tendance = ''\n self.hum_max = '0'\n self.hum_min = '0'\n self.hum_max_date = '0'\n self.hum_min_date = '0'\n self.hum_mean = '0'\n\n def __tendance(self, dt, seuil):\n if len(dt) < 3:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n if len(dt) > 20:\n p1 = dt[-20]\n p2 = dt[-10]\n p3 = dt[-1]\n else:\n p1 = dt[0]\n p2 = dt[len(dt) / 2]\n p3 = dt[-1]\n if abs(p3 - p2) < seuil:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n elif abs(p2 - p1) < seuil and p3 > p2 or abs(p3 - p2\n ) < seuil and p2 > p1:\n return 'mdi-arrow-top-right-bold-outline torange'\n elif abs(p2 - p1) < seuil and p3 < p2 or abs(p3 - p2\n ) < seuil and p2 < p1:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 > p2 > p3:\n return 'mdi-arrow-bottom-right-bold-outline tlightblue'\n elif p1 < p2 < p3:\n return 'mdi-arrow-up-bold-outline tred'\n else:\n return 'mdi-arrow-left-right-bold-outline tgreen'\n\n def compute_from_data(self, dta, dha, date):\n self.temp_max = -2000\n self.temp_min = 2000\n self.temp_mean = 0\n for i, t in enumerate(dta):\n self.temp_mean += t\n if t > self.temp_max:\n self.temp_max = t\n self.temp_max_date = date[i]\n if t < self.temp_min:\n self.temp_min = t\n self.temp_min_date = date[i]\n if len(dta) > 0:\n self.temp_mean = '{:.2f}'.format(self.temp_mean / float(len(dta)))\n self.temp_max = '{:.2f}'.format(self.temp_max)\n self.temp_min = '{:.2f}'.format(self.temp_min)\n self.temperature = '{:.2f}'.format(dta[-1])\n self.temp_tendance = self.__tendance(dta, 0.05)\n self.hum_max = -2000\n self.hum_min = 2000\n self.hum_mean = 0\n for i, t in enumerate(dha):\n self.hum_mean += t\n if t > self.hum_max:\n self.hum_max = t\n self.hum_max_date = date[i]\n if t < self.hum_min:\n self.hum_min = t\n self.hum_min_date = date[i]\n if len(dha) > 0:\n self.hum_mean = '{:.2f}'.format(self.hum_mean / float(len(dha)))\n self.hum_max = '{:.2f}'.format(self.hum_max)\n self.hum_min = '{:.2f}'.format(self.hum_min)\n self.hum_tendance = self.__tendance(dha, 0.05)\n self.humidity = '{:.2f}'.format(dha[-1])\n\n\ndef getData(ll, smoo):\n data = resample_data(get_data(ll), 1000)\n if smoo > 0:\n data = smooth_data(data, smoo)\n print(len(data))\n dates = []\n temperatures = []\n humidity = []\n i = 0\n for sset in data:\n i += 1\n dates.append(sset.date.strftime('%Y-%m-%d %H:%M:%S'))\n temperatures.append(sset.server_room_temperature)\n humidity.append(sset.server_room_humidity)\n d = displaydata()\n d.compute_from_data(temperatures, humidity, dates)\n return dates, temperatures, humidity, d\n\n\ndef get_actual_data():\n data = get_data('lastone')\n return '{:.2f}'.format(data[0].server_room_temperature), '{:.2f}'.format(\n data[0].server_room_humidity)\n",
"step-5": "\"\"\"\ndefinition of a sensor\n\"\"\"\nimport datetime\nimport pytz\n\nclass tlimit:\n\n def __init__(self, name, text):\n self.name = name\n self.text = text\n\n\ntime_limit = [\n tlimit(\"All\", \"All Data\"),\n tlimit(\"day\", \"Current day\"),\n tlimit(\"24hours\", \"Last 24 hours\"),\n tlimit(\"3days\", \"Three last days\"),\n tlimit(\"7days\", \"Seven last days\"),\n tlimit(\"month\", \"Current month\"),\n tlimit(\"30days\", \"Last 30 days\"),\n tlimit(\"year\", \"Current year\"),\n]\n\ntz = pytz.timezone(\"Europe/Paris\")\nutz = pytz.timezone(\"UTC\")\n\n\ndef request_meteodata(request: str):\n \"\"\"\n execute a request in the MeteoData database\n :param request: the request to execute\n :return: the feteched result\n \"\"\"\n import MySQLdb\n import platform\n if platform.system() == \"Windows\":\n MySQLParams = {\n 'host' : \"192.168.5.1\",\n 'user' : \"MeteoRobot\",\n 'passwd': \"robot\",\n 'db' : \"MeteoData\"\n }\n else:\n MySQLParams = {\n 'host' : \"localhost\",\n 'user' : \"MeteoRobot\",\n 'passwd': \"robot\",\n 'db' : \"MeteoData\"\n }\n try:\n con = MySQLdb.connect(**MySQLParams)\n cur = con.cursor()\n cur.execute(request)\n con.commit()\n data = cur.fetchall()\n except MySQLdb.Error as err:\n print(str(err))\n return []\n except Exception as err:\n print(str(err))\n return []\n con.close()\n return data\n\n\nclass SensorData:\n date = datetime.datetime(1970, 1, 1, 0, 0, 0)\n server_room_temperature = 0.0\n server_room_humidity = 0.0\n\n def __init__(self, d, t, h):\n self.date = d\n self.server_room_temperature = t\n self.server_room_humidity = h\n\n def __str__(self):\n return str(self.date) + \" {:.2f}°C {:.1f}%\".format(self.server_room_temperature, self.server_room_humidity)\n\n\ndef get_data(last):\n \"\"\"\n get the database data on the last period\n :param last: duration of the period\n :return: the data\n \"\"\"\n Table = \"ServerRoom\"\n filter = \"\"\n if last == \"lastone\":\n data = request_meteodata(\"SELECT * from `ServerRoom` ORDER BY id DESC LIMIT 1 \")\n if len(data) == 0:\n return [SensorData(datetime.datetime.now(), 0, 0)]\n res = []\n for d in data:\n res.append(SensorData(d[1], d[2], d[3]))\n return res\n if last != \"All\":\n limit = datetime.datetime.now().astimezone(utz)\n if last == \"24hours\":\n limit -= datetime.timedelta(hours=24)\n else:\n limit = limit.replace(hour=0, minute=0, second=0, microsecond=0)\n if last == \"3days\":\n limit -= datetime.timedelta(days=3)\n elif last == \"7days\":\n limit -= datetime.timedelta(days=7)\n elif last == \"month\":\n limit = limit.replace(day=1)\n elif last == \"30days\":\n limit -= datetime.timedelta(days=30)\n elif last == \"year\":\n limit = limit.replace(day=1, month=1)\n filter = \" WHERE `date` > '\" + str(limit) + \"'\"\n order = \" ORDER BY `date` ASC\"\n req = \"SELECT * FROM `\" + Table + \"`\" + filter + order\n data = request_meteodata(req)\n if len(data) == 0:\n print(\"no data: get all\")\n req = \"SELECT * FROM `\" + Table + \"`\" + order\n data = request_meteodata(req)\n res = []\n for d in data:\n res.append(SensorData(d[1], d[2], d[3]))\n return res\n\n\ndef smooth_data(data, smooth_width):\n \"\"\"\n smooth the curve plotted by data\n :param data: the input data\n :param smooth_width: the width of the mobile average\n :return: the smoothed data\n \"\"\"\n out = []\n for i, dat in enumerate(data):\n low = max(0, i - smooth_width)\n high = min((len(data) - 1), low + 2 * smooth_width)\n n = 0\n s_temperature = 0\n s_humidity = 0\n for d in data[low:high]:\n n += 1\n s_temperature += d.server_room_temperature\n s_humidity += d.server_room_humidity\n s_temperature /= float(max(1, n))\n s_humidity /= float(max(1, n))\n out.append(SensorData(dat.date, s_temperature, s_humidity))\n return out\n\n\ndef resample_data(data, entity_number):\n \"\"\"\n limit the amount of dat\n :param data: input data\n :param entity_number: maximum number of entity in output\n :return: he resampled data\n \"\"\"\n if len(data) <= entity_number:\n # not that many entity: nothing to do\n return data\n interval = int(len(data)/entity_number + 1)\n out = []\n for i, dat in enumerate(data):\n if i % interval == 0:\n out.append(dat)\n return out\n\n\nclass displaydata:\n \"\"\"\n lass to encapsulate the meteo result to display\n \"\"\"\n def __init__(self):\n self.temperature = \"0\"\n self.temp_tendance = \"\"\n self.temp_max = \"0\"\n self.temp_min = \"0\"\n self.temp_max_date = \"0\"\n self.temp_min_date = \"0\"\n self.temp_mean = \"0\"\n self.humidity = \"0\"\n self.hum_tendance = \"\"\n self.hum_max = \"0\"\n self.hum_min = \"0\"\n self.hum_max_date = \"0\"\n self.hum_min_date = \"0\"\n self.hum_mean = \"0\"\n\n def __tendance(self, dt, seuil):\n if len(dt) < 3:\n return \"mdi-arrow-left-right-bold-outline tgreen\"\n if len(dt) > 20:\n p1 = dt[-20]\n p2 = dt[-10]\n p3 = dt[-1]\n else:\n p1 = dt[0]\n p2 = dt[len(dt)/2]\n p3 = dt[-1]\n if abs(p3 - p2) < seuil:\n return \"mdi-arrow-left-right-bold-outline tgreen\"\n elif (abs(p2 - p1) < seuil and p3 > p2) or (abs(p3 - p2) < seuil and p2 > p1):\n return \"mdi-arrow-top-right-bold-outline torange\"\n elif (abs(p2 - p1) < seuil and p3 < p2) or (abs(p3 - p2) < seuil and p2 < p1):\n return \"mdi-arrow-bottom-right-bold-outline tlightblue\"\n elif p1 > p2 > p3:\n return \"mdi-arrow-bottom-right-bold-outline tlightblue\"\n elif p1 < p2 < p3:\n return \"mdi-arrow-up-bold-outline tred\"\n else:\n return \"mdi-arrow-left-right-bold-outline tgreen\"\n\n def compute_from_data(self, dta, dha, date):\n self.temp_max = -2000\n self.temp_min = 2000\n self.temp_mean = 0\n for i, t in enumerate(dta):\n self.temp_mean += t\n if t > self.temp_max:\n self.temp_max = t\n self.temp_max_date = date[i]\n if t < self.temp_min:\n self.temp_min = t\n self.temp_min_date = date[i]\n if len(dta) > 0:\n self.temp_mean = \"{:.2f}\".format(self.temp_mean / float(len(dta)))\n self.temp_max = \"{:.2f}\".format(self.temp_max)\n self.temp_min = \"{:.2f}\".format(self.temp_min)\n self.temperature = \"{:.2f}\".format(dta[-1])\n self.temp_tendance = self.__tendance(dta, 0.05)\n\n self.hum_max = -2000\n self.hum_min = 2000\n self.hum_mean = 0\n for i, t in enumerate(dha):\n self.hum_mean += t\n if t > self.hum_max:\n self.hum_max = t\n self.hum_max_date = date[i]\n if t < self.hum_min:\n self.hum_min = t\n self.hum_min_date = date[i]\n if len(dha) > 0:\n self.hum_mean = \"{:.2f}\".format(self.hum_mean / float(len(dha)))\n self.hum_max = \"{:.2f}\".format(self.hum_max)\n self.hum_min = \"{:.2f}\".format(self.hum_min)\n self.hum_tendance = self.__tendance(dha, 0.05)\n self.humidity = \"{:.2f}\".format(dha[-1])\n\n\ndef getData(ll, smoo):\n data = resample_data(get_data(ll), 1000)\n if smoo > 0:\n data = smooth_data(data, smoo)\n print(len(data))\n dates = []\n temperatures = []\n humidity = []\n i = 0\n for sset in data:\n i += 1\n dates.append(sset.date.strftime(\"%Y-%m-%d %H:%M:%S\"))\n temperatures.append(sset.server_room_temperature)\n humidity.append(sset.server_room_humidity)\n d = displaydata()\n d.compute_from_data(temperatures, humidity, dates)\n return dates, temperatures, humidity, d\n\n\ndef get_actual_data():\n data = get_data(\"lastone\")\n return \"{:.2f}\".format(data[0].server_room_temperature), \"{:.2f}\".format(data[0].server_room_humidity)\n",
"step-ids": [
12,
13,
14,
18,
20
]
}
|
[
12,
13,
14,
18,
20
] |
import sys
'''
Given a string, does the string contain an equal number of uppercase and
lowercase letters? Ignore whitespace, numbers, and punctuation. Return the
string “true” if balanced or the string “false” if not balanced.
'''
for line in sys.stdin:
lower = 0
upper = 0
# Count number of lowercase and uppercase letters
for x in range(0, len(line)):
if 'a' <= line[x] <= 'z':
lower = lower + 1
elif 'A' <= line[x] <= 'Z':
upper = upper + 1
# Determine if balanced or not
if lower == upper:
print('true')
else:
print('false')
# Repeat for each input line
|
normal
|
{
"blob_id": "4b3664153940b064b424bd77de473a6409437f88",
"index": 3279,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor line in sys.stdin:\n lower = 0\n upper = 0\n for x in range(0, len(line)):\n if 'a' <= line[x] <= 'z':\n lower = lower + 1\n elif 'A' <= line[x] <= 'Z':\n upper = upper + 1\n if lower == upper:\n print('true')\n else:\n print('false')\n",
"step-3": "import sys\n<mask token>\nfor line in sys.stdin:\n lower = 0\n upper = 0\n for x in range(0, len(line)):\n if 'a' <= line[x] <= 'z':\n lower = lower + 1\n elif 'A' <= line[x] <= 'Z':\n upper = upper + 1\n if lower == upper:\n print('true')\n else:\n print('false')\n",
"step-4": "import sys\n\n'''\nGiven a string, does the string contain an equal number of uppercase and \nlowercase letters? Ignore whitespace, numbers, and punctuation. Return the \nstring “true” if balanced or the string “false” if not balanced.\n'''\nfor line in sys.stdin:\n lower = 0\n upper = 0\n\n # Count number of lowercase and uppercase letters\n for x in range(0, len(line)):\n if 'a' <= line[x] <= 'z':\n lower = lower + 1\n elif 'A' <= line[x] <= 'Z':\n upper = upper + 1\n\n # Determine if balanced or not\n if lower == upper:\n print('true')\n else:\n print('false')\n\n # Repeat for each input line\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from django.db import models # db에 있는 models을 가져옴
from django.utils import timezone # 유틸에 있는 timezone을 가져옴
# Create your models here.
class Post(models.Model):
# Post라는 객체를 정의함 인수로 장고모델을 가져왔음
# 장고모델이기 때문에 데이터베이스에 저장된다.
author = models.ForeignKey('auth.User') # 외래키, 다른 객체에 대한 링크
title = models.CharField(max_length=200) # 글자수 제한
text = models.TextField() # 글자수제한없음
created_date = models.DateTimeField(default=timezone.now) # Date형식
published_date = models.DateTimeField(blank=True, null=True)
def publish(self): # 파이썬의 메소드
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class User(models.Model):
id = models.CharField(max_length=30, primary_key='true')
password = models.CharField(max_length=50)
reg_date = models.DateField(default=timezone.now)
upt_date = models.DateField(default=timezone.now)
last_pwd = models.CharField(max_length=50)
def chg_password(self):
self.last_pwd = self.password
self.save()
def __id__(self):
return self.id
|
normal
|
{
"blob_id": "3aa8c9b39174f0ed5799d6991516b34ca669b7d6",
"index": 9765,
"step-1": "<mask token>\n\n\nclass Post(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n",
"step-2": "<mask token>\n\n\nclass Post(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def publish(self):\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n",
"step-3": "<mask token>\n\n\nclass Post(models.Model):\n author = models.ForeignKey('auth.User')\n title = models.CharField(max_length=200)\n text = models.TextField()\n created_date = models.DateTimeField(default=timezone.now)\n published_date = models.DateTimeField(blank=True, null=True)\n\n def publish(self):\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n",
"step-4": "from django.db import models\nfrom django.utils import timezone\n\n\nclass Post(models.Model):\n author = models.ForeignKey('auth.User')\n title = models.CharField(max_length=200)\n text = models.TextField()\n created_date = models.DateTimeField(default=timezone.now)\n published_date = models.DateTimeField(blank=True, null=True)\n\n def publish(self):\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n",
"step-5": "from django.db import models # db에 있는 models을 가져옴\nfrom django.utils import timezone # 유틸에 있는 timezone을 가져옴\n\n\n# Create your models here.\n\nclass Post(models.Model):\n # Post라는 객체를 정의함 인수로 장고모델을 가져왔음\n # 장고모델이기 때문에 데이터베이스에 저장된다.\n author = models.ForeignKey('auth.User') # 외래키, 다른 객체에 대한 링크\n title = models.CharField(max_length=200) # 글자수 제한\n text = models.TextField() # 글자수제한없음\n created_date = models.DateTimeField(default=timezone.now) # Date형식\n published_date = models.DateTimeField(blank=True, null=True)\n\n def publish(self): # 파이썬의 메소드\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n\n",
"step-ids": [
6,
7,
8,
9,
10
]
}
|
[
6,
7,
8,
9,
10
] |
from PyQt5.QtCore import QObject, pyqtSlot
from Controllers.BookController import BookController
from Model.BookModel import BookModel
from Controllers.DatabaseController import DatabaseController
#Issuance Controller class contains the issuance properties and performs database operations for the issuance
class IssuanceController(QObject):
def __init__(self, model):
super().__init__()
self._database_controller = DatabaseController()
self._model = model
@pyqtSlot(str)
def change_issuance_id(self, value):
self._model.issuance_id = value
@pyqtSlot(str)
def change_student_id(self, value):
self._model.student_id = value
@pyqtSlot(str)
def change_staff_id(self, value):
self._model.staff_id = value
@pyqtSlot(str)
def change_book_id(self, value):
self._model.book_id = value
@pyqtSlot(str)
def change_release_date(self, value):
self._model.release_date = value
@pyqtSlot(str)
def change_due_date(self, value):
self._model.due_date = value
@pyqtSlot(bool)
def add(self, value):
self._model.is_add_click = True if value else False
def GetIssuedBooks(self):
try:
mycursor = self._database_controller.CursorTuple()
mycursor.execute(mycursor.execute("SELECT issuance_id, CONCAT(student.first_name, ' ', student.middle_name, ' ', student.last_name) AS full_name, student.student_id, book.title, issuance.book_id, issuance.release_date, issuance.due_date, CONCAT(staff.first_name, ' ', staff.middle_name, ' ', staff.last_name) AS staff_name FROM issuance LEFT JOIN book ON book.book_id = issuance.book_id LEFT JOIN student ON student.student_id = issuance.student_id LEFT JOIN staff ON staff.staff_id = issuance.staff_id WHERE issuance.is_returned = 0"))
books = mycursor.fetchall()
return books
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
finally:
self._database_controller.Close()
def BorrowBook(self):
try:
mycursor = self._database_controller.Cursor()
sql = "INSERT INTO issuance (student_id, staff_id, book_id, release_date, due_date, is_returned) VALUES (%s, %s, %s, %s, %s, %s)"
val = (
self._model.student_id,
self._model.staff_id,
self._model.book_id,
self._model.release_date,
self._model.due_date,
'0',
)
mycursor.execute(sql, val)
self._database_controller.Commit()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
finally:
self._database_controller.Close()
return mycursor.rowcount, "record inserted."
def UpdateIssuance(self):
try:
mycursor = self._database_controller.Cursor()
sql = "UPDATE issuance SET is_returned = 1 WHERE issuance_id = %s"
val = (
self._model.issuance_id,
)
mycursor.execute(sql, val)
self._database_controller.Commit()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
finally:
self._database_controller.Close()
return mycursor.rowcount, "record inserted."
|
normal
|
{
"blob_id": "1d4df09256324cce50fad096cdeff289af229728",
"index": 3132,
"step-1": "<mask token>\n\n\nclass IssuanceController(QObject):\n\n def __init__(self, model):\n super().__init__()\n self._database_controller = DatabaseController()\n self._model = model\n <mask token>\n\n @pyqtSlot(str)\n def change_student_id(self, value):\n self._model.student_id = value\n\n @pyqtSlot(str)\n def change_staff_id(self, value):\n self._model.staff_id = value\n\n @pyqtSlot(str)\n def change_book_id(self, value):\n self._model.book_id = value\n <mask token>\n\n @pyqtSlot(str)\n def change_due_date(self, value):\n self._model.due_date = value\n\n @pyqtSlot(bool)\n def add(self, value):\n self._model.is_add_click = True if value else False\n\n def GetIssuedBooks(self):\n try:\n mycursor = self._database_controller.CursorTuple()\n mycursor.execute(mycursor.execute(\n \"SELECT issuance_id, CONCAT(student.first_name, ' ', student.middle_name, ' ', student.last_name) AS full_name, student.student_id, book.title, issuance.book_id, issuance.release_date, issuance.due_date, CONCAT(staff.first_name, ' ', staff.middle_name, ' ', staff.last_name) AS staff_name FROM issuance LEFT JOIN book ON book.book_id = issuance.book_id LEFT JOIN student ON student.student_id = issuance.student_id LEFT JOIN staff ON staff.staff_id = issuance.staff_id WHERE issuance.is_returned = 0\"\n ))\n books = mycursor.fetchall()\n return books\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass IssuanceController(QObject):\n\n def __init__(self, model):\n super().__init__()\n self._database_controller = DatabaseController()\n self._model = model\n <mask token>\n\n @pyqtSlot(str)\n def change_student_id(self, value):\n self._model.student_id = value\n\n @pyqtSlot(str)\n def change_staff_id(self, value):\n self._model.staff_id = value\n\n @pyqtSlot(str)\n def change_book_id(self, value):\n self._model.book_id = value\n <mask token>\n\n @pyqtSlot(str)\n def change_due_date(self, value):\n self._model.due_date = value\n\n @pyqtSlot(bool)\n def add(self, value):\n self._model.is_add_click = True if value else False\n\n def GetIssuedBooks(self):\n try:\n mycursor = self._database_controller.CursorTuple()\n mycursor.execute(mycursor.execute(\n \"SELECT issuance_id, CONCAT(student.first_name, ' ', student.middle_name, ' ', student.last_name) AS full_name, student.student_id, book.title, issuance.book_id, issuance.release_date, issuance.due_date, CONCAT(staff.first_name, ' ', staff.middle_name, ' ', staff.last_name) AS staff_name FROM issuance LEFT JOIN book ON book.book_id = issuance.book_id LEFT JOIN student ON student.student_id = issuance.student_id LEFT JOIN staff ON staff.staff_id = issuance.staff_id WHERE issuance.is_returned = 0\"\n ))\n books = mycursor.fetchall()\n return books\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n <mask token>\n\n def UpdateIssuance(self):\n try:\n mycursor = self._database_controller.Cursor()\n sql = 'UPDATE issuance SET is_returned = 1 WHERE issuance_id = %s'\n val = self._model.issuance_id,\n mycursor.execute(sql, val)\n self._database_controller.Commit()\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n return mycursor.rowcount, 'record inserted.'\n",
"step-3": "<mask token>\n\n\nclass IssuanceController(QObject):\n\n def __init__(self, model):\n super().__init__()\n self._database_controller = DatabaseController()\n self._model = model\n\n @pyqtSlot(str)\n def change_issuance_id(self, value):\n self._model.issuance_id = value\n\n @pyqtSlot(str)\n def change_student_id(self, value):\n self._model.student_id = value\n\n @pyqtSlot(str)\n def change_staff_id(self, value):\n self._model.staff_id = value\n\n @pyqtSlot(str)\n def change_book_id(self, value):\n self._model.book_id = value\n\n @pyqtSlot(str)\n def change_release_date(self, value):\n self._model.release_date = value\n\n @pyqtSlot(str)\n def change_due_date(self, value):\n self._model.due_date = value\n\n @pyqtSlot(bool)\n def add(self, value):\n self._model.is_add_click = True if value else False\n\n def GetIssuedBooks(self):\n try:\n mycursor = self._database_controller.CursorTuple()\n mycursor.execute(mycursor.execute(\n \"SELECT issuance_id, CONCAT(student.first_name, ' ', student.middle_name, ' ', student.last_name) AS full_name, student.student_id, book.title, issuance.book_id, issuance.release_date, issuance.due_date, CONCAT(staff.first_name, ' ', staff.middle_name, ' ', staff.last_name) AS staff_name FROM issuance LEFT JOIN book ON book.book_id = issuance.book_id LEFT JOIN student ON student.student_id = issuance.student_id LEFT JOIN staff ON staff.staff_id = issuance.staff_id WHERE issuance.is_returned = 0\"\n ))\n books = mycursor.fetchall()\n return books\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n\n def BorrowBook(self):\n try:\n mycursor = self._database_controller.Cursor()\n sql = (\n 'INSERT INTO issuance (student_id, staff_id, book_id, release_date, due_date, is_returned) VALUES (%s, %s, %s, %s, %s, %s)'\n )\n val = (self._model.student_id, self._model.staff_id, self.\n _model.book_id, self._model.release_date, self._model.\n due_date, '0')\n mycursor.execute(sql, val)\n self._database_controller.Commit()\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n return mycursor.rowcount, 'record inserted.'\n\n def UpdateIssuance(self):\n try:\n mycursor = self._database_controller.Cursor()\n sql = 'UPDATE issuance SET is_returned = 1 WHERE issuance_id = %s'\n val = self._model.issuance_id,\n mycursor.execute(sql, val)\n self._database_controller.Commit()\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n return mycursor.rowcount, 'record inserted.'\n",
"step-4": "from PyQt5.QtCore import QObject, pyqtSlot\nfrom Controllers.BookController import BookController\nfrom Model.BookModel import BookModel\nfrom Controllers.DatabaseController import DatabaseController\n\n\nclass IssuanceController(QObject):\n\n def __init__(self, model):\n super().__init__()\n self._database_controller = DatabaseController()\n self._model = model\n\n @pyqtSlot(str)\n def change_issuance_id(self, value):\n self._model.issuance_id = value\n\n @pyqtSlot(str)\n def change_student_id(self, value):\n self._model.student_id = value\n\n @pyqtSlot(str)\n def change_staff_id(self, value):\n self._model.staff_id = value\n\n @pyqtSlot(str)\n def change_book_id(self, value):\n self._model.book_id = value\n\n @pyqtSlot(str)\n def change_release_date(self, value):\n self._model.release_date = value\n\n @pyqtSlot(str)\n def change_due_date(self, value):\n self._model.due_date = value\n\n @pyqtSlot(bool)\n def add(self, value):\n self._model.is_add_click = True if value else False\n\n def GetIssuedBooks(self):\n try:\n mycursor = self._database_controller.CursorTuple()\n mycursor.execute(mycursor.execute(\n \"SELECT issuance_id, CONCAT(student.first_name, ' ', student.middle_name, ' ', student.last_name) AS full_name, student.student_id, book.title, issuance.book_id, issuance.release_date, issuance.due_date, CONCAT(staff.first_name, ' ', staff.middle_name, ' ', staff.last_name) AS staff_name FROM issuance LEFT JOIN book ON book.book_id = issuance.book_id LEFT JOIN student ON student.student_id = issuance.student_id LEFT JOIN staff ON staff.staff_id = issuance.staff_id WHERE issuance.is_returned = 0\"\n ))\n books = mycursor.fetchall()\n return books\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n\n def BorrowBook(self):\n try:\n mycursor = self._database_controller.Cursor()\n sql = (\n 'INSERT INTO issuance (student_id, staff_id, book_id, release_date, due_date, is_returned) VALUES (%s, %s, %s, %s, %s, %s)'\n )\n val = (self._model.student_id, self._model.staff_id, self.\n _model.book_id, self._model.release_date, self._model.\n due_date, '0')\n mycursor.execute(sql, val)\n self._database_controller.Commit()\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n return mycursor.rowcount, 'record inserted.'\n\n def UpdateIssuance(self):\n try:\n mycursor = self._database_controller.Cursor()\n sql = 'UPDATE issuance SET is_returned = 1 WHERE issuance_id = %s'\n val = self._model.issuance_id,\n mycursor.execute(sql, val)\n self._database_controller.Commit()\n except mysql.connector.Error as err:\n print('Something went wrong: {}'.format(err))\n finally:\n self._database_controller.Close()\n return mycursor.rowcount, 'record inserted.'\n",
"step-5": "from PyQt5.QtCore import QObject, pyqtSlot\nfrom Controllers.BookController import BookController\nfrom Model.BookModel import BookModel\nfrom Controllers.DatabaseController import DatabaseController\n\n#Issuance Controller class contains the issuance properties and performs database operations for the issuance\nclass IssuanceController(QObject):\n\n def __init__(self, model):\n super().__init__()\n self._database_controller = DatabaseController()\n self._model = model\n\n @pyqtSlot(str)\n def change_issuance_id(self, value):\n self._model.issuance_id = value\n\n @pyqtSlot(str)\n def change_student_id(self, value):\n self._model.student_id = value\n\n @pyqtSlot(str)\n def change_staff_id(self, value):\n self._model.staff_id = value\n\n @pyqtSlot(str)\n def change_book_id(self, value):\n self._model.book_id = value\n\n @pyqtSlot(str)\n def change_release_date(self, value):\n self._model.release_date = value\n\n @pyqtSlot(str)\n def change_due_date(self, value):\n self._model.due_date = value\n\n @pyqtSlot(bool)\n def add(self, value):\n self._model.is_add_click = True if value else False\n\n def GetIssuedBooks(self):\n try:\n mycursor = self._database_controller.CursorTuple()\n mycursor.execute(mycursor.execute(\"SELECT issuance_id, CONCAT(student.first_name, ' ', student.middle_name, ' ', student.last_name) AS full_name, student.student_id, book.title, issuance.book_id, issuance.release_date, issuance.due_date, CONCAT(staff.first_name, ' ', staff.middle_name, ' ', staff.last_name) AS staff_name FROM issuance LEFT JOIN book ON book.book_id = issuance.book_id LEFT JOIN student ON student.student_id = issuance.student_id LEFT JOIN staff ON staff.staff_id = issuance.staff_id WHERE issuance.is_returned = 0\"))\n books = mycursor.fetchall()\n return books\n except mysql.connector.Error as err:\n print(\"Something went wrong: {}\".format(err))\n finally:\n self._database_controller.Close()\n\n def BorrowBook(self):\n try:\n mycursor = self._database_controller.Cursor()\n sql = \"INSERT INTO issuance (student_id, staff_id, book_id, release_date, due_date, is_returned) VALUES (%s, %s, %s, %s, %s, %s)\"\n val = (\n self._model.student_id, \n self._model.staff_id, \n self._model.book_id, \n self._model.release_date, \n self._model.due_date,\n '0', \n )\n mycursor.execute(sql, val)\n self._database_controller.Commit()\n except mysql.connector.Error as err:\n print(\"Something went wrong: {}\".format(err))\n finally:\n self._database_controller.Close()\n return mycursor.rowcount, \"record inserted.\"\n\n def UpdateIssuance(self):\n try:\n mycursor = self._database_controller.Cursor()\n sql = \"UPDATE issuance SET is_returned = 1 WHERE issuance_id = %s\"\n val = (\n self._model.issuance_id,\n )\n mycursor.execute(sql, val)\n self._database_controller.Commit()\n except mysql.connector.Error as err:\n print(\"Something went wrong: {}\".format(err))\n finally:\n self._database_controller.Close()\n return mycursor.rowcount, \"record inserted.\"\n",
"step-ids": [
8,
9,
12,
13,
14
]
}
|
[
8,
9,
12,
13,
14
] |
import os
import hashlib
import argparse
def hashfile(path, blocksize=65536):
afile = open(path, 'rb')
hasher = hashlib.md5()
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
afile.close()
return hasher.hexdigest()
def make_duplicate_list(filepath):
unique_hashes = {}
duplicate_files = {}
for dir_name, subdir_list, file_list in os.walk(filepath):
for filename in file_list:
path = os.path.join(dir_name, filename)
file_hash = hashfile(path)
if file_hash in unique_hashes:
if file_hash not in duplicate_files:
# More than 2 duplicate files with same hash can exist,
# so list of filepaths is created.
duplicate_files[file_hash] = []
duplicate_files[file_hash].append(unique_hashes[file_hash])
duplicate_files[file_hash].append(path)
else:
unique_hashes[file_hash] = path
return duplicate_files
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="duplicates detector")
parser.add_argument("path_to_folder",
help="path to folder containig duplicates")
args = parser.parse_args()
path = args.path_to_folder
duplicates = make_duplicate_list(path)
for idx, (key, value) in enumerate(duplicates.items(), 1):
print("{}) {} files with {} MD5 hash were " +
"found:".format(idx, len(value), key))
for idx, folder in enumerate(value, 1):
print(" {}. {}".format(idx, folder))
|
normal
|
{
"blob_id": "e99c158e54fd86b00e4e045e7fb28d961089800d",
"index": 3289,
"step-1": "<mask token>\n\n\ndef hashfile(path, blocksize=65536):\n afile = open(path, 'rb')\n hasher = hashlib.md5()\n buf = afile.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(blocksize)\n afile.close()\n return hasher.hexdigest()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef hashfile(path, blocksize=65536):\n afile = open(path, 'rb')\n hasher = hashlib.md5()\n buf = afile.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(blocksize)\n afile.close()\n return hasher.hexdigest()\n\n\ndef make_duplicate_list(filepath):\n unique_hashes = {}\n duplicate_files = {}\n for dir_name, subdir_list, file_list in os.walk(filepath):\n for filename in file_list:\n path = os.path.join(dir_name, filename)\n file_hash = hashfile(path)\n if file_hash in unique_hashes:\n if file_hash not in duplicate_files:\n duplicate_files[file_hash] = []\n duplicate_files[file_hash].append(unique_hashes[file_hash])\n duplicate_files[file_hash].append(path)\n else:\n unique_hashes[file_hash] = path\n return duplicate_files\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef hashfile(path, blocksize=65536):\n afile = open(path, 'rb')\n hasher = hashlib.md5()\n buf = afile.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(blocksize)\n afile.close()\n return hasher.hexdigest()\n\n\ndef make_duplicate_list(filepath):\n unique_hashes = {}\n duplicate_files = {}\n for dir_name, subdir_list, file_list in os.walk(filepath):\n for filename in file_list:\n path = os.path.join(dir_name, filename)\n file_hash = hashfile(path)\n if file_hash in unique_hashes:\n if file_hash not in duplicate_files:\n duplicate_files[file_hash] = []\n duplicate_files[file_hash].append(unique_hashes[file_hash])\n duplicate_files[file_hash].append(path)\n else:\n unique_hashes[file_hash] = path\n return duplicate_files\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='duplicates detector')\n parser.add_argument('path_to_folder', help=\n 'path to folder containig duplicates')\n args = parser.parse_args()\n path = args.path_to_folder\n duplicates = make_duplicate_list(path)\n for idx, (key, value) in enumerate(duplicates.items(), 1):\n print('{}) {} files with {} MD5 hash were ' + 'found:'.format(idx,\n len(value), key))\n for idx, folder in enumerate(value, 1):\n print(' {}. {}'.format(idx, folder))\n",
"step-4": "import os\nimport hashlib\nimport argparse\n\n\ndef hashfile(path, blocksize=65536):\n afile = open(path, 'rb')\n hasher = hashlib.md5()\n buf = afile.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(blocksize)\n afile.close()\n return hasher.hexdigest()\n\n\ndef make_duplicate_list(filepath):\n unique_hashes = {}\n duplicate_files = {}\n for dir_name, subdir_list, file_list in os.walk(filepath):\n for filename in file_list:\n path = os.path.join(dir_name, filename)\n file_hash = hashfile(path)\n if file_hash in unique_hashes:\n if file_hash not in duplicate_files:\n duplicate_files[file_hash] = []\n duplicate_files[file_hash].append(unique_hashes[file_hash])\n duplicate_files[file_hash].append(path)\n else:\n unique_hashes[file_hash] = path\n return duplicate_files\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='duplicates detector')\n parser.add_argument('path_to_folder', help=\n 'path to folder containig duplicates')\n args = parser.parse_args()\n path = args.path_to_folder\n duplicates = make_duplicate_list(path)\n for idx, (key, value) in enumerate(duplicates.items(), 1):\n print('{}) {} files with {} MD5 hash were ' + 'found:'.format(idx,\n len(value), key))\n for idx, folder in enumerate(value, 1):\n print(' {}. {}'.format(idx, folder))\n",
"step-5": "import os\nimport hashlib\nimport argparse\n\n\ndef hashfile(path, blocksize=65536):\n afile = open(path, 'rb')\n hasher = hashlib.md5()\n buf = afile.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(blocksize)\n afile.close()\n return hasher.hexdigest()\n\n\ndef make_duplicate_list(filepath):\n unique_hashes = {}\n duplicate_files = {}\n for dir_name, subdir_list, file_list in os.walk(filepath):\n for filename in file_list:\n path = os.path.join(dir_name, filename)\n file_hash = hashfile(path)\n if file_hash in unique_hashes:\n if file_hash not in duplicate_files:\n # More than 2 duplicate files with same hash can exist,\n # so list of filepaths is created.\n duplicate_files[file_hash] = []\n duplicate_files[file_hash].append(unique_hashes[file_hash])\n duplicate_files[file_hash].append(path)\n else:\n unique_hashes[file_hash] = path\n return duplicate_files\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"duplicates detector\")\n parser.add_argument(\"path_to_folder\",\n help=\"path to folder containig duplicates\")\n args = parser.parse_args()\n path = args.path_to_folder\n duplicates = make_duplicate_list(path)\n for idx, (key, value) in enumerate(duplicates.items(), 1):\n print(\"{}) {} files with {} MD5 hash were \" +\n \"found:\".format(idx, len(value), key))\n for idx, folder in enumerate(value, 1):\n print(\" {}. {}\".format(idx, folder))\n\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
class ObjectDetectionResult(object):
def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):
self.object_class = 0
self.confidence = 0
self.lt = Point(ltx, lty)
self.rb = Point(rbx, rby)
self.result_text = text
def IsRectInvalid(self):
return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.
y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Point(object):
<|reserved_special_token_0|>
class ObjectDetectionResult(object):
def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):
self.object_class = 0
self.confidence = 0
self.lt = Point(ltx, lty)
self.rb = Point(rbx, rby)
self.result_text = text
def IsRectInvalid(self):
return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.
y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class ObjectDetectionResult(object):
def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):
self.object_class = 0
self.confidence = 0
self.lt = Point(ltx, lty)
self.rb = Point(rbx, rby)
self.result_text = text
def IsRectInvalid(self):
return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.
y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)
<|reserved_special_token_1|>
STATUS_DISCONNECT = 0
STATUS_CONNECTED = 1
STATUS_OPEN_CH_REQUEST = 2
STATUS_OPENED = 3
STATUS_EXITING = 4
STATUS_EXITTED = 5
CONTENT_TYPE_IMAGE = 0
CONTENT_TYPE_VIDEO = 1
STATUS_OK = 0
STATUS_ERROR = 1
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class ObjectDetectionResult(object):
def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):
self.object_class = 0
self.confidence = 0
self.lt = Point(ltx, lty)
self.rb = Point(rbx, rby)
self.result_text = text
def IsRectInvalid(self):
return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.
y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)
<|reserved_special_token_1|>
STATUS_DISCONNECT = 0
STATUS_CONNECTED = 1
STATUS_OPEN_CH_REQUEST = 2
STATUS_OPENED = 3
STATUS_EXITING = 4
STATUS_EXITTED = 5
CONTENT_TYPE_IMAGE = 0
CONTENT_TYPE_VIDEO = 1
STATUS_OK = 0
STATUS_ERROR = 1
class Point(object):
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
class ObjectDetectionResult(object):
def __init__(self, ltx = 0, lty = 0, rbx = 0, rby = 0, text = None):
self.object_class = 0
self.confidence = 0
self.lt = Point(ltx, lty)
self.rb = Point(rbx, rby)
self.result_text = text
def IsRectInvalid(self):
return ((self.lt.x < 0) or \
(self.lt.y < 0) or \
(self.rb.x < 0) or \
(self.rb.y < 0) or \
(self.lt.x > self.rb.x) or \
(self.lt.y > self.rb.y))
|
flexible
|
{
"blob_id": "0ceb9eac46e3182821e65a1ae3a69d842db51e62",
"index": 7879,
"step-1": "<mask token>\n\n\nclass ObjectDetectionResult(object):\n\n def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):\n self.object_class = 0\n self.confidence = 0\n self.lt = Point(ltx, lty)\n self.rb = Point(rbx, rby)\n self.result_text = text\n\n def IsRectInvalid(self):\n return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.\n y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)\n",
"step-2": "<mask token>\n\n\nclass Point(object):\n <mask token>\n\n\nclass ObjectDetectionResult(object):\n\n def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):\n self.object_class = 0\n self.confidence = 0\n self.lt = Point(ltx, lty)\n self.rb = Point(rbx, rby)\n self.result_text = text\n\n def IsRectInvalid(self):\n return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.\n y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)\n",
"step-3": "<mask token>\n\n\nclass Point(object):\n\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n\nclass ObjectDetectionResult(object):\n\n def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):\n self.object_class = 0\n self.confidence = 0\n self.lt = Point(ltx, lty)\n self.rb = Point(rbx, rby)\n self.result_text = text\n\n def IsRectInvalid(self):\n return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.\n y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)\n",
"step-4": "STATUS_DISCONNECT = 0\nSTATUS_CONNECTED = 1\nSTATUS_OPEN_CH_REQUEST = 2\nSTATUS_OPENED = 3\nSTATUS_EXITING = 4\nSTATUS_EXITTED = 5\nCONTENT_TYPE_IMAGE = 0\nCONTENT_TYPE_VIDEO = 1\nSTATUS_OK = 0\nSTATUS_ERROR = 1\n\n\nclass Point(object):\n\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n\nclass ObjectDetectionResult(object):\n\n def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):\n self.object_class = 0\n self.confidence = 0\n self.lt = Point(ltx, lty)\n self.rb = Point(rbx, rby)\n self.result_text = text\n\n def IsRectInvalid(self):\n return (self.lt.x < 0 or self.lt.y < 0 or self.rb.x < 0 or self.rb.\n y < 0 or self.lt.x > self.rb.x or self.lt.y > self.rb.y)\n",
"step-5": "\nSTATUS_DISCONNECT = 0\nSTATUS_CONNECTED = 1\nSTATUS_OPEN_CH_REQUEST = 2\nSTATUS_OPENED = 3\nSTATUS_EXITING = 4\nSTATUS_EXITTED = 5\n\nCONTENT_TYPE_IMAGE = 0\nCONTENT_TYPE_VIDEO = 1\n\nSTATUS_OK = 0\nSTATUS_ERROR = 1\n\nclass Point(object):\n def __init__(self, x = 0, y = 0):\n self.x = x\n self.y = y\n\n\nclass ObjectDetectionResult(object):\n def __init__(self, ltx = 0, lty = 0, rbx = 0, rby = 0, text = None):\n self.object_class = 0\n self.confidence = 0\n self.lt = Point(ltx, lty)\n self.rb = Point(rbx, rby)\n self.result_text = text\n \n def IsRectInvalid(self):\n return ((self.lt.x < 0) or \\\n (self.lt.y < 0) or \\\n (self.rb.x < 0) or \\\n (self.rb.y < 0) or \\\n (self.lt.x > self.rb.x) or \\\n (self.lt.y > self.rb.y))\n\n\n\n\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
# Generated by Django 3.0.7 on 2020-06-15 15:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0003_auto_20200615_1225'),
]
operations = [
migrations.AlterField(
model_name='product',
name='harmonizacao',
field=models.TextField(null=True),
),
migrations.AlterField(
model_name='product',
name='history',
field=models.TextField(null=True),
),
migrations.AlterField(
model_name='product',
name='premios',
field=models.TextField(null=True),
),
]
|
normal
|
{
"blob_id": "c382b298cce8d7045d6ce8a84f90b3800dba7717",
"index": 297,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('products', '0003_auto_20200615_1225')]\n operations = [migrations.AlterField(model_name='product', name=\n 'harmonizacao', field=models.TextField(null=True)), migrations.\n AlterField(model_name='product', name='history', field=models.\n TextField(null=True)), migrations.AlterField(model_name='product',\n name='premios', field=models.TextField(null=True))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('products', '0003_auto_20200615_1225')]\n operations = [migrations.AlterField(model_name='product', name=\n 'harmonizacao', field=models.TextField(null=True)), migrations.\n AlterField(model_name='product', name='history', field=models.\n TextField(null=True)), migrations.AlterField(model_name='product',\n name='premios', field=models.TextField(null=True))]\n",
"step-5": "# Generated by Django 3.0.7 on 2020-06-15 15:26\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('products', '0003_auto_20200615_1225'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='product',\n name='harmonizacao',\n field=models.TextField(null=True),\n ),\n migrations.AlterField(\n model_name='product',\n name='history',\n field=models.TextField(null=True),\n ),\n migrations.AlterField(\n model_name='product',\n name='premios',\n field=models.TextField(null=True),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import os, glob, argparse, json, re
from collections import defaultdict
import numpy as np
import pandas as pd
from utils.CONSTANTS import output_dir, all_chromosomes, BINNED_CHRSZ, dataset_expts
def extract_chrom_num(s):
m = re.search('\d+', s)
if m is None:
return 24
else:
return int(m.group(0))
def main(expt_set, chrom, checkpoint_code, dataset='val', model_list=[], directory=None):
if directory is None:
directory = output_dir
model_list = sorted(model_list, key=extract_chrom_num)
print('Using the following {} models'.format(len(model_list)), model_list)
ensemble_code = 'c' + 'c'.join([str(extract_chrom_num(e)) for e in model_list])
ensemble_imp_path = 'averaged_preds-{}/{}'.format(checkpoint_code, ensemble_code)
imp_dir = os.path.join(directory, '{}_imputations/{}/'.format(dataset, expt_set))
os.makedirs(imp_dir+ensemble_imp_path, exist_ok=True)
pred_track_names = dataset_expts[dataset]
print('averaging chromosome: {}'.format(chrom))
for t in pred_track_names:
print(t, flush=True)
model_count = 0
avg = np.zeros(BINNED_CHRSZ[chrom])
expts_included = []
for m in model_list:
imp_path = imp_dir+m+'/{}.{}.{}.npz'.format(t, chrom, checkpoint_code)
if os.path.exists(imp_path):
vals = np.load(imp_path)['arr_0']
assert vals.shape[0] == BINNED_CHRSZ[chrom], 'wrong shape: pred shape {} != chrom shape {}'.format(vals.shape[0],
BINNED_CHRSZ[chrom])
avg += vals
model_count += 1
expts_included.append(m)
else:
print('No imputations {} {}'.format(m, t))
avg /= model_count
all_zeros = not np.any(avg)
assert not all_zeros, 'EMPTY ARRAY, NOT SAVING'
nans = np.isnan(avg).any()
assert not nans, 'NANS in ARRAY, NOT SAVING'
np.savez_compressed(imp_dir+ensemble_imp_path+'/{}.{}.npz'.format(t, chrom), avg)
# save list of models which had predictions and were therefore included
with open(imp_dir+ensemble_imp_path+'/{}.{}_info.txt'.format(t, chrom), 'w') as f:
for expt in expts_included:
f.write(expt+'\n')
print('Done', flush=True)
return ensemble_imp_path
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('expt_set')
parser.add_argument('chrom')
parser.add_argument('checkpoint_code') # 07.1
parser.add_argument('dataset')
parser.add_argument('-model_list', nargs='+', required=True, help='Model names e.g. chromschr21')
parser.add_argument('--directory', default=None)
args = parser.parse_args()
main(args.expt_set, args.chrom, args.checkpoint_code, dataset=args.dataset,
model_list=args.model_list, directory=args.directory)
|
normal
|
{
"blob_id": "c6d61a0159073304309cd4b1534ed5aed666bab5",
"index": 3666,
"step-1": "<mask token>\n\n\ndef main(expt_set, chrom, checkpoint_code, dataset='val', model_list=[],\n directory=None):\n if directory is None:\n directory = output_dir\n model_list = sorted(model_list, key=extract_chrom_num)\n print('Using the following {} models'.format(len(model_list)), model_list)\n ensemble_code = 'c' + 'c'.join([str(extract_chrom_num(e)) for e in\n model_list])\n ensemble_imp_path = 'averaged_preds-{}/{}'.format(checkpoint_code,\n ensemble_code)\n imp_dir = os.path.join(directory, '{}_imputations/{}/'.format(dataset,\n expt_set))\n os.makedirs(imp_dir + ensemble_imp_path, exist_ok=True)\n pred_track_names = dataset_expts[dataset]\n print('averaging chromosome: {}'.format(chrom))\n for t in pred_track_names:\n print(t, flush=True)\n model_count = 0\n avg = np.zeros(BINNED_CHRSZ[chrom])\n expts_included = []\n for m in model_list:\n imp_path = imp_dir + m + '/{}.{}.{}.npz'.format(t, chrom,\n checkpoint_code)\n if os.path.exists(imp_path):\n vals = np.load(imp_path)['arr_0']\n assert vals.shape[0] == BINNED_CHRSZ[chrom\n ], 'wrong shape: pred shape {} != chrom shape {}'.format(\n vals.shape[0], BINNED_CHRSZ[chrom])\n avg += vals\n model_count += 1\n expts_included.append(m)\n else:\n print('No imputations {} {}'.format(m, t))\n avg /= model_count\n all_zeros = not np.any(avg)\n assert not all_zeros, 'EMPTY ARRAY, NOT SAVING'\n nans = np.isnan(avg).any()\n assert not nans, 'NANS in ARRAY, NOT SAVING'\n np.savez_compressed(imp_dir + ensemble_imp_path + '/{}.{}.npz'.\n format(t, chrom), avg)\n with open(imp_dir + ensemble_imp_path + '/{}.{}_info.txt'.format(t,\n chrom), 'w') as f:\n for expt in expts_included:\n f.write(expt + '\\n')\n print('Done', flush=True)\n return ensemble_imp_path\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef extract_chrom_num(s):\n m = re.search('\\\\d+', s)\n if m is None:\n return 24\n else:\n return int(m.group(0))\n\n\ndef main(expt_set, chrom, checkpoint_code, dataset='val', model_list=[],\n directory=None):\n if directory is None:\n directory = output_dir\n model_list = sorted(model_list, key=extract_chrom_num)\n print('Using the following {} models'.format(len(model_list)), model_list)\n ensemble_code = 'c' + 'c'.join([str(extract_chrom_num(e)) for e in\n model_list])\n ensemble_imp_path = 'averaged_preds-{}/{}'.format(checkpoint_code,\n ensemble_code)\n imp_dir = os.path.join(directory, '{}_imputations/{}/'.format(dataset,\n expt_set))\n os.makedirs(imp_dir + ensemble_imp_path, exist_ok=True)\n pred_track_names = dataset_expts[dataset]\n print('averaging chromosome: {}'.format(chrom))\n for t in pred_track_names:\n print(t, flush=True)\n model_count = 0\n avg = np.zeros(BINNED_CHRSZ[chrom])\n expts_included = []\n for m in model_list:\n imp_path = imp_dir + m + '/{}.{}.{}.npz'.format(t, chrom,\n checkpoint_code)\n if os.path.exists(imp_path):\n vals = np.load(imp_path)['arr_0']\n assert vals.shape[0] == BINNED_CHRSZ[chrom\n ], 'wrong shape: pred shape {} != chrom shape {}'.format(\n vals.shape[0], BINNED_CHRSZ[chrom])\n avg += vals\n model_count += 1\n expts_included.append(m)\n else:\n print('No imputations {} {}'.format(m, t))\n avg /= model_count\n all_zeros = not np.any(avg)\n assert not all_zeros, 'EMPTY ARRAY, NOT SAVING'\n nans = np.isnan(avg).any()\n assert not nans, 'NANS in ARRAY, NOT SAVING'\n np.savez_compressed(imp_dir + ensemble_imp_path + '/{}.{}.npz'.\n format(t, chrom), avg)\n with open(imp_dir + ensemble_imp_path + '/{}.{}_info.txt'.format(t,\n chrom), 'w') as f:\n for expt in expts_included:\n f.write(expt + '\\n')\n print('Done', flush=True)\n return ensemble_imp_path\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef extract_chrom_num(s):\n m = re.search('\\\\d+', s)\n if m is None:\n return 24\n else:\n return int(m.group(0))\n\n\ndef main(expt_set, chrom, checkpoint_code, dataset='val', model_list=[],\n directory=None):\n if directory is None:\n directory = output_dir\n model_list = sorted(model_list, key=extract_chrom_num)\n print('Using the following {} models'.format(len(model_list)), model_list)\n ensemble_code = 'c' + 'c'.join([str(extract_chrom_num(e)) for e in\n model_list])\n ensemble_imp_path = 'averaged_preds-{}/{}'.format(checkpoint_code,\n ensemble_code)\n imp_dir = os.path.join(directory, '{}_imputations/{}/'.format(dataset,\n expt_set))\n os.makedirs(imp_dir + ensemble_imp_path, exist_ok=True)\n pred_track_names = dataset_expts[dataset]\n print('averaging chromosome: {}'.format(chrom))\n for t in pred_track_names:\n print(t, flush=True)\n model_count = 0\n avg = np.zeros(BINNED_CHRSZ[chrom])\n expts_included = []\n for m in model_list:\n imp_path = imp_dir + m + '/{}.{}.{}.npz'.format(t, chrom,\n checkpoint_code)\n if os.path.exists(imp_path):\n vals = np.load(imp_path)['arr_0']\n assert vals.shape[0] == BINNED_CHRSZ[chrom\n ], 'wrong shape: pred shape {} != chrom shape {}'.format(\n vals.shape[0], BINNED_CHRSZ[chrom])\n avg += vals\n model_count += 1\n expts_included.append(m)\n else:\n print('No imputations {} {}'.format(m, t))\n avg /= model_count\n all_zeros = not np.any(avg)\n assert not all_zeros, 'EMPTY ARRAY, NOT SAVING'\n nans = np.isnan(avg).any()\n assert not nans, 'NANS in ARRAY, NOT SAVING'\n np.savez_compressed(imp_dir + ensemble_imp_path + '/{}.{}.npz'.\n format(t, chrom), avg)\n with open(imp_dir + ensemble_imp_path + '/{}.{}_info.txt'.format(t,\n chrom), 'w') as f:\n for expt in expts_included:\n f.write(expt + '\\n')\n print('Done', flush=True)\n return ensemble_imp_path\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('expt_set')\n parser.add_argument('chrom')\n parser.add_argument('checkpoint_code')\n parser.add_argument('dataset')\n parser.add_argument('-model_list', nargs='+', required=True, help=\n 'Model names e.g. chromschr21')\n parser.add_argument('--directory', default=None)\n args = parser.parse_args()\n main(args.expt_set, args.chrom, args.checkpoint_code, dataset=args.\n dataset, model_list=args.model_list, directory=args.directory)\n",
"step-4": "import os, glob, argparse, json, re\nfrom collections import defaultdict\nimport numpy as np\nimport pandas as pd\nfrom utils.CONSTANTS import output_dir, all_chromosomes, BINNED_CHRSZ, dataset_expts\n\n\ndef extract_chrom_num(s):\n m = re.search('\\\\d+', s)\n if m is None:\n return 24\n else:\n return int(m.group(0))\n\n\ndef main(expt_set, chrom, checkpoint_code, dataset='val', model_list=[],\n directory=None):\n if directory is None:\n directory = output_dir\n model_list = sorted(model_list, key=extract_chrom_num)\n print('Using the following {} models'.format(len(model_list)), model_list)\n ensemble_code = 'c' + 'c'.join([str(extract_chrom_num(e)) for e in\n model_list])\n ensemble_imp_path = 'averaged_preds-{}/{}'.format(checkpoint_code,\n ensemble_code)\n imp_dir = os.path.join(directory, '{}_imputations/{}/'.format(dataset,\n expt_set))\n os.makedirs(imp_dir + ensemble_imp_path, exist_ok=True)\n pred_track_names = dataset_expts[dataset]\n print('averaging chromosome: {}'.format(chrom))\n for t in pred_track_names:\n print(t, flush=True)\n model_count = 0\n avg = np.zeros(BINNED_CHRSZ[chrom])\n expts_included = []\n for m in model_list:\n imp_path = imp_dir + m + '/{}.{}.{}.npz'.format(t, chrom,\n checkpoint_code)\n if os.path.exists(imp_path):\n vals = np.load(imp_path)['arr_0']\n assert vals.shape[0] == BINNED_CHRSZ[chrom\n ], 'wrong shape: pred shape {} != chrom shape {}'.format(\n vals.shape[0], BINNED_CHRSZ[chrom])\n avg += vals\n model_count += 1\n expts_included.append(m)\n else:\n print('No imputations {} {}'.format(m, t))\n avg /= model_count\n all_zeros = not np.any(avg)\n assert not all_zeros, 'EMPTY ARRAY, NOT SAVING'\n nans = np.isnan(avg).any()\n assert not nans, 'NANS in ARRAY, NOT SAVING'\n np.savez_compressed(imp_dir + ensemble_imp_path + '/{}.{}.npz'.\n format(t, chrom), avg)\n with open(imp_dir + ensemble_imp_path + '/{}.{}_info.txt'.format(t,\n chrom), 'w') as f:\n for expt in expts_included:\n f.write(expt + '\\n')\n print('Done', flush=True)\n return ensemble_imp_path\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('expt_set')\n parser.add_argument('chrom')\n parser.add_argument('checkpoint_code')\n parser.add_argument('dataset')\n parser.add_argument('-model_list', nargs='+', required=True, help=\n 'Model names e.g. chromschr21')\n parser.add_argument('--directory', default=None)\n args = parser.parse_args()\n main(args.expt_set, args.chrom, args.checkpoint_code, dataset=args.\n dataset, model_list=args.model_list, directory=args.directory)\n",
"step-5": "import os, glob, argparse, json, re\nfrom collections import defaultdict\n\nimport numpy as np\nimport pandas as pd\n\nfrom utils.CONSTANTS import output_dir, all_chromosomes, BINNED_CHRSZ, dataset_expts\n\n\ndef extract_chrom_num(s):\n m = re.search('\\d+', s)\n if m is None:\n return 24\n else:\n return int(m.group(0))\n\ndef main(expt_set, chrom, checkpoint_code, dataset='val', model_list=[], directory=None):\n if directory is None:\n directory = output_dir\n \n model_list = sorted(model_list, key=extract_chrom_num)\n print('Using the following {} models'.format(len(model_list)), model_list)\n ensemble_code = 'c' + 'c'.join([str(extract_chrom_num(e)) for e in model_list])\n ensemble_imp_path = 'averaged_preds-{}/{}'.format(checkpoint_code, ensemble_code)\n\n imp_dir = os.path.join(directory, '{}_imputations/{}/'.format(dataset, expt_set))\n os.makedirs(imp_dir+ensemble_imp_path, exist_ok=True)\n pred_track_names = dataset_expts[dataset]\n \n print('averaging chromosome: {}'.format(chrom))\n \n for t in pred_track_names:\n print(t, flush=True)\n model_count = 0\n avg = np.zeros(BINNED_CHRSZ[chrom])\n expts_included = []\n for m in model_list:\n imp_path = imp_dir+m+'/{}.{}.{}.npz'.format(t, chrom, checkpoint_code)\n if os.path.exists(imp_path):\n vals = np.load(imp_path)['arr_0']\n assert vals.shape[0] == BINNED_CHRSZ[chrom], 'wrong shape: pred shape {} != chrom shape {}'.format(vals.shape[0],\n BINNED_CHRSZ[chrom])\n avg += vals\n model_count += 1\n expts_included.append(m)\n else:\n print('No imputations {} {}'.format(m, t))\n\n avg /= model_count\n all_zeros = not np.any(avg)\n assert not all_zeros, 'EMPTY ARRAY, NOT SAVING'\n nans = np.isnan(avg).any()\n assert not nans, 'NANS in ARRAY, NOT SAVING'\n \n np.savez_compressed(imp_dir+ensemble_imp_path+'/{}.{}.npz'.format(t, chrom), avg)\n # save list of models which had predictions and were therefore included\n with open(imp_dir+ensemble_imp_path+'/{}.{}_info.txt'.format(t, chrom), 'w') as f:\n for expt in expts_included:\n f.write(expt+'\\n')\n \n print('Done', flush=True)\n return ensemble_imp_path\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('expt_set')\n parser.add_argument('chrom')\n parser.add_argument('checkpoint_code') # 07.1\n parser.add_argument('dataset')\n parser.add_argument('-model_list', nargs='+', required=True, help='Model names e.g. chromschr21')\n parser.add_argument('--directory', default=None)\n args = parser.parse_args()\n main(args.expt_set, args.chrom, args.checkpoint_code, dataset=args.dataset,\n model_list=args.model_list, directory=args.directory)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def main():
import sys
from pyramid.paster import get_appsettings
from sqlalchemy import engine_from_config
from pyvideohub.models import ScopedSession, Base
config_file = sys.argv[1]
settings = get_appsettings(config_file)
engine = engine_from_config(settings, 'sqlalchemy.')
ScopedSession.configure(bind=engine)
Base.metadata.create_all(engine)
print('DB initialized done.')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def main():
import sys
from pyramid.paster import get_appsettings
from sqlalchemy import engine_from_config
from pyvideohub.models import ScopedSession, Base
config_file = sys.argv[1]
settings = get_appsettings(config_file)
engine = engine_from_config(settings, 'sqlalchemy.')
ScopedSession.configure(bind=engine)
Base.metadata.create_all(engine)
print('DB initialized done.')
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
#!/usr/bin/env python
def main():
import sys
from pyramid.paster import get_appsettings
from sqlalchemy import engine_from_config
from pyvideohub.models import ScopedSession, Base
config_file = sys.argv[1]
settings = get_appsettings(config_file)
engine = engine_from_config(settings, 'sqlalchemy.')
ScopedSession.configure(bind=engine)
Base.metadata.create_all(engine)
print('DB initialized done.')
if __name__ == '__main__':
main()
|
flexible
|
{
"blob_id": "dbb66930edd70729e4df7d3023e83a6eae65cccd",
"index": 1030,
"step-1": "<mask token>\n",
"step-2": "def main():\n import sys\n from pyramid.paster import get_appsettings\n from sqlalchemy import engine_from_config\n from pyvideohub.models import ScopedSession, Base\n config_file = sys.argv[1]\n settings = get_appsettings(config_file)\n engine = engine_from_config(settings, 'sqlalchemy.')\n ScopedSession.configure(bind=engine)\n Base.metadata.create_all(engine)\n print('DB initialized done.')\n\n\n<mask token>\n",
"step-3": "def main():\n import sys\n from pyramid.paster import get_appsettings\n from sqlalchemy import engine_from_config\n from pyvideohub.models import ScopedSession, Base\n config_file = sys.argv[1]\n settings = get_appsettings(config_file)\n engine = engine_from_config(settings, 'sqlalchemy.')\n ScopedSession.configure(bind=engine)\n Base.metadata.create_all(engine)\n print('DB initialized done.')\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "#!/usr/bin/env python\n\ndef main():\n import sys\n from pyramid.paster import get_appsettings\n from sqlalchemy import engine_from_config\n from pyvideohub.models import ScopedSession, Base\n \n config_file = sys.argv[1]\n settings = get_appsettings(config_file)\n engine = engine_from_config(settings, 'sqlalchemy.')\n ScopedSession.configure(bind=engine)\n Base.metadata.create_all(engine)\n\n print('DB initialized done.')\n \n\n\nif __name__ == '__main__':\n main()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
""".. Ignore pydocstyle D400."""
from rolca.payment.api.views import (
PaymentViewSet,
)
routeList = ((r'payment', PaymentViewSet),)
|
normal
|
{
"blob_id": "2bfdc259bcd5ff058ee8661a14afd8a915b8372b",
"index": 7020,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nrouteList = ('payment', PaymentViewSet),\n",
"step-3": "<mask token>\nfrom rolca.payment.api.views import PaymentViewSet\nrouteList = ('payment', PaymentViewSet),\n",
"step-4": "\"\"\".. Ignore pydocstyle D400.\"\"\"\nfrom rolca.payment.api.views import (\n PaymentViewSet,\n)\n\nrouteList = ((r'payment', PaymentViewSet),)\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#While Loop
count = 0
while count<9:
print("Number:",count)
count = count+1
print("Good Bye")
#For Loop
fruits = ['Mango','Grapes','Apple']
for fruit in fruits:
print("current fruits:",fruit)
print("Good bye")
|
normal
|
{
"blob_id": "9b3040fa02cf8f039bac146f8a73384731c56722",
"index": 9142,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile count < 9:\n print('Number:', count)\n count = count + 1\nprint('Good Bye')\n<mask token>\nfor fruit in fruits:\n print('current fruits:', fruit)\nprint('Good bye')\n",
"step-3": "count = 0\nwhile count < 9:\n print('Number:', count)\n count = count + 1\nprint('Good Bye')\nfruits = ['Mango', 'Grapes', 'Apple']\nfor fruit in fruits:\n print('current fruits:', fruit)\nprint('Good bye')\n",
"step-4": "#While Loop\ncount = 0\nwhile count<9:\n print(\"Number:\",count)\n count = count+1\n\nprint(\"Good Bye\") \n\n#For Loop \nfruits = ['Mango','Grapes','Apple']\n\nfor fruit in fruits:\n print(\"current fruits:\",fruit)\n\nprint(\"Good bye\")\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#!/usr/bin/python3
"""
This module contains a Fabric function definition.
"""
from datetime import datetime, time
from fabric.api import *
from pathlib import Path
def do_pack():
timestamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
archive = "web_static_" + timestamp + ".tgz"
local("mkdir -p versions")
local("tar -cvzf versions/{} web_static/".format(archive))
my_file = Path("versions/{}".format(archive))
if my_file.is_file():
return my_file
else:
return None
|
normal
|
{
"blob_id": "6f3de70267956a6c7c3c5b261cf591051de4c548",
"index": 1968,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef do_pack():\n timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n archive = 'web_static_' + timestamp + '.tgz'\n local('mkdir -p versions')\n local('tar -cvzf versions/{} web_static/'.format(archive))\n my_file = Path('versions/{}'.format(archive))\n if my_file.is_file():\n return my_file\n else:\n return None\n",
"step-3": "<mask token>\nfrom datetime import datetime, time\nfrom fabric.api import *\nfrom pathlib import Path\n\n\ndef do_pack():\n timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n archive = 'web_static_' + timestamp + '.tgz'\n local('mkdir -p versions')\n local('tar -cvzf versions/{} web_static/'.format(archive))\n my_file = Path('versions/{}'.format(archive))\n if my_file.is_file():\n return my_file\n else:\n return None\n",
"step-4": "#!/usr/bin/python3\n\"\"\"\n This module contains a Fabric function definition.\n\"\"\"\nfrom datetime import datetime, time\nfrom fabric.api import *\nfrom pathlib import Path\n\n\ndef do_pack():\n timestamp = datetime.utcnow().strftime(\"%Y%m%d%H%M%S\")\n archive = \"web_static_\" + timestamp + \".tgz\"\n\n local(\"mkdir -p versions\")\n local(\"tar -cvzf versions/{} web_static/\".format(archive))\n\n my_file = Path(\"versions/{}\".format(archive))\n if my_file.is_file():\n return my_file\n else:\n return None\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
print('hello guys')
print('hello everyone')
<|reserved_special_token_1|>
print ("hello guys")
print ("hello everyone")
|
flexible
|
{
"blob_id": "4d87c3f70809bbd488159f0b55131af903c7e7b4",
"index": 1509,
"step-1": "<mask token>\n",
"step-2": "print('hello guys')\nprint('hello everyone')\n",
"step-3": "print (\"hello guys\")\nprint (\"hello everyone\")",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def over_nine_thousand(lst):
sum = 0
for number in lst:
sum += number
if sum > 9000:
break
return sum
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def over_nine_thousand(lst):
sum = 0
for number in lst:
sum += number
if sum > 9000:
break
return sum
print(over_nine_thousand([8000, 900, 120, 5000]))
<|reserved_special_token_1|>
#Write your function here
def over_nine_thousand(lst):
sum = 0
for number in lst:
sum += number
if (sum > 9000):
break
return sum
#Uncomment the line below when your function is done
print(over_nine_thousand([8000, 900, 120, 5000]))
#9020
|
flexible
|
{
"blob_id": "c2f39e33030cbe7c5d4827b47fb28d7604bdbc6d",
"index": 8135,
"step-1": "<mask token>\n",
"step-2": "def over_nine_thousand(lst):\n sum = 0\n for number in lst:\n sum += number\n if sum > 9000:\n break\n return sum\n\n\n<mask token>\n",
"step-3": "def over_nine_thousand(lst):\n sum = 0\n for number in lst:\n sum += number\n if sum > 9000:\n break\n return sum\n\n\nprint(over_nine_thousand([8000, 900, 120, 5000]))\n",
"step-4": "#Write your function here\ndef over_nine_thousand(lst):\n sum = 0\n for number in lst:\n sum += number\n if (sum > 9000):\n break\n return sum\n\n#Uncomment the line below when your function is done\nprint(over_nine_thousand([8000, 900, 120, 5000]))\n\n#9020",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from abstract_class_V import V
import torch
import torch.nn as nn
class V_test_abstract(V):
def __init__(self):
super(V_test_abstract, self).__init__()
def V_setup(self,y,X,nu):
self.explicit_gradient = False
self.need_higherorderderiv = True
self.dim = X.shape[1]
self.beta = nn.Parameter(torch.zeros(self.dim*5+4),requires_grad=True)
self.y = y
self.X = X
self.nu = nu
# beta[:dim] = z
# beta[(dim):(2dim)] = r1_local
# beta[(2dim):(3dim)] = r2_local
# beta[(3dim):(4dim)] = r1_local_plus
# beta[(4dim):(5dim)] = r2_local_plus
# beta[5dim] = r1_global
# beta[5dim+1] = r2_global
# beta[5dim+2] = sigma
# beta[5dim+3] = w0
return()
def forward(self):
z = self.beta[:self.dim]
r1_local = self.beta[(self.dim):(2*self.dim)]
r2_local = self.beta[(2*self.dim):(3*self.dim)]
r1_local_plus = self.beta[(3*self.dim):(4*self.dim)]
r2_local_plus = self.beta[(4*self.dim):(5*self.dim)]
r1_global = self.beta[5*self.dim]
r2_global = self.beta[5*self.dim+1]
sigma = self.beta[5*self.dim+2]
w0 = self.beta[5*self.dim+3]
tau = r1_global * torch.sqrt(r2_global)
lamb = r1_local * torch.sqrt(r2_local)
lambda_plus = r1_local_plus * torch.sqrt(r2_local_plus)
w = z * lamb * lambda_plus * tau
outy = (self.y - (w0 + self.X.mv(w)))*(self.y - (w0 + self.X.mv(w)))/(sigma*sigma) * 0.5
outz = torch.dot(z,z) * 0.5
outr1_local = torch.dot(r1_local,r1_local)
outr2_local = ((0.5*self.nu+1)*torch.log(r2_local) + 0.5 * self.nu/r2_local).sum()
outr1_global = r1_global*r1_global * 0.5
outr2_global = 1.5 * torch.log(r2_global) + 0.5/r2_global
outw0 = w0*w0/(25.)
out = outy+outz+outr1_local+outr2_local+outr1_global+outr2_global+outw0
return(out)
def load_explcit_gradient(self):
return()
|
normal
|
{
"blob_id": "27e9e63338d422b5fca6f7a67fa3d255602a3358",
"index": 225,
"step-1": "<mask token>\n\n\nclass V_test_abstract(V):\n\n def __init__(self):\n super(V_test_abstract, self).__init__()\n <mask token>\n\n def forward(self):\n z = self.beta[:self.dim]\n r1_local = self.beta[self.dim:2 * self.dim]\n r2_local = self.beta[2 * self.dim:3 * self.dim]\n r1_local_plus = self.beta[3 * self.dim:4 * self.dim]\n r2_local_plus = self.beta[4 * self.dim:5 * self.dim]\n r1_global = self.beta[5 * self.dim]\n r2_global = self.beta[5 * self.dim + 1]\n sigma = self.beta[5 * self.dim + 2]\n w0 = self.beta[5 * self.dim + 3]\n tau = r1_global * torch.sqrt(r2_global)\n lamb = r1_local * torch.sqrt(r2_local)\n lambda_plus = r1_local_plus * torch.sqrt(r2_local_plus)\n w = z * lamb * lambda_plus * tau\n outy = (self.y - (w0 + self.X.mv(w))) * (self.y - (w0 + self.X.mv(w))\n ) / (sigma * sigma) * 0.5\n outz = torch.dot(z, z) * 0.5\n outr1_local = torch.dot(r1_local, r1_local)\n outr2_local = ((0.5 * self.nu + 1) * torch.log(r2_local) + 0.5 *\n self.nu / r2_local).sum()\n outr1_global = r1_global * r1_global * 0.5\n outr2_global = 1.5 * torch.log(r2_global) + 0.5 / r2_global\n outw0 = w0 * w0 / 25.0\n out = (outy + outz + outr1_local + outr2_local + outr1_global +\n outr2_global + outw0)\n return out\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass V_test_abstract(V):\n\n def __init__(self):\n super(V_test_abstract, self).__init__()\n\n def V_setup(self, y, X, nu):\n self.explicit_gradient = False\n self.need_higherorderderiv = True\n self.dim = X.shape[1]\n self.beta = nn.Parameter(torch.zeros(self.dim * 5 + 4),\n requires_grad=True)\n self.y = y\n self.X = X\n self.nu = nu\n return ()\n\n def forward(self):\n z = self.beta[:self.dim]\n r1_local = self.beta[self.dim:2 * self.dim]\n r2_local = self.beta[2 * self.dim:3 * self.dim]\n r1_local_plus = self.beta[3 * self.dim:4 * self.dim]\n r2_local_plus = self.beta[4 * self.dim:5 * self.dim]\n r1_global = self.beta[5 * self.dim]\n r2_global = self.beta[5 * self.dim + 1]\n sigma = self.beta[5 * self.dim + 2]\n w0 = self.beta[5 * self.dim + 3]\n tau = r1_global * torch.sqrt(r2_global)\n lamb = r1_local * torch.sqrt(r2_local)\n lambda_plus = r1_local_plus * torch.sqrt(r2_local_plus)\n w = z * lamb * lambda_plus * tau\n outy = (self.y - (w0 + self.X.mv(w))) * (self.y - (w0 + self.X.mv(w))\n ) / (sigma * sigma) * 0.5\n outz = torch.dot(z, z) * 0.5\n outr1_local = torch.dot(r1_local, r1_local)\n outr2_local = ((0.5 * self.nu + 1) * torch.log(r2_local) + 0.5 *\n self.nu / r2_local).sum()\n outr1_global = r1_global * r1_global * 0.5\n outr2_global = 1.5 * torch.log(r2_global) + 0.5 / r2_global\n outw0 = w0 * w0 / 25.0\n out = (outy + outz + outr1_local + outr2_local + outr1_global +\n outr2_global + outw0)\n return out\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass V_test_abstract(V):\n\n def __init__(self):\n super(V_test_abstract, self).__init__()\n\n def V_setup(self, y, X, nu):\n self.explicit_gradient = False\n self.need_higherorderderiv = True\n self.dim = X.shape[1]\n self.beta = nn.Parameter(torch.zeros(self.dim * 5 + 4),\n requires_grad=True)\n self.y = y\n self.X = X\n self.nu = nu\n return ()\n\n def forward(self):\n z = self.beta[:self.dim]\n r1_local = self.beta[self.dim:2 * self.dim]\n r2_local = self.beta[2 * self.dim:3 * self.dim]\n r1_local_plus = self.beta[3 * self.dim:4 * self.dim]\n r2_local_plus = self.beta[4 * self.dim:5 * self.dim]\n r1_global = self.beta[5 * self.dim]\n r2_global = self.beta[5 * self.dim + 1]\n sigma = self.beta[5 * self.dim + 2]\n w0 = self.beta[5 * self.dim + 3]\n tau = r1_global * torch.sqrt(r2_global)\n lamb = r1_local * torch.sqrt(r2_local)\n lambda_plus = r1_local_plus * torch.sqrt(r2_local_plus)\n w = z * lamb * lambda_plus * tau\n outy = (self.y - (w0 + self.X.mv(w))) * (self.y - (w0 + self.X.mv(w))\n ) / (sigma * sigma) * 0.5\n outz = torch.dot(z, z) * 0.5\n outr1_local = torch.dot(r1_local, r1_local)\n outr2_local = ((0.5 * self.nu + 1) * torch.log(r2_local) + 0.5 *\n self.nu / r2_local).sum()\n outr1_global = r1_global * r1_global * 0.5\n outr2_global = 1.5 * torch.log(r2_global) + 0.5 / r2_global\n outw0 = w0 * w0 / 25.0\n out = (outy + outz + outr1_local + outr2_local + outr1_global +\n outr2_global + outw0)\n return out\n\n def load_explcit_gradient(self):\n return ()\n",
"step-4": "from abstract_class_V import V\nimport torch\nimport torch.nn as nn\n\n\nclass V_test_abstract(V):\n\n def __init__(self):\n super(V_test_abstract, self).__init__()\n\n def V_setup(self, y, X, nu):\n self.explicit_gradient = False\n self.need_higherorderderiv = True\n self.dim = X.shape[1]\n self.beta = nn.Parameter(torch.zeros(self.dim * 5 + 4),\n requires_grad=True)\n self.y = y\n self.X = X\n self.nu = nu\n return ()\n\n def forward(self):\n z = self.beta[:self.dim]\n r1_local = self.beta[self.dim:2 * self.dim]\n r2_local = self.beta[2 * self.dim:3 * self.dim]\n r1_local_plus = self.beta[3 * self.dim:4 * self.dim]\n r2_local_plus = self.beta[4 * self.dim:5 * self.dim]\n r1_global = self.beta[5 * self.dim]\n r2_global = self.beta[5 * self.dim + 1]\n sigma = self.beta[5 * self.dim + 2]\n w0 = self.beta[5 * self.dim + 3]\n tau = r1_global * torch.sqrt(r2_global)\n lamb = r1_local * torch.sqrt(r2_local)\n lambda_plus = r1_local_plus * torch.sqrt(r2_local_plus)\n w = z * lamb * lambda_plus * tau\n outy = (self.y - (w0 + self.X.mv(w))) * (self.y - (w0 + self.X.mv(w))\n ) / (sigma * sigma) * 0.5\n outz = torch.dot(z, z) * 0.5\n outr1_local = torch.dot(r1_local, r1_local)\n outr2_local = ((0.5 * self.nu + 1) * torch.log(r2_local) + 0.5 *\n self.nu / r2_local).sum()\n outr1_global = r1_global * r1_global * 0.5\n outr2_global = 1.5 * torch.log(r2_global) + 0.5 / r2_global\n outw0 = w0 * w0 / 25.0\n out = (outy + outz + outr1_local + outr2_local + outr1_global +\n outr2_global + outw0)\n return out\n\n def load_explcit_gradient(self):\n return ()\n",
"step-5": "from abstract_class_V import V\nimport torch\nimport torch.nn as nn\n\n\nclass V_test_abstract(V):\n def __init__(self):\n super(V_test_abstract, self).__init__()\n\n def V_setup(self,y,X,nu):\n self.explicit_gradient = False\n self.need_higherorderderiv = True\n self.dim = X.shape[1]\n self.beta = nn.Parameter(torch.zeros(self.dim*5+4),requires_grad=True)\n self.y = y\n self.X = X\n self.nu = nu\n\n # beta[:dim] = z\n # beta[(dim):(2dim)] = r1_local\n # beta[(2dim):(3dim)] = r2_local\n # beta[(3dim):(4dim)] = r1_local_plus\n # beta[(4dim):(5dim)] = r2_local_plus\n # beta[5dim] = r1_global\n # beta[5dim+1] = r2_global\n # beta[5dim+2] = sigma\n # beta[5dim+3] = w0\n return()\n\n def forward(self):\n z = self.beta[:self.dim]\n r1_local = self.beta[(self.dim):(2*self.dim)]\n r2_local = self.beta[(2*self.dim):(3*self.dim)]\n r1_local_plus = self.beta[(3*self.dim):(4*self.dim)]\n r2_local_plus = self.beta[(4*self.dim):(5*self.dim)]\n r1_global = self.beta[5*self.dim]\n r2_global = self.beta[5*self.dim+1]\n sigma = self.beta[5*self.dim+2]\n w0 = self.beta[5*self.dim+3]\n\n tau = r1_global * torch.sqrt(r2_global)\n lamb = r1_local * torch.sqrt(r2_local)\n lambda_plus = r1_local_plus * torch.sqrt(r2_local_plus)\n w = z * lamb * lambda_plus * tau\n\n outy = (self.y - (w0 + self.X.mv(w)))*(self.y - (w0 + self.X.mv(w)))/(sigma*sigma) * 0.5\n outz = torch.dot(z,z) * 0.5\n outr1_local = torch.dot(r1_local,r1_local)\n outr2_local = ((0.5*self.nu+1)*torch.log(r2_local) + 0.5 * self.nu/r2_local).sum()\n outr1_global = r1_global*r1_global * 0.5\n outr2_global = 1.5 * torch.log(r2_global) + 0.5/r2_global\n outw0 = w0*w0/(25.)\n out = outy+outz+outr1_local+outr2_local+outr1_global+outr2_global+outw0\n return(out)\n\n def load_explcit_gradient(self):\n return()",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
class Users(MethodView):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def put(self):
pass
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Users(MethodView):
def get(self):
return jsonify({'status': 'OK', 'users': [{'name': 'Pepe', 'age':
35, 'ocupation': 'Engineer'}, {'name': 'Bob', 'age': 20,
'ocupation': 'Student'}]})
def post(self):
pass
def put(self):
pass
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Users(MethodView):
def get(self):
return jsonify({'status': 'OK', 'users': [{'name': 'Pepe', 'age':
35, 'ocupation': 'Engineer'}, {'name': 'Bob', 'age': 20,
'ocupation': 'Student'}]})
def post(self):
pass
def put(self):
pass
def delete(self):
pass
<|reserved_special_token_1|>
from flask import jsonify
from flask.views import MethodView
class Users(MethodView):
def get(self):
return jsonify({'status': 'OK', 'users': [{'name': 'Pepe', 'age':
35, 'ocupation': 'Engineer'}, {'name': 'Bob', 'age': 20,
'ocupation': 'Student'}]})
def post(self):
pass
def put(self):
pass
def delete(self):
pass
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
from flask import jsonify
from flask.views import MethodView
class Users(MethodView):
def get(self):
return jsonify(
{
'status': 'OK',
'users': [
{'name': 'Pepe', 'age': 35, 'ocupation': "Engineer"},
{'name': 'Bob', 'age': 20, 'ocupation': "Student"}
]
}
)
def post(self):
# create user
pass
def put(self):
# update user
pass
def delete(self):
# delete user
pass
|
flexible
|
{
"blob_id": "781ce153d5053078ee11cecc13d055a67999a651",
"index": 3800,
"step-1": "<mask token>\n\n\nclass Users(MethodView):\n <mask token>\n <mask token>\n\n def put(self):\n pass\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Users(MethodView):\n\n def get(self):\n return jsonify({'status': 'OK', 'users': [{'name': 'Pepe', 'age': \n 35, 'ocupation': 'Engineer'}, {'name': 'Bob', 'age': 20,\n 'ocupation': 'Student'}]})\n\n def post(self):\n pass\n\n def put(self):\n pass\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Users(MethodView):\n\n def get(self):\n return jsonify({'status': 'OK', 'users': [{'name': 'Pepe', 'age': \n 35, 'ocupation': 'Engineer'}, {'name': 'Bob', 'age': 20,\n 'ocupation': 'Student'}]})\n\n def post(self):\n pass\n\n def put(self):\n pass\n\n def delete(self):\n pass\n",
"step-4": "from flask import jsonify\nfrom flask.views import MethodView\n\n\nclass Users(MethodView):\n\n def get(self):\n return jsonify({'status': 'OK', 'users': [{'name': 'Pepe', 'age': \n 35, 'ocupation': 'Engineer'}, {'name': 'Bob', 'age': 20,\n 'ocupation': 'Student'}]})\n\n def post(self):\n pass\n\n def put(self):\n pass\n\n def delete(self):\n pass\n",
"step-5": "# -*- coding: utf-8 -*-\nfrom flask import jsonify\nfrom flask.views import MethodView\n\n\nclass Users(MethodView):\n\n def get(self):\n return jsonify(\n {\n 'status': 'OK',\n 'users': [\n {'name': 'Pepe', 'age': 35, 'ocupation': \"Engineer\"},\n {'name': 'Bob', 'age': 20, 'ocupation': \"Student\"}\n ]\n }\n )\n\n def post(self):\n # create user\n pass\n\n def put(self):\n # update user\n pass\n\n def delete(self):\n # delete user\n pass\n",
"step-ids": [
2,
4,
5,
6,
7
]
}
|
[
2,
4,
5,
6,
7
] |
string1 = "Vegetable"
#string2 = "Fruit"
string2 = "vegetable"
print(string1 == string2)
print(string1 != string2)
if string1.lower() == string2.lower():
print("The strings are equal")
else:
print("The strings are not equal")
number1 = 25
number2 = 30
# ==
# !=
# >
# <
# >=
# <=
if number1 <= number2:
print("number 1 is greater")
name_1 = "Stephen"
name_2 = "stephen"
number_1 = 45
number_2 = 30
if name_1.lower() == name_2.lower() and number_1 < number_2:
print("We passed the test")
if name_1.lower() == name_2.lower() or number_1 < number_2:
print("We passed the test")
|
normal
|
{
"blob_id": "fecaf41152e8c98784585abfdb3777fc0a4824f3",
"index": 1052,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(string1 == string2)\nprint(string1 != string2)\nif string1.lower() == string2.lower():\n print('The strings are equal')\nelse:\n print('The strings are not equal')\n<mask token>\nif number1 <= number2:\n print('number 1 is greater')\n<mask token>\nif name_1.lower() == name_2.lower() and number_1 < number_2:\n print('We passed the test')\nif name_1.lower() == name_2.lower() or number_1 < number_2:\n print('We passed the test')\n",
"step-3": "string1 = 'Vegetable'\nstring2 = 'vegetable'\nprint(string1 == string2)\nprint(string1 != string2)\nif string1.lower() == string2.lower():\n print('The strings are equal')\nelse:\n print('The strings are not equal')\nnumber1 = 25\nnumber2 = 30\nif number1 <= number2:\n print('number 1 is greater')\nname_1 = 'Stephen'\nname_2 = 'stephen'\nnumber_1 = 45\nnumber_2 = 30\nif name_1.lower() == name_2.lower() and number_1 < number_2:\n print('We passed the test')\nif name_1.lower() == name_2.lower() or number_1 < number_2:\n print('We passed the test')\n",
"step-4": "\nstring1 = \"Vegetable\"\n#string2 = \"Fruit\"\nstring2 = \"vegetable\"\n\nprint(string1 == string2)\n\nprint(string1 != string2)\n\n\nif string1.lower() == string2.lower():\n print(\"The strings are equal\")\nelse:\n print(\"The strings are not equal\")\n\nnumber1 = 25\nnumber2 = 30\n\n# ==\n# !=\n# >\n# <\n# >=\n# <=\n\nif number1 <= number2:\n print(\"number 1 is greater\")\n\n\n\nname_1 = \"Stephen\"\nname_2 = \"stephen\"\n\nnumber_1 = 45\nnumber_2 = 30\nif name_1.lower() == name_2.lower() and number_1 < number_2:\n print(\"We passed the test\")\n\nif name_1.lower() == name_2.lower() or number_1 < number_2:\n print(\"We passed the test\")",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
@app.route('/')
def index(date=''):
date = request.args.get('date')
if not date:
now = datetime.datetime.now()
date = '%02d.%02d.%04d' % (now.day, now.month, now.year)
conn = sqlite3.connect('data.db')
c = conn.cursor()
res = c.execute(
"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) "
% (date,))
hour = list()
temp = list()
hum = list()
for row in res:
hour.append(row[0])
temp.append('%.1f' % row[1])
hum.append('%.1f' % row[2])
return render_template('index.html', date=date, hour=hour, temp=temp,
hum=hum)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@app.route('/')
def index(date=''):
date = request.args.get('date')
if not date:
now = datetime.datetime.now()
date = '%02d.%02d.%04d' % (now.day, now.month, now.year)
conn = sqlite3.connect('data.db')
c = conn.cursor()
res = c.execute(
"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) "
% (date,))
hour = list()
temp = list()
hum = list()
for row in res:
hour.append(row[0])
temp.append('%.1f' % row[1])
hum.append('%.1f' % row[2])
return render_template('index.html', date=date, hour=hour, temp=temp,
hum=hum)
if __name__ == '__main__':
app.debug = True
app.run(host='127.0.0.1', port=8888)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
app = Flask(__name__)
@app.route('/')
def index(date=''):
date = request.args.get('date')
if not date:
now = datetime.datetime.now()
date = '%02d.%02d.%04d' % (now.day, now.month, now.year)
conn = sqlite3.connect('data.db')
c = conn.cursor()
res = c.execute(
"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) "
% (date,))
hour = list()
temp = list()
hum = list()
for row in res:
hour.append(row[0])
temp.append('%.1f' % row[1])
hum.append('%.1f' % row[2])
return render_template('index.html', date=date, hour=hour, temp=temp,
hum=hum)
if __name__ == '__main__':
app.debug = True
app.run(host='127.0.0.1', port=8888)
<|reserved_special_token_1|>
from flask import Flask, request
from flask import render_template
import sqlite3
import datetime
app = Flask(__name__)
@app.route('/')
def index(date=''):
date = request.args.get('date')
if not date:
now = datetime.datetime.now()
date = '%02d.%02d.%04d' % (now.day, now.month, now.year)
conn = sqlite3.connect('data.db')
c = conn.cursor()
res = c.execute(
"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) "
% (date,))
hour = list()
temp = list()
hum = list()
for row in res:
hour.append(row[0])
temp.append('%.1f' % row[1])
hum.append('%.1f' % row[2])
return render_template('index.html', date=date, hour=hour, temp=temp,
hum=hum)
if __name__ == '__main__':
app.debug = True
app.run(host='127.0.0.1', port=8888)
<|reserved_special_token_1|>
from flask import Flask, request
from flask import render_template
import sqlite3
import datetime
app = Flask(__name__)
@app.route('/')
def index(date = ""):
date = request.args.get('date')
if not date:
now = datetime.datetime.now()
date = "%02d.%02d.%04d" % (now.day, now.month, now.year)
conn = sqlite3.connect("data.db")
c = conn.cursor()
res = c.execute("SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data "
"WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' "
"GROUP BY STRFTIME('%%H', date) " % (date, ))
hour = list()
temp = list()
hum = list()
for row in res:
hour.append(row[0])
temp.append("%.1f" % row[1])
hum.append("%.1f" % row[2])
return render_template('index.html', date = date, hour = hour, temp = temp, hum = hum)
if __name__ == '__main__':
app.debug = True
app.run(host = "127.0.0.1", port = 8888)
|
flexible
|
{
"blob_id": "f6fe33e04ccdca1d9714caec412478d0cfc8b363",
"index": 5559,
"step-1": "<mask token>\n\n\n@app.route('/')\ndef index(date=''):\n date = request.args.get('date')\n if not date:\n now = datetime.datetime.now()\n date = '%02d.%02d.%04d' % (now.day, now.month, now.year)\n conn = sqlite3.connect('data.db')\n c = conn.cursor()\n res = c.execute(\n \"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) \"\n % (date,))\n hour = list()\n temp = list()\n hum = list()\n for row in res:\n hour.append(row[0])\n temp.append('%.1f' % row[1])\n hum.append('%.1f' % row[2])\n return render_template('index.html', date=date, hour=hour, temp=temp,\n hum=hum)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@app.route('/')\ndef index(date=''):\n date = request.args.get('date')\n if not date:\n now = datetime.datetime.now()\n date = '%02d.%02d.%04d' % (now.day, now.month, now.year)\n conn = sqlite3.connect('data.db')\n c = conn.cursor()\n res = c.execute(\n \"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) \"\n % (date,))\n hour = list()\n temp = list()\n hum = list()\n for row in res:\n hour.append(row[0])\n temp.append('%.1f' % row[1])\n hum.append('%.1f' % row[2])\n return render_template('index.html', date=date, hour=hour, temp=temp,\n hum=hum)\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='127.0.0.1', port=8888)\n",
"step-3": "<mask token>\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index(date=''):\n date = request.args.get('date')\n if not date:\n now = datetime.datetime.now()\n date = '%02d.%02d.%04d' % (now.day, now.month, now.year)\n conn = sqlite3.connect('data.db')\n c = conn.cursor()\n res = c.execute(\n \"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) \"\n % (date,))\n hour = list()\n temp = list()\n hum = list()\n for row in res:\n hour.append(row[0])\n temp.append('%.1f' % row[1])\n hum.append('%.1f' % row[2])\n return render_template('index.html', date=date, hour=hour, temp=temp,\n hum=hum)\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='127.0.0.1', port=8888)\n",
"step-4": "from flask import Flask, request\nfrom flask import render_template\nimport sqlite3\nimport datetime\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index(date=''):\n date = request.args.get('date')\n if not date:\n now = datetime.datetime.now()\n date = '%02d.%02d.%04d' % (now.day, now.month, now.year)\n conn = sqlite3.connect('data.db')\n c = conn.cursor()\n res = c.execute(\n \"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' GROUP BY STRFTIME('%%H', date) \"\n % (date,))\n hour = list()\n temp = list()\n hum = list()\n for row in res:\n hour.append(row[0])\n temp.append('%.1f' % row[1])\n hum.append('%.1f' % row[2])\n return render_template('index.html', date=date, hour=hour, temp=temp,\n hum=hum)\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='127.0.0.1', port=8888)\n",
"step-5": "from flask import Flask, request\n\nfrom flask import render_template\nimport sqlite3\nimport datetime\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index(date = \"\"):\n date = request.args.get('date')\n\n if not date:\n now = datetime.datetime.now()\n date = \"%02d.%02d.%04d\" % (now.day, now.month, now.year)\n\n conn = sqlite3.connect(\"data.db\")\n c = conn.cursor()\n res = c.execute(\"SELECT STRFTIME('%%H', date), AVG(temp), AVG(hum) FROM data \"\n \"WHERE STRFTIME('%%d.%%m.%%Y', date)='%s' \"\n \"GROUP BY STRFTIME('%%H', date) \" % (date, ))\n hour = list()\n temp = list()\n hum = list()\n for row in res:\n hour.append(row[0])\n temp.append(\"%.1f\" % row[1])\n hum.append(\"%.1f\" % row[2])\n\n return render_template('index.html', date = date, hour = hour, temp = temp, hum = hum)\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host = \"127.0.0.1\", port = 8888)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
__author__ = 'NikolaiEgorov'
def Lad(a1, a2, b1, b2):
if (a1 == b1) | (a2 == b2):
return 'YES'
else:
return 'NO'
a1 = int(input())
a2 = int(input())
b1 = int(input())
b2 = int(input())
print(Lad(a1, a2, b1, b2))
|
normal
|
{
"blob_id": "0f55b598058b65c9dbf9cd4761d1ff6fc7091b19",
"index": 8791,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef Lad(a1, a2, b1, b2):\n if (a1 == b1) | (a2 == b2):\n return 'YES'\n else:\n return 'NO'\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef Lad(a1, a2, b1, b2):\n if (a1 == b1) | (a2 == b2):\n return 'YES'\n else:\n return 'NO'\n\n\n<mask token>\nprint(Lad(a1, a2, b1, b2))\n",
"step-4": "__author__ = 'NikolaiEgorov'\n\n\ndef Lad(a1, a2, b1, b2):\n if (a1 == b1) | (a2 == b2):\n return 'YES'\n else:\n return 'NO'\n\n\na1 = int(input())\na2 = int(input())\nb1 = int(input())\nb2 = int(input())\nprint(Lad(a1, a2, b1, b2))\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#import bmm_mysql_connect # Import my connection module
import csv
import MySQLdb
import os
#bmm_mysql_connect.connect() # Connecting to mysql test database
#mycur = conn.cursor() # Creating my cursor
path = os.path.expanduser('~/Projects/bmm_private/login_test.txt')
login = csv.reader(file(path))
# Assign login details to connection variables
for i in login:
host = i[0]
user = i[1]
passwd = i[2]
db = i[3]
# Connect to test database
conn = MySQLdb.connect(host=host,
user=user,
passwd=passwd,
db=db)
mycur = conn.cursor() # Creating my cursor
# creates a 'rooms' list, with reader function of csv module
# each row of the csv is made into it's own list with elements
rooms = csv.reader(file('list.txt'))
for room in rooms: #for each list in the list rooms
room_number = room[0] #pulls first element of each list and assigns to room_number variable
region = room[1] #pulls second element of each list and assigns to region variable
# Inserts the room number and reqion into the rooms table in the test database.
mycur.execute("INSERT INTO rooms VALUES (%r, %r)", (room_number, region))
conn.commit() # Commit the changes to the table
mycur.execute("SELECT * FROM rooms")
print mycur.fetchall()
|
normal
|
{
"blob_id": "4569413c8ea985a010a1fea4835a5b368a23663a",
"index": 9455,
"step-1": "#import bmm_mysql_connect # Import my connection module\nimport csv \nimport MySQLdb \nimport os\n\n#bmm_mysql_connect.connect() # Connecting to mysql test database\n#mycur = conn.cursor() # Creating my cursor\n\npath = os.path.expanduser('~/Projects/bmm_private/login_test.txt')\nlogin = csv.reader(file(path)) \n\n# Assign login details to connection variables\nfor i in login:\n host = i[0]\n user = i[1]\n passwd = i[2]\n db = i[3]\n\n# Connect to test database\nconn = MySQLdb.connect(host=host, \n user=user, \n passwd=passwd, \n db=db) \n\nmycur = conn.cursor() # Creating my cursor\n\n# creates a 'rooms' list, with reader function of csv module\n# each row of the csv is made into it's own list with elements\nrooms = csv.reader(file('list.txt')) \n\nfor room in rooms: \t\t\t#for each list in the list rooms\n \n room_number = room[0] \t#pulls first element of each list and assigns to room_number variable\n region = room[1] \t#pulls second element of each list and assigns to region variable\n\n\n # Inserts the room number and reqion into the rooms table in the test database.\n mycur.execute(\"INSERT INTO rooms VALUES (%r, %r)\", (room_number, region))\n\nconn.commit() # Commit the changes to the table\nmycur.execute(\"SELECT * FROM rooms\")\nprint mycur.fetchall()",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
class UserClass(AbstractBaseUser):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def get_full_name(self):
return self.first_name + ' ' + self.last_name
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class AdminUser(models.Model):
"""Model for admin user data"""
role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,
default=STAFF)
class BasicUser(models.Model):
"""Model for basic user data"""
type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,
default=RESTAURANT)
preferred_contact = models.CharField(max_length=20, choices=
PREFERRED_CONTACT, default=EMAIL)
position = models.CharField(verbose_name='position/title', max_length=
255, unique=False, null=True)
restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.
CASCADE, null=True)
program = models.ForeignKey('profiles.Program', on_delete=models.
CASCADE, null=True)
courier = models.ForeignKey('profiles.Courier', on_delete=models.
CASCADE, null=True)
class Schedule(models.Model):
monday_start = models.TimeField(auto_now=False, null=True, blank=True)
monday_end = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)
thursday_start = models.TimeField(auto_now=False, null=True, blank=True)
thursday_end = models.TimeField(auto_now=False, null=True, blank=True)
friday_start = models.TimeField(auto_now=False, null=True, blank=True)
friday_end = models.TimeField(auto_now=False, null=True, blank=True)
saturday_start = models.TimeField(auto_now=False, null=True, blank=True)
saturday_end = models.TimeField(auto_now=False, null=True, blank=True)
sunday_start = models.TimeField(auto_now=False, null=True, blank=True)
sunday_end = models.TimeField(auto_now=False, null=True, blank=True)
def getSchedule(self):
schedule = {}
if self.monday_start:
schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')
else:
schedule['monday_start'] = ''
if self.monday_end:
schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')
else:
schedule['monday_end'] = ''
if self.tuesday_start:
schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'
)
else:
schedule['tuesday_start'] = ''
if self.tuesday_end:
schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')
else:
schedule['tuesday_end'] = ''
if self.wednesday_start:
schedule['wednesday_start'] = self.wednesday_start.strftime(
'%-I:%M %p')
else:
schedule['wednesday_start'] = ''
if self.wednesday_end:
schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'
)
else:
schedule['wednesday_end'] = ''
if self.thursday_start:
schedule['thursday_start'] = self.thursday_start.strftime(
'%-I:%M %p')
else:
schedule['thursday_start'] = ''
if self.thursday_end:
schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')
else:
schedule['thursday_end'] = ''
if self.friday_start:
schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')
else:
schedule['friday_start'] = ''
if self.friday_end:
schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')
else:
schedule['friday_end'] = ''
if self.saturday_start:
schedule['saturday_start'] = self.saturday_start.strftime(
'%-I:%M %p')
else:
schedule['saturday_start'] = ''
if self.saturday_end:
schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')
else:
schedule['saturday_end'] = ''
if self.sunday_start:
schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')
else:
schedule['sunday_start'] = ''
if self.sunday_end:
schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')
else:
schedule['sunday_end'] = ''
return schedule
class Restaurant(models.Model):
created_at = models.DateTimeField(auto_now=True)
company_name = models.CharField(verbose_name='company name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='restaurant_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField()
uber_eats = models.BooleanField(default=False)
delivery_capacity = models.BooleanField(default=False)
packaging = models.BooleanField(default=False)
health_certificate = models.CharField(verbose_name='health certificate',
max_length=255, unique=False)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='coordinates', max_length=
255, unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='restaurants', on_delete=models.DO_NOTHING, null=True)
class Program(models.Model):
created_at = models.DateTimeField(auto_now=True)
program_name = models.CharField(verbose_name='program name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='program_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField(default=0, null=True)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='address', max_length=255,
unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='programs', on_delete=models.DO_NOTHING, null=True)
class Courier(models.Model):
created_at = models.DateTimeField(auto_now=True)
class Profile(models.Model):
user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars', blank=True)
def __str__(self):
return self.user.username
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class UserClassManager(BaseUserManager):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def create_basic_user(self, type, last_name, first_name, email,
password, phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
user_object = BasicUser.objects.create(type=type)
new_account.user_object = user_object
new_account.user_type = BASIC_USER
user_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
def create_user(self, last_name, first_name, email, password,
phone_number=''):
new_account = self.model(email=self.normalize_email(email))
new_account.set_password(password)
new_account.last_name = last_name
new_account.first_name = first_name
new_account.phone_number = phone_number
new_account.save(using=self._db)
return new_account
def create_superuser(self, last_name, first_name, email, password,
phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
new_account.staff = True
new_account.admin = True
admin_object = AdminUser.objects.create(role=SUPER_ADMIN)
new_account.admin_object = admin_object
new_account.user_type = ADMIN
admin_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class UserClass(AbstractBaseUser):
"""Class for general user - can be basic user or admin"""
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False, default='')
active = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
email = models.EmailField(verbose_name='email', max_length=255, unique=True
)
last_name = models.CharField(verbose_name='last name', max_length=255,
unique=False)
first_name = models.CharField(verbose_name='first name', max_length=255,
unique=False)
objects = UserClassManager()
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
image = models.CharField(verbose_name='user image', max_length=255,
unique=False, default='defaultIcon.png')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
user_type = models.CharField(max_length=20, choices=USER_TYPES, default
=BASIC_USER)
user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.
DO_NOTHING, null=True, related_name='basic_user_parent')
admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models
.DO_NOTHING, null=True, related_name='admin_user_parent')
def has_module_perms(self, app_label):
return True
@property
def is_admin(self):
return self.admin
def get_full_name(self):
return self.first_name + ' ' + self.last_name
def get_short_name(self):
return self.first_name
@property
def is_staff(self):
return self.staff
def __str__(self):
return self.email
class AdminUser(models.Model):
"""Model for admin user data"""
role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,
default=STAFF)
class BasicUser(models.Model):
"""Model for basic user data"""
type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,
default=RESTAURANT)
preferred_contact = models.CharField(max_length=20, choices=
PREFERRED_CONTACT, default=EMAIL)
position = models.CharField(verbose_name='position/title', max_length=
255, unique=False, null=True)
restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.
CASCADE, null=True)
program = models.ForeignKey('profiles.Program', on_delete=models.
CASCADE, null=True)
courier = models.ForeignKey('profiles.Courier', on_delete=models.
CASCADE, null=True)
class Schedule(models.Model):
monday_start = models.TimeField(auto_now=False, null=True, blank=True)
monday_end = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)
thursday_start = models.TimeField(auto_now=False, null=True, blank=True)
thursday_end = models.TimeField(auto_now=False, null=True, blank=True)
friday_start = models.TimeField(auto_now=False, null=True, blank=True)
friday_end = models.TimeField(auto_now=False, null=True, blank=True)
saturday_start = models.TimeField(auto_now=False, null=True, blank=True)
saturday_end = models.TimeField(auto_now=False, null=True, blank=True)
sunday_start = models.TimeField(auto_now=False, null=True, blank=True)
sunday_end = models.TimeField(auto_now=False, null=True, blank=True)
def getSchedule(self):
schedule = {}
if self.monday_start:
schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')
else:
schedule['monday_start'] = ''
if self.monday_end:
schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')
else:
schedule['monday_end'] = ''
if self.tuesday_start:
schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'
)
else:
schedule['tuesday_start'] = ''
if self.tuesday_end:
schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')
else:
schedule['tuesday_end'] = ''
if self.wednesday_start:
schedule['wednesday_start'] = self.wednesday_start.strftime(
'%-I:%M %p')
else:
schedule['wednesday_start'] = ''
if self.wednesday_end:
schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'
)
else:
schedule['wednesday_end'] = ''
if self.thursday_start:
schedule['thursday_start'] = self.thursday_start.strftime(
'%-I:%M %p')
else:
schedule['thursday_start'] = ''
if self.thursday_end:
schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')
else:
schedule['thursday_end'] = ''
if self.friday_start:
schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')
else:
schedule['friday_start'] = ''
if self.friday_end:
schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')
else:
schedule['friday_end'] = ''
if self.saturday_start:
schedule['saturday_start'] = self.saturday_start.strftime(
'%-I:%M %p')
else:
schedule['saturday_start'] = ''
if self.saturday_end:
schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')
else:
schedule['saturday_end'] = ''
if self.sunday_start:
schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')
else:
schedule['sunday_start'] = ''
if self.sunday_end:
schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')
else:
schedule['sunday_end'] = ''
return schedule
class Restaurant(models.Model):
created_at = models.DateTimeField(auto_now=True)
company_name = models.CharField(verbose_name='company name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='restaurant_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField()
uber_eats = models.BooleanField(default=False)
delivery_capacity = models.BooleanField(default=False)
packaging = models.BooleanField(default=False)
health_certificate = models.CharField(verbose_name='health certificate',
max_length=255, unique=False)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='coordinates', max_length=
255, unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='restaurants', on_delete=models.DO_NOTHING, null=True)
class Program(models.Model):
created_at = models.DateTimeField(auto_now=True)
program_name = models.CharField(verbose_name='program name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='program_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField(default=0, null=True)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='address', max_length=255,
unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='programs', on_delete=models.DO_NOTHING, null=True)
class Courier(models.Model):
created_at = models.DateTimeField(auto_now=True)
class Profile(models.Model):
user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars', blank=True)
def __str__(self):
return self.user.username
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class UserClassManager(BaseUserManager):
<|reserved_special_token_0|>
def create_staffuser(self, last_name, first_name, email, password, role,
phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
new_account.staff = True
admin_object = AdminUser.objects.create(role=role)
new_account.admin_object = admin_object
new_account.user_type = ADMIN
admin_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
def create_basic_user(self, type, last_name, first_name, email,
password, phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
user_object = BasicUser.objects.create(type=type)
new_account.user_object = user_object
new_account.user_type = BASIC_USER
user_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
def create_user(self, last_name, first_name, email, password,
phone_number=''):
new_account = self.model(email=self.normalize_email(email))
new_account.set_password(password)
new_account.last_name = last_name
new_account.first_name = first_name
new_account.phone_number = phone_number
new_account.save(using=self._db)
return new_account
def create_superuser(self, last_name, first_name, email, password,
phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
new_account.staff = True
new_account.admin = True
admin_object = AdminUser.objects.create(role=SUPER_ADMIN)
new_account.admin_object = admin_object
new_account.user_type = ADMIN
admin_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class UserClass(AbstractBaseUser):
"""Class for general user - can be basic user or admin"""
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False, default='')
active = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
email = models.EmailField(verbose_name='email', max_length=255, unique=True
)
last_name = models.CharField(verbose_name='last name', max_length=255,
unique=False)
first_name = models.CharField(verbose_name='first name', max_length=255,
unique=False)
objects = UserClassManager()
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
image = models.CharField(verbose_name='user image', max_length=255,
unique=False, default='defaultIcon.png')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
user_type = models.CharField(max_length=20, choices=USER_TYPES, default
=BASIC_USER)
user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.
DO_NOTHING, null=True, related_name='basic_user_parent')
admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models
.DO_NOTHING, null=True, related_name='admin_user_parent')
def has_module_perms(self, app_label):
return True
@property
def is_admin(self):
return self.admin
def get_full_name(self):
return self.first_name + ' ' + self.last_name
def get_short_name(self):
return self.first_name
@property
def is_staff(self):
return self.staff
def __str__(self):
return self.email
class AdminUser(models.Model):
"""Model for admin user data"""
role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,
default=STAFF)
class BasicUser(models.Model):
"""Model for basic user data"""
type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,
default=RESTAURANT)
preferred_contact = models.CharField(max_length=20, choices=
PREFERRED_CONTACT, default=EMAIL)
position = models.CharField(verbose_name='position/title', max_length=
255, unique=False, null=True)
restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.
CASCADE, null=True)
program = models.ForeignKey('profiles.Program', on_delete=models.
CASCADE, null=True)
courier = models.ForeignKey('profiles.Courier', on_delete=models.
CASCADE, null=True)
class Schedule(models.Model):
monday_start = models.TimeField(auto_now=False, null=True, blank=True)
monday_end = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)
thursday_start = models.TimeField(auto_now=False, null=True, blank=True)
thursday_end = models.TimeField(auto_now=False, null=True, blank=True)
friday_start = models.TimeField(auto_now=False, null=True, blank=True)
friday_end = models.TimeField(auto_now=False, null=True, blank=True)
saturday_start = models.TimeField(auto_now=False, null=True, blank=True)
saturday_end = models.TimeField(auto_now=False, null=True, blank=True)
sunday_start = models.TimeField(auto_now=False, null=True, blank=True)
sunday_end = models.TimeField(auto_now=False, null=True, blank=True)
def getSchedule(self):
schedule = {}
if self.monday_start:
schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')
else:
schedule['monday_start'] = ''
if self.monday_end:
schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')
else:
schedule['monday_end'] = ''
if self.tuesday_start:
schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'
)
else:
schedule['tuesday_start'] = ''
if self.tuesday_end:
schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')
else:
schedule['tuesday_end'] = ''
if self.wednesday_start:
schedule['wednesday_start'] = self.wednesday_start.strftime(
'%-I:%M %p')
else:
schedule['wednesday_start'] = ''
if self.wednesday_end:
schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'
)
else:
schedule['wednesday_end'] = ''
if self.thursday_start:
schedule['thursday_start'] = self.thursday_start.strftime(
'%-I:%M %p')
else:
schedule['thursday_start'] = ''
if self.thursday_end:
schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')
else:
schedule['thursday_end'] = ''
if self.friday_start:
schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')
else:
schedule['friday_start'] = ''
if self.friday_end:
schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')
else:
schedule['friday_end'] = ''
if self.saturday_start:
schedule['saturday_start'] = self.saturday_start.strftime(
'%-I:%M %p')
else:
schedule['saturday_start'] = ''
if self.saturday_end:
schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')
else:
schedule['saturday_end'] = ''
if self.sunday_start:
schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')
else:
schedule['sunday_start'] = ''
if self.sunday_end:
schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')
else:
schedule['sunday_end'] = ''
return schedule
class Restaurant(models.Model):
created_at = models.DateTimeField(auto_now=True)
company_name = models.CharField(verbose_name='company name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='restaurant_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField()
uber_eats = models.BooleanField(default=False)
delivery_capacity = models.BooleanField(default=False)
packaging = models.BooleanField(default=False)
health_certificate = models.CharField(verbose_name='health certificate',
max_length=255, unique=False)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='coordinates', max_length=
255, unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='restaurants', on_delete=models.DO_NOTHING, null=True)
class Program(models.Model):
created_at = models.DateTimeField(auto_now=True)
program_name = models.CharField(verbose_name='program name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='program_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField(default=0, null=True)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='address', max_length=255,
unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='programs', on_delete=models.DO_NOTHING, null=True)
class Courier(models.Model):
created_at = models.DateTimeField(auto_now=True)
class Profile(models.Model):
user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars', blank=True)
def __str__(self):
return self.user.username
<|reserved_special_token_1|>
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
BASIC_ADMIN = 'ADMIN'
SUPER_ADMIN = 'SUPER'
MANAGER = 'MNGR'
DEVELOPER = 'DEV'
STAFF = 'STAFF'
ADMIN_ROLE_OPTIONS = [(BASIC_ADMIN, 'basic admin'), (SUPER_ADMIN,
'super admin'), (MANAGER, 'manager'), (DEVELOPER, 'developer'), (STAFF,
'stuff')]
PROGRAM = 'PR'
RESTAURANT = 'RE'
USER_TYPE_OPTIONS = [(PROGRAM, 'Program'), (RESTAURANT, 'Restaurant')]
PHONE = 'PH'
EMAIL = 'EM'
PREFERRED_CONTACT = [(PHONE, 'Phone'), (EMAIL, 'Email')]
ADMIN = 'ADM'
BASIC_USER = 'BSC'
USER_TYPES = [(ADMIN, 'Admin'), (BASIC_USER, 'Basic User')]
class UserClassManager(BaseUserManager):
"""Manager for User class"""
def create_staffuser(self, last_name, first_name, email, password, role,
phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
new_account.staff = True
admin_object = AdminUser.objects.create(role=role)
new_account.admin_object = admin_object
new_account.user_type = ADMIN
admin_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
def create_basic_user(self, type, last_name, first_name, email,
password, phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
user_object = BasicUser.objects.create(type=type)
new_account.user_object = user_object
new_account.user_type = BASIC_USER
user_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
def create_user(self, last_name, first_name, email, password,
phone_number=''):
new_account = self.model(email=self.normalize_email(email))
new_account.set_password(password)
new_account.last_name = last_name
new_account.first_name = first_name
new_account.phone_number = phone_number
new_account.save(using=self._db)
return new_account
def create_superuser(self, last_name, first_name, email, password,
phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name
=last_name, first_name=first_name, email=email, password=password)
new_account.staff = True
new_account.admin = True
admin_object = AdminUser.objects.create(role=SUPER_ADMIN)
new_account.admin_object = admin_object
new_account.user_type = ADMIN
admin_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
REQUIRED_FIELDS = []
USERNAME_FIELD = 'email'
class UserClass(AbstractBaseUser):
"""Class for general user - can be basic user or admin"""
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False, default='')
active = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
email = models.EmailField(verbose_name='email', max_length=255, unique=True
)
last_name = models.CharField(verbose_name='last name', max_length=255,
unique=False)
first_name = models.CharField(verbose_name='first name', max_length=255,
unique=False)
objects = UserClassManager()
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
image = models.CharField(verbose_name='user image', max_length=255,
unique=False, default='defaultIcon.png')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
user_type = models.CharField(max_length=20, choices=USER_TYPES, default
=BASIC_USER)
user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.
DO_NOTHING, null=True, related_name='basic_user_parent')
admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models
.DO_NOTHING, null=True, related_name='admin_user_parent')
def has_module_perms(self, app_label):
return True
@property
def is_admin(self):
return self.admin
def get_full_name(self):
return self.first_name + ' ' + self.last_name
def get_short_name(self):
return self.first_name
@property
def is_staff(self):
return self.staff
def __str__(self):
return self.email
class AdminUser(models.Model):
"""Model for admin user data"""
role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,
default=STAFF)
class BasicUser(models.Model):
"""Model for basic user data"""
type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,
default=RESTAURANT)
preferred_contact = models.CharField(max_length=20, choices=
PREFERRED_CONTACT, default=EMAIL)
position = models.CharField(verbose_name='position/title', max_length=
255, unique=False, null=True)
restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.
CASCADE, null=True)
program = models.ForeignKey('profiles.Program', on_delete=models.
CASCADE, null=True)
courier = models.ForeignKey('profiles.Courier', on_delete=models.
CASCADE, null=True)
class Schedule(models.Model):
monday_start = models.TimeField(auto_now=False, null=True, blank=True)
monday_end = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)
thursday_start = models.TimeField(auto_now=False, null=True, blank=True)
thursday_end = models.TimeField(auto_now=False, null=True, blank=True)
friday_start = models.TimeField(auto_now=False, null=True, blank=True)
friday_end = models.TimeField(auto_now=False, null=True, blank=True)
saturday_start = models.TimeField(auto_now=False, null=True, blank=True)
saturday_end = models.TimeField(auto_now=False, null=True, blank=True)
sunday_start = models.TimeField(auto_now=False, null=True, blank=True)
sunday_end = models.TimeField(auto_now=False, null=True, blank=True)
def getSchedule(self):
schedule = {}
if self.monday_start:
schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')
else:
schedule['monday_start'] = ''
if self.monday_end:
schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')
else:
schedule['monday_end'] = ''
if self.tuesday_start:
schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'
)
else:
schedule['tuesday_start'] = ''
if self.tuesday_end:
schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')
else:
schedule['tuesday_end'] = ''
if self.wednesday_start:
schedule['wednesday_start'] = self.wednesday_start.strftime(
'%-I:%M %p')
else:
schedule['wednesday_start'] = ''
if self.wednesday_end:
schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'
)
else:
schedule['wednesday_end'] = ''
if self.thursday_start:
schedule['thursday_start'] = self.thursday_start.strftime(
'%-I:%M %p')
else:
schedule['thursday_start'] = ''
if self.thursday_end:
schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')
else:
schedule['thursday_end'] = ''
if self.friday_start:
schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')
else:
schedule['friday_start'] = ''
if self.friday_end:
schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')
else:
schedule['friday_end'] = ''
if self.saturday_start:
schedule['saturday_start'] = self.saturday_start.strftime(
'%-I:%M %p')
else:
schedule['saturday_start'] = ''
if self.saturday_end:
schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')
else:
schedule['saturday_end'] = ''
if self.sunday_start:
schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')
else:
schedule['sunday_start'] = ''
if self.sunday_end:
schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')
else:
schedule['sunday_end'] = ''
return schedule
class Restaurant(models.Model):
created_at = models.DateTimeField(auto_now=True)
company_name = models.CharField(verbose_name='company name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='restaurant_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField()
uber_eats = models.BooleanField(default=False)
delivery_capacity = models.BooleanField(default=False)
packaging = models.BooleanField(default=False)
health_certificate = models.CharField(verbose_name='health certificate',
max_length=255, unique=False)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='coordinates', max_length=
255, unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='restaurants', on_delete=models.DO_NOTHING, null=True)
class Program(models.Model):
created_at = models.DateTimeField(auto_now=True)
program_name = models.CharField(verbose_name='program name', max_length
=255, unique=False)
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models
.DO_NOTHING, related_name='program_object', null=True)
phone_number = models.CharField(verbose_name='phone number', max_length
=255, unique=False)
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.
DO_NOTHING, null=True)
meals = models.IntegerField(default=0, null=True)
address = models.CharField(verbose_name='address', max_length=255,
unique=False)
coordinates = models.CharField(verbose_name='address', max_length=255,
unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255,
unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255,
unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview',
related_name='programs', on_delete=models.DO_NOTHING, null=True)
class Courier(models.Model):
created_at = models.DateTimeField(auto_now=True)
class Profile(models.Model):
user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars', blank=True)
def __str__(self):
return self.user.username
<|reserved_special_token_1|>
# from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
# from applications.models import ApplicationReview
# from profiles.models import Restaurant, Program, Courier
# Enum for Admin
BASIC_ADMIN = 'ADMIN'
SUPER_ADMIN = 'SUPER'
MANAGER = 'MNGR'
DEVELOPER = 'DEV'
STAFF = 'STAFF'
ADMIN_ROLE_OPTIONS = [
(BASIC_ADMIN, 'basic admin'),
(SUPER_ADMIN, 'super admin'),
(MANAGER, 'manager'),
(DEVELOPER, 'developer'),
(STAFF, 'stuff'),
]
PROGRAM = "PR"
RESTAURANT = "RE"
USER_TYPE_OPTIONS = [
(PROGRAM, 'Program'),
(RESTAURANT, 'Restaurant'),
]
PHONE = "PH"
EMAIL = "EM"
PREFERRED_CONTACT = [
(PHONE, 'Phone'),
(EMAIL, 'Email'),
]
ADMIN = "ADM"
BASIC_USER = "BSC"
USER_TYPES = [
(ADMIN, 'Admin'),
(BASIC_USER, 'Basic User'),
]
class UserClassManager(BaseUserManager):
"""Manager for User class"""
# method for creatig admins, but not super admins
def create_staffuser(self, last_name, first_name, email, password, role, phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name=last_name, first_name=first_name,
email=email, password=password)
new_account.staff = True
admin_object = AdminUser.objects.create(role=role)
new_account.admin_object = admin_object
new_account.user_type = ADMIN
admin_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
def create_basic_user(self, type, last_name, first_name, email, password, phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name=last_name, first_name=first_name,
email=email, password=password)
user_object = BasicUser.objects.create(type=type)
new_account.user_object = user_object
new_account.user_type = BASIC_USER
user_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
# method for creating restaurants, schools, etc.
def create_user(self, last_name, first_name, email, password, phone_number=''):
new_account = self.model(email=self.normalize_email(email),)
new_account.set_password(password)
new_account.last_name = last_name
new_account.first_name = first_name
new_account.phone_number = phone_number
new_account.save(using=self._db)
return new_account
# method for creating superadmins
def create_superuser(self, last_name, first_name, email, password, phone_number=''):
new_account = self.create_user(phone_number=phone_number, last_name=last_name, first_name=first_name,
email=email, password=password)
new_account.staff = True
new_account.admin = True
admin_object = AdminUser.objects.create(role=SUPER_ADMIN)
new_account.admin_object = admin_object
new_account.user_type = ADMIN
admin_object.save(using=self._db)
new_account.save(using=self._db)
return new_account
# add any required fields here other than email and password
REQUIRED_FIELDS = []
USERNAME_FIELD = 'email'
class UserClass(AbstractBaseUser):
"""Class for general user - can be basic user or admin"""
phone_number = models.CharField(verbose_name='phone number', max_length=255, unique=False, default='')
active = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
email = models.EmailField(verbose_name='email', max_length=255, unique=True, )
last_name = models.CharField(verbose_name='last name', max_length=255, unique=False, )
first_name = models.CharField(verbose_name='first name', max_length=255, unique=False, )
objects = UserClassManager()
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
image = models.CharField(verbose_name='user image', max_length=255, unique=False, default='defaultIcon.png')
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ['first_name', 'last_name']
user_type = models.CharField(
max_length=20,
choices=USER_TYPES,
default=BASIC_USER,
)
user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.DO_NOTHING, null=True, related_name='basic_user_parent')
admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models.DO_NOTHING, null=True, related_name='admin_user_parent')
def has_module_perms(self, app_label):
return True
@property
def is_admin(self):
return self.admin
def get_full_name(self):
return self.first_name + ' ' + self.last_name
def get_short_name(self):
return self.first_name
@property
def is_staff(self):
return self.staff
def __str__(self):
return self.email
class AdminUser(models.Model):
"""Model for admin user data"""
role = models.CharField(
max_length=20,
choices=ADMIN_ROLE_OPTIONS,
default=STAFF,
)
class BasicUser(models.Model):
"""Model for basic user data"""
type = models.CharField(
max_length=20,
choices=USER_TYPE_OPTIONS,
default=RESTAURANT,
)
preferred_contact = models.CharField(
max_length=20,
choices=PREFERRED_CONTACT,
default=EMAIL,
)
position = models.CharField(verbose_name='position/title', max_length=255, unique=False, null=True)
restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.CASCADE, null=True)
program = models.ForeignKey('profiles.Program', on_delete=models.CASCADE, null=True)
courier = models.ForeignKey('profiles.Courier', on_delete=models.CASCADE, null=True)
class Schedule(models.Model):
monday_start = models.TimeField(auto_now=False, null=True, blank=True)
monday_end = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)
tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)
wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)
thursday_start = models.TimeField(auto_now=False, null=True, blank=True)
thursday_end = models.TimeField(auto_now=False, null=True, blank=True)
friday_start = models.TimeField(auto_now=False, null=True, blank=True)
friday_end = models.TimeField(auto_now=False, null=True, blank=True)
saturday_start = models.TimeField(auto_now=False, null=True, blank=True)
saturday_end = models.TimeField(auto_now=False, null=True, blank=True)
sunday_start = models.TimeField(auto_now=False, null=True, blank=True)
sunday_end = models.TimeField(auto_now=False, null=True, blank=True)
def getSchedule(self):
schedule = {}
if self.monday_start:
schedule['monday_start'] = self.monday_start.strftime("%-I:%M %p")
else:
schedule['monday_start'] = ''
if self.monday_end:
schedule['monday_end'] = self.monday_end.strftime("%-I:%M %p")
else:
schedule['monday_end'] = ''
if self.tuesday_start:
schedule['tuesday_start'] = self.tuesday_start.strftime("%-I:%M %p")
else:
schedule['tuesday_start'] = ''
if self.tuesday_end:
schedule['tuesday_end'] = self.tuesday_end.strftime("%-I:%M %p")
else:
schedule['tuesday_end'] = ''
if self.wednesday_start:
schedule['wednesday_start'] = self.wednesday_start.strftime("%-I:%M %p")
else:
schedule['wednesday_start'] = ''
if self.wednesday_end:
schedule['wednesday_end'] = self.wednesday_end.strftime("%-I:%M %p")
else:
schedule['wednesday_end'] = ''
if self.thursday_start:
schedule['thursday_start'] = self.thursday_start.strftime("%-I:%M %p")
else:
schedule['thursday_start'] = ''
if self.thursday_end:
schedule['thursday_end'] = self.thursday_end.strftime("%-I:%M %p")
else:
schedule['thursday_end'] = ''
if self.friday_start:
schedule['friday_start'] = self.friday_start.strftime("%-I:%M %p")
else:
schedule['friday_start'] = ''
if self.friday_end:
schedule['friday_end'] = self.friday_end.strftime("%-I:%M %p")
else:
schedule['friday_end'] = ''
if self.saturday_start:
schedule['saturday_start'] = self.saturday_start.strftime("%-I:%M %p")
else:
schedule['saturday_start'] = ''
if self.saturday_end:
schedule['saturday_end'] = self.saturday_end.strftime("%-I:%M %p")
else:
schedule['saturday_end'] = ''
if self.sunday_start:
schedule['sunday_start'] = self.sunday_start.strftime("%-I:%M %p")
else:
schedule['sunday_start'] = ''
if self.sunday_end:
schedule['sunday_end'] = self.sunday_end.strftime("%-I:%M %p")
else:
schedule['sunday_end'] = ''
return schedule
class Restaurant(models.Model):
created_at = models.DateTimeField(auto_now=True)
company_name = models.CharField(verbose_name='company name', max_length=255, unique=False, )
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models.DO_NOTHING, related_name="restaurant_object", null=True)
phone_number = models.CharField(verbose_name='phone number', max_length=255, unique=False, )
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.DO_NOTHING, null=True)
meals = models.IntegerField()
uber_eats = models.BooleanField(default=False)
delivery_capacity = models.BooleanField(default=False)
packaging = models.BooleanField(default=False)
health_certificate = models.CharField(verbose_name='health certificate', max_length=255, unique=False, )
address = models.CharField(verbose_name='address', max_length=255, unique=False, )
coordinates = models.CharField(verbose_name='coordinates', max_length=255, unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255, unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255, unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview', related_name='restaurants',
on_delete=models.DO_NOTHING, null=True)
class Program(models.Model):
created_at = models.DateTimeField(auto_now=True)
program_name = models.CharField(verbose_name='program name', max_length=255, unique=False, )
main_contact = models.ForeignKey('profiles.UserClass', on_delete=models.DO_NOTHING, related_name="program_object", null=True)
phone_number = models.CharField(verbose_name='phone number', max_length=255, unique=False, )
schedule = models.ForeignKey('profiles.Schedule', on_delete=models.DO_NOTHING, null=True)
meals = models.IntegerField(default=0, null=True)
address = models.CharField(verbose_name='address', max_length=255, unique=False, )
coordinates = models.CharField(verbose_name='address', max_length=255, unique=False, null=True)
latitude = models.CharField(verbose_name='latitude', max_length=255, unique=False, null=True)
longitude = models.CharField(verbose_name='longitude', max_length=255, unique=False, null=True)
review = models.ForeignKey('applications.ApplicationReview', related_name="programs",
on_delete=models.DO_NOTHING, null=True)
class Courier(models.Model):
created_at = models.DateTimeField(auto_now=True)
class Profile(models.Model):
user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars', blank=True)
def __str__(self):
return self.user.username
|
flexible
|
{
"blob_id": "8a1f024be00200218782c919b21161bf48fc817e",
"index": 7805,
"step-1": "<mask token>\n\n\nclass UserClass(AbstractBaseUser):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def get_full_name(self):\n return self.first_name + ' ' + self.last_name\n <mask token>\n <mask token>\n <mask token>\n\n\nclass AdminUser(models.Model):\n \"\"\"Model for admin user data\"\"\"\n role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,\n default=STAFF)\n\n\nclass BasicUser(models.Model):\n \"\"\"Model for basic user data\"\"\"\n type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,\n default=RESTAURANT)\n preferred_contact = models.CharField(max_length=20, choices=\n PREFERRED_CONTACT, default=EMAIL)\n position = models.CharField(verbose_name='position/title', max_length=\n 255, unique=False, null=True)\n restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.\n CASCADE, null=True)\n program = models.ForeignKey('profiles.Program', on_delete=models.\n CASCADE, null=True)\n courier = models.ForeignKey('profiles.Courier', on_delete=models.\n CASCADE, null=True)\n\n\nclass Schedule(models.Model):\n monday_start = models.TimeField(auto_now=False, null=True, blank=True)\n monday_end = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_start = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_end = models.TimeField(auto_now=False, null=True, blank=True)\n friday_start = models.TimeField(auto_now=False, null=True, blank=True)\n friday_end = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_start = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_end = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_start = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_end = models.TimeField(auto_now=False, null=True, blank=True)\n\n def getSchedule(self):\n schedule = {}\n if self.monday_start:\n schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')\n else:\n schedule['monday_start'] = ''\n if self.monday_end:\n schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')\n else:\n schedule['monday_end'] = ''\n if self.tuesday_start:\n schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'\n )\n else:\n schedule['tuesday_start'] = ''\n if self.tuesday_end:\n schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')\n else:\n schedule['tuesday_end'] = ''\n if self.wednesday_start:\n schedule['wednesday_start'] = self.wednesday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['wednesday_start'] = ''\n if self.wednesday_end:\n schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'\n )\n else:\n schedule['wednesday_end'] = ''\n if self.thursday_start:\n schedule['thursday_start'] = self.thursday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['thursday_start'] = ''\n if self.thursday_end:\n schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')\n else:\n schedule['thursday_end'] = ''\n if self.friday_start:\n schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')\n else:\n schedule['friday_start'] = ''\n if self.friday_end:\n schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')\n else:\n schedule['friday_end'] = ''\n if self.saturday_start:\n schedule['saturday_start'] = self.saturday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['saturday_start'] = ''\n if self.saturday_end:\n schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')\n else:\n schedule['saturday_end'] = ''\n if self.sunday_start:\n schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')\n else:\n schedule['sunday_start'] = ''\n if self.sunday_end:\n schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')\n else:\n schedule['sunday_end'] = ''\n return schedule\n\n\nclass Restaurant(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n company_name = models.CharField(verbose_name='company name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='restaurant_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField()\n uber_eats = models.BooleanField(default=False)\n delivery_capacity = models.BooleanField(default=False)\n packaging = models.BooleanField(default=False)\n health_certificate = models.CharField(verbose_name='health certificate',\n max_length=255, unique=False)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='coordinates', max_length=\n 255, unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='restaurants', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Program(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n program_name = models.CharField(verbose_name='program name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='program_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField(default=0, null=True)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='address', max_length=255,\n unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='programs', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Courier(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)\n avatar = models.ImageField(upload_to='avatars', blank=True)\n\n def __str__(self):\n return self.user.username\n",
"step-2": "<mask token>\n\n\nclass UserClassManager(BaseUserManager):\n <mask token>\n <mask token>\n\n def create_basic_user(self, type, last_name, first_name, email,\n password, phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n user_object = BasicUser.objects.create(type=type)\n new_account.user_object = user_object\n new_account.user_type = BASIC_USER\n user_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n\n def create_user(self, last_name, first_name, email, password,\n phone_number=''):\n new_account = self.model(email=self.normalize_email(email))\n new_account.set_password(password)\n new_account.last_name = last_name\n new_account.first_name = first_name\n new_account.phone_number = phone_number\n new_account.save(using=self._db)\n return new_account\n\n def create_superuser(self, last_name, first_name, email, password,\n phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n new_account.staff = True\n new_account.admin = True\n admin_object = AdminUser.objects.create(role=SUPER_ADMIN)\n new_account.admin_object = admin_object\n new_account.user_type = ADMIN\n admin_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n <mask token>\n <mask token>\n\n\nclass UserClass(AbstractBaseUser):\n \"\"\"Class for general user - can be basic user or admin\"\"\"\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False, default='')\n active = models.BooleanField(default=True)\n is_active = models.BooleanField(default=True)\n email = models.EmailField(verbose_name='email', max_length=255, unique=True\n )\n last_name = models.CharField(verbose_name='last name', max_length=255,\n unique=False)\n first_name = models.CharField(verbose_name='first name', max_length=255,\n unique=False)\n objects = UserClassManager()\n staff = models.BooleanField(default=False)\n admin = models.BooleanField(default=False)\n image = models.CharField(verbose_name='user image', max_length=255,\n unique=False, default='defaultIcon.png')\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['first_name', 'last_name']\n user_type = models.CharField(max_length=20, choices=USER_TYPES, default\n =BASIC_USER)\n user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.\n DO_NOTHING, null=True, related_name='basic_user_parent')\n admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models\n .DO_NOTHING, null=True, related_name='admin_user_parent')\n\n def has_module_perms(self, app_label):\n return True\n\n @property\n def is_admin(self):\n return self.admin\n\n def get_full_name(self):\n return self.first_name + ' ' + self.last_name\n\n def get_short_name(self):\n return self.first_name\n\n @property\n def is_staff(self):\n return self.staff\n\n def __str__(self):\n return self.email\n\n\nclass AdminUser(models.Model):\n \"\"\"Model for admin user data\"\"\"\n role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,\n default=STAFF)\n\n\nclass BasicUser(models.Model):\n \"\"\"Model for basic user data\"\"\"\n type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,\n default=RESTAURANT)\n preferred_contact = models.CharField(max_length=20, choices=\n PREFERRED_CONTACT, default=EMAIL)\n position = models.CharField(verbose_name='position/title', max_length=\n 255, unique=False, null=True)\n restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.\n CASCADE, null=True)\n program = models.ForeignKey('profiles.Program', on_delete=models.\n CASCADE, null=True)\n courier = models.ForeignKey('profiles.Courier', on_delete=models.\n CASCADE, null=True)\n\n\nclass Schedule(models.Model):\n monday_start = models.TimeField(auto_now=False, null=True, blank=True)\n monday_end = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_start = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_end = models.TimeField(auto_now=False, null=True, blank=True)\n friday_start = models.TimeField(auto_now=False, null=True, blank=True)\n friday_end = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_start = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_end = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_start = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_end = models.TimeField(auto_now=False, null=True, blank=True)\n\n def getSchedule(self):\n schedule = {}\n if self.monday_start:\n schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')\n else:\n schedule['monday_start'] = ''\n if self.monday_end:\n schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')\n else:\n schedule['monday_end'] = ''\n if self.tuesday_start:\n schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'\n )\n else:\n schedule['tuesday_start'] = ''\n if self.tuesday_end:\n schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')\n else:\n schedule['tuesday_end'] = ''\n if self.wednesday_start:\n schedule['wednesday_start'] = self.wednesday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['wednesday_start'] = ''\n if self.wednesday_end:\n schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'\n )\n else:\n schedule['wednesday_end'] = ''\n if self.thursday_start:\n schedule['thursday_start'] = self.thursday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['thursday_start'] = ''\n if self.thursday_end:\n schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')\n else:\n schedule['thursday_end'] = ''\n if self.friday_start:\n schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')\n else:\n schedule['friday_start'] = ''\n if self.friday_end:\n schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')\n else:\n schedule['friday_end'] = ''\n if self.saturday_start:\n schedule['saturday_start'] = self.saturday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['saturday_start'] = ''\n if self.saturday_end:\n schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')\n else:\n schedule['saturday_end'] = ''\n if self.sunday_start:\n schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')\n else:\n schedule['sunday_start'] = ''\n if self.sunday_end:\n schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')\n else:\n schedule['sunday_end'] = ''\n return schedule\n\n\nclass Restaurant(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n company_name = models.CharField(verbose_name='company name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='restaurant_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField()\n uber_eats = models.BooleanField(default=False)\n delivery_capacity = models.BooleanField(default=False)\n packaging = models.BooleanField(default=False)\n health_certificate = models.CharField(verbose_name='health certificate',\n max_length=255, unique=False)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='coordinates', max_length=\n 255, unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='restaurants', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Program(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n program_name = models.CharField(verbose_name='program name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='program_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField(default=0, null=True)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='address', max_length=255,\n unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='programs', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Courier(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)\n avatar = models.ImageField(upload_to='avatars', blank=True)\n\n def __str__(self):\n return self.user.username\n",
"step-3": "<mask token>\n\n\nclass UserClassManager(BaseUserManager):\n <mask token>\n\n def create_staffuser(self, last_name, first_name, email, password, role,\n phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n new_account.staff = True\n admin_object = AdminUser.objects.create(role=role)\n new_account.admin_object = admin_object\n new_account.user_type = ADMIN\n admin_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n\n def create_basic_user(self, type, last_name, first_name, email,\n password, phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n user_object = BasicUser.objects.create(type=type)\n new_account.user_object = user_object\n new_account.user_type = BASIC_USER\n user_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n\n def create_user(self, last_name, first_name, email, password,\n phone_number=''):\n new_account = self.model(email=self.normalize_email(email))\n new_account.set_password(password)\n new_account.last_name = last_name\n new_account.first_name = first_name\n new_account.phone_number = phone_number\n new_account.save(using=self._db)\n return new_account\n\n def create_superuser(self, last_name, first_name, email, password,\n phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n new_account.staff = True\n new_account.admin = True\n admin_object = AdminUser.objects.create(role=SUPER_ADMIN)\n new_account.admin_object = admin_object\n new_account.user_type = ADMIN\n admin_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n <mask token>\n <mask token>\n\n\nclass UserClass(AbstractBaseUser):\n \"\"\"Class for general user - can be basic user or admin\"\"\"\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False, default='')\n active = models.BooleanField(default=True)\n is_active = models.BooleanField(default=True)\n email = models.EmailField(verbose_name='email', max_length=255, unique=True\n )\n last_name = models.CharField(verbose_name='last name', max_length=255,\n unique=False)\n first_name = models.CharField(verbose_name='first name', max_length=255,\n unique=False)\n objects = UserClassManager()\n staff = models.BooleanField(default=False)\n admin = models.BooleanField(default=False)\n image = models.CharField(verbose_name='user image', max_length=255,\n unique=False, default='defaultIcon.png')\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['first_name', 'last_name']\n user_type = models.CharField(max_length=20, choices=USER_TYPES, default\n =BASIC_USER)\n user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.\n DO_NOTHING, null=True, related_name='basic_user_parent')\n admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models\n .DO_NOTHING, null=True, related_name='admin_user_parent')\n\n def has_module_perms(self, app_label):\n return True\n\n @property\n def is_admin(self):\n return self.admin\n\n def get_full_name(self):\n return self.first_name + ' ' + self.last_name\n\n def get_short_name(self):\n return self.first_name\n\n @property\n def is_staff(self):\n return self.staff\n\n def __str__(self):\n return self.email\n\n\nclass AdminUser(models.Model):\n \"\"\"Model for admin user data\"\"\"\n role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,\n default=STAFF)\n\n\nclass BasicUser(models.Model):\n \"\"\"Model for basic user data\"\"\"\n type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,\n default=RESTAURANT)\n preferred_contact = models.CharField(max_length=20, choices=\n PREFERRED_CONTACT, default=EMAIL)\n position = models.CharField(verbose_name='position/title', max_length=\n 255, unique=False, null=True)\n restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.\n CASCADE, null=True)\n program = models.ForeignKey('profiles.Program', on_delete=models.\n CASCADE, null=True)\n courier = models.ForeignKey('profiles.Courier', on_delete=models.\n CASCADE, null=True)\n\n\nclass Schedule(models.Model):\n monday_start = models.TimeField(auto_now=False, null=True, blank=True)\n monday_end = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_start = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_end = models.TimeField(auto_now=False, null=True, blank=True)\n friday_start = models.TimeField(auto_now=False, null=True, blank=True)\n friday_end = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_start = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_end = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_start = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_end = models.TimeField(auto_now=False, null=True, blank=True)\n\n def getSchedule(self):\n schedule = {}\n if self.monday_start:\n schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')\n else:\n schedule['monday_start'] = ''\n if self.monday_end:\n schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')\n else:\n schedule['monday_end'] = ''\n if self.tuesday_start:\n schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'\n )\n else:\n schedule['tuesday_start'] = ''\n if self.tuesday_end:\n schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')\n else:\n schedule['tuesday_end'] = ''\n if self.wednesday_start:\n schedule['wednesday_start'] = self.wednesday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['wednesday_start'] = ''\n if self.wednesday_end:\n schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'\n )\n else:\n schedule['wednesday_end'] = ''\n if self.thursday_start:\n schedule['thursday_start'] = self.thursday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['thursday_start'] = ''\n if self.thursday_end:\n schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')\n else:\n schedule['thursday_end'] = ''\n if self.friday_start:\n schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')\n else:\n schedule['friday_start'] = ''\n if self.friday_end:\n schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')\n else:\n schedule['friday_end'] = ''\n if self.saturday_start:\n schedule['saturday_start'] = self.saturday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['saturday_start'] = ''\n if self.saturday_end:\n schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')\n else:\n schedule['saturday_end'] = ''\n if self.sunday_start:\n schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')\n else:\n schedule['sunday_start'] = ''\n if self.sunday_end:\n schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')\n else:\n schedule['sunday_end'] = ''\n return schedule\n\n\nclass Restaurant(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n company_name = models.CharField(verbose_name='company name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='restaurant_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField()\n uber_eats = models.BooleanField(default=False)\n delivery_capacity = models.BooleanField(default=False)\n packaging = models.BooleanField(default=False)\n health_certificate = models.CharField(verbose_name='health certificate',\n max_length=255, unique=False)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='coordinates', max_length=\n 255, unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='restaurants', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Program(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n program_name = models.CharField(verbose_name='program name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='program_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField(default=0, null=True)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='address', max_length=255,\n unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='programs', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Courier(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)\n avatar = models.ImageField(upload_to='avatars', blank=True)\n\n def __str__(self):\n return self.user.username\n",
"step-4": "from django.db.models.signals import post_save\nfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager\nfrom django.db import models\nBASIC_ADMIN = 'ADMIN'\nSUPER_ADMIN = 'SUPER'\nMANAGER = 'MNGR'\nDEVELOPER = 'DEV'\nSTAFF = 'STAFF'\nADMIN_ROLE_OPTIONS = [(BASIC_ADMIN, 'basic admin'), (SUPER_ADMIN,\n 'super admin'), (MANAGER, 'manager'), (DEVELOPER, 'developer'), (STAFF,\n 'stuff')]\nPROGRAM = 'PR'\nRESTAURANT = 'RE'\nUSER_TYPE_OPTIONS = [(PROGRAM, 'Program'), (RESTAURANT, 'Restaurant')]\nPHONE = 'PH'\nEMAIL = 'EM'\nPREFERRED_CONTACT = [(PHONE, 'Phone'), (EMAIL, 'Email')]\nADMIN = 'ADM'\nBASIC_USER = 'BSC'\nUSER_TYPES = [(ADMIN, 'Admin'), (BASIC_USER, 'Basic User')]\n\n\nclass UserClassManager(BaseUserManager):\n \"\"\"Manager for User class\"\"\"\n\n def create_staffuser(self, last_name, first_name, email, password, role,\n phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n new_account.staff = True\n admin_object = AdminUser.objects.create(role=role)\n new_account.admin_object = admin_object\n new_account.user_type = ADMIN\n admin_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n\n def create_basic_user(self, type, last_name, first_name, email,\n password, phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n user_object = BasicUser.objects.create(type=type)\n new_account.user_object = user_object\n new_account.user_type = BASIC_USER\n user_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n\n def create_user(self, last_name, first_name, email, password,\n phone_number=''):\n new_account = self.model(email=self.normalize_email(email))\n new_account.set_password(password)\n new_account.last_name = last_name\n new_account.first_name = first_name\n new_account.phone_number = phone_number\n new_account.save(using=self._db)\n return new_account\n\n def create_superuser(self, last_name, first_name, email, password,\n phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name\n =last_name, first_name=first_name, email=email, password=password)\n new_account.staff = True\n new_account.admin = True\n admin_object = AdminUser.objects.create(role=SUPER_ADMIN)\n new_account.admin_object = admin_object\n new_account.user_type = ADMIN\n admin_object.save(using=self._db)\n new_account.save(using=self._db)\n return new_account\n REQUIRED_FIELDS = []\n USERNAME_FIELD = 'email'\n\n\nclass UserClass(AbstractBaseUser):\n \"\"\"Class for general user - can be basic user or admin\"\"\"\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False, default='')\n active = models.BooleanField(default=True)\n is_active = models.BooleanField(default=True)\n email = models.EmailField(verbose_name='email', max_length=255, unique=True\n )\n last_name = models.CharField(verbose_name='last name', max_length=255,\n unique=False)\n first_name = models.CharField(verbose_name='first name', max_length=255,\n unique=False)\n objects = UserClassManager()\n staff = models.BooleanField(default=False)\n admin = models.BooleanField(default=False)\n image = models.CharField(verbose_name='user image', max_length=255,\n unique=False, default='defaultIcon.png')\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['first_name', 'last_name']\n user_type = models.CharField(max_length=20, choices=USER_TYPES, default\n =BASIC_USER)\n user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.\n DO_NOTHING, null=True, related_name='basic_user_parent')\n admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models\n .DO_NOTHING, null=True, related_name='admin_user_parent')\n\n def has_module_perms(self, app_label):\n return True\n\n @property\n def is_admin(self):\n return self.admin\n\n def get_full_name(self):\n return self.first_name + ' ' + self.last_name\n\n def get_short_name(self):\n return self.first_name\n\n @property\n def is_staff(self):\n return self.staff\n\n def __str__(self):\n return self.email\n\n\nclass AdminUser(models.Model):\n \"\"\"Model for admin user data\"\"\"\n role = models.CharField(max_length=20, choices=ADMIN_ROLE_OPTIONS,\n default=STAFF)\n\n\nclass BasicUser(models.Model):\n \"\"\"Model for basic user data\"\"\"\n type = models.CharField(max_length=20, choices=USER_TYPE_OPTIONS,\n default=RESTAURANT)\n preferred_contact = models.CharField(max_length=20, choices=\n PREFERRED_CONTACT, default=EMAIL)\n position = models.CharField(verbose_name='position/title', max_length=\n 255, unique=False, null=True)\n restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.\n CASCADE, null=True)\n program = models.ForeignKey('profiles.Program', on_delete=models.\n CASCADE, null=True)\n courier = models.ForeignKey('profiles.Courier', on_delete=models.\n CASCADE, null=True)\n\n\nclass Schedule(models.Model):\n monday_start = models.TimeField(auto_now=False, null=True, blank=True)\n monday_end = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_start = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_end = models.TimeField(auto_now=False, null=True, blank=True)\n friday_start = models.TimeField(auto_now=False, null=True, blank=True)\n friday_end = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_start = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_end = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_start = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_end = models.TimeField(auto_now=False, null=True, blank=True)\n\n def getSchedule(self):\n schedule = {}\n if self.monday_start:\n schedule['monday_start'] = self.monday_start.strftime('%-I:%M %p')\n else:\n schedule['monday_start'] = ''\n if self.monday_end:\n schedule['monday_end'] = self.monday_end.strftime('%-I:%M %p')\n else:\n schedule['monday_end'] = ''\n if self.tuesday_start:\n schedule['tuesday_start'] = self.tuesday_start.strftime('%-I:%M %p'\n )\n else:\n schedule['tuesday_start'] = ''\n if self.tuesday_end:\n schedule['tuesday_end'] = self.tuesday_end.strftime('%-I:%M %p')\n else:\n schedule['tuesday_end'] = ''\n if self.wednesday_start:\n schedule['wednesday_start'] = self.wednesday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['wednesday_start'] = ''\n if self.wednesday_end:\n schedule['wednesday_end'] = self.wednesday_end.strftime('%-I:%M %p'\n )\n else:\n schedule['wednesday_end'] = ''\n if self.thursday_start:\n schedule['thursday_start'] = self.thursday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['thursday_start'] = ''\n if self.thursday_end:\n schedule['thursday_end'] = self.thursday_end.strftime('%-I:%M %p')\n else:\n schedule['thursday_end'] = ''\n if self.friday_start:\n schedule['friday_start'] = self.friday_start.strftime('%-I:%M %p')\n else:\n schedule['friday_start'] = ''\n if self.friday_end:\n schedule['friday_end'] = self.friday_end.strftime('%-I:%M %p')\n else:\n schedule['friday_end'] = ''\n if self.saturday_start:\n schedule['saturday_start'] = self.saturday_start.strftime(\n '%-I:%M %p')\n else:\n schedule['saturday_start'] = ''\n if self.saturday_end:\n schedule['saturday_end'] = self.saturday_end.strftime('%-I:%M %p')\n else:\n schedule['saturday_end'] = ''\n if self.sunday_start:\n schedule['sunday_start'] = self.sunday_start.strftime('%-I:%M %p')\n else:\n schedule['sunday_start'] = ''\n if self.sunday_end:\n schedule['sunday_end'] = self.sunday_end.strftime('%-I:%M %p')\n else:\n schedule['sunday_end'] = ''\n return schedule\n\n\nclass Restaurant(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n company_name = models.CharField(verbose_name='company name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='restaurant_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField()\n uber_eats = models.BooleanField(default=False)\n delivery_capacity = models.BooleanField(default=False)\n packaging = models.BooleanField(default=False)\n health_certificate = models.CharField(verbose_name='health certificate',\n max_length=255, unique=False)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='coordinates', max_length=\n 255, unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='restaurants', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Program(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n program_name = models.CharField(verbose_name='program name', max_length\n =255, unique=False)\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models\n .DO_NOTHING, related_name='program_object', null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length\n =255, unique=False)\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.\n DO_NOTHING, null=True)\n meals = models.IntegerField(default=0, null=True)\n address = models.CharField(verbose_name='address', max_length=255,\n unique=False)\n coordinates = models.CharField(verbose_name='address', max_length=255,\n unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255,\n unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255,\n unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview',\n related_name='programs', on_delete=models.DO_NOTHING, null=True)\n\n\nclass Courier(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)\n avatar = models.ImageField(upload_to='avatars', blank=True)\n\n def __str__(self):\n return self.user.username\n",
"step-5": "# from django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager\nfrom django.db import models\n\n# from applications.models import ApplicationReview\n# from profiles.models import Restaurant, Program, Courier\n\n\n\n\n\n# Enum for Admin\nBASIC_ADMIN = 'ADMIN'\nSUPER_ADMIN = 'SUPER'\nMANAGER = 'MNGR'\nDEVELOPER = 'DEV'\nSTAFF = 'STAFF'\n\n\nADMIN_ROLE_OPTIONS = [\n (BASIC_ADMIN, 'basic admin'),\n (SUPER_ADMIN, 'super admin'),\n (MANAGER, 'manager'),\n (DEVELOPER, 'developer'),\n (STAFF, 'stuff'),\n]\n\n\nPROGRAM = \"PR\"\nRESTAURANT = \"RE\"\n\nUSER_TYPE_OPTIONS = [\n (PROGRAM, 'Program'),\n (RESTAURANT, 'Restaurant'),\n]\n\n\nPHONE = \"PH\"\nEMAIL = \"EM\"\n\n\n\nPREFERRED_CONTACT = [\n (PHONE, 'Phone'),\n (EMAIL, 'Email'),\n]\n\n\nADMIN = \"ADM\"\nBASIC_USER = \"BSC\"\n\nUSER_TYPES = [\n (ADMIN, 'Admin'),\n (BASIC_USER, 'Basic User'),\n]\n\n\nclass UserClassManager(BaseUserManager):\n \"\"\"Manager for User class\"\"\"\n\n # method for creatig admins, but not super admins\n def create_staffuser(self, last_name, first_name, email, password, role, phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name=last_name, first_name=first_name,\n email=email, password=password)\n new_account.staff = True\n\n admin_object = AdminUser.objects.create(role=role)\n new_account.admin_object = admin_object\n new_account.user_type = ADMIN\n admin_object.save(using=self._db)\n\n new_account.save(using=self._db)\n return new_account\n\n def create_basic_user(self, type, last_name, first_name, email, password, phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name=last_name, first_name=first_name,\n email=email, password=password)\n user_object = BasicUser.objects.create(type=type)\n new_account.user_object = user_object\n new_account.user_type = BASIC_USER\n\n user_object.save(using=self._db)\n new_account.save(using=self._db)\n\n return new_account\n\n # method for creating restaurants, schools, etc.\n def create_user(self, last_name, first_name, email, password, phone_number=''):\n new_account = self.model(email=self.normalize_email(email),)\n new_account.set_password(password)\n\n new_account.last_name = last_name\n new_account.first_name = first_name\n\n new_account.phone_number = phone_number\n\n new_account.save(using=self._db)\n return new_account\n\n # method for creating superadmins\n def create_superuser(self, last_name, first_name, email, password, phone_number=''):\n new_account = self.create_user(phone_number=phone_number, last_name=last_name, first_name=first_name,\n email=email, password=password)\n new_account.staff = True\n new_account.admin = True\n\n admin_object = AdminUser.objects.create(role=SUPER_ADMIN)\n new_account.admin_object = admin_object\n new_account.user_type = ADMIN\n admin_object.save(using=self._db)\n\n new_account.save(using=self._db)\n return new_account\n\n # add any required fields here other than email and password\n REQUIRED_FIELDS = []\n USERNAME_FIELD = 'email'\n\n\nclass UserClass(AbstractBaseUser):\n \"\"\"Class for general user - can be basic user or admin\"\"\"\n phone_number = models.CharField(verbose_name='phone number', max_length=255, unique=False, default='')\n active = models.BooleanField(default=True)\n\n is_active = models.BooleanField(default=True)\n\n email = models.EmailField(verbose_name='email', max_length=255, unique=True, )\n last_name = models.CharField(verbose_name='last name', max_length=255, unique=False, )\n first_name = models.CharField(verbose_name='first name', max_length=255, unique=False, )\n objects = UserClassManager()\n staff = models.BooleanField(default=False)\n admin = models.BooleanField(default=False)\n image = models.CharField(verbose_name='user image', max_length=255, unique=False, default='defaultIcon.png')\n USERNAME_FIELD = \"email\"\n REQUIRED_FIELDS = ['first_name', 'last_name']\n\n user_type = models.CharField(\n max_length=20,\n choices=USER_TYPES,\n default=BASIC_USER,\n )\n\n user_object = models.ForeignKey('profiles.BasicUser', on_delete=models.DO_NOTHING, null=True, related_name='basic_user_parent')\n admin_object = models.ForeignKey('profiles.AdminUser', on_delete=models.DO_NOTHING, null=True, related_name='admin_user_parent')\n\n def has_module_perms(self, app_label):\n return True\n\n @property\n def is_admin(self):\n return self.admin\n\n def get_full_name(self):\n return self.first_name + ' ' + self.last_name\n\n def get_short_name(self):\n return self.first_name\n\n @property\n def is_staff(self):\n return self.staff\n\n def __str__(self):\n return self.email\n\nclass AdminUser(models.Model):\n \"\"\"Model for admin user data\"\"\"\n role = models.CharField(\n max_length=20,\n choices=ADMIN_ROLE_OPTIONS,\n default=STAFF,\n )\n\n\nclass BasicUser(models.Model):\n \"\"\"Model for basic user data\"\"\"\n type = models.CharField(\n max_length=20,\n choices=USER_TYPE_OPTIONS,\n default=RESTAURANT,\n )\n\n preferred_contact = models.CharField(\n max_length=20,\n choices=PREFERRED_CONTACT,\n default=EMAIL,\n )\n\n position = models.CharField(verbose_name='position/title', max_length=255, unique=False, null=True)\n\n restaurant = models.ForeignKey('profiles.Restaurant', on_delete=models.CASCADE, null=True)\n program = models.ForeignKey('profiles.Program', on_delete=models.CASCADE, null=True)\n courier = models.ForeignKey('profiles.Courier', on_delete=models.CASCADE, null=True)\n\n\nclass Schedule(models.Model):\n monday_start = models.TimeField(auto_now=False, null=True, blank=True)\n monday_end = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n tuesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_start = models.TimeField(auto_now=False, null=True, blank=True)\n wednesday_end = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_start = models.TimeField(auto_now=False, null=True, blank=True)\n thursday_end = models.TimeField(auto_now=False, null=True, blank=True)\n friday_start = models.TimeField(auto_now=False, null=True, blank=True)\n friday_end = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_start = models.TimeField(auto_now=False, null=True, blank=True)\n saturday_end = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_start = models.TimeField(auto_now=False, null=True, blank=True)\n sunday_end = models.TimeField(auto_now=False, null=True, blank=True)\n\n def getSchedule(self):\n schedule = {}\n if self.monday_start:\n schedule['monday_start'] = self.monday_start.strftime(\"%-I:%M %p\")\n else:\n schedule['monday_start'] = ''\n if self.monday_end:\n schedule['monday_end'] = self.monday_end.strftime(\"%-I:%M %p\")\n else:\n schedule['monday_end'] = ''\n if self.tuesday_start:\n schedule['tuesday_start'] = self.tuesday_start.strftime(\"%-I:%M %p\")\n else:\n schedule['tuesday_start'] = ''\n if self.tuesday_end:\n schedule['tuesday_end'] = self.tuesday_end.strftime(\"%-I:%M %p\")\n else:\n schedule['tuesday_end'] = ''\n if self.wednesday_start:\n schedule['wednesday_start'] = self.wednesday_start.strftime(\"%-I:%M %p\")\n else:\n schedule['wednesday_start'] = ''\n if self.wednesday_end:\n schedule['wednesday_end'] = self.wednesday_end.strftime(\"%-I:%M %p\")\n else:\n schedule['wednesday_end'] = ''\n if self.thursday_start:\n schedule['thursday_start'] = self.thursday_start.strftime(\"%-I:%M %p\")\n else:\n schedule['thursday_start'] = ''\n if self.thursday_end:\n schedule['thursday_end'] = self.thursday_end.strftime(\"%-I:%M %p\")\n else:\n schedule['thursday_end'] = ''\n if self.friday_start:\n schedule['friday_start'] = self.friday_start.strftime(\"%-I:%M %p\")\n else:\n schedule['friday_start'] = ''\n if self.friday_end:\n schedule['friday_end'] = self.friday_end.strftime(\"%-I:%M %p\")\n else:\n schedule['friday_end'] = ''\n if self.saturday_start:\n schedule['saturday_start'] = self.saturday_start.strftime(\"%-I:%M %p\")\n else:\n schedule['saturday_start'] = ''\n if self.saturday_end:\n schedule['saturday_end'] = self.saturday_end.strftime(\"%-I:%M %p\")\n else:\n schedule['saturday_end'] = ''\n if self.sunday_start:\n schedule['sunday_start'] = self.sunday_start.strftime(\"%-I:%M %p\")\n else:\n schedule['sunday_start'] = ''\n if self.sunday_end:\n schedule['sunday_end'] = self.sunday_end.strftime(\"%-I:%M %p\")\n else:\n schedule['sunday_end'] = ''\n\n return schedule\n\n\nclass Restaurant(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n company_name = models.CharField(verbose_name='company name', max_length=255, unique=False, )\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models.DO_NOTHING, related_name=\"restaurant_object\", null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length=255, unique=False, )\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.DO_NOTHING, null=True)\n meals = models.IntegerField()\n uber_eats = models.BooleanField(default=False)\n delivery_capacity = models.BooleanField(default=False)\n packaging = models.BooleanField(default=False)\n health_certificate = models.CharField(verbose_name='health certificate', max_length=255, unique=False, )\n address = models.CharField(verbose_name='address', max_length=255, unique=False, )\n coordinates = models.CharField(verbose_name='coordinates', max_length=255, unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255, unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255, unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview', related_name='restaurants',\n on_delete=models.DO_NOTHING, null=True)\n\n\n\n\nclass Program(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n program_name = models.CharField(verbose_name='program name', max_length=255, unique=False, )\n main_contact = models.ForeignKey('profiles.UserClass', on_delete=models.DO_NOTHING, related_name=\"program_object\", null=True)\n phone_number = models.CharField(verbose_name='phone number', max_length=255, unique=False, )\n schedule = models.ForeignKey('profiles.Schedule', on_delete=models.DO_NOTHING, null=True)\n meals = models.IntegerField(default=0, null=True)\n address = models.CharField(verbose_name='address', max_length=255, unique=False, )\n coordinates = models.CharField(verbose_name='address', max_length=255, unique=False, null=True)\n latitude = models.CharField(verbose_name='latitude', max_length=255, unique=False, null=True)\n longitude = models.CharField(verbose_name='longitude', max_length=255, unique=False, null=True)\n review = models.ForeignKey('applications.ApplicationReview', related_name=\"programs\",\n on_delete=models.DO_NOTHING, null=True)\n\n\n\n\n\nclass Courier(models.Model):\n created_at = models.DateTimeField(auto_now=True)\n\n\n\n\n\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(BasicUser, on_delete=models.CASCADE)\n avatar = models.ImageField(upload_to='avatars', blank=True)\n\n def __str__(self):\n return self.user.username\n",
"step-ids": [
20,
31,
32,
36,
37
]
}
|
[
20,
31,
32,
36,
37
] |
<|reserved_special_token_0|>
def final_option(dict_of_options, back):
"""
adds the final option to the dictionary based on a boolean
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean
:return: dict_of_options but with a new, final key added in
"""
if back:
dict_of_options['back'] = return_false
else:
dict_of_options['end_process'] = end_process
return dict_of_options
def basic_menu(dict_of_options, back=False):
"""
basic text based user interface, allows user to select a function to run from a dictionary of options, by using a
simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to
ending process since that's how the main menu does it and unsure of where else function will be called
:return: run the chosen function
"""
choose = True
dict_of_options = final_option(dict_of_options, back)
list_of_options = list(dict_of_options.keys())
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
pick = input('\nType the numeric code you wish to run\n\n')
if pick in [str(i) for i in range(len(dict_of_options))]:
choose = dict_of_options[list_of_options[int(pick)]]()
else:
print('{} is not currently an option!\n'.format(pick))
def basic_menu_non_functional(list_of_options):
"""
basic text based user interface, allows user to select multiple options from a list of available choices.
:param list_of_options: list of available choices
:return: a list of chosen strings
"""
choose = True
list_of_options.append('back')
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
picks = input('\nType the numeric codes you wish to run\n\n').split(','
)
choice = []
if str(len(list_of_options)) in picks:
return True
for pick in picks:
if pick in [str(i) for i in range(len(list_of_options))]:
choice.append(list_of_options[int(pick)])
else:
print('{} is not currently an option!\n'.format(pick))
if len(choice) > 0:
return choice
<|reserved_special_token_0|>
def project_visibility_menu():
"""
creates menu to allow user to set which project groups are visible in the run_scrapers menu
:return: creates a txt file containing the list of desired project names, one per row.
"""
projects = [i.split('.')[0] for i in os.listdir(
'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]
print('Available projects are:\n')
for project in enumerate(projects):
print('\t{} - {}'.format(project[0], project[1]))
print('\t{} - back'.format(len(projects)))
choices = input(
'\nType the options you wish to select.\nFor multiple, comma separate\n\n'
).split(',')
if str(len(projects)) in choices:
return True
else:
choice_list = []
for choice in choices:
if choice.isdigit() and int(choice) in range(len(projects)):
choice_list.append(projects[int(choice)])
print(
'You have selected to display the following spider groupings:\n\t{}\n'
.format(choice_list))
save_list_to_txt(choice_list,
'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'
)
return True
<|reserved_special_token_0|>
def replace_default_urls():
"""
function for replacing default urls config with recent scrapes
:return: defaults.json is updated
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict[key] = value
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
, 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def create_new_config():
"""
function which creates a whole new config file to store recent scraped urls in
:return: new config is created
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
urls_dict = json.load(recent_urls_json)
config_name = input('Type a name for the new config file:\n').replace(' ',
'_').replace(':', '')
config_desc = input('Type a brief description for the new config file:\n')
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'
.format(config_name), 'w') as fp:
json.dump(urls_dict, fp, sort_keys=True, indent=4)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'
, 'a') as input_descs:
input_descs.write('\n{}: {}'.format(config_name, config_desc))
print('\nSuccessfully saved recently scraped urls to new config: {}.json'
.format(config_name))
def clear_recent_urls():
"""
function which bleaches the recent urls config in order to start fresh next time
:return: recent_urls will become an empty dictionary.
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key in recent_dict.keys():
recent_dict[key] = []
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
, 'w') as fp:
json.dump(recent_dict, fp, sort_keys=True, indent=4)
def select_date_interval_menu():
"""
function allows user to inout start and end date to define an interval of dates
:return: list of dates
"""
while True:
start_date = input(
'\nInput desired start date with format dd-mm-yyyy:\n')
try:
start_date = datetime.strptime(start_date, '%d-%m-%Y')
break
except ValueError:
print('invalid start date selected')
while True:
end_date = input(
"""
Input desired start date with format dd-mm-yyyy,
or hit enter to select todays date
"""
)
if end_date == '':
end_date = date.today()
break
else:
try:
end_date = datetime.strptime(end_date, '%d-%m-%Y')
break
except ValueError:
print('invalid end date selected')
list_of_dates = pd.date_range(start_date, end_date, freq='d')
list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]
return list_of_dates
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def final_option(dict_of_options, back):
"""
adds the final option to the dictionary based on a boolean
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean
:return: dict_of_options but with a new, final key added in
"""
if back:
dict_of_options['back'] = return_false
else:
dict_of_options['end_process'] = end_process
return dict_of_options
def basic_menu(dict_of_options, back=False):
"""
basic text based user interface, allows user to select a function to run from a dictionary of options, by using a
simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to
ending process since that's how the main menu does it and unsure of where else function will be called
:return: run the chosen function
"""
choose = True
dict_of_options = final_option(dict_of_options, back)
list_of_options = list(dict_of_options.keys())
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
pick = input('\nType the numeric code you wish to run\n\n')
if pick in [str(i) for i in range(len(dict_of_options))]:
choose = dict_of_options[list_of_options[int(pick)]]()
else:
print('{} is not currently an option!\n'.format(pick))
def basic_menu_non_functional(list_of_options):
"""
basic text based user interface, allows user to select multiple options from a list of available choices.
:param list_of_options: list of available choices
:return: a list of chosen strings
"""
choose = True
list_of_options.append('back')
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
picks = input('\nType the numeric codes you wish to run\n\n').split(','
)
choice = []
if str(len(list_of_options)) in picks:
return True
for pick in picks:
if pick in [str(i) for i in range(len(list_of_options))]:
choice.append(list_of_options[int(pick)])
else:
print('{} is not currently an option!\n'.format(pick))
if len(choice) > 0:
return choice
<|reserved_special_token_0|>
def project_visibility_menu():
"""
creates menu to allow user to set which project groups are visible in the run_scrapers menu
:return: creates a txt file containing the list of desired project names, one per row.
"""
projects = [i.split('.')[0] for i in os.listdir(
'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]
print('Available projects are:\n')
for project in enumerate(projects):
print('\t{} - {}'.format(project[0], project[1]))
print('\t{} - back'.format(len(projects)))
choices = input(
'\nType the options you wish to select.\nFor multiple, comma separate\n\n'
).split(',')
if str(len(projects)) in choices:
return True
else:
choice_list = []
for choice in choices:
if choice.isdigit() and int(choice) in range(len(projects)):
choice_list.append(projects[int(choice)])
print(
'You have selected to display the following spider groupings:\n\t{}\n'
.format(choice_list))
save_list_to_txt(choice_list,
'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'
)
return True
def set_config():
"""
menu to set the url configs.
:return: will set the start_urls of the spiders.
"""
available_configs = open(
'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'
, 'r')
options = available_configs.readlines()
options_dict = {}
print('available configs include:\n')
for option in enumerate(options):
options_dict[option[0]] = option[1].split(':')[0]
print('\t{} - {}'.format(option[0], option[1].replace('\n', '')))
print('\t{} - back'.format(len(options)))
chosen = input('\ncomma separate for multiple\n').split(',')
if str(len(options)) in chosen or chosen == ['']:
return True
configs = []
for choice in chosen:
if int(choice) in options_dict:
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'
.format(options_dict[int(choice)])) as f:
configs.append(json.load(f))
final_config = defaultdict(list)
for config in configs:
for key, value in config.items():
if key in final_config:
final_config[key] += value
else:
final_config[key] = value
for key, value in final_config.items():
if any(isinstance(val, list) for val in value):
final_config[key] = flatten_list_of_lists(value, make_set=True)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
for key, value in default_dict.items():
if key not in final_config.keys():
final_config[key] = value
with open(
'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'
) as fp:
json.dump(final_config, fp, sort_keys=True, indent=4)
return True
def append_recent_urls():
"""
function for appending recent scraped urls to default urls json
:return: default.json is updated
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict.setdefault(key, []).extend(value)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
, 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def replace_default_urls():
"""
function for replacing default urls config with recent scrapes
:return: defaults.json is updated
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict[key] = value
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
, 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def create_new_config():
"""
function which creates a whole new config file to store recent scraped urls in
:return: new config is created
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
urls_dict = json.load(recent_urls_json)
config_name = input('Type a name for the new config file:\n').replace(' ',
'_').replace(':', '')
config_desc = input('Type a brief description for the new config file:\n')
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'
.format(config_name), 'w') as fp:
json.dump(urls_dict, fp, sort_keys=True, indent=4)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'
, 'a') as input_descs:
input_descs.write('\n{}: {}'.format(config_name, config_desc))
print('\nSuccessfully saved recently scraped urls to new config: {}.json'
.format(config_name))
def clear_recent_urls():
"""
function which bleaches the recent urls config in order to start fresh next time
:return: recent_urls will become an empty dictionary.
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key in recent_dict.keys():
recent_dict[key] = []
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
, 'w') as fp:
json.dump(recent_dict, fp, sort_keys=True, indent=4)
def select_date_interval_menu():
"""
function allows user to inout start and end date to define an interval of dates
:return: list of dates
"""
while True:
start_date = input(
'\nInput desired start date with format dd-mm-yyyy:\n')
try:
start_date = datetime.strptime(start_date, '%d-%m-%Y')
break
except ValueError:
print('invalid start date selected')
while True:
end_date = input(
"""
Input desired start date with format dd-mm-yyyy,
or hit enter to select todays date
"""
)
if end_date == '':
end_date = date.today()
break
else:
try:
end_date = datetime.strptime(end_date, '%d-%m-%Y')
break
except ValueError:
print('invalid end date selected')
list_of_dates = pd.date_range(start_date, end_date, freq='d')
list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]
return list_of_dates
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def final_option(dict_of_options, back):
"""
adds the final option to the dictionary based on a boolean
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean
:return: dict_of_options but with a new, final key added in
"""
if back:
dict_of_options['back'] = return_false
else:
dict_of_options['end_process'] = end_process
return dict_of_options
def basic_menu(dict_of_options, back=False):
"""
basic text based user interface, allows user to select a function to run from a dictionary of options, by using a
simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to
ending process since that's how the main menu does it and unsure of where else function will be called
:return: run the chosen function
"""
choose = True
dict_of_options = final_option(dict_of_options, back)
list_of_options = list(dict_of_options.keys())
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
pick = input('\nType the numeric code you wish to run\n\n')
if pick in [str(i) for i in range(len(dict_of_options))]:
choose = dict_of_options[list_of_options[int(pick)]]()
else:
print('{} is not currently an option!\n'.format(pick))
def basic_menu_non_functional(list_of_options):
"""
basic text based user interface, allows user to select multiple options from a list of available choices.
:param list_of_options: list of available choices
:return: a list of chosen strings
"""
choose = True
list_of_options.append('back')
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
picks = input('\nType the numeric codes you wish to run\n\n').split(','
)
choice = []
if str(len(list_of_options)) in picks:
return True
for pick in picks:
if pick in [str(i) for i in range(len(list_of_options))]:
choice.append(list_of_options[int(pick)])
else:
print('{} is not currently an option!\n'.format(pick))
if len(choice) > 0:
return choice
def select_spiders(spiders_dict):
"""
select from spiders available. allows user to select all spiders, select all spiders within a
project group, select some comma separated list of individual/groups of spiders, or by prefixing a
given selection with "-", the user can remove a spider from his or her selection.
:param spiders_dict: dictionary who's keys are broad options and values are lists of spiders
:return: list containing the spiders the user has selected to run
"""
print('Available spiders include:\n')
enumerated_keys = list(enumerate(spiders_dict.keys()))
for key_group in enumerated_keys:
print('{} - {}'.format(key_group[0], key_group[1]))
for spider in zip(alphabet_list_length(len(key_group[1])),
spiders_dict[key_group[1]]):
print('\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name)
)
print('{} - run all'.format(len(spiders_dict.keys())))
print('{} - back'.format(len(spiders_dict.keys()) + 1))
choices = input(
"""
for multiple, comma separate. To remove, use "-" prefix
i.e.: 0,-0a to run all of group 0 except the first
"""
).replace(' ', '').split(',')
if str(len(spiders_dict.keys()) + 1) in choices:
return False
if str(len(spiders_dict.keys())) in choices:
chosen_spiders = list(spiders_dict.values())
else:
chosen_spiders = []
for choice in choices:
if choice.isdigit():
if choice in [str(i[0]) for i in enumerated_keys]:
chosen_spiders.append(spiders_dict[enumerated_keys[int(
choice)][1]])
else:
print('{} is not an option!'.format(choice))
elif '-' not in choice:
numeric = re.findall('\\d+', choice)
if len(numeric) == 1:
alpha = choice.split(numeric[0])[1]
alpha = len(alphabet_list_length(0, index=alpha)) - 1
try:
chosen_spiders.append(spiders_dict[enumerated_keys[
int(numeric[0])][1]][alpha])
except IndexError:
print('{} is not an option!'.format(choice))
else:
print('{} is not an option!'.format(choice))
if any(isinstance(el, list) for el in chosen_spiders):
chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)
else:
chosen_spiders = list(set(chosen_spiders))
to_remove = [choice for choice in choices if '-' in choice]
if len(to_remove) > 0:
for removee in to_remove:
if removee.replace('-', '').isdigit():
if removee.replace('-', '') in [str(i[0]) for i in
enumerated_keys]:
for spider in spiders_dict[enumerated_keys[int(removee.
replace('-', ''))][1]]:
chosen_spiders.remove(spider)
else:
print('{} is not an option!'.format(removee))
else:
numeric = re.findall('\\d+', removee)
if len(numeric) == 1:
alpha = removee.split(numeric[0])[1]
alpha = len(alphabet_list_length(0, index=alpha)) - 1
try:
chosen_spiders.remove(spiders_dict[enumerated_keys[
int(numeric[0])][1]][alpha])
except IndexError:
print('{} is not an option!'.format(removee))
else:
print('{} is not an option!'.format(removee))
if len(chosen_spiders) > 0:
return chosen_spiders
else:
print("You haven't selected any spiders!")
return False
def project_visibility_menu():
"""
creates menu to allow user to set which project groups are visible in the run_scrapers menu
:return: creates a txt file containing the list of desired project names, one per row.
"""
projects = [i.split('.')[0] for i in os.listdir(
'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]
print('Available projects are:\n')
for project in enumerate(projects):
print('\t{} - {}'.format(project[0], project[1]))
print('\t{} - back'.format(len(projects)))
choices = input(
'\nType the options you wish to select.\nFor multiple, comma separate\n\n'
).split(',')
if str(len(projects)) in choices:
return True
else:
choice_list = []
for choice in choices:
if choice.isdigit() and int(choice) in range(len(projects)):
choice_list.append(projects[int(choice)])
print(
'You have selected to display the following spider groupings:\n\t{}\n'
.format(choice_list))
save_list_to_txt(choice_list,
'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'
)
return True
def set_config():
"""
menu to set the url configs.
:return: will set the start_urls of the spiders.
"""
available_configs = open(
'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'
, 'r')
options = available_configs.readlines()
options_dict = {}
print('available configs include:\n')
for option in enumerate(options):
options_dict[option[0]] = option[1].split(':')[0]
print('\t{} - {}'.format(option[0], option[1].replace('\n', '')))
print('\t{} - back'.format(len(options)))
chosen = input('\ncomma separate for multiple\n').split(',')
if str(len(options)) in chosen or chosen == ['']:
return True
configs = []
for choice in chosen:
if int(choice) in options_dict:
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'
.format(options_dict[int(choice)])) as f:
configs.append(json.load(f))
final_config = defaultdict(list)
for config in configs:
for key, value in config.items():
if key in final_config:
final_config[key] += value
else:
final_config[key] = value
for key, value in final_config.items():
if any(isinstance(val, list) for val in value):
final_config[key] = flatten_list_of_lists(value, make_set=True)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
for key, value in default_dict.items():
if key not in final_config.keys():
final_config[key] = value
with open(
'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'
) as fp:
json.dump(final_config, fp, sort_keys=True, indent=4)
return True
def append_recent_urls():
"""
function for appending recent scraped urls to default urls json
:return: default.json is updated
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict.setdefault(key, []).extend(value)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
, 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def replace_default_urls():
"""
function for replacing default urls config with recent scrapes
:return: defaults.json is updated
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict[key] = value
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
, 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def create_new_config():
"""
function which creates a whole new config file to store recent scraped urls in
:return: new config is created
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
urls_dict = json.load(recent_urls_json)
config_name = input('Type a name for the new config file:\n').replace(' ',
'_').replace(':', '')
config_desc = input('Type a brief description for the new config file:\n')
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'
.format(config_name), 'w') as fp:
json.dump(urls_dict, fp, sort_keys=True, indent=4)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'
, 'a') as input_descs:
input_descs.write('\n{}: {}'.format(config_name, config_desc))
print('\nSuccessfully saved recently scraped urls to new config: {}.json'
.format(config_name))
def clear_recent_urls():
"""
function which bleaches the recent urls config in order to start fresh next time
:return: recent_urls will become an empty dictionary.
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key in recent_dict.keys():
recent_dict[key] = []
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
, 'w') as fp:
json.dump(recent_dict, fp, sort_keys=True, indent=4)
def select_date_interval_menu():
"""
function allows user to inout start and end date to define an interval of dates
:return: list of dates
"""
while True:
start_date = input(
'\nInput desired start date with format dd-mm-yyyy:\n')
try:
start_date = datetime.strptime(start_date, '%d-%m-%Y')
break
except ValueError:
print('invalid start date selected')
while True:
end_date = input(
"""
Input desired start date with format dd-mm-yyyy,
or hit enter to select todays date
"""
)
if end_date == '':
end_date = date.today()
break
else:
try:
end_date = datetime.strptime(end_date, '%d-%m-%Y')
break
except ValueError:
print('invalid end date selected')
list_of_dates = pd.date_range(start_date, end_date, freq='d')
list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]
return list_of_dates
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import re
import os
import json
from datetime import date, datetime
from collections import defaultdict
import pandas as pd
from HousingPriceScraper.HousingPriceScraper.functions.basic_functions import return_false, end_process, alphabet_list_length, flatten_list_of_lists
from HousingPriceScraper.HousingPriceScraper.functions.data_management import save_list_to_txt
def final_option(dict_of_options, back):
"""
adds the final option to the dictionary based on a boolean
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean
:return: dict_of_options but with a new, final key added in
"""
if back:
dict_of_options['back'] = return_false
else:
dict_of_options['end_process'] = end_process
return dict_of_options
def basic_menu(dict_of_options, back=False):
"""
basic text based user interface, allows user to select a function to run from a dictionary of options, by using a
simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to
ending process since that's how the main menu does it and unsure of where else function will be called
:return: run the chosen function
"""
choose = True
dict_of_options = final_option(dict_of_options, back)
list_of_options = list(dict_of_options.keys())
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
pick = input('\nType the numeric code you wish to run\n\n')
if pick in [str(i) for i in range(len(dict_of_options))]:
choose = dict_of_options[list_of_options[int(pick)]]()
else:
print('{} is not currently an option!\n'.format(pick))
def basic_menu_non_functional(list_of_options):
"""
basic text based user interface, allows user to select multiple options from a list of available choices.
:param list_of_options: list of available choices
:return: a list of chosen strings
"""
choose = True
list_of_options.append('back')
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
picks = input('\nType the numeric codes you wish to run\n\n').split(','
)
choice = []
if str(len(list_of_options)) in picks:
return True
for pick in picks:
if pick in [str(i) for i in range(len(list_of_options))]:
choice.append(list_of_options[int(pick)])
else:
print('{} is not currently an option!\n'.format(pick))
if len(choice) > 0:
return choice
def select_spiders(spiders_dict):
"""
select from spiders available. allows user to select all spiders, select all spiders within a
project group, select some comma separated list of individual/groups of spiders, or by prefixing a
given selection with "-", the user can remove a spider from his or her selection.
:param spiders_dict: dictionary who's keys are broad options and values are lists of spiders
:return: list containing the spiders the user has selected to run
"""
print('Available spiders include:\n')
enumerated_keys = list(enumerate(spiders_dict.keys()))
for key_group in enumerated_keys:
print('{} - {}'.format(key_group[0], key_group[1]))
for spider in zip(alphabet_list_length(len(key_group[1])),
spiders_dict[key_group[1]]):
print('\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name)
)
print('{} - run all'.format(len(spiders_dict.keys())))
print('{} - back'.format(len(spiders_dict.keys()) + 1))
choices = input(
"""
for multiple, comma separate. To remove, use "-" prefix
i.e.: 0,-0a to run all of group 0 except the first
"""
).replace(' ', '').split(',')
if str(len(spiders_dict.keys()) + 1) in choices:
return False
if str(len(spiders_dict.keys())) in choices:
chosen_spiders = list(spiders_dict.values())
else:
chosen_spiders = []
for choice in choices:
if choice.isdigit():
if choice in [str(i[0]) for i in enumerated_keys]:
chosen_spiders.append(spiders_dict[enumerated_keys[int(
choice)][1]])
else:
print('{} is not an option!'.format(choice))
elif '-' not in choice:
numeric = re.findall('\\d+', choice)
if len(numeric) == 1:
alpha = choice.split(numeric[0])[1]
alpha = len(alphabet_list_length(0, index=alpha)) - 1
try:
chosen_spiders.append(spiders_dict[enumerated_keys[
int(numeric[0])][1]][alpha])
except IndexError:
print('{} is not an option!'.format(choice))
else:
print('{} is not an option!'.format(choice))
if any(isinstance(el, list) for el in chosen_spiders):
chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)
else:
chosen_spiders = list(set(chosen_spiders))
to_remove = [choice for choice in choices if '-' in choice]
if len(to_remove) > 0:
for removee in to_remove:
if removee.replace('-', '').isdigit():
if removee.replace('-', '') in [str(i[0]) for i in
enumerated_keys]:
for spider in spiders_dict[enumerated_keys[int(removee.
replace('-', ''))][1]]:
chosen_spiders.remove(spider)
else:
print('{} is not an option!'.format(removee))
else:
numeric = re.findall('\\d+', removee)
if len(numeric) == 1:
alpha = removee.split(numeric[0])[1]
alpha = len(alphabet_list_length(0, index=alpha)) - 1
try:
chosen_spiders.remove(spiders_dict[enumerated_keys[
int(numeric[0])][1]][alpha])
except IndexError:
print('{} is not an option!'.format(removee))
else:
print('{} is not an option!'.format(removee))
if len(chosen_spiders) > 0:
return chosen_spiders
else:
print("You haven't selected any spiders!")
return False
def project_visibility_menu():
"""
creates menu to allow user to set which project groups are visible in the run_scrapers menu
:return: creates a txt file containing the list of desired project names, one per row.
"""
projects = [i.split('.')[0] for i in os.listdir(
'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]
print('Available projects are:\n')
for project in enumerate(projects):
print('\t{} - {}'.format(project[0], project[1]))
print('\t{} - back'.format(len(projects)))
choices = input(
'\nType the options you wish to select.\nFor multiple, comma separate\n\n'
).split(',')
if str(len(projects)) in choices:
return True
else:
choice_list = []
for choice in choices:
if choice.isdigit() and int(choice) in range(len(projects)):
choice_list.append(projects[int(choice)])
print(
'You have selected to display the following spider groupings:\n\t{}\n'
.format(choice_list))
save_list_to_txt(choice_list,
'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'
)
return True
def set_config():
"""
menu to set the url configs.
:return: will set the start_urls of the spiders.
"""
available_configs = open(
'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'
, 'r')
options = available_configs.readlines()
options_dict = {}
print('available configs include:\n')
for option in enumerate(options):
options_dict[option[0]] = option[1].split(':')[0]
print('\t{} - {}'.format(option[0], option[1].replace('\n', '')))
print('\t{} - back'.format(len(options)))
chosen = input('\ncomma separate for multiple\n').split(',')
if str(len(options)) in chosen or chosen == ['']:
return True
configs = []
for choice in chosen:
if int(choice) in options_dict:
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'
.format(options_dict[int(choice)])) as f:
configs.append(json.load(f))
final_config = defaultdict(list)
for config in configs:
for key, value in config.items():
if key in final_config:
final_config[key] += value
else:
final_config[key] = value
for key, value in final_config.items():
if any(isinstance(val, list) for val in value):
final_config[key] = flatten_list_of_lists(value, make_set=True)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
for key, value in default_dict.items():
if key not in final_config.keys():
final_config[key] = value
with open(
'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'
) as fp:
json.dump(final_config, fp, sort_keys=True, indent=4)
return True
def append_recent_urls():
"""
function for appending recent scraped urls to default urls json
:return: default.json is updated
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict.setdefault(key, []).extend(value)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
, 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def replace_default_urls():
"""
function for replacing default urls config with recent scrapes
:return: defaults.json is updated
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
) as default_urls_json:
default_dict = json.load(default_urls_json)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict[key] = value
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'
, 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def create_new_config():
"""
function which creates a whole new config file to store recent scraped urls in
:return: new config is created
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
urls_dict = json.load(recent_urls_json)
config_name = input('Type a name for the new config file:\n').replace(' ',
'_').replace(':', '')
config_desc = input('Type a brief description for the new config file:\n')
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'
.format(config_name), 'w') as fp:
json.dump(urls_dict, fp, sort_keys=True, indent=4)
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'
, 'a') as input_descs:
input_descs.write('\n{}: {}'.format(config_name, config_desc))
print('\nSuccessfully saved recently scraped urls to new config: {}.json'
.format(config_name))
def clear_recent_urls():
"""
function which bleaches the recent urls config in order to start fresh next time
:return: recent_urls will become an empty dictionary.
"""
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
) as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key in recent_dict.keys():
recent_dict[key] = []
with open(
'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'
, 'w') as fp:
json.dump(recent_dict, fp, sort_keys=True, indent=4)
def select_date_interval_menu():
"""
function allows user to inout start and end date to define an interval of dates
:return: list of dates
"""
while True:
start_date = input(
'\nInput desired start date with format dd-mm-yyyy:\n')
try:
start_date = datetime.strptime(start_date, '%d-%m-%Y')
break
except ValueError:
print('invalid start date selected')
while True:
end_date = input(
"""
Input desired start date with format dd-mm-yyyy,
or hit enter to select todays date
"""
)
if end_date == '':
end_date = date.today()
break
else:
try:
end_date = datetime.strptime(end_date, '%d-%m-%Y')
break
except ValueError:
print('invalid end date selected')
list_of_dates = pd.date_range(start_date, end_date, freq='d')
list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]
return list_of_dates
<|reserved_special_token_1|>
"""
contains generic code for use in main menus. currently this is a function which turns dictionaries of functions
into a menu. I envision any further menu functions being stored here so don't expect it to run like a pipeline but
rather like a suite of individual menus.
TODO - refactor spider selection function as jesus christ that things fat
- incorporate spider selector in config manager options
"""
import re
import os
import json
from datetime import date, datetime
from collections import defaultdict
import pandas as pd
from HousingPriceScraper.HousingPriceScraper.functions.basic_functions import return_false, end_process, \
alphabet_list_length, flatten_list_of_lists
from HousingPriceScraper.HousingPriceScraper.functions.data_management import save_list_to_txt
def final_option(dict_of_options, back):
"""
adds the final option to the dictionary based on a boolean
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean
:return: dict_of_options but with a new, final key added in
"""
if back:
dict_of_options['back'] = return_false
else:
dict_of_options['end_process'] = end_process
return dict_of_options
def basic_menu(dict_of_options, back=False):
"""
basic text based user interface, allows user to select a function to run from a dictionary of options, by using a
simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.
:param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important
that these functions don't require parameters.
:param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to
ending process since that's how the main menu does it and unsure of where else function will be called
:return: run the chosen function
"""
choose = True
dict_of_options = final_option(dict_of_options, back)
list_of_options = list(dict_of_options.keys())
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
pick = input('\nType the numeric code you wish to run\n\n')
if pick in [str(i) for i in range((len(dict_of_options)))]:
choose = dict_of_options[list_of_options[int(pick)]]()
else:
print('{} is not currently an option!\n'.format(pick))
def basic_menu_non_functional(list_of_options):
"""
basic text based user interface, allows user to select multiple options from a list of available choices.
:param list_of_options: list of available choices
:return: a list of chosen strings
"""
choose = True
list_of_options.append('back')
while choose:
print('The following options are available:\n')
for option in enumerate(list_of_options):
print('\t{} - {}'.format(option[0], option[1]))
picks = input('\nType the numeric codes you wish to run\n\n').split(',')
choice = []
if str(len(list_of_options)) in picks:
return True
for pick in picks:
if pick in [str(i) for i in range((len(list_of_options)))]:
choice.append(list_of_options[int(pick)])
else:
print('{} is not currently an option!\n'.format(pick))
if len(choice) > 0:
return choice
def select_spiders(spiders_dict):
"""
select from spiders available. allows user to select all spiders, select all spiders within a
project group, select some comma separated list of individual/groups of spiders, or by prefixing a
given selection with "-", the user can remove a spider from his or her selection.
:param spiders_dict: dictionary who's keys are broad options and values are lists of spiders
:return: list containing the spiders the user has selected to run
"""
print('Available spiders include:\n')
enumerated_keys = list(enumerate(spiders_dict.keys()))
for key_group in enumerated_keys:
print('{} - {}'.format(key_group[0], key_group[1]))
for spider in zip(alphabet_list_length(len(key_group[1])), spiders_dict[key_group[1]]):
print('\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name))
print('{} - run all'.format(len(spiders_dict.keys())))
print('{} - back'.format(len(spiders_dict.keys())+1))
choices = input('\nfor multiple, comma separate. To remove, use "-" prefix\ni.e.: 0,-0a to run all of group 0 except the first\n').replace(' ', '').split(',')
if str(len(spiders_dict.keys())+1) in choices:
return False
if str(len(spiders_dict.keys())) in choices:
chosen_spiders = list(spiders_dict.values())
else:
chosen_spiders = []
for choice in choices:
if choice.isdigit():
if choice in [str(i[0]) for i in enumerated_keys]:
chosen_spiders.append(spiders_dict[enumerated_keys[int(choice)][1]])
else:
print('{} is not an option!'.format(choice))
elif '-' not in choice:
numeric = re.findall(r'\d+', choice)
if len(numeric) == 1:
alpha = choice.split(numeric[0])[1]
alpha = len(alphabet_list_length(0, index=alpha))-1
try:
chosen_spiders.append(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha])
except IndexError:
print('{} is not an option!'.format(choice))
else:
print('{} is not an option!'.format(choice))
if any(isinstance(el, list) for el in chosen_spiders):
chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)
else:
chosen_spiders = list(set(chosen_spiders))
to_remove = [choice for choice in choices if '-' in choice]
if len(to_remove) > 0:
for removee in to_remove:
if removee.replace('-', '').isdigit():
if removee.replace('-', '') in [str(i[0]) for i in enumerated_keys]:
for spider in spiders_dict[enumerated_keys[int(removee.replace('-', ''))][1]]:
chosen_spiders.remove(spider)
else:
print('{} is not an option!'.format(removee))
else:
numeric = re.findall(r'\d+', removee)
if len(numeric) == 1:
alpha = removee.split(numeric[0])[1]
alpha = len(alphabet_list_length(0, index=alpha)) - 1
try:
chosen_spiders.remove(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha])
except IndexError:
print('{} is not an option!'.format(removee))
else:
print('{} is not an option!'.format(removee))
if len(chosen_spiders) > 0:
return chosen_spiders
else:
print("You haven't selected any spiders!")
return False
def project_visibility_menu():
"""
creates menu to allow user to set which project groups are visible in the run_scrapers menu
:return: creates a txt file containing the list of desired project names, one per row.
"""
projects = [i.split('.')[0] for i in os.listdir('HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]
print('Available projects are:\n')
for project in enumerate(projects):
print('\t{} - {}'.format(project[0], project[1]))
print('\t{} - back'.format(len(projects)))
choices = input('\nType the options you wish to select.\nFor multiple, comma separate\n\n').split(',')
if str(len(projects)) in choices:
return True
else:
choice_list = []
for choice in choices:
if choice.isdigit() and int(choice) in range(len(projects)):
choice_list.append(projects[int(choice)])
print('You have selected to display the following spider groupings:\n\t{}\n'.format(choice_list))
save_list_to_txt(choice_list, 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt')
return True
def set_config():
"""
menu to set the url configs.
:return: will set the start_urls of the spiders.
"""
available_configs = open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'r')
options = available_configs.readlines()
options_dict = {}
print('available configs include:\n')
for option in enumerate(options):
options_dict[option[0]] = option[1].split(':')[0]
print('\t{} - {}'.format(option[0], option[1].replace('\n', '')))
print('\t{} - back'.format(len(options)))
chosen = input('\ncomma separate for multiple\n').split(',')
if (str(len(options)) in chosen) or (chosen == ['']):
return True
configs = []
for choice in chosen:
if int(choice) in options_dict:
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(options_dict[int(choice)])) as f:
configs.append(json.load(f))
final_config = defaultdict(list)
for config in configs:
for key, value in config.items():
if key in final_config:
final_config[key] += value
else:
final_config[key] = value
for key, value in final_config.items():
if any(isinstance(val, list) for val in value):
final_config[key] = flatten_list_of_lists(value, make_set=True)
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:
default_dict = json.load(default_urls_json)
for key, value in default_dict.items():
if key not in final_config.keys():
final_config[key] = value
with open('HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w') as fp:
json.dump(final_config, fp, sort_keys=True, indent=4)
return True
def append_recent_urls():
"""
function for appending recent scraped urls to default urls json
:return: default.json is updated
"""
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:
default_dict = json.load(default_urls_json)
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict.setdefault(key, []).extend(value)
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def replace_default_urls():
"""
function for replacing default urls config with recent scrapes
:return: defaults.json is updated
"""
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:
default_dict = json.load(default_urls_json)
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key, value in recent_dict.items():
default_dict[key] = value
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp:
json.dump(default_dict, fp, sort_keys=True, indent=4)
def create_new_config():
"""
function which creates a whole new config file to store recent scraped urls in
:return: new config is created
"""
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:
urls_dict = json.load(recent_urls_json)
config_name = input('Type a name for the new config file:\n').replace(' ', '_').replace(':', '')
config_desc = input('Type a brief description for the new config file:\n')
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(config_name), 'w') as fp:
json.dump(urls_dict, fp, sort_keys=True, indent=4)
with open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'a') as input_descs:
input_descs.write('\n{}: {}'.format(config_name, config_desc))
print('\nSuccessfully saved recently scraped urls to new config: {}.json'.format(config_name))
def clear_recent_urls():
"""
function which bleaches the recent urls config in order to start fresh next time
:return: recent_urls will become an empty dictionary.
"""
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:
recent_dict = json.load(recent_urls_json)
for key in recent_dict.keys():
recent_dict[key] = []
with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json', 'w') as fp:
json.dump(recent_dict, fp, sort_keys=True, indent=4)
def select_date_interval_menu():
"""
function allows user to inout start and end date to define an interval of dates
:return: list of dates
"""
while True:
start_date = input('\nInput desired start date with format dd-mm-yyyy:\n')
try:
start_date = datetime.strptime(start_date, '%d-%m-%Y')
break
except ValueError:
print('invalid start date selected')
while True:
end_date = input('\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n')
if end_date == '':
end_date = date.today()
break
else:
try:
end_date = datetime.strptime(end_date, '%d-%m-%Y')
break
except ValueError:
print('invalid end date selected')
list_of_dates = pd.date_range(start_date, end_date, freq='d')
list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]
return list_of_dates
|
flexible
|
{
"blob_id": "f28b47e1b07011ce9d0708331f68d7f16195c567",
"index": 7225,
"step-1": "<mask token>\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\n<mask token>\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\n<mask token>\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n",
"step-2": "<mask token>\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\n<mask token>\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if str(len(options)) in chosen or chosen == ['']:\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'\n ) as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n",
"step-3": "<mask token>\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\ndef select_spiders(spiders_dict):\n \"\"\"\n select from spiders available. allows user to select all spiders, select all spiders within a\n project group, select some comma separated list of individual/groups of spiders, or by prefixing a\n given selection with \"-\", the user can remove a spider from his or her selection.\n\n :param spiders_dict: dictionary who's keys are broad options and values are lists of spiders\n :return: list containing the spiders the user has selected to run\n \"\"\"\n print('Available spiders include:\\n')\n enumerated_keys = list(enumerate(spiders_dict.keys()))\n for key_group in enumerated_keys:\n print('{} - {}'.format(key_group[0], key_group[1]))\n for spider in zip(alphabet_list_length(len(key_group[1])),\n spiders_dict[key_group[1]]):\n print('\\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name)\n )\n print('{} - run all'.format(len(spiders_dict.keys())))\n print('{} - back'.format(len(spiders_dict.keys()) + 1))\n choices = input(\n \"\"\"\nfor multiple, comma separate. To remove, use \"-\" prefix\ni.e.: 0,-0a to run all of group 0 except the first\n\"\"\"\n ).replace(' ', '').split(',')\n if str(len(spiders_dict.keys()) + 1) in choices:\n return False\n if str(len(spiders_dict.keys())) in choices:\n chosen_spiders = list(spiders_dict.values())\n else:\n chosen_spiders = []\n for choice in choices:\n if choice.isdigit():\n if choice in [str(i[0]) for i in enumerated_keys]:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(\n choice)][1]])\n else:\n print('{} is not an option!'.format(choice))\n elif '-' not in choice:\n numeric = re.findall('\\\\d+', choice)\n if len(numeric) == 1:\n alpha = choice.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.append(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(choice))\n else:\n print('{} is not an option!'.format(choice))\n if any(isinstance(el, list) for el in chosen_spiders):\n chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)\n else:\n chosen_spiders = list(set(chosen_spiders))\n to_remove = [choice for choice in choices if '-' in choice]\n if len(to_remove) > 0:\n for removee in to_remove:\n if removee.replace('-', '').isdigit():\n if removee.replace('-', '') in [str(i[0]) for i in\n enumerated_keys]:\n for spider in spiders_dict[enumerated_keys[int(removee.\n replace('-', ''))][1]]:\n chosen_spiders.remove(spider)\n else:\n print('{} is not an option!'.format(removee))\n else:\n numeric = re.findall('\\\\d+', removee)\n if len(numeric) == 1:\n alpha = removee.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.remove(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(removee))\n else:\n print('{} is not an option!'.format(removee))\n if len(chosen_spiders) > 0:\n return chosen_spiders\n else:\n print(\"You haven't selected any spiders!\")\n return False\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if str(len(options)) in chosen or chosen == ['']:\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'\n ) as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n",
"step-4": "<mask token>\nimport re\nimport os\nimport json\nfrom datetime import date, datetime\nfrom collections import defaultdict\nimport pandas as pd\nfrom HousingPriceScraper.HousingPriceScraper.functions.basic_functions import return_false, end_process, alphabet_list_length, flatten_list_of_lists\nfrom HousingPriceScraper.HousingPriceScraper.functions.data_management import save_list_to_txt\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\ndef select_spiders(spiders_dict):\n \"\"\"\n select from spiders available. allows user to select all spiders, select all spiders within a\n project group, select some comma separated list of individual/groups of spiders, or by prefixing a\n given selection with \"-\", the user can remove a spider from his or her selection.\n\n :param spiders_dict: dictionary who's keys are broad options and values are lists of spiders\n :return: list containing the spiders the user has selected to run\n \"\"\"\n print('Available spiders include:\\n')\n enumerated_keys = list(enumerate(spiders_dict.keys()))\n for key_group in enumerated_keys:\n print('{} - {}'.format(key_group[0], key_group[1]))\n for spider in zip(alphabet_list_length(len(key_group[1])),\n spiders_dict[key_group[1]]):\n print('\\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name)\n )\n print('{} - run all'.format(len(spiders_dict.keys())))\n print('{} - back'.format(len(spiders_dict.keys()) + 1))\n choices = input(\n \"\"\"\nfor multiple, comma separate. To remove, use \"-\" prefix\ni.e.: 0,-0a to run all of group 0 except the first\n\"\"\"\n ).replace(' ', '').split(',')\n if str(len(spiders_dict.keys()) + 1) in choices:\n return False\n if str(len(spiders_dict.keys())) in choices:\n chosen_spiders = list(spiders_dict.values())\n else:\n chosen_spiders = []\n for choice in choices:\n if choice.isdigit():\n if choice in [str(i[0]) for i in enumerated_keys]:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(\n choice)][1]])\n else:\n print('{} is not an option!'.format(choice))\n elif '-' not in choice:\n numeric = re.findall('\\\\d+', choice)\n if len(numeric) == 1:\n alpha = choice.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.append(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(choice))\n else:\n print('{} is not an option!'.format(choice))\n if any(isinstance(el, list) for el in chosen_spiders):\n chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)\n else:\n chosen_spiders = list(set(chosen_spiders))\n to_remove = [choice for choice in choices if '-' in choice]\n if len(to_remove) > 0:\n for removee in to_remove:\n if removee.replace('-', '').isdigit():\n if removee.replace('-', '') in [str(i[0]) for i in\n enumerated_keys]:\n for spider in spiders_dict[enumerated_keys[int(removee.\n replace('-', ''))][1]]:\n chosen_spiders.remove(spider)\n else:\n print('{} is not an option!'.format(removee))\n else:\n numeric = re.findall('\\\\d+', removee)\n if len(numeric) == 1:\n alpha = removee.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.remove(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(removee))\n else:\n print('{} is not an option!'.format(removee))\n if len(chosen_spiders) > 0:\n return chosen_spiders\n else:\n print(\"You haven't selected any spiders!\")\n return False\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if str(len(options)) in chosen or chosen == ['']:\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'\n ) as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n",
"step-5": "\"\"\"\ncontains generic code for use in main menus. currently this is a function which turns dictionaries of functions\ninto a menu. I envision any further menu functions being stored here so don't expect it to run like a pipeline but\nrather like a suite of individual menus.\n\nTODO - refactor spider selection function as jesus christ that things fat\n - incorporate spider selector in config manager options\n\"\"\"\nimport re\nimport os\nimport json\nfrom datetime import date, datetime\nfrom collections import defaultdict\nimport pandas as pd\nfrom HousingPriceScraper.HousingPriceScraper.functions.basic_functions import return_false, end_process, \\\n alphabet_list_length, flatten_list_of_lists\nfrom HousingPriceScraper.HousingPriceScraper.functions.data_management import save_list_to_txt\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range((len(dict_of_options)))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(',')\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range((len(list_of_options)))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\ndef select_spiders(spiders_dict):\n \"\"\"\n select from spiders available. allows user to select all spiders, select all spiders within a\n project group, select some comma separated list of individual/groups of spiders, or by prefixing a\n given selection with \"-\", the user can remove a spider from his or her selection.\n\n :param spiders_dict: dictionary who's keys are broad options and values are lists of spiders\n :return: list containing the spiders the user has selected to run\n \"\"\"\n print('Available spiders include:\\n')\n enumerated_keys = list(enumerate(spiders_dict.keys()))\n for key_group in enumerated_keys:\n print('{} - {}'.format(key_group[0], key_group[1]))\n for spider in zip(alphabet_list_length(len(key_group[1])), spiders_dict[key_group[1]]):\n print('\\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name))\n print('{} - run all'.format(len(spiders_dict.keys())))\n print('{} - back'.format(len(spiders_dict.keys())+1))\n choices = input('\\nfor multiple, comma separate. To remove, use \"-\" prefix\\ni.e.: 0,-0a to run all of group 0 except the first\\n').replace(' ', '').split(',')\n if str(len(spiders_dict.keys())+1) in choices:\n return False\n if str(len(spiders_dict.keys())) in choices:\n chosen_spiders = list(spiders_dict.values())\n else:\n chosen_spiders = []\n for choice in choices:\n if choice.isdigit():\n if choice in [str(i[0]) for i in enumerated_keys]:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(choice)][1]])\n else:\n print('{} is not an option!'.format(choice))\n elif '-' not in choice:\n numeric = re.findall(r'\\d+', choice)\n if len(numeric) == 1:\n alpha = choice.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha))-1\n try:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(choice))\n else:\n print('{} is not an option!'.format(choice))\n if any(isinstance(el, list) for el in chosen_spiders):\n chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)\n else:\n chosen_spiders = list(set(chosen_spiders))\n to_remove = [choice for choice in choices if '-' in choice]\n if len(to_remove) > 0:\n for removee in to_remove:\n if removee.replace('-', '').isdigit():\n if removee.replace('-', '') in [str(i[0]) for i in enumerated_keys]:\n for spider in spiders_dict[enumerated_keys[int(removee.replace('-', ''))][1]]:\n chosen_spiders.remove(spider)\n else:\n print('{} is not an option!'.format(removee))\n else:\n numeric = re.findall(r'\\d+', removee)\n if len(numeric) == 1:\n alpha = removee.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.remove(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(removee))\n else:\n print('{} is not an option!'.format(removee))\n if len(chosen_spiders) > 0:\n return chosen_spiders\n else:\n print(\"You haven't selected any spiders!\")\n return False\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir('HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input('\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n').split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print('You have selected to display the following spider groupings:\\n\\t{}\\n'.format(choice_list))\n save_list_to_txt(choice_list, 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt')\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if (str(len(options)) in chosen) or (chosen == ['']):\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open('HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w') as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ', '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'.format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json', 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input('\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input('\\nInput desired start date with format dd-mm-yyyy,\\nor hit enter to select todays date\\n')\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n",
"step-ids": [
8,
10,
11,
12,
13
]
}
|
[
8,
10,
11,
12,
13
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for i in range(2):
shaan.forward(200)
shaan.right(90)
shaan.forward(250)
shaan.right(90)
shaan.left(60)
for i in range(4):
shaan.forward(200)
shaan.right(120)
shaan.forward(100)
shaan.left(150)
shaan.forward(100)
shaan.right(90)
shaan.forward(20)
shaan.right(90)
shaan.forward(135)
shaan.left(30)
shaan.forward(60)
shaan.right(120)
shaan.forward(32.5)
shaan.pu()
shaan.left(90)
shaan.forward(60)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(32.5)
shaan.pd()
shaan.left(90)
shaan.forward(165)
shaan.left(90)
shaan.forward(100)
shaan.left(90)
shaan.forward(100)
shaan.right(90)
shaan.forward(50)
shaan.right(90)
shaan.forward(100)
shaan.right(180)
shaan.forward(75)
shaan.pu()
shaan.left(90)
shaan.forward(20)
shaan.pd()
shaan.begin_fill()
shaan.circle(5, 360)
shaan.end_fill()
shaan.pu()
shaan.forward(1000)
turtle.done()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
shaan = turtle.Turtle()
for i in range(2):
shaan.forward(200)
shaan.right(90)
shaan.forward(250)
shaan.right(90)
shaan.left(60)
for i in range(4):
shaan.forward(200)
shaan.right(120)
shaan.forward(100)
shaan.left(150)
shaan.forward(100)
shaan.right(90)
shaan.forward(20)
shaan.right(90)
shaan.forward(135)
shaan.left(30)
shaan.forward(60)
shaan.right(120)
shaan.forward(32.5)
shaan.pu()
shaan.left(90)
shaan.forward(60)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(32.5)
shaan.pd()
shaan.left(90)
shaan.forward(165)
shaan.left(90)
shaan.forward(100)
shaan.left(90)
shaan.forward(100)
shaan.right(90)
shaan.forward(50)
shaan.right(90)
shaan.forward(100)
shaan.right(180)
shaan.forward(75)
shaan.pu()
shaan.left(90)
shaan.forward(20)
shaan.pd()
shaan.begin_fill()
shaan.circle(5, 360)
shaan.end_fill()
shaan.pu()
shaan.forward(1000)
turtle.done()
<|reserved_special_token_1|>
import turtle
import random
shaan = turtle.Turtle()
for i in range(2):
shaan.forward(200)
shaan.right(90)
shaan.forward(250)
shaan.right(90)
shaan.left(60)
for i in range(4):
shaan.forward(200)
shaan.right(120)
shaan.forward(100)
shaan.left(150)
shaan.forward(100)
shaan.right(90)
shaan.forward(20)
shaan.right(90)
shaan.forward(135)
shaan.left(30)
shaan.forward(60)
shaan.right(120)
shaan.forward(32.5)
shaan.pu()
shaan.left(90)
shaan.forward(60)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(32.5)
shaan.pd()
shaan.left(90)
shaan.forward(165)
shaan.left(90)
shaan.forward(100)
shaan.left(90)
shaan.forward(100)
shaan.right(90)
shaan.forward(50)
shaan.right(90)
shaan.forward(100)
shaan.right(180)
shaan.forward(75)
shaan.pu()
shaan.left(90)
shaan.forward(20)
shaan.pd()
shaan.begin_fill()
shaan.circle(5, 360)
shaan.end_fill()
shaan.pu()
shaan.forward(1000)
turtle.done()
<|reserved_special_token_1|>
import turtle
import random
shaan = turtle.Turtle()
#shaan.color(50,50,50)
#shaan.begin_fill()
for i in range (2):
shaan.forward(200)
shaan.right(90)
shaan.forward(250)
shaan.right(90)
shaan.left(60)
for i in range(4):
shaan.forward(200)
shaan.right(120)
shaan.forward(100)
shaan.left(150)
shaan.forward(100)
shaan.right(90)
shaan.forward(20)
shaan.right(90)
shaan.forward(135)
shaan.left(30)
shaan.forward(60)
shaan.right(120)
shaan.forward(32.5)
shaan.pu()
shaan.left(90)
shaan.forward(60)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(30)
shaan.pd()
for i in range(4):
shaan.forward(25)
shaan.right(90)
shaan.forward(25)
shaan.pu()
shaan.forward(32.5)
shaan.pd()
shaan.left(90)
shaan.forward(165)
shaan.left(90)
shaan.forward(100)
shaan.left(90)
shaan.forward(100)
shaan.right(90)
shaan.forward(50)
shaan.right(90)
shaan.forward(100)
shaan.right(180)
shaan.forward(75)
shaan.pu()
shaan.left(90)
shaan.forward(20)
shaan.pd()
shaan.begin_fill()
shaan.circle(5,360)
shaan.end_fill()
shaan.pu()
shaan.forward(1000)
turtle.done()
#shaan.end_fill()
|
flexible
|
{
"blob_id": "6f13ebe7355d530ba3403aab54b313ecf35b1261",
"index": 4523,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(2):\n shaan.forward(200)\n shaan.right(90)\n shaan.forward(250)\n shaan.right(90)\nshaan.left(60)\nfor i in range(4):\n shaan.forward(200)\n shaan.right(120)\nshaan.forward(100)\nshaan.left(150)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(20)\nshaan.right(90)\nshaan.forward(135)\nshaan.left(30)\nshaan.forward(60)\nshaan.right(120)\nshaan.forward(32.5)\nshaan.pu()\nshaan.left(90)\nshaan.forward(60)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(32.5)\nshaan.pd()\nshaan.left(90)\nshaan.forward(165)\nshaan.left(90)\nshaan.forward(100)\nshaan.left(90)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(50)\nshaan.right(90)\nshaan.forward(100)\nshaan.right(180)\nshaan.forward(75)\nshaan.pu()\nshaan.left(90)\nshaan.forward(20)\nshaan.pd()\nshaan.begin_fill()\nshaan.circle(5, 360)\nshaan.end_fill()\nshaan.pu()\nshaan.forward(1000)\nturtle.done()\n",
"step-3": "<mask token>\nshaan = turtle.Turtle()\nfor i in range(2):\n shaan.forward(200)\n shaan.right(90)\n shaan.forward(250)\n shaan.right(90)\nshaan.left(60)\nfor i in range(4):\n shaan.forward(200)\n shaan.right(120)\nshaan.forward(100)\nshaan.left(150)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(20)\nshaan.right(90)\nshaan.forward(135)\nshaan.left(30)\nshaan.forward(60)\nshaan.right(120)\nshaan.forward(32.5)\nshaan.pu()\nshaan.left(90)\nshaan.forward(60)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(32.5)\nshaan.pd()\nshaan.left(90)\nshaan.forward(165)\nshaan.left(90)\nshaan.forward(100)\nshaan.left(90)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(50)\nshaan.right(90)\nshaan.forward(100)\nshaan.right(180)\nshaan.forward(75)\nshaan.pu()\nshaan.left(90)\nshaan.forward(20)\nshaan.pd()\nshaan.begin_fill()\nshaan.circle(5, 360)\nshaan.end_fill()\nshaan.pu()\nshaan.forward(1000)\nturtle.done()\n",
"step-4": "import turtle\nimport random\nshaan = turtle.Turtle()\nfor i in range(2):\n shaan.forward(200)\n shaan.right(90)\n shaan.forward(250)\n shaan.right(90)\nshaan.left(60)\nfor i in range(4):\n shaan.forward(200)\n shaan.right(120)\nshaan.forward(100)\nshaan.left(150)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(20)\nshaan.right(90)\nshaan.forward(135)\nshaan.left(30)\nshaan.forward(60)\nshaan.right(120)\nshaan.forward(32.5)\nshaan.pu()\nshaan.left(90)\nshaan.forward(60)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\nfor i in range(4):\n shaan.forward(25)\n shaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(32.5)\nshaan.pd()\nshaan.left(90)\nshaan.forward(165)\nshaan.left(90)\nshaan.forward(100)\nshaan.left(90)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(50)\nshaan.right(90)\nshaan.forward(100)\nshaan.right(180)\nshaan.forward(75)\nshaan.pu()\nshaan.left(90)\nshaan.forward(20)\nshaan.pd()\nshaan.begin_fill()\nshaan.circle(5, 360)\nshaan.end_fill()\nshaan.pu()\nshaan.forward(1000)\nturtle.done()\n",
"step-5": "import turtle\nimport random\n\nshaan = turtle.Turtle()\n\n#shaan.color(50,50,50)\n\n#shaan.begin_fill()\nfor i in range (2):\n\tshaan.forward(200)\n\tshaan.right(90)\n\tshaan.forward(250)\n\tshaan.right(90)\n\nshaan.left(60)\n\nfor i in range(4):\n\tshaan.forward(200)\n\tshaan.right(120)\n\nshaan.forward(100)\nshaan.left(150)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(20)\nshaan.right(90)\nshaan.forward(135)\nshaan.left(30)\nshaan.forward(60)\n\nshaan.right(120)\nshaan.forward(32.5)\nshaan.pu()\nshaan.left(90)\nshaan.forward(60)\nshaan.pd()\n\n\nfor i in range(4):\n\tshaan.forward(25)\n\tshaan.right(90)\n\nshaan.forward(25)\nshaan.right(90)\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\n\n\nfor i in range(4):\n\tshaan.forward(25)\n\tshaan.right(90)\n\nshaan.forward(25)\nshaan.pu()\nshaan.forward(30)\nshaan.pd()\n\nfor i in range(4):\n\tshaan.forward(25)\n\tshaan.right(90)\n\nshaan.forward(25)\nshaan.pu()\nshaan.forward(32.5)\nshaan.pd()\n\n\nshaan.left(90)\nshaan.forward(165)\nshaan.left(90)\nshaan.forward(100)\nshaan.left(90)\nshaan.forward(100)\nshaan.right(90)\nshaan.forward(50)\nshaan.right(90)\nshaan.forward(100)\nshaan.right(180)\nshaan.forward(75)\nshaan.pu()\nshaan.left(90)\nshaan.forward(20)\nshaan.pd()\nshaan.begin_fill()\nshaan.circle(5,360)\nshaan.end_fill()\nshaan.pu()\nshaan.forward(1000)\n\nturtle.done()\n\n\n\n\n\n\n\n\n\n\n#shaan.end_fill()",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
data
data.describe()
data.dtypes
pd.crosstab(data.salary, data.left)
pd.crosstab(data.salary, data.left).plot(kind='bar')
plt.show()
<|reserved_special_token_0|>
print(q)
print(q.sum(1))
print(q.div(q.sum(1), axis=0))
q.div(q.sum(1), axis=0).plot(kind='bar', stacked=True)
plt.show()
data[data.left == 0].satisfaction_level.hist()
plt.show()
data[data.left == 1].satisfaction_level.hist()
plt.show()
<|reserved_special_token_0|>
model.fit(X, y)
pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))
print(model.score(X, y))
model.predict_proba([[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.7, 4.0,
160, 3.0, 0, 0]])
<|reserved_special_token_0|>
abs(pred - y).sum() / len(y)
<|reserved_special_token_0|>
model2.fit(Xtrain, ytrain)
<|reserved_special_token_0|>
print(metrics.accuracy_score(ytest, pred))
print(metrics.confusion_matrix(ytest, pred))
print(metrics.classification_report(ytest, pred))
print(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10
).mean())
print(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy',
cv=10).mean())
print(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy',
cv=10).mean())
print(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy',
cv=10).mean())
<|reserved_special_token_1|>
<|reserved_special_token_0|>
data = pd.read_csv('hr_employee_retension/HR_comma_sep.csv')
data
data.describe()
data.dtypes
pd.crosstab(data.salary, data.left)
pd.crosstab(data.salary, data.left).plot(kind='bar')
plt.show()
q = pd.crosstab(data.salary, data.left)
print(q)
print(q.sum(1))
print(q.div(q.sum(1), axis=0))
q.div(q.sum(1), axis=0).plot(kind='bar', stacked=True)
plt.show()
data[data.left == 0].satisfaction_level.hist()
plt.show()
data[data.left == 1].satisfaction_level.hist()
plt.show()
y, X = dmatrices(
'left~satisfaction_level+last_evaluation+number_project+average_montly_hours+time_spend_company +Work_accident+promotion_last_5years+C(sales)+C(salary)'
, data, return_type='dataframe')
X = X.rename(columns={'C(sales)[T.RandD]': 'Department: Random',
'C(sales)[T.accounting]': 'Department: Accounting', 'C(sales)[T.hr]':
'Department: HR', 'C(sales)[T.management]': 'Department: Management',
'C(sales)[T.marketing]': 'Department: Marketing',
'C(sales)[T.product_mng]': 'Department: Product_Management',
'C(sales)[T.sales]': 'Department: Sales', 'C(sales)[T.support]':
'Department: Support', 'C(sales)[T.technical]': 'Department: Technical',
'C(salary)[T.low]': 'Salary: Low', 'C(salary)[T.medium]': 'Salary: Medium'}
)
y = np.ravel(y)
model = LogisticRegression()
model.fit(X, y)
pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))
print(model.score(X, y))
model.predict_proba([[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.7, 4.0,
160, 3.0, 0, 0]])
pred = model.predict(X)
abs(pred - y).sum() / len(y)
Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.3,
random_state=0)
model2 = LogisticRegression(C=10000)
model2.fit(Xtrain, ytrain)
pred = model2.predict(Xtest)
print(metrics.accuracy_score(ytest, pred))
print(metrics.confusion_matrix(ytest, pred))
print(metrics.classification_report(ytest, pred))
print(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10
).mean())
print(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy',
cv=10).mean())
print(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy',
cv=10).mean())
print(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy',
cv=10).mean())
<|reserved_special_token_1|>
import numpy as np
import pandas as pd
from patsy import dmatrices
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn import metrics
import matplotlib.pyplot as plt
data = pd.read_csv('hr_employee_retension/HR_comma_sep.csv')
data
data.describe()
data.dtypes
pd.crosstab(data.salary, data.left)
pd.crosstab(data.salary, data.left).plot(kind='bar')
plt.show()
q = pd.crosstab(data.salary, data.left)
print(q)
print(q.sum(1))
print(q.div(q.sum(1), axis=0))
q.div(q.sum(1), axis=0).plot(kind='bar', stacked=True)
plt.show()
data[data.left == 0].satisfaction_level.hist()
plt.show()
data[data.left == 1].satisfaction_level.hist()
plt.show()
y, X = dmatrices(
'left~satisfaction_level+last_evaluation+number_project+average_montly_hours+time_spend_company +Work_accident+promotion_last_5years+C(sales)+C(salary)'
, data, return_type='dataframe')
X = X.rename(columns={'C(sales)[T.RandD]': 'Department: Random',
'C(sales)[T.accounting]': 'Department: Accounting', 'C(sales)[T.hr]':
'Department: HR', 'C(sales)[T.management]': 'Department: Management',
'C(sales)[T.marketing]': 'Department: Marketing',
'C(sales)[T.product_mng]': 'Department: Product_Management',
'C(sales)[T.sales]': 'Department: Sales', 'C(sales)[T.support]':
'Department: Support', 'C(sales)[T.technical]': 'Department: Technical',
'C(salary)[T.low]': 'Salary: Low', 'C(salary)[T.medium]': 'Salary: Medium'}
)
y = np.ravel(y)
model = LogisticRegression()
model.fit(X, y)
pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))
print(model.score(X, y))
model.predict_proba([[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.7, 4.0,
160, 3.0, 0, 0]])
pred = model.predict(X)
abs(pred - y).sum() / len(y)
Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.3,
random_state=0)
model2 = LogisticRegression(C=10000)
model2.fit(Xtrain, ytrain)
pred = model2.predict(Xtest)
print(metrics.accuracy_score(ytest, pred))
print(metrics.confusion_matrix(ytest, pred))
print(metrics.classification_report(ytest, pred))
print(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10
).mean())
print(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy',
cv=10).mean())
print(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy',
cv=10).mean())
print(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy',
cv=10).mean())
<|reserved_special_token_1|>
#!/usr/bin/env python
# coding: utf-8
# HR Employee Retension Rate, predicting an employee likely to leave or not.
# In[ ]:
import numpy as np # 数组常用库
import pandas as pd # 读入csv常用库
from patsy import dmatrices # 可根据离散变量自动生成哑变量
from sklearn.linear_model import LogisticRegression # sk-learn库Logistic Regression模型
from sklearn.model_selection import train_test_split, cross_val_score # sk-learn库训练与测试
from sklearn import metrics # 生成各项测试指标库
import matplotlib.pyplot as plt # 画图常用库
# In[ ]:
# 从../input/HR_comma_sep.csv文件中读入数据
data = pd.read_csv("hr_employee_retension/HR_comma_sep.csv")
data
# In[ ]:
data.describe()
data.dtypes
# 观察离职人数与工资分布的关系
# In[ ]:
# 观察离职比例与工资分布的关系
pd.crosstab(data.salary, data.left)
pd.crosstab(data.salary, data.left).plot(kind='bar')
plt.show()
# In[ ]:
q = pd.crosstab(data.salary, data.left)
print(q)
print(q.sum(1))
print(q.div(q.sum(1), axis=0)) # axis=0 is to get which value in q.sum(1) to divide to.
q.div(q.sum(1), axis = 0).plot(kind='bar', stacked = True)
plt.show()
# In[ ]:
# 观察员工满意度的分布图(histogram)
data[data.left==0].satisfaction_level.hist()
plt.show()
# In[ ]:
data[data.left==1].satisfaction_level.hist()
plt.show()
# In[ ]:
# dmatrices将数据中的离散变量变成哑变量,并指明用satisfaction_level, last_evaluation, ... 来预测left
# 然后重命名列的名字
# C(xxx) categorical feature
# 'y~X' like R language
y, X = dmatrices('left~satisfaction_level+last_evaluation+number_project+average_montly_hours+time_spend_company\
+Work_accident+promotion_last_5years+C(sales)+C(salary)', data, return_type='dataframe')
X = X.rename(columns = {
'C(sales)[T.RandD]': 'Department: Random',
'C(sales)[T.accounting]': 'Department: Accounting',
'C(sales)[T.hr]': 'Department: HR',
'C(sales)[T.management]': 'Department: Management',
'C(sales)[T.marketing]': 'Department: Marketing',
'C(sales)[T.product_mng]': 'Department: Product_Management',
'C(sales)[T.sales]': 'Department: Sales',
'C(sales)[T.support]': 'Department: Support',
'C(sales)[T.technical]': 'Department: Technical',
'C(salary)[T.low]': 'Salary: Low',
'C(salary)[T.medium]': 'Salary: Medium'})
y = np.ravel(y) #将y变成np的一维数组
# In[ ]:
# zip(a,b)可将a的每一个元素和b里对应位置的元素组成一对
# 用X和y训练模型,然后输出X中每一项自变量对于y的影响
model = LogisticRegression()
model.fit(X, y)
pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))
# In[ ]:
# model.score为准确率(0到1之间)
print(model.score(X,y))
# In[ ]:
#一个高工资HR,对公司满意度0.5, 上次评审0.7分,做过4个项目,每月平均工作160小时,在公司呆了3年,过去5年没有被晋升,没有工伤
model.predict_proba([[1,0,0,1,0,0,0,0,0,0,0,0, 0.5, 0.7, 4.0, 160, 3.0, 0, 0]])
# In[ ]:
pred = model.predict(X)
(abs(pred-y)).sum() / len(y) # 錯誤率 不相等才是1
# In[ ]:
# 生成7:3的训练测试集
Xtrain, Xtest, ytrain, ytest=train_test_split(X, y, test_size=0.3, random_state=0)
model2 = LogisticRegression(C=10000)
model2.fit(Xtrain, ytrain)
pred = model2.predict(Xtest)
# In[ ]:
# 观察实际离职/未离职被预测成为离职/未离职的数目
print(metrics.accuracy_score(ytest, pred))
print(metrics.confusion_matrix(ytest, pred))
# prediction
#
#
#actual
#
#
#
# classification_report会输出每一类对应的precision, recall
print(metrics.classification_report(ytest, pred))
# In[ ]:
# 10份的交叉验证Cross Validation
print(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10).mean())
print(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy', cv=10).mean())
print(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy', cv=10).mean()) # best
print(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy', cv=10).mean())
|
flexible
|
{
"blob_id": "a1bf4b941b845b43ec640b19a001e290b46c488c",
"index": 7021,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndata\ndata.describe()\ndata.dtypes\npd.crosstab(data.salary, data.left)\npd.crosstab(data.salary, data.left).plot(kind='bar')\nplt.show()\n<mask token>\nprint(q)\nprint(q.sum(1))\nprint(q.div(q.sum(1), axis=0))\nq.div(q.sum(1), axis=0).plot(kind='bar', stacked=True)\nplt.show()\ndata[data.left == 0].satisfaction_level.hist()\nplt.show()\ndata[data.left == 1].satisfaction_level.hist()\nplt.show()\n<mask token>\nmodel.fit(X, y)\npd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))\nprint(model.score(X, y))\nmodel.predict_proba([[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.7, 4.0, \n 160, 3.0, 0, 0]])\n<mask token>\nabs(pred - y).sum() / len(y)\n<mask token>\nmodel2.fit(Xtrain, ytrain)\n<mask token>\nprint(metrics.accuracy_score(ytest, pred))\nprint(metrics.confusion_matrix(ytest, pred))\nprint(metrics.classification_report(ytest, pred))\nprint(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10\n ).mean())\nprint(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy',\n cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy',\n cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy',\n cv=10).mean())\n",
"step-3": "<mask token>\ndata = pd.read_csv('hr_employee_retension/HR_comma_sep.csv')\ndata\ndata.describe()\ndata.dtypes\npd.crosstab(data.salary, data.left)\npd.crosstab(data.salary, data.left).plot(kind='bar')\nplt.show()\nq = pd.crosstab(data.salary, data.left)\nprint(q)\nprint(q.sum(1))\nprint(q.div(q.sum(1), axis=0))\nq.div(q.sum(1), axis=0).plot(kind='bar', stacked=True)\nplt.show()\ndata[data.left == 0].satisfaction_level.hist()\nplt.show()\ndata[data.left == 1].satisfaction_level.hist()\nplt.show()\ny, X = dmatrices(\n 'left~satisfaction_level+last_evaluation+number_project+average_montly_hours+time_spend_company +Work_accident+promotion_last_5years+C(sales)+C(salary)'\n , data, return_type='dataframe')\nX = X.rename(columns={'C(sales)[T.RandD]': 'Department: Random',\n 'C(sales)[T.accounting]': 'Department: Accounting', 'C(sales)[T.hr]':\n 'Department: HR', 'C(sales)[T.management]': 'Department: Management',\n 'C(sales)[T.marketing]': 'Department: Marketing',\n 'C(sales)[T.product_mng]': 'Department: Product_Management',\n 'C(sales)[T.sales]': 'Department: Sales', 'C(sales)[T.support]':\n 'Department: Support', 'C(sales)[T.technical]': 'Department: Technical',\n 'C(salary)[T.low]': 'Salary: Low', 'C(salary)[T.medium]': 'Salary: Medium'}\n )\ny = np.ravel(y)\nmodel = LogisticRegression()\nmodel.fit(X, y)\npd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))\nprint(model.score(X, y))\nmodel.predict_proba([[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.7, 4.0, \n 160, 3.0, 0, 0]])\npred = model.predict(X)\nabs(pred - y).sum() / len(y)\nXtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.3,\n random_state=0)\nmodel2 = LogisticRegression(C=10000)\nmodel2.fit(Xtrain, ytrain)\npred = model2.predict(Xtest)\nprint(metrics.accuracy_score(ytest, pred))\nprint(metrics.confusion_matrix(ytest, pred))\nprint(metrics.classification_report(ytest, pred))\nprint(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10\n ).mean())\nprint(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy',\n cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy',\n cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy',\n cv=10).mean())\n",
"step-4": "import numpy as np\nimport pandas as pd\nfrom patsy import dmatrices\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\ndata = pd.read_csv('hr_employee_retension/HR_comma_sep.csv')\ndata\ndata.describe()\ndata.dtypes\npd.crosstab(data.salary, data.left)\npd.crosstab(data.salary, data.left).plot(kind='bar')\nplt.show()\nq = pd.crosstab(data.salary, data.left)\nprint(q)\nprint(q.sum(1))\nprint(q.div(q.sum(1), axis=0))\nq.div(q.sum(1), axis=0).plot(kind='bar', stacked=True)\nplt.show()\ndata[data.left == 0].satisfaction_level.hist()\nplt.show()\ndata[data.left == 1].satisfaction_level.hist()\nplt.show()\ny, X = dmatrices(\n 'left~satisfaction_level+last_evaluation+number_project+average_montly_hours+time_spend_company +Work_accident+promotion_last_5years+C(sales)+C(salary)'\n , data, return_type='dataframe')\nX = X.rename(columns={'C(sales)[T.RandD]': 'Department: Random',\n 'C(sales)[T.accounting]': 'Department: Accounting', 'C(sales)[T.hr]':\n 'Department: HR', 'C(sales)[T.management]': 'Department: Management',\n 'C(sales)[T.marketing]': 'Department: Marketing',\n 'C(sales)[T.product_mng]': 'Department: Product_Management',\n 'C(sales)[T.sales]': 'Department: Sales', 'C(sales)[T.support]':\n 'Department: Support', 'C(sales)[T.technical]': 'Department: Technical',\n 'C(salary)[T.low]': 'Salary: Low', 'C(salary)[T.medium]': 'Salary: Medium'}\n )\ny = np.ravel(y)\nmodel = LogisticRegression()\nmodel.fit(X, y)\npd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))\nprint(model.score(X, y))\nmodel.predict_proba([[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.7, 4.0, \n 160, 3.0, 0, 0]])\npred = model.predict(X)\nabs(pred - y).sum() / len(y)\nXtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.3,\n random_state=0)\nmodel2 = LogisticRegression(C=10000)\nmodel2.fit(Xtrain, ytrain)\npred = model2.predict(Xtest)\nprint(metrics.accuracy_score(ytest, pred))\nprint(metrics.confusion_matrix(ytest, pred))\nprint(metrics.classification_report(ytest, pred))\nprint(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10\n ).mean())\nprint(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy',\n cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy',\n cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy',\n cv=10).mean())\n",
"step-5": "#!/usr/bin/env python\n# coding: utf-8\n# HR Employee Retension Rate, predicting an employee likely to leave or not.\n# In[ ]:\nimport numpy as np # 数组常用库\nimport pandas as pd # 读入csv常用库\nfrom patsy import dmatrices # 可根据离散变量自动生成哑变量\nfrom sklearn.linear_model import LogisticRegression # sk-learn库Logistic Regression模型\nfrom sklearn.model_selection import train_test_split, cross_val_score # sk-learn库训练与测试\nfrom sklearn import metrics # 生成各项测试指标库\nimport matplotlib.pyplot as plt # 画图常用库\n\n# In[ ]:\n# 从../input/HR_comma_sep.csv文件中读入数据\ndata = pd.read_csv(\"hr_employee_retension/HR_comma_sep.csv\")\ndata\n\n# In[ ]:\ndata.describe()\ndata.dtypes\n# 观察离职人数与工资分布的关系\n\n# In[ ]:\n# 观察离职比例与工资分布的关系\npd.crosstab(data.salary, data.left)\npd.crosstab(data.salary, data.left).plot(kind='bar')\nplt.show()\n\n# In[ ]:\nq = pd.crosstab(data.salary, data.left)\nprint(q)\nprint(q.sum(1))\nprint(q.div(q.sum(1), axis=0)) # axis=0 is to get which value in q.sum(1) to divide to.\nq.div(q.sum(1), axis = 0).plot(kind='bar', stacked = True)\nplt.show()\n\n# In[ ]:\n# 观察员工满意度的分布图(histogram)\ndata[data.left==0].satisfaction_level.hist()\nplt.show()\n\n# In[ ]:\ndata[data.left==1].satisfaction_level.hist()\nplt.show()\n\n\n# In[ ]:\n# dmatrices将数据中的离散变量变成哑变量,并指明用satisfaction_level, last_evaluation, ... 来预测left\n# 然后重命名列的名字\n# C(xxx) categorical feature\n# 'y~X' like R language\ny, X = dmatrices('left~satisfaction_level+last_evaluation+number_project+average_montly_hours+time_spend_company\\\n +Work_accident+promotion_last_5years+C(sales)+C(salary)', data, return_type='dataframe')\nX = X.rename(columns = {\n 'C(sales)[T.RandD]': 'Department: Random',\n 'C(sales)[T.accounting]': 'Department: Accounting',\n 'C(sales)[T.hr]': 'Department: HR',\n 'C(sales)[T.management]': 'Department: Management',\n 'C(sales)[T.marketing]': 'Department: Marketing',\n 'C(sales)[T.product_mng]': 'Department: Product_Management',\n 'C(sales)[T.sales]': 'Department: Sales',\n 'C(sales)[T.support]': 'Department: Support',\n 'C(sales)[T.technical]': 'Department: Technical',\n 'C(salary)[T.low]': 'Salary: Low',\n 'C(salary)[T.medium]': 'Salary: Medium'})\ny = np.ravel(y) #将y变成np的一维数组\n\n# In[ ]:\n# zip(a,b)可将a的每一个元素和b里对应位置的元素组成一对\n# 用X和y训练模型,然后输出X中每一项自变量对于y的影响\nmodel = LogisticRegression()\nmodel.fit(X, y)\npd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))\n\n# In[ ]:\n# model.score为准确率(0到1之间)\nprint(model.score(X,y))\n\n# In[ ]:\n#一个高工资HR,对公司满意度0.5, 上次评审0.7分,做过4个项目,每月平均工作160小时,在公司呆了3年,过去5年没有被晋升,没有工伤\nmodel.predict_proba([[1,0,0,1,0,0,0,0,0,0,0,0, 0.5, 0.7, 4.0, 160, 3.0, 0, 0]])\n\n# In[ ]:\npred = model.predict(X)\n(abs(pred-y)).sum() / len(y) # 錯誤率 不相等才是1\n\n# In[ ]:\n# 生成7:3的训练测试集\nXtrain, Xtest, ytrain, ytest=train_test_split(X, y, test_size=0.3, random_state=0)\n\nmodel2 = LogisticRegression(C=10000)\nmodel2.fit(Xtrain, ytrain)\npred = model2.predict(Xtest)\n\n# In[ ]:\n# 观察实际离职/未离职被预测成为离职/未离职的数目\nprint(metrics.accuracy_score(ytest, pred))\nprint(metrics.confusion_matrix(ytest, pred))\n# prediction\n#\n#\n#actual\n#\n#\n#\n# classification_report会输出每一类对应的precision, recall\nprint(metrics.classification_report(ytest, pred))\n\n# In[ ]:\n# 10份的交叉验证Cross Validation\nprint(cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=10), X, y, scoring='accuracy', cv=10).mean())\nprint(cross_val_score(LogisticRegression(C=1000), X, y, scoring='accuracy', cv=10).mean()) # best\nprint(cross_val_score(LogisticRegression(C=10000), X, y, scoring='accuracy', cv=10).mean())\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for eachfile in os.listdir(desktop_directory):
if os.path.isfile(desktop_directory + eachfile):
fileName, fileExtension = os.path.splitext(eachfile)
if all(fileExtension != e for e in exclude_these):
ext = fileExtension[1:]
if not os.path.exists(destination_folder + ext):
os.mkdir(destination_folder + ext)
os.rename(desktop_directory + eachfile, destination_folder +
ext + '/' + eachfile)
<|reserved_special_token_1|>
desktop_directory = '/home/vineeth/Desktop/'
destination_folder = '/home/vineeth/Documents/'
exclude_these = ['.desktop', '.exe', '.lnk']
<|reserved_special_token_0|>
for eachfile in os.listdir(desktop_directory):
if os.path.isfile(desktop_directory + eachfile):
fileName, fileExtension = os.path.splitext(eachfile)
if all(fileExtension != e for e in exclude_these):
ext = fileExtension[1:]
if not os.path.exists(destination_folder + ext):
os.mkdir(destination_folder + ext)
os.rename(desktop_directory + eachfile, destination_folder +
ext + '/' + eachfile)
<|reserved_special_token_1|>
desktop_directory = '/home/vineeth/Desktop/'
destination_folder = '/home/vineeth/Documents/'
exclude_these = ['.desktop', '.exe', '.lnk']
import os
for eachfile in os.listdir(desktop_directory):
if os.path.isfile(desktop_directory + eachfile):
fileName, fileExtension = os.path.splitext(eachfile)
if all(fileExtension != e for e in exclude_these):
ext = fileExtension[1:]
if not os.path.exists(destination_folder + ext):
os.mkdir(destination_folder + ext)
os.rename(desktop_directory + eachfile, destination_folder +
ext + '/' + eachfile)
<|reserved_special_token_1|>
#This program sorts the files on Desktop on the basis of file extension and move them in separate folders in Documents folder.
desktop_directory="/home/vineeth/Desktop/" #LINUX
destination_folder="/home/vineeth/Documents/" #LINUX
#desktop_directory="C:/Users/VINEETH/Desktop/" #Windows
#destination_folder="C:/Users/VINEETH/Documents/" #Windows
exclude_these = ['.desktop','.exe','.lnk']
import os
for eachfile in os.listdir(desktop_directory):
if os.path.isfile(desktop_directory+eachfile):
fileName, fileExtension = os.path.splitext(eachfile)
if(all(fileExtension!=e for e in exclude_these)):
ext=fileExtension[1:]
if not os.path.exists(destination_folder+ext):
os.mkdir(destination_folder+ext)
os.rename(desktop_directory+eachfile,destination_folder+ext+"/"+eachfile)
|
flexible
|
{
"blob_id": "805b64a7bd727a88081a6ead574fff9b1542070f",
"index": 2023,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor eachfile in os.listdir(desktop_directory):\n if os.path.isfile(desktop_directory + eachfile):\n fileName, fileExtension = os.path.splitext(eachfile)\n if all(fileExtension != e for e in exclude_these):\n ext = fileExtension[1:]\n if not os.path.exists(destination_folder + ext):\n os.mkdir(destination_folder + ext)\n os.rename(desktop_directory + eachfile, destination_folder +\n ext + '/' + eachfile)\n",
"step-3": "desktop_directory = '/home/vineeth/Desktop/'\ndestination_folder = '/home/vineeth/Documents/'\nexclude_these = ['.desktop', '.exe', '.lnk']\n<mask token>\nfor eachfile in os.listdir(desktop_directory):\n if os.path.isfile(desktop_directory + eachfile):\n fileName, fileExtension = os.path.splitext(eachfile)\n if all(fileExtension != e for e in exclude_these):\n ext = fileExtension[1:]\n if not os.path.exists(destination_folder + ext):\n os.mkdir(destination_folder + ext)\n os.rename(desktop_directory + eachfile, destination_folder +\n ext + '/' + eachfile)\n",
"step-4": "desktop_directory = '/home/vineeth/Desktop/'\ndestination_folder = '/home/vineeth/Documents/'\nexclude_these = ['.desktop', '.exe', '.lnk']\nimport os\nfor eachfile in os.listdir(desktop_directory):\n if os.path.isfile(desktop_directory + eachfile):\n fileName, fileExtension = os.path.splitext(eachfile)\n if all(fileExtension != e for e in exclude_these):\n ext = fileExtension[1:]\n if not os.path.exists(destination_folder + ext):\n os.mkdir(destination_folder + ext)\n os.rename(desktop_directory + eachfile, destination_folder +\n ext + '/' + eachfile)\n",
"step-5": "#This program sorts the files on Desktop on the basis of file extension and move them in separate folders in Documents folder.\n\ndesktop_directory=\"/home/vineeth/Desktop/\" #LINUX\ndestination_folder=\"/home/vineeth/Documents/\" #LINUX\n\n#desktop_directory=\"C:/Users/VINEETH/Desktop/\" #Windows\n#destination_folder=\"C:/Users/VINEETH/Documents/\" #Windows\n\nexclude_these = ['.desktop','.exe','.lnk']\nimport os\nfor eachfile in os.listdir(desktop_directory):\n if os.path.isfile(desktop_directory+eachfile):\n fileName, fileExtension = os.path.splitext(eachfile)\n if(all(fileExtension!=e for e in exclude_these)):\n ext=fileExtension[1:]\n if not os.path.exists(destination_folder+ext):\n os.mkdir(destination_folder+ext)\n os.rename(desktop_directory+eachfile,destination_folder+ext+\"/\"+eachfile)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class ModelInfo:
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class ModelInfo:
def __init__(self, name: str, path: str, filter: str):
self.name: str = name
self.path: str = path
self.filter: str = filter
|
flexible
|
{
"blob_id": "def089c2749444797ac3079809c082dacab08554",
"index": 1167,
"step-1": "<mask token>\n",
"step-2": "class ModelInfo:\n <mask token>\n",
"step-3": "class ModelInfo:\n\n def __init__(self, name: str, path: str, filter: str):\n self.name: str = name\n self.path: str = path\n self.filter: str = filter\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = '__all__'
<|reserved_special_token_1|>
from django import forms
from .models import BlogPost
class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = '__all__'
|
flexible
|
{
"blob_id": "c4624425f57211e583b5fbaec3943539ce6fea6f",
"index": 88,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass BlogPostForm(forms.ModelForm):\n\n\n class Meta:\n model = BlogPost\n fields = '__all__'\n",
"step-3": "from django import forms\nfrom .models import BlogPost\n\n\nclass BlogPostForm(forms.ModelForm):\n\n\n class Meta:\n model = BlogPost\n fields = '__all__'\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
import azure.functions as func
import json
from ..common import cosmos_client
def main(req: func.HttpRequest) -> func.HttpResponse:
return func.HttpResponse(
body = json.dumps(cosmos_client.DB.Goals),
mimetype="application/json",
charset="utf-8"
)
# [
# {'amount':1000, 'description': 'foo bar baz prize'},
# {'amount':2000, 'description': 'foo bar baz prize'}
# ]
|
normal
|
{
"blob_id": "e38be2890526c640ba8d9db5a376ff57ba9e0aa2",
"index": 8703,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main(req: func.HttpRequest) ->func.HttpResponse:\n return func.HttpResponse(body=json.dumps(cosmos_client.DB.Goals),\n mimetype='application/json', charset='utf-8')\n",
"step-3": "import azure.functions as func\nimport json\nfrom ..common import cosmos_client\n\n\ndef main(req: func.HttpRequest) ->func.HttpResponse:\n return func.HttpResponse(body=json.dumps(cosmos_client.DB.Goals),\n mimetype='application/json', charset='utf-8')\n",
"step-4": "import azure.functions as func\nimport json\nfrom ..common import cosmos_client\n\ndef main(req: func.HttpRequest) -> func.HttpResponse:\n \n return func.HttpResponse(\n body = json.dumps(cosmos_client.DB.Goals),\n mimetype=\"application/json\",\n charset=\"utf-8\"\n )\n\n # [\n # {'amount':1000, 'description': 'foo bar baz prize'}, \n # {'amount':2000, 'description': 'foo bar baz prize'}\n # ]",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
class LogisticRegression:
'''LogisticRegression for binary classification
max_iter: the maximum iteration times for training
learning_rate: learing rate for gradiend decsend training
Input's shape should be [sample_nums, data_dims]
attrs:
max_iter
learning_rate
(after fit)
w
b
costs
methods:
fit
predict
predict_proba
score
'''
def __init__(self, max_iter=2000, learning_rate=0.01):
self.max_iter = max_iter
self.learning_rate = learning_rate
print('LogisticRegression Model(learning_rate={}, max_iteration={})'.format(
self.learning_rate, self.max_iter))
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def initialize_with_zeros(self, dim):
w = np.zeros((dim, 1))
b = 0
assert (w.shape == (dim, 1))
assert (isinstance(b, float) or isinstance(b, int))
return w, b
def propagate(self, w, b, X, Y):
m = X.shape[0]
A = self.sigmoid(np.dot(X, w) + b)
cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
dw = 1 / m * np.dot(X.T, A - Y)
db = 1 / m * np.sum(A - Y)
assert (dw.shape == w.shape)
assert (db.dtype == float)
cost = np.squeeze(cost)
assert (cost.shape == ())
grads = {'dw': dw,
'db': db}
return grads, cost
def optimize(self, w, b, X, Y, max_iter, learning_rate, print_cost=False):
costs = []
for i in range(1, max_iter+1):
grads, cost = self.propagate(w, b, X, Y)
w -= learning_rate * grads['dw']
b -= learning_rate * grads['db']
if i % 100 == 0:
costs.append(cost)
if print_cost:
print('Cost after iteration %i: %f'%(i, cost))
return w, b, costs
def fit(self, X, Y, print_cost=False):
print('Fit starting:')
w, b = self.initialize_with_zeros(X.shape[1])
iter_time = 0
self.w, self.b, self.costs = self.optimize(w, b, X, Y, self.max_iter, self.learning_rate, print_cost)
print('Fit complished!')
def predict_proba(self, X):
return self.sigmoid(np.dot(X, self.w) + self.b)
def predict(self, X):
proba = self.predict_proba(X)
pre = np.zeros_like(proba, dtype=np.int)
pre[proba > 0.5] = 1
pre = np.squeeze(pre)
return pre
def score(self, X_test, Y_test):
Y_pre = self.predict(X_test)
score = np.sum(Y_pre == Y_test) / len(Y_pre)
return score
def __str__(self):
return 'LogisticRegression Model(learning_rate={}, max_iteration={})'.format(
self.learning_rate, self.max_iter)
if __name__ == '__main__':
from sklearn import datasets
from sklearn.model_selection import train_test_split
data = datasets.load_iris()
x = data.data[:100, [0,1]]
# x = np.hstack([np.ones((100, 1)), x])
y = np.array([1 if i > 0 else 0 for i in data.target[:100]])
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)
model = LogisticRegression()
model.fit(x_train, y_train.reshape(len(y_train), -1), True)
print('Train Score:{}'.format(model.score(x_train, y_train)))
print('Test Score:{}'.format(model.score(x_test, y_test)))
plt.subplot(211)
x_samples = np.linspace(4, 7, 500)
y_samples = (- model.b - model.w[0]*x_samples) / model.w[1]
plt.plot(x_samples, y_samples, 'r')
plt.scatter(x[:50, 0], x[:50, 1], label='negative')
plt.scatter(x[50:100, 0], x[50:100, 1], label='positive')
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.title('LosRes Results on iris datasets')
plt.legend()
plt.subplots_adjust(hspace=0.5,wspace=0.25)
plt.subplot(212)
plt.plot(range(len(model.costs)), model.costs, '-o')
plt.xlabel('steps')
plt.ylabel('loss')
plt.title('loss function')
plt.show()
|
normal
|
{
"blob_id": "1dd62264aafe8ee745a3cfdfb994ac6a40c1af42",
"index": 1848,
"step-1": "<mask token>\n\n\nclass LogisticRegression:\n <mask token>\n\n def __init__(self, max_iter=2000, learning_rate=0.01):\n self.max_iter = max_iter\n self.learning_rate = learning_rate\n print('LogisticRegression Model(learning_rate={}, max_iteration={})'\n .format(self.learning_rate, self.max_iter))\n <mask token>\n\n def initialize_with_zeros(self, dim):\n w = np.zeros((dim, 1))\n b = 0\n assert w.shape == (dim, 1)\n assert isinstance(b, float) or isinstance(b, int)\n return w, b\n\n def propagate(self, w, b, X, Y):\n m = X.shape[0]\n A = self.sigmoid(np.dot(X, w) + b)\n cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))\n dw = 1 / m * np.dot(X.T, A - Y)\n db = 1 / m * np.sum(A - Y)\n assert dw.shape == w.shape\n assert db.dtype == float\n cost = np.squeeze(cost)\n assert cost.shape == ()\n grads = {'dw': dw, 'db': db}\n return grads, cost\n\n def optimize(self, w, b, X, Y, max_iter, learning_rate, print_cost=False):\n costs = []\n for i in range(1, max_iter + 1):\n grads, cost = self.propagate(w, b, X, Y)\n w -= learning_rate * grads['dw']\n b -= learning_rate * grads['db']\n if i % 100 == 0:\n costs.append(cost)\n if print_cost:\n print('Cost after iteration %i: %f' % (i, cost))\n return w, b, costs\n <mask token>\n\n def predict_proba(self, X):\n return self.sigmoid(np.dot(X, self.w) + self.b)\n\n def predict(self, X):\n proba = self.predict_proba(X)\n pre = np.zeros_like(proba, dtype=np.int)\n pre[proba > 0.5] = 1\n pre = np.squeeze(pre)\n return pre\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass LogisticRegression:\n <mask token>\n\n def __init__(self, max_iter=2000, learning_rate=0.01):\n self.max_iter = max_iter\n self.learning_rate = learning_rate\n print('LogisticRegression Model(learning_rate={}, max_iteration={})'\n .format(self.learning_rate, self.max_iter))\n\n def sigmoid(self, z):\n return 1 / (1 + np.exp(-z))\n\n def initialize_with_zeros(self, dim):\n w = np.zeros((dim, 1))\n b = 0\n assert w.shape == (dim, 1)\n assert isinstance(b, float) or isinstance(b, int)\n return w, b\n\n def propagate(self, w, b, X, Y):\n m = X.shape[0]\n A = self.sigmoid(np.dot(X, w) + b)\n cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))\n dw = 1 / m * np.dot(X.T, A - Y)\n db = 1 / m * np.sum(A - Y)\n assert dw.shape == w.shape\n assert db.dtype == float\n cost = np.squeeze(cost)\n assert cost.shape == ()\n grads = {'dw': dw, 'db': db}\n return grads, cost\n\n def optimize(self, w, b, X, Y, max_iter, learning_rate, print_cost=False):\n costs = []\n for i in range(1, max_iter + 1):\n grads, cost = self.propagate(w, b, X, Y)\n w -= learning_rate * grads['dw']\n b -= learning_rate * grads['db']\n if i % 100 == 0:\n costs.append(cost)\n if print_cost:\n print('Cost after iteration %i: %f' % (i, cost))\n return w, b, costs\n\n def fit(self, X, Y, print_cost=False):\n print('Fit starting:')\n w, b = self.initialize_with_zeros(X.shape[1])\n iter_time = 0\n self.w, self.b, self.costs = self.optimize(w, b, X, Y, self.\n max_iter, self.learning_rate, print_cost)\n print('Fit complished!')\n\n def predict_proba(self, X):\n return self.sigmoid(np.dot(X, self.w) + self.b)\n\n def predict(self, X):\n proba = self.predict_proba(X)\n pre = np.zeros_like(proba, dtype=np.int)\n pre[proba > 0.5] = 1\n pre = np.squeeze(pre)\n return pre\n\n def score(self, X_test, Y_test):\n Y_pre = self.predict(X_test)\n score = np.sum(Y_pre == Y_test) / len(Y_pre)\n return score\n\n def __str__(self):\n return ('LogisticRegression Model(learning_rate={}, max_iteration={})'\n .format(self.learning_rate, self.max_iter))\n\n\n<mask token>\n",
"step-3": "<mask token>\nmatplotlib.use('TkAgg')\n<mask token>\n\n\nclass LogisticRegression:\n \"\"\"LogisticRegression for binary classification\n \n max_iter: the maximum iteration times for training\n learning_rate: learing rate for gradiend decsend training\n\n Input's shape should be [sample_nums, data_dims]\n\n attrs:\n max_iter\n learning_rate\n (after fit)\n w\n b\n costs\n\n methods:\n fit\n predict\n predict_proba\n score \n \"\"\"\n\n def __init__(self, max_iter=2000, learning_rate=0.01):\n self.max_iter = max_iter\n self.learning_rate = learning_rate\n print('LogisticRegression Model(learning_rate={}, max_iteration={})'\n .format(self.learning_rate, self.max_iter))\n\n def sigmoid(self, z):\n return 1 / (1 + np.exp(-z))\n\n def initialize_with_zeros(self, dim):\n w = np.zeros((dim, 1))\n b = 0\n assert w.shape == (dim, 1)\n assert isinstance(b, float) or isinstance(b, int)\n return w, b\n\n def propagate(self, w, b, X, Y):\n m = X.shape[0]\n A = self.sigmoid(np.dot(X, w) + b)\n cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))\n dw = 1 / m * np.dot(X.T, A - Y)\n db = 1 / m * np.sum(A - Y)\n assert dw.shape == w.shape\n assert db.dtype == float\n cost = np.squeeze(cost)\n assert cost.shape == ()\n grads = {'dw': dw, 'db': db}\n return grads, cost\n\n def optimize(self, w, b, X, Y, max_iter, learning_rate, print_cost=False):\n costs = []\n for i in range(1, max_iter + 1):\n grads, cost = self.propagate(w, b, X, Y)\n w -= learning_rate * grads['dw']\n b -= learning_rate * grads['db']\n if i % 100 == 0:\n costs.append(cost)\n if print_cost:\n print('Cost after iteration %i: %f' % (i, cost))\n return w, b, costs\n\n def fit(self, X, Y, print_cost=False):\n print('Fit starting:')\n w, b = self.initialize_with_zeros(X.shape[1])\n iter_time = 0\n self.w, self.b, self.costs = self.optimize(w, b, X, Y, self.\n max_iter, self.learning_rate, print_cost)\n print('Fit complished!')\n\n def predict_proba(self, X):\n return self.sigmoid(np.dot(X, self.w) + self.b)\n\n def predict(self, X):\n proba = self.predict_proba(X)\n pre = np.zeros_like(proba, dtype=np.int)\n pre[proba > 0.5] = 1\n pre = np.squeeze(pre)\n return pre\n\n def score(self, X_test, Y_test):\n Y_pre = self.predict(X_test)\n score = np.sum(Y_pre == Y_test) / len(Y_pre)\n return score\n\n def __str__(self):\n return ('LogisticRegression Model(learning_rate={}, max_iteration={})'\n .format(self.learning_rate, self.max_iter))\n\n\nif __name__ == '__main__':\n from sklearn import datasets\n from sklearn.model_selection import train_test_split\n data = datasets.load_iris()\n x = data.data[:100, [0, 1]]\n y = np.array([(1 if i > 0 else 0) for i in data.target[:100]])\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)\n model = LogisticRegression()\n model.fit(x_train, y_train.reshape(len(y_train), -1), True)\n print('Train Score:{}'.format(model.score(x_train, y_train)))\n print('Test Score:{}'.format(model.score(x_test, y_test)))\n plt.subplot(211)\n x_samples = np.linspace(4, 7, 500)\n y_samples = (-model.b - model.w[0] * x_samples) / model.w[1]\n plt.plot(x_samples, y_samples, 'r')\n plt.scatter(x[:50, 0], x[:50, 1], label='negative')\n plt.scatter(x[50:100, 0], x[50:100, 1], label='positive')\n plt.xlabel('petal length')\n plt.ylabel('petal width')\n plt.title('LosRes Results on iris datasets')\n plt.legend()\n plt.subplots_adjust(hspace=0.5, wspace=0.25)\n plt.subplot(212)\n plt.plot(range(len(model.costs)), model.costs, '-o')\n plt.xlabel('steps')\n plt.ylabel('loss')\n plt.title('loss function')\n plt.show()\n",
"step-4": "import numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\n\nclass LogisticRegression:\n \"\"\"LogisticRegression for binary classification\n \n max_iter: the maximum iteration times for training\n learning_rate: learing rate for gradiend decsend training\n\n Input's shape should be [sample_nums, data_dims]\n\n attrs:\n max_iter\n learning_rate\n (after fit)\n w\n b\n costs\n\n methods:\n fit\n predict\n predict_proba\n score \n \"\"\"\n\n def __init__(self, max_iter=2000, learning_rate=0.01):\n self.max_iter = max_iter\n self.learning_rate = learning_rate\n print('LogisticRegression Model(learning_rate={}, max_iteration={})'\n .format(self.learning_rate, self.max_iter))\n\n def sigmoid(self, z):\n return 1 / (1 + np.exp(-z))\n\n def initialize_with_zeros(self, dim):\n w = np.zeros((dim, 1))\n b = 0\n assert w.shape == (dim, 1)\n assert isinstance(b, float) or isinstance(b, int)\n return w, b\n\n def propagate(self, w, b, X, Y):\n m = X.shape[0]\n A = self.sigmoid(np.dot(X, w) + b)\n cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))\n dw = 1 / m * np.dot(X.T, A - Y)\n db = 1 / m * np.sum(A - Y)\n assert dw.shape == w.shape\n assert db.dtype == float\n cost = np.squeeze(cost)\n assert cost.shape == ()\n grads = {'dw': dw, 'db': db}\n return grads, cost\n\n def optimize(self, w, b, X, Y, max_iter, learning_rate, print_cost=False):\n costs = []\n for i in range(1, max_iter + 1):\n grads, cost = self.propagate(w, b, X, Y)\n w -= learning_rate * grads['dw']\n b -= learning_rate * grads['db']\n if i % 100 == 0:\n costs.append(cost)\n if print_cost:\n print('Cost after iteration %i: %f' % (i, cost))\n return w, b, costs\n\n def fit(self, X, Y, print_cost=False):\n print('Fit starting:')\n w, b = self.initialize_with_zeros(X.shape[1])\n iter_time = 0\n self.w, self.b, self.costs = self.optimize(w, b, X, Y, self.\n max_iter, self.learning_rate, print_cost)\n print('Fit complished!')\n\n def predict_proba(self, X):\n return self.sigmoid(np.dot(X, self.w) + self.b)\n\n def predict(self, X):\n proba = self.predict_proba(X)\n pre = np.zeros_like(proba, dtype=np.int)\n pre[proba > 0.5] = 1\n pre = np.squeeze(pre)\n return pre\n\n def score(self, X_test, Y_test):\n Y_pre = self.predict(X_test)\n score = np.sum(Y_pre == Y_test) / len(Y_pre)\n return score\n\n def __str__(self):\n return ('LogisticRegression Model(learning_rate={}, max_iteration={})'\n .format(self.learning_rate, self.max_iter))\n\n\nif __name__ == '__main__':\n from sklearn import datasets\n from sklearn.model_selection import train_test_split\n data = datasets.load_iris()\n x = data.data[:100, [0, 1]]\n y = np.array([(1 if i > 0 else 0) for i in data.target[:100]])\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)\n model = LogisticRegression()\n model.fit(x_train, y_train.reshape(len(y_train), -1), True)\n print('Train Score:{}'.format(model.score(x_train, y_train)))\n print('Test Score:{}'.format(model.score(x_test, y_test)))\n plt.subplot(211)\n x_samples = np.linspace(4, 7, 500)\n y_samples = (-model.b - model.w[0] * x_samples) / model.w[1]\n plt.plot(x_samples, y_samples, 'r')\n plt.scatter(x[:50, 0], x[:50, 1], label='negative')\n plt.scatter(x[50:100, 0], x[50:100, 1], label='positive')\n plt.xlabel('petal length')\n plt.ylabel('petal width')\n plt.title('LosRes Results on iris datasets')\n plt.legend()\n plt.subplots_adjust(hspace=0.5, wspace=0.25)\n plt.subplot(212)\n plt.plot(range(len(model.costs)), model.costs, '-o')\n plt.xlabel('steps')\n plt.ylabel('loss')\n plt.title('loss function')\n plt.show()\n",
"step-5": "import numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\n\n\nclass LogisticRegression:\n '''LogisticRegression for binary classification\n \n max_iter: the maximum iteration times for training\n learning_rate: learing rate for gradiend decsend training\n\n Input's shape should be [sample_nums, data_dims]\n\n attrs:\n max_iter\n learning_rate\n (after fit)\n w\n b\n costs\n\n methods:\n fit\n predict\n predict_proba\n score \n '''\n\n def __init__(self, max_iter=2000, learning_rate=0.01):\n self.max_iter = max_iter\n self.learning_rate = learning_rate\n print('LogisticRegression Model(learning_rate={}, max_iteration={})'.format(\n self.learning_rate, self.max_iter))\n\n\n def sigmoid(self, z):\n return 1 / (1 + np.exp(-z))\n\n\n def initialize_with_zeros(self, dim):\n w = np.zeros((dim, 1))\n b = 0\n\n assert (w.shape == (dim, 1))\n assert (isinstance(b, float) or isinstance(b, int))\n\n return w, b \n\n\n def propagate(self, w, b, X, Y):\n m = X.shape[0]\n A = self.sigmoid(np.dot(X, w) + b)\n cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))\n\n dw = 1 / m * np.dot(X.T, A - Y)\n db = 1 / m * np.sum(A - Y) \n\n assert (dw.shape == w.shape)\n assert (db.dtype == float)\n cost = np.squeeze(cost)\n assert (cost.shape == ())\n grads = {'dw': dw,\n 'db': db}\n\n return grads, cost\n\n\n def optimize(self, w, b, X, Y, max_iter, learning_rate, print_cost=False):\n costs = []\n for i in range(1, max_iter+1):\n grads, cost = self.propagate(w, b, X, Y)\n w -= learning_rate * grads['dw']\n b -= learning_rate * grads['db']\n\n if i % 100 == 0:\n costs.append(cost)\n if print_cost:\n print('Cost after iteration %i: %f'%(i, cost))\n return w, b, costs\n\n\n def fit(self, X, Y, print_cost=False):\n print('Fit starting:')\n w, b = self.initialize_with_zeros(X.shape[1])\n iter_time = 0\n\n self.w, self.b, self.costs = self.optimize(w, b, X, Y, self.max_iter, self.learning_rate, print_cost)\n print('Fit complished!')\n\n\n def predict_proba(self, X):\n return self.sigmoid(np.dot(X, self.w) + self.b)\n\n\n def predict(self, X):\n proba = self.predict_proba(X)\n pre = np.zeros_like(proba, dtype=np.int)\n pre[proba > 0.5] = 1\n pre = np.squeeze(pre)\n return pre\n\n\n def score(self, X_test, Y_test):\n Y_pre = self.predict(X_test)\n score = np.sum(Y_pre == Y_test) / len(Y_pre)\n return score\n\n\n def __str__(self):\n return 'LogisticRegression Model(learning_rate={}, max_iteration={})'.format(\n self.learning_rate, self.max_iter)\n\n\nif __name__ == '__main__':\n from sklearn import datasets\n from sklearn.model_selection import train_test_split\n data = datasets.load_iris()\n x = data.data[:100, [0,1]]\n # x = np.hstack([np.ones((100, 1)), x])\n y = np.array([1 if i > 0 else 0 for i in data.target[:100]])\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)\n\n model = LogisticRegression()\n model.fit(x_train, y_train.reshape(len(y_train), -1), True)\n print('Train Score:{}'.format(model.score(x_train, y_train)))\n print('Test Score:{}'.format(model.score(x_test, y_test)))\n\n plt.subplot(211)\n x_samples = np.linspace(4, 7, 500)\n y_samples = (- model.b - model.w[0]*x_samples) / model.w[1]\n plt.plot(x_samples, y_samples, 'r')\n plt.scatter(x[:50, 0], x[:50, 1], label='negative')\n plt.scatter(x[50:100, 0], x[50:100, 1], label='positive')\n plt.xlabel('petal length')\n plt.ylabel('petal width')\n plt.title('LosRes Results on iris datasets')\n plt.legend()\n \n plt.subplots_adjust(hspace=0.5,wspace=0.25)\n plt.subplot(212)\n plt.plot(range(len(model.costs)), model.costs, '-o')\n plt.xlabel('steps')\n plt.ylabel('loss')\n plt.title('loss function')\n plt.show()",
"step-ids": [
7,
11,
13,
14,
15
]
}
|
[
7,
11,
13,
14,
15
] |
#!/usr/bin/env python3
import json
import sys
import time
import zmq
log_file = "./mavlink-log.txt"
zmq_context = zmq.Context()
connect_to = sys.argv[1]
send_socket = zmq_context.socket(zmq.PUSH)
send_socket.connect(connect_to)
def get_first_timestamp(log_file):
with open(log_file) as f:
for line in f:
line_json = json.loads(line)
return line_json["timestamp"]
start_time_file = get_first_timestamp(log_file)
start_time_importer = time.time()
with open(log_file) as f:
for line in f:
line_json = json.loads(line)
importer_age = time.time() - start_time_importer
line_age = line_json["timestamp"] - start_time_file
sleep_time = line_age - importer_age
if sleep_time > 0:
#print(str(line_age)+" - "+str(importer_age))
#print(sleep_time)
time.sleep(sleep_time)
print(line_json)
send_socket.send_json(line_json)
|
normal
|
{
"blob_id": "49679782ac696b3dc4f5038565f88304a44098e1",
"index": 6188,
"step-1": "<mask token>\n\n\ndef get_first_timestamp(log_file):\n with open(log_file) as f:\n for line in f:\n line_json = json.loads(line)\n return line_json['timestamp']\n\n\n<mask token>\n",
"step-2": "<mask token>\nsend_socket.connect(connect_to)\n\n\ndef get_first_timestamp(log_file):\n with open(log_file) as f:\n for line in f:\n line_json = json.loads(line)\n return line_json['timestamp']\n\n\n<mask token>\nwith open(log_file) as f:\n for line in f:\n line_json = json.loads(line)\n importer_age = time.time() - start_time_importer\n line_age = line_json['timestamp'] - start_time_file\n sleep_time = line_age - importer_age\n if sleep_time > 0:\n time.sleep(sleep_time)\n print(line_json)\n send_socket.send_json(line_json)\n",
"step-3": "<mask token>\nlog_file = './mavlink-log.txt'\nzmq_context = zmq.Context()\nconnect_to = sys.argv[1]\nsend_socket = zmq_context.socket(zmq.PUSH)\nsend_socket.connect(connect_to)\n\n\ndef get_first_timestamp(log_file):\n with open(log_file) as f:\n for line in f:\n line_json = json.loads(line)\n return line_json['timestamp']\n\n\nstart_time_file = get_first_timestamp(log_file)\nstart_time_importer = time.time()\nwith open(log_file) as f:\n for line in f:\n line_json = json.loads(line)\n importer_age = time.time() - start_time_importer\n line_age = line_json['timestamp'] - start_time_file\n sleep_time = line_age - importer_age\n if sleep_time > 0:\n time.sleep(sleep_time)\n print(line_json)\n send_socket.send_json(line_json)\n",
"step-4": "import json\nimport sys\nimport time\nimport zmq\nlog_file = './mavlink-log.txt'\nzmq_context = zmq.Context()\nconnect_to = sys.argv[1]\nsend_socket = zmq_context.socket(zmq.PUSH)\nsend_socket.connect(connect_to)\n\n\ndef get_first_timestamp(log_file):\n with open(log_file) as f:\n for line in f:\n line_json = json.loads(line)\n return line_json['timestamp']\n\n\nstart_time_file = get_first_timestamp(log_file)\nstart_time_importer = time.time()\nwith open(log_file) as f:\n for line in f:\n line_json = json.loads(line)\n importer_age = time.time() - start_time_importer\n line_age = line_json['timestamp'] - start_time_file\n sleep_time = line_age - importer_age\n if sleep_time > 0:\n time.sleep(sleep_time)\n print(line_json)\n send_socket.send_json(line_json)\n",
"step-5": "#!/usr/bin/env python3\n\nimport json\nimport sys\nimport time\nimport zmq\n\nlog_file = \"./mavlink-log.txt\"\n\nzmq_context = zmq.Context()\n\nconnect_to = sys.argv[1]\nsend_socket = zmq_context.socket(zmq.PUSH)\nsend_socket.connect(connect_to)\n\ndef get_first_timestamp(log_file):\n\twith open(log_file) as f:\n\t\tfor line in f:\n\t\t\tline_json = json.loads(line)\n\t\t\treturn line_json[\"timestamp\"]\n\n\n\nstart_time_file = get_first_timestamp(log_file)\nstart_time_importer = time.time()\n\nwith open(log_file) as f:\n\tfor line in f:\n\t\tline_json = json.loads(line)\n\n\t\timporter_age = time.time() - start_time_importer\n\t\tline_age = line_json[\"timestamp\"] - start_time_file\n\n\t\tsleep_time = line_age - importer_age\n\n\t\tif sleep_time > 0:\n\t\t\t#print(str(line_age)+\" - \"+str(importer_age))\n\t\t\t#print(sleep_time)\n\t\t\ttime.sleep(sleep_time)\n\n\n\t\tprint(line_json)\n\t\tsend_socket.send_json(line_json)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for _k, _v in _lr_action_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_action:
_lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
<|reserved_special_token_0|>
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto:
_lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
<|reserved_special_token_0|>
<|reserved_special_token_1|>
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = """AND BREAK CHAR COLON COMA CTE_F CTE_I CTE_STRING DETERMINANT DIFFERENT DIVIDE DO DOUBLEEQUAL ELSE EQUAL FLOAT FROM FUNCTION ID IF INPUT INT INVERSA LBRACE LCORCH LOWEREQUAL LOWERTHAN LPAREN MAIN MINUS MOREEQUAL MORETHAN OR PLUS PRINT PROGRAM RBRACE RCORCH RETURN RPAREN SEMICOLON TIMES TO TRANSPUESTA VAR VOID WHILEprogram : PROGRAM ID COLON varsGlobal function main endPrograma
| PROGRAM ID COLON function main endPrograma
| PROGRAM ID COLON varsGlobal main endPrograma
| PROGRAM ID COLON main endPrograma
endPrograma :varsGlobal : VAR varAuxGlobal1
varAuxGlobal1 : tipo varAuxGlobal2 SEMICOLON
| tipo varAuxGlobal2 SEMICOLON varAuxGlobal1
varAuxGlobal2 : ID
| ID COMA varAuxGlobal2
| ID LCORCH CTE_I RCORCH
| ID LCORCH CTE_I RCORCH COMA varAuxGlobal2
| ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH
| ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2
main : nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE
| nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE
| nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE
nomMain : MAIN
vars : VAR varAux1
varAux1 : tipo varAux2 SEMICOLON
| tipo varAux2 SEMICOLON varAux1
varAux2 : ID push_var
| ID push_var COMA varAux2
| ID LCORCH CTE_I RCORCH push_arreglo
| ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2
| ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz
| ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2
push_var :push_arreglo :push_matriz :tipo : INT
| FLOAT
| CHAR
tipoFunc : INT
| FLOAT
| CHAR
| VOID
bloque : LBRACE RBRACE
| LBRACE bloqueAux RBRACE
function : FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc
| FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc
| FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function
| FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function
| FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc
| FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function
| FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc
| FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc
| FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function
| FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc
| FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function
| FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function
functionReturn : RETURN exp creaCuadReturn SEMICOLON
| empty
creaCuadReturn :
endProc :
param : tipo ID paramAvarTable
| tipo ID paramAvarTable COMA param
| empty
paramAvarTable : empty :
push_function :nomFunc : ID push_function
bloqueAux : estatuto
| estatuto bloqueAux
while : WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3
while1 :while2 :while3 :loopFromDo : FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE
estatuto : asignacion
| condicion
| escritura
| while
| loopFromDo
| comparacion
| llamadaAFuncion SEMICOLON
| lectura
| BREAK generaCuadbreak SEMICOLON
| transpuesta
| inversa
transpuesta : ID push_id TRANSPUESTA creaTrans SEMICOLON
inversa : ID push_id INVERSA creaInversa SEMICOLON
creaInversa : creaTrans : generaCuadbreak : llamadaAFuncion : ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion
| ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN
actualizaFuncion : gosub :
generarEra :
paramFuncion : ID push_id2 paramFuncionAux
| ID push_id2 paramFuncionAux COMA paramFuncion
| exp paramFuncionAux
| exp paramFuncionAux COMA paramFuncion
| empty
paramFuncionAux : push_id2 :arreglo : ID push_id LCORCH exp RCORCH ver_dim1
matrix : ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2
ver_dim2 : asignacion : ID push_id EQUAL push_poper expresion create_asign SEMICOLON
| arreglo EQUAL push_poper exp create_asign SEMICOLON
| matrix EQUAL push_poper exp create_asign SEMICOLON
| ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON
| ID push_id EQUAL push_poper determinante SEMICOLON
determinante : ID push_id DETERMINANT
push_id_dimensionada :create_asign_dim :ver_dim1 :create_asign :comparacion : ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON
condicion : IF LPAREN expresion RPAREN cond bloque condFinal
| IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal
cond :condElse :condFinal :escritura : PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON
| PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON
lectura : INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON
quad_print :escrituraAux : expresion
| CTE_STRING push_cte
| expresion COMA escrituraAux
| CTE_STRING push_cte COMA escrituraAux
| llamadaAFuncion
expresion : exp
| exp comp exp quad_comp
comp : LOWERTHAN push_poper
| MORETHAN push_poper
| DIFFERENT push_poper
| DOUBLEEQUAL push_poper
| LOWEREQUAL push_poper
| MOREEQUAL push_poper
quad_comp :exp : termino quad_term
| termino quad_term exp1
exp1 : PLUS push_poper exp
| MINUS push_poper exp
quad_term :quad_fact :termino : factor quad_fact
| factor quad_fact termino1
termino1 : TIMES push_poper termino
| DIVIDE push_poper termino
factor : LPAREN expresion RPAREN
| factorAux
factorAux : PLUS push_poper var_cte
| MINUS push_poper var_cte
| var_cte
push_id :push_cte :push_poper :var_cte : ID push_id
| CTE_I push_cte
| CTE_F push_cte
| CTE_STRING push_cte
| arreglo
| matrix
"""
_lr_action_items = {'MOREEQUAL': ([106, 107, 108, 110, 112, 113, 114, 115,
117, 119, 120, 144, 146, 150, 153, 154, 155, 156, 158, 190, 195, 198,
199, 201, 203, 218, 219, 257, 258, 276, 277, 278, 279, 305, 315], [-149,
-157, -139, -158, -140, -151, -151, -151, -150, 160, -146, -151, -150,
-135, -141, -155, -156, -154, -153, -156, -136, -148, -147, -142, -145,
-109, -150, -98, -153, -137, -138, -144, -143, -100, -99]),
'CTE_STRING': ([78, 80, 82, 95, 103, 104, 105, 109, 111, 116, 124, 126,
127, 131, 151, 152, 160, 161, 162, 163, 164, 165, 166, 171, 174, 176,
177, 191, 196, 197, 200, 202, 205, 206, 207, 208, 210, 211, 239, 245,
246, 247, 248, 256, 291, 293, 307, 309], [-152, -152, 114, 114, 114,
144, 114, -152, -152, 114, -152, 114, -152, 114, 114, 114, -152, -152,
-152, -152, 114, -152, -152, 114, 114, 114, 114, 144, -152, -152, -152,
-152, -133, -130, -131, -128, -132, -129, 144, 114, 114, 114, 114, 114,
114, 114, 114, 114]), 'LCORCH': ([34, 57, 75, 86, 94, 117, 122, 146,
158, 218, 219, 226, 252, 258], [40, -150, -150, 126, 133, -150, 168, -
150, 126, 256, -150, -150, 284, 126]), 'RETURN': ([50, 52, 53, 54, 58,
61, 62, 66, 67, 68, 72, 81, 89, 99, 100, 132, 136, 141, 185, 217, 223,
238, 244, 250, 255, 261, 274, 275, 280, 282, 289, 290, 300, 304, 312,
318, 319, 322, 328], [-63, -77, -79, -71, -74, -70, -80, -73, -75, -72,
95, -64, -76, 95, 95, -78, 95, 95, 95, -82, -81, -102, -103, -116, -111,
-105, -117, -118, -38, -112, -101, -104, -39, -119, -116, -68, -113, -
65, -69]), 'DO': ([321], [324]), 'VOID': ([5], [13]), 'EQUAL': ([47, 49,
57, 75, 86, 130, 218, 257, 305, 315], [78, 80, -150, -150, 127, 177, -
109, -98, -100, -99]), 'CHAR': ([5, 10, 35, 39, 55, 142, 167], [15, 25,
25, 25, 25, 25, 25]), 'VAR': ([4, 37, 72, 100], [10, 55, 55, 55]),
'WHILE': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68, 72, 84, 89,
96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250, 255, 261,
274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319, 322, 326,
328], [63, 63, 63, -77, -79, -71, -74, -70, -80, -73, -75, -72, 63, -19,
-76, 63, 63, -78, 63, -20, -21, -82, -81, -102, -103, 63, -116, -111, -
105, -117, -118, -38, -112, -101, -104, 63, -39, -119, -116, -68, -113,
-65, 63, -69]), 'PROGRAM': ([0], [2]), 'PRINT': ([37, 46, 50, 52, 53,
54, 58, 61, 62, 66, 67, 68, 72, 84, 89, 96, 100, 132, 139, 167, 212,
217, 223, 238, 244, 249, 250, 255, 261, 274, 275, 280, 282, 289, 290,
295, 300, 304, 312, 318, 319, 322, 326, 328], [48, 48, 48, -77, -79, -
71, -74, -70, -80, -73, -75, -72, 48, -19, -76, 48, 48, -78, 48, -20, -
21, -82, -81, -102, -103, 48, -116, -111, -105, -117, -118, -38, -112,
-101, -104, 48, -39, -119, -116, -68, -113, -65, 48, -69]), 'MORETHAN':
([106, 107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 144, 146, 150,
153, 154, 155, 156, 158, 190, 195, 198, 199, 201, 203, 218, 219, 257,
258, 276, 277, 278, 279, 305, 315], [-149, -157, -139, -158, -140, -151,
-151, -151, -150, 166, -146, -151, -150, -135, -141, -155, -156, -154,
-153, -156, -136, -148, -147, -142, -145, -109, -150, -98, -153, -137,
-138, -144, -143, -100, -99]), 'MINUS': ([78, 80, 82, 95, 103, 104, 105,
106, 107, 108, 110, 112, 113, 114, 115, 116, 117, 120, 124, 126, 127,
131, 144, 146, 150, 153, 154, 155, 156, 158, 160, 161, 162, 163, 164,
165, 166, 171, 174, 176, 177, 190, 191, 196, 197, 198, 199, 200, 201,
202, 203, 205, 206, 207, 208, 210, 211, 218, 219, 226, 239, 245, 246,
247, 248, 256, 257, 258, 278, 279, 291, 293, 305, 307, 309, 315], [-152,
-152, 109, 109, 109, 109, 109, -149, -157, -139, -158, -140, -151, -151,
-151, 109, -150, -146, -152, 109, -152, 109, -151, -150, 197, -141, -
155, -156, -154, -153, -152, -152, -152, -152, 109, -152, -152, 109,
109, 109, 109, -156, 109, -152, -152, -148, -147, -152, -142, -152, -
145, -133, -130, -131, -128, -132, -129, -109, -150, -150, 109, 109,
109, 109, 109, 109, -98, -153, -144, -143, 109, 109, -100, 109, 109, -
99]), 'DIVIDE': ([106, 107, 110, 112, 113, 114, 115, 117, 120, 144, 146,
153, 154, 155, 156, 158, 190, 198, 199, 203, 218, 219, 226, 257, 258,
305, 315], [-149, -157, -158, -140, -151, -151, -151, -150, -146, -151,
-150, 200, -155, -156, -154, -153, -156, -148, -147, -145, -109, -150,
-150, -98, -153, -100, -99]), 'RCORCH': ([70, 106, 107, 108, 110, 112,
113, 114, 115, 117, 120, 150, 153, 154, 155, 156, 158, 173, 179, 195,
198, 199, 201, 203, 213, 218, 257, 276, 277, 278, 279, 287, 302, 305,
315], [94, -149, -157, -139, -158, -140, -151, -151, -151, -150, -146,
-135, -141, -155, -156, -154, -153, 218, 230, -136, -148, -147, -142, -
145, 252, -109, -98, -137, -138, -144, -143, 305, 313, -100, -99]),
'DETERMINANT': ([219, 258], [-150, 288]), 'RPAREN': ([17, 35, 43, 44,
74, 101, 106, 107, 108, 110, 112, 113, 114, 115, 117, 118, 119, 120,
142, 144, 145, 146, 147, 148, 150, 153, 154, 155, 156, 157, 158, 170,
176, 178, 188, 190, 195, 198, 199, 201, 203, 209, 215, 218, 224, 225,
226, 227, 228, 240, 241, 251, 257, 262, 263, 264, 273, 276, 277, 278,
279, 291, 292, 293, 305, 306, 307, 308, 315, 316, 317], [29, 42, 73, -
58, -59, -56, -149, -157, -139, -158, -140, -151, -151, -151, -150, 159,
-126, -146, -60, -151, -121, -150, 192, 193, -135, -141, -155, -156, -
154, 203, -153, -150, -60, 229, -57, -122, -136, -148, -147, -142, -145,
-134, 254, -109, -89, -95, -97, -96, 265, -123, -125, -127, -98, 291, -
96, -93, -124, -137, -138, -144, -143, -87, -91, -60, -100, -86, -60, -
94, -99, -92, 321]), 'SEMICOLON': ([33, 34, 59, 65, 71, 76, 93, 94, 106,
107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 121, 122, 125, 128,
135, 143, 149, 150, 153, 154, 155, 156, 158, 169, 172, 175, 180, 181,
189, 192, 193, 194, 195, 198, 199, 201, 203, 209, 216, 218, 219, 220,
221, 222, 230, 242, 243, 251, 252, 253, 254, 257, 258, 259, 260, 276,
277, 278, 279, 285, 286, 288, 291, 296, 305, 306, 313, 314, 315, 320,
325], [39, -9, 89, -85, -10, 89, 132, -11, -149, -157, -139, -158, -140,
-151, -151, -151, -150, -126, -146, 167, -28, -83, -84, -54, -110, -110,
-135, -141, -155, -156, -154, -153, -22, 217, 223, -12, 231, 238, -120,
-120, 244, -136, -148, -147, -142, -145, -134, 255, -109, -150, -110, -
110, 261, -13, 274, 275, -127, -29, -23, -120, -98, -153, 289, 290, -
137, -138, -144, -143, -24, 304, -106, -87, -14, -100, -86, -30, -25, -
99, -26, -27]), 'LOWERTHAN': ([106, 107, 108, 110, 112, 113, 114, 115,
117, 119, 120, 144, 146, 150, 153, 154, 155, 156, 158, 190, 195, 198,
199, 201, 203, 218, 219, 257, 258, 276, 277, 278, 279, 305, 315], [-149,
-157, -139, -158, -140, -151, -151, -151, -150, 163, -146, -151, -150,
-135, -141, -155, -156, -154, -153, -156, -136, -148, -147, -142, -145,
-109, -150, -98, -153, -137, -138, -144, -143, -100, -99]),
'LOWEREQUAL': ([106, 107, 108, 110, 112, 113, 114, 115, 117, 119, 120,
144, 146, 150, 153, 154, 155, 156, 158, 190, 195, 198, 199, 201, 203,
218, 219, 257, 258, 276, 277, 278, 279, 305, 315], [-149, -157, -139, -
158, -140, -151, -151, -151, -150, 165, -146, -151, -150, -135, -141, -
155, -156, -154, -153, -156, -136, -148, -147, -142, -145, -109, -150,
-98, -153, -137, -138, -144, -143, -100, -99]), 'TO': ([265], [294]),
'COLON': ([3], [4]), 'CTE_I': ([40, 78, 80, 82, 95, 103, 104, 105, 109,
111, 116, 124, 126, 127, 131, 133, 151, 152, 160, 161, 162, 163, 164,
165, 166, 168, 171, 174, 176, 177, 191, 196, 197, 200, 202, 205, 206,
207, 208, 210, 211, 239, 245, 246, 247, 248, 256, 284, 291, 293, 307,
309], [70, -152, -152, 115, 115, 115, 115, 115, -152, -152, 115, -152,
115, -152, 115, 179, 115, 115, -152, -152, -152, -152, 115, -152, -152,
213, 115, 115, 115, 115, 115, -152, -152, -152, -152, -133, -130, -131,
-128, -132, -129, 115, 115, 115, 115, 115, 115, 302, 115, 115, 115, 115
]), 'CTE_F': ([78, 80, 82, 95, 103, 104, 105, 109, 111, 116, 124, 126,
127, 131, 151, 152, 160, 161, 162, 163, 164, 165, 166, 171, 174, 176,
177, 191, 196, 197, 200, 202, 205, 206, 207, 208, 210, 211, 239, 245,
246, 247, 248, 256, 291, 293, 307, 309], [-152, -152, 113, 113, 113,
113, 113, -152, -152, 113, -152, 113, -152, 113, 113, 113, -152, -152,
-152, -152, 113, -152, -152, 113, 113, 113, 113, 113, -152, -152, -152,
-152, -133, -130, -131, -128, -132, -129, 113, 113, 113, 113, 113, 113,
113, 113, 113, 113]), 'PLUS': ([78, 80, 82, 95, 103, 104, 105, 106, 107,
108, 110, 112, 113, 114, 115, 116, 117, 120, 124, 126, 127, 131, 144,
146, 150, 153, 154, 155, 156, 158, 160, 161, 162, 163, 164, 165, 166,
171, 174, 176, 177, 190, 191, 196, 197, 198, 199, 200, 201, 202, 203,
205, 206, 207, 208, 210, 211, 218, 219, 226, 239, 245, 246, 247, 248,
256, 257, 258, 278, 279, 291, 293, 305, 307, 309, 315], [-152, -152,
111, 111, 111, 111, 111, -149, -157, -139, -158, -140, -151, -151, -151,
111, -150, -146, -152, 111, -152, 111, -151, -150, 196, -141, -155, -
156, -154, -153, -152, -152, -152, -152, 111, -152, -152, 111, 111, 111,
111, -156, 111, -152, -152, -148, -147, -152, -142, -152, -145, -133, -
130, -131, -128, -132, -129, -109, -150, -150, 111, 111, 111, 111, 111,
111, -98, -153, -144, -143, 111, 111, -100, 111, 111, -99]), '$end': ([
1, 8, 18, 20, 21, 30, 31, 32, 38, 88, 92, 102], [0, -5, -5, -4, -5, -3,
-5, -2, -1, -17, -15, -16]), 'FUNCTION': ([4, 7, 26, 39, 69, 137, 183,
184, 186, 232, 234, 236, 237, 268, 270, 272, 298], [5, 5, -6, -7, -8, -
55, 5, -55, -55, -55, 5, 5, -55, 5, -55, 5, 5]), 'DIFFERENT': ([106,
107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 144, 146, 150, 153,
154, 155, 156, 158, 190, 195, 198, 199, 201, 203, 218, 219, 257, 258,
276, 277, 278, 279, 305, 315], [-149, -157, -139, -158, -140, -151, -
151, -151, -150, 161, -146, -151, -150, -135, -141, -155, -156, -154, -
153, -156, -136, -148, -147, -142, -145, -109, -150, -98, -153, -137, -
138, -144, -143, -100, -99]), 'RBRACE': ([50, 52, 53, 54, 58, 59, 61,
62, 64, 66, 67, 68, 72, 77, 81, 89, 97, 98, 99, 100, 106, 107, 108, 110,
112, 113, 114, 115, 117, 119, 120, 132, 136, 138, 140, 141, 150, 153,
154, 155, 156, 158, 182, 185, 187, 195, 198, 199, 201, 203, 209, 217,
218, 223, 231, 235, 238, 244, 249, 250, 251, 255, 257, 261, 274, 275,
276, 277, 278, 279, 280, 281, 282, 289, 290, 291, 300, 304, 305, 306,
310, 312, 315, 318, 319, 322, 327, 328], [-63, -77, -79, -71, -74, 88,
-70, -80, 92, -73, -75, -72, -60, 102, -64, -76, 137, -53, -60, -60, -
149, -157, -139, -158, -140, -151, -151, -151, -150, -126, -146, -78, -
60, 184, 186, -60, -135, -141, -155, -156, -154, -153, 232, -60, 237, -
136, -148, -147, -142, -145, -134, -82, -109, -81, -52, 270, -102, -103,
280, -116, -127, -111, -98, -105, -117, -118, -137, -138, -144, -143, -
38, 300, -112, -101, -104, -87, -39, -119, -100, -86, 318, -116, -99, -
68, -113, -65, 328, -69]), 'DOUBLEEQUAL': ([57, 75, 86, 106, 107, 108,
110, 112, 113, 114, 115, 117, 119, 120, 144, 146, 150, 153, 154, 155,
156, 158, 190, 195, 198, 199, 201, 203, 218, 219, 257, 258, 276, 277,
278, 279, 305, 315], [-150, -150, 124, -149, -157, -139, -158, -140, -
151, -151, -151, -150, 162, -146, -151, -150, -135, -141, -155, -156, -
154, -153, -156, -136, -148, -147, -142, -145, -109, -150, -98, -153, -
137, -138, -144, -143, -100, -99]), 'INVERSA': ([57, 75, 86], [-150, -
150, 125]), 'TIMES': ([106, 107, 110, 112, 113, 114, 115, 117, 120, 144,
146, 153, 154, 155, 156, 158, 190, 198, 199, 203, 218, 219, 226, 257,
258, 305, 315], [-149, -157, -158, -140, -151, -151, -151, -150, -146,
-151, -150, 202, -155, -156, -154, -153, -156, -148, -147, -145, -109,
-150, -150, -98, -153, -100, -99]), 'LPAREN': ([6, 11, 27, 28, 36, 48,
51, 56, 57, 60, 63, 75, 78, 79, 80, 82, 85, 87, 91, 95, 103, 104, 105,
116, 124, 126, 127, 129, 131, 146, 160, 161, 162, 163, 164, 165, 166,
171, 174, 176, 177, 191, 196, 197, 200, 202, 205, 206, 207, 208, 210,
211, 219, 239, 245, 246, 247, 248, 256, 291, 293, 294, 307, 309], [17,
-18, 35, -61, -62, -152, 82, -152, -88, 90, -66, -88, -152, 104, -152,
116, 123, -90, 131, 116, 116, 116, 116, 116, -152, 116, -152, 176, 116,
-88, -152, -152, -152, -152, 116, -152, -152, 116, 116, 116, 116, 116,
-152, -152, -152, -152, -133, -130, -131, -128, -132, -129, -88, 116,
116, 116, 116, 116, 116, 116, 116, 309, 116, 116]), 'COMA': ([34, 74,
94, 101, 106, 107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 122,
144, 145, 146, 150, 153, 154, 155, 156, 158, 169, 190, 195, 198, 199,
201, 203, 209, 218, 226, 227, 230, 251, 252, 257, 263, 264, 276, 277,
278, 279, 285, 292, 305, 313, 315, 320], [41, -59, 134, 142, -149, -157,
-139, -158, -140, -151, -151, -151, -150, -126, -146, -28, -151, 191, -
150, -135, -141, -155, -156, -154, -153, 214, 239, -136, -148, -147, -
142, -145, -134, -109, -97, -96, 267, -127, -29, -98, -96, 293, -137, -
138, -144, -143, 303, 307, -100, -30, -99, 323]), 'INPUT': ([37, 46, 50,
52, 53, 54, 58, 61, 62, 66, 67, 68, 72, 84, 89, 96, 100, 132, 139, 167,
212, 217, 223, 238, 244, 249, 250, 255, 261, 274, 275, 280, 282, 289,
290, 295, 300, 304, 312, 318, 319, 322, 326, 328], [56, 56, 56, -77, -
79, -71, -74, -70, -80, -73, -75, -72, 56, -19, -76, 56, 56, -78, 56, -
20, -21, -82, -81, -102, -103, 56, -116, -111, -105, -117, -118, -38, -
112, -101, -104, 56, -39, -119, -116, -68, -113, -65, 56, -69]), 'ELSE':
([250, 280, 300], [283, -38, -39]), 'ID': ([2, 12, 13, 14, 15, 16, 22,
23, 24, 25, 37, 41, 45, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68, 72,
78, 80, 82, 83, 84, 89, 90, 95, 96, 100, 103, 104, 105, 109, 111, 116,
123, 124, 126, 127, 131, 132, 134, 139, 151, 152, 160, 161, 162, 163,
164, 165, 166, 167, 171, 174, 176, 177, 191, 196, 197, 200, 202, 205,
206, 207, 208, 210, 211, 212, 214, 217, 223, 238, 239, 244, 245, 246,
247, 248, 249, 250, 255, 256, 261, 267, 274, 275, 280, 282, 289, 290,
291, 293, 295, 300, 303, 304, 307, 309, 312, 318, 319, 322, 323, 326,
328], [3, -34, -37, -35, -36, 28, 34, -31, -32, -33, 57, 34, 74, 75, 75,
-77, -79, -71, -74, -70, -80, -73, -75, -72, 75, -152, -152, 117, 122,
-19, -76, 130, 117, 75, 75, 117, 146, 117, -152, -152, 117, 170, -152,
117, -152, 117, -78, 34, 75, 117, 117, -152, -152, -152, -152, 117, -
152, -152, -20, 117, 219, 226, 117, 146, -152, -152, -152, -152, -133,
-130, -131, -128, -132, -129, -21, 122, -82, -81, -102, 146, -103, 117,
117, 117, 117, 75, -116, -111, 117, -105, 34, -117, -118, -38, -112, -
101, -104, 117, 226, 75, -39, 122, -119, 226, 117, -116, -68, -113, -65,
122, 75, -69]), 'IF': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68,
72, 84, 89, 96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250,
255, 261, 274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319,
322, 326, 328], [51, 51, 51, -77, -79, -71, -74, -70, -80, -73, -75, -
72, 51, -19, -76, 51, 51, -78, 51, -20, -21, -82, -81, -102, -103, 51,
-116, -111, -105, -117, -118, -38, -112, -101, -104, 51, -39, -119, -
116, -68, -113, -65, 51, -69]), 'LBRACE': ([29, 42, 73, 159, 204, 229,
266, 283, 301, 324], [37, 72, 100, -114, 249, -67, 295, -115, 249, 326]
), 'FROM': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68, 72, 84, 89,
96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250, 255, 261,
274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319, 322, 326,
328], [60, 60, 60, -77, -79, -71, -74, -70, -80, -73, -75, -72, 60, -19,
-76, 60, 60, -78, 60, -20, -21, -82, -81, -102, -103, 60, -116, -111, -
105, -117, -118, -38, -112, -101, -104, 60, -39, -119, -116, -68, -113,
-65, 60, -69]), 'INT': ([5, 10, 35, 39, 55, 142, 167], [12, 23, 23, 23,
23, 23, 23]), 'FLOAT': ([5, 10, 35, 39, 55, 142, 167], [14, 24, 24, 24,
24, 24, 24]), 'BREAK': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68,
72, 84, 89, 96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250,
255, 261, 274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319,
322, 326, 328], [65, 65, 65, -77, -79, -71, -74, -70, -80, -73, -75, -
72, 65, -19, -76, 65, 65, -78, 65, -20, -21, -82, -81, -102, -103, 65,
-116, -111, -105, -117, -118, -38, -112, -101, -104, 65, -39, -119, -
116, -68, -113, -65, 65, -69]), 'TRANSPUESTA': ([57, 75, 86], [-150, -
150, 128]), 'MAIN': ([4, 7, 9, 19, 26, 39, 69, 137, 183, 184, 186, 232,
233, 234, 236, 237, 268, 269, 270, 271, 272, 297, 298, 299, 311], [11,
11, 11, 11, -6, -7, -8, -55, -40, -55, -55, -55, -42, -44, -46, -55, -
41, -45, -55, -50, -47, -43, -49, -48, -51])}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_action:
_lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'creaTrans': ([128], [175]), 'creaCuadReturn': ([135], [
181]), 'quad_fact': ([112], [153]), 'creaInversa': ([125], [172]),
'vars': ([37, 72, 100], [46, 96, 139]), 'condFinal': ([250, 312], [282,
319]), 'paramFuncion': ([176, 293, 307], [224, 308, 316]),
'push_function': ([28], [36]), 'push_arreglo': ([252], [285]),
'endProc': ([137, 184, 186, 232, 237, 270], [183, 234, 236, 268, 272,
298]), 'var_cte': ([82, 95, 103, 104, 105, 116, 126, 131, 151, 152, 164,
171, 174, 176, 177, 191, 239, 245, 246, 247, 248, 256, 291, 293, 307,
309], [106, 106, 106, 106, 106, 106, 106, 106, 198, 199, 106, 106, 106,
106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106]),
'while3': ([318], [322]), 'arreglo': ([37, 46, 50, 72, 82, 95, 96, 100,
103, 104, 105, 116, 126, 131, 139, 151, 152, 164, 171, 174, 176, 177,
191, 239, 245, 246, 247, 248, 249, 256, 291, 293, 295, 307, 309, 326],
[47, 47, 47, 47, 107, 107, 47, 47, 107, 107, 107, 107, 107, 107, 47,
107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 47,
107, 107, 107, 47, 107, 107, 47]), 'nomMain': ([4, 7, 9, 19], [6, 6, 6,
6]), 'cond': ([159], [204]), 'termino': ([82, 95, 103, 104, 105, 116,
126, 131, 164, 171, 174, 176, 177, 191, 239, 245, 246, 247, 248, 256,
291, 293, 307, 309], [108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
108, 108, 108, 108, 108, 108, 108, 278, 279, 108, 108, 108, 108, 108]),
'create_asign': ([143, 149, 220, 221], [189, 194, 259, 260]),
'tipoFunc': ([5], [16]), 'bloque': ([204, 301], [250, 312]), 'push_id':
([57, 75, 117, 146, 170, 219, 226], [86, 86, 158, 158, 215, 258, 158]),
'quad_print': ([192, 193, 254], [242, 243, 286]), 'varsGlobal': ([4], [
7]), 'matrix': ([37, 46, 50, 72, 82, 95, 96, 100, 103, 104, 105, 116,
126, 131, 139, 151, 152, 164, 171, 174, 176, 177, 191, 239, 245, 246,
247, 248, 249, 256, 291, 293, 295, 307, 309, 326], [49, 49, 49, 49, 110,
110, 49, 49, 110, 110, 110, 110, 110, 110, 49, 110, 110, 110, 110, 110,
110, 110, 110, 110, 110, 110, 110, 110, 49, 110, 110, 110, 49, 110, 110,
49]), 'tipo': ([10, 35, 39, 55, 142, 167], [22, 45, 22, 83, 45, 83]),
'inversa': ([37, 46, 50, 72, 96, 100, 139, 249, 295, 326], [62, 62, 62,
62, 62, 62, 62, 62, 62, 62]), 'exp1': ([150], [195]), 'estatuto': ([37,
46, 50, 72, 96, 100, 139, 249, 295, 326], [50, 50, 50, 50, 50, 50, 50,
50, 50, 50]), 'determinante': ([174], [222]), 'param': ([35, 142], [43,
188]), 'varAux2': ([83, 214, 303, 323], [121, 253, 314, 325]),
'varAuxGlobal2': ([22, 41, 134, 267], [33, 71, 180, 296]),
'varAuxGlobal1': ([10, 39], [26, 69]), 'program': ([0], [1]),
'functionReturn': ([72, 99, 100, 136, 141, 185], [97, 138, 140, 182,
187, 235]), 'varAux1': ([55, 167], [84, 212]), 'paramAvarTable': ([74],
[101]), 'main': ([4, 7, 9, 19], [8, 18, 21, 31]), 'lectura': ([37, 46,
50, 72, 96, 100, 139, 249, 295, 326], [52, 52, 52, 52, 52, 52, 52, 52,
52, 52]), 'empty': ([35, 72, 99, 100, 136, 141, 142, 176, 185, 293, 307
], [44, 98, 98, 98, 98, 98, 44, 225, 98, 225, 225]), 'function': ([4, 7,
183, 234, 236, 268, 272, 298], [9, 19, 233, 269, 271, 297, 299, 311]),
'escrituraAux': ([104, 191, 239], [147, 240, 273]), 'push_poper': ([48,
56, 78, 80, 109, 111, 124, 127, 160, 161, 162, 163, 165, 166, 196, 197,
200, 202], [79, 85, 103, 105, 151, 152, 171, 174, 205, 206, 207, 208,
210, 211, 245, 246, 247, 248]), 'push_var': ([122], [169]), 'gosub': ([
224], [262]), 'ver_dim2': ([305], [315]), 'comp': ([119], [164]),
'factor': ([82, 95, 103, 104, 105, 116, 126, 131, 164, 171, 174, 176,
177, 191, 239, 245, 246, 247, 248, 256, 291, 293, 307, 309], [112, 112,
112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112,
112, 112, 112, 112, 112, 112, 112, 112]), 'actualizaFuncion': ([57, 75,
146, 219], [87, 87, 87, 87]), 'transpuesta': ([37, 46, 50, 72, 96, 100,
139, 249, 295, 326], [53, 53, 53, 53, 53, 53, 53, 53, 53, 53]),
'condElse': ([283], [301]), 'condicion': ([37, 46, 50, 72, 96, 100, 139,
249, 295, 326], [54, 54, 54, 54, 54, 54, 54, 54, 54, 54]), 'quad_term':
([108], [150]), 'push_cte': ([113, 114, 115, 144], [154, 155, 156, 190]
), 'quad_comp': ([209], [251]), 'generarEra': ([87], [129]),
'loopFromDo': ([37, 46, 50, 72, 96, 100, 139, 249, 295, 326], [58, 58,
58, 58, 58, 58, 58, 58, 58, 58]), 'expresion': ([82, 104, 116, 131, 171,
174, 177, 191, 239, 291, 309], [118, 145, 157, 178, 216, 220, 228, 145,
145, 306, 317]), 'endPrograma': ([8, 18, 21, 31], [20, 30, 32, 38]),
'llamadaAFuncion': ([37, 46, 50, 72, 96, 100, 104, 139, 174, 191, 239,
249, 295, 326], [59, 76, 76, 76, 76, 76, 148, 76, 221, 241, 241, 76, 76,
76]), 'push_matriz': ([313], [320]), 'asignacion': ([37, 46, 50, 72, 96,
100, 139, 249, 295, 326], [61, 61, 61, 61, 61, 61, 61, 61, 61, 61]),
'while2': ([229], [266]), 'generaCuadbreak': ([65], [93]), 'while1': ([
63], [91]), 'push_id2': ([226], [263]), 'bloqueAux': ([37, 46, 50, 72,
96, 100, 139, 249, 295, 326], [64, 77, 81, 99, 136, 141, 185, 281, 310,
327]), 'ver_dim1': ([218], [257]), 'while': ([37, 46, 50, 72, 96, 100,
139, 249, 295, 326], [66, 66, 66, 66, 66, 66, 66, 66, 66, 66]),
'termino1': ([153], [201]), 'exp': ([82, 95, 103, 104, 105, 116, 126,
131, 164, 171, 174, 176, 177, 191, 239, 245, 246, 256, 291, 293, 307,
309], [119, 135, 143, 119, 149, 119, 173, 119, 209, 119, 119, 227, 119,
119, 119, 276, 277, 287, 119, 227, 227, 119]), 'nomFunc': ([16], [27]),
'factorAux': ([82, 95, 103, 104, 105, 116, 126, 131, 164, 171, 174, 176,
177, 191, 239, 245, 246, 247, 248, 256, 291, 293, 307, 309], [120, 120,
120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120,
120, 120, 120, 120, 120, 120, 120, 120]), 'comparacion': ([37, 46, 50,
72, 96, 100, 139, 249, 295, 326], [67, 67, 67, 67, 67, 67, 67, 67, 67,
67]), 'paramFuncionAux': ([227, 263], [264, 292]), 'escritura': ([37,
46, 50, 72, 96, 100, 139, 249, 295, 326], [68, 68, 68, 68, 68, 68, 68,
68, 68, 68])}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto:
_lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [("S' -> program", "S'", 1, None, None, None), (
'program -> PROGRAM ID COLON varsGlobal function main endPrograma',
'program', 7, 'p_program', 'lexAndSyn.py', 144), (
'program -> PROGRAM ID COLON function main endPrograma', 'program', 6,
'p_program', 'lexAndSyn.py', 145), (
'program -> PROGRAM ID COLON varsGlobal main endPrograma', 'program', 6,
'p_program', 'lexAndSyn.py', 146), (
'program -> PROGRAM ID COLON main endPrograma', 'program', 5,
'p_program', 'lexAndSyn.py', 147), ('endPrograma -> <empty>',
'endPrograma', 0, 'p_endPrograma', 'lexAndSyn.py', 153), (
'varsGlobal -> VAR varAuxGlobal1', 'varsGlobal', 2, 'p_varsGlobal',
'lexAndSyn.py', 158), ('varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON',
'varAuxGlobal1', 3, 'p_varAuxGlobal1', 'lexAndSyn.py', 162), (
'varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON varAuxGlobal1',
'varAuxGlobal1', 4, 'p_varAuxGlobal1', 'lexAndSyn.py', 163), (
'varAuxGlobal2 -> ID', 'varAuxGlobal2', 1, 'p_varAuxGlobal2',
'lexAndSyn.py', 167), ('varAuxGlobal2 -> ID COMA varAuxGlobal2',
'varAuxGlobal2', 3, 'p_varAuxGlobal2', 'lexAndSyn.py', 168), (
'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH', 'varAuxGlobal2', 4,
'p_varAuxGlobal2', 'lexAndSyn.py', 169), (
'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH COMA varAuxGlobal2',
'varAuxGlobal2', 6, 'p_varAuxGlobal2', 'lexAndSyn.py', 170), (
'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH',
'varAuxGlobal2', 7, 'p_varAuxGlobal2', 'lexAndSyn.py', 171), (
'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2'
, 'varAuxGlobal2', 9, 'p_varAuxGlobal2', 'lexAndSyn.py', 172), (
'main -> nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE', 'main', 6,
'p_main', 'lexAndSyn.py', 180), (
'main -> nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE', 'main', 7,
'p_main', 'lexAndSyn.py', 181), (
'main -> nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE', 'main',
6, 'p_main', 'lexAndSyn.py', 182), ('nomMain -> MAIN', 'nomMain', 1,
'p_nomMain', 'lexAndSyn.py', 186), ('vars -> VAR varAux1', 'vars', 2,
'p_vars', 'lexAndSyn.py', 196), ('varAux1 -> tipo varAux2 SEMICOLON',
'varAux1', 3, 'p_varAux1', 'lexAndSyn.py', 200), (
'varAux1 -> tipo varAux2 SEMICOLON varAux1', 'varAux1', 4, 'p_varAux1',
'lexAndSyn.py', 201), ('varAux2 -> ID push_var', 'varAux2', 2,
'p_varAux2', 'lexAndSyn.py', 205), (
'varAux2 -> ID push_var COMA varAux2', 'varAux2', 4, 'p_varAux2',
'lexAndSyn.py', 206), ('varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo',
'varAux2', 5, 'p_varAux2', 'lexAndSyn.py', 207), (
'varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2',
'varAux2', 7, 'p_varAux2', 'lexAndSyn.py', 208), (
'varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz',
'varAux2', 8, 'p_varAux2', 'lexAndSyn.py', 209), (
'varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2'
, 'varAux2', 10, 'p_varAux2', 'lexAndSyn.py', 210), (
'push_var -> <empty>', 'push_var', 0, 'p_pushVariable', 'lexAndSyn.py',
214), ('push_arreglo -> <empty>', 'push_arreglo', 0, 'p_arreglo',
'lexAndSyn.py', 220), ('push_matriz -> <empty>', 'push_matriz', 0,
'p_matriz', 'lexAndSyn.py', 231), ('tipo -> INT', 'tipo', 1, 'p_tipo',
'lexAndSyn.py', 246), ('tipo -> FLOAT', 'tipo', 1, 'p_tipo',
'lexAndSyn.py', 247), ('tipo -> CHAR', 'tipo', 1, 'p_tipo',
'lexAndSyn.py', 248), ('tipoFunc -> INT', 'tipoFunc', 1, 'p_tipoFunc',
'lexAndSyn.py', 253), ('tipoFunc -> FLOAT', 'tipoFunc', 1, 'p_tipoFunc',
'lexAndSyn.py', 254), ('tipoFunc -> CHAR', 'tipoFunc', 1, 'p_tipoFunc',
'lexAndSyn.py', 255), ('tipoFunc -> VOID', 'tipoFunc', 1, 'p_tipoFunc',
'lexAndSyn.py', 256), ('bloque -> LBRACE RBRACE', 'bloque', 2,
'p_bloque', 'lexAndSyn.py', 261), ('bloque -> LBRACE bloqueAux RBRACE',
'bloque', 3, 'p_bloque', 'lexAndSyn.py', 262), (
'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc'
, 'function', 9, 'p_function', 'lexAndSyn.py', 268), (
'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc'
, 'function', 11, 'p_function', 'lexAndSyn.py', 269), (
'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function'
, 'function', 10, 'p_function', 'lexAndSyn.py', 270), (
'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function'
, 'function', 12, 'p_function', 'lexAndSyn.py', 271), (
'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc'
, 'function', 10, 'p_function', 'lexAndSyn.py', 272), (
'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function'
, 'function', 11, 'p_function', 'lexAndSyn.py', 273), (
'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc'
, 'function', 10, 'p_function', 'lexAndSyn.py', 274), (
'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc'
, 'function', 11, 'p_function', 'lexAndSyn.py', 275), (
'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function'
, 'function', 12, 'p_function', 'lexAndSyn.py', 276), (
'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc'
, 'function', 12, 'p_function', 'lexAndSyn.py', 277), (
'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function'
, 'function', 11, 'p_function', 'lexAndSyn.py', 278), (
'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function'
, 'function', 13, 'p_function', 'lexAndSyn.py', 279), (
'functionReturn -> RETURN exp creaCuadReturn SEMICOLON',
'functionReturn', 4, 'p_functionReturn', 'lexAndSyn.py', 283), (
'functionReturn -> empty', 'functionReturn', 1, 'p_functionReturn',
'lexAndSyn.py', 284), ('creaCuadReturn -> <empty>', 'creaCuadReturn', 0,
'p_creaCuadReturn', 'lexAndSyn.py', 288), ('endProc -> <empty>',
'endProc', 0, 'p_endProc', 'lexAndSyn.py', 293), (
'param -> tipo ID paramAvarTable', 'param', 3, 'p_param',
'lexAndSyn.py', 298), ('param -> tipo ID paramAvarTable COMA param',
'param', 5, 'p_param', 'lexAndSyn.py', 299), ('param -> empty', 'param',
1, 'p_param', 'lexAndSyn.py', 300), ('paramAvarTable -> <empty>',
'paramAvarTable', 0, 'p_paramAvarTable', 'lexAndSyn.py', 305), (
'empty -> <empty>', 'empty', 0, 'p_empty', 'lexAndSyn.py', 311), (
'push_function -> <empty>', 'push_function', 0, 'p_push_function',
'lexAndSyn.py', 315), ('nomFunc -> ID push_function', 'nomFunc', 2,
'p_nomFunc', 'lexAndSyn.py', 324), ('bloqueAux -> estatuto',
'bloqueAux', 1, 'p_bloqueAux', 'lexAndSyn.py', 333), (
'bloqueAux -> estatuto bloqueAux', 'bloqueAux', 2, 'p_bloqueAux',
'lexAndSyn.py', 334), (
'while -> WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3'
, 'while', 10, 'p_while', 'lexAndSyn.py', 338), ('while1 -> <empty>',
'while1', 0, 'p_while1', 'lexAndSyn.py', 342), ('while2 -> <empty>',
'while2', 0, 'p_while2', 'lexAndSyn.py', 346), ('while3 -> <empty>',
'while3', 0, 'p_while3', 'lexAndSyn.py', 350), (
'loopFromDo -> FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE'
, 'loopFromDo', 14, 'p_loopFromDo', 'lexAndSyn.py', 354), (
'estatuto -> asignacion', 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py',
366), ('estatuto -> condicion', 'estatuto', 1, 'p_estatuto',
'lexAndSyn.py', 367), ('estatuto -> escritura', 'estatuto', 1,
'p_estatuto', 'lexAndSyn.py', 368), ('estatuto -> while', 'estatuto', 1,
'p_estatuto', 'lexAndSyn.py', 369), ('estatuto -> loopFromDo',
'estatuto', 1, 'p_estatuto', 'lexAndSyn.py', 370), (
'estatuto -> comparacion', 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py',
371), ('estatuto -> llamadaAFuncion SEMICOLON', 'estatuto', 2,
'p_estatuto', 'lexAndSyn.py', 372), ('estatuto -> lectura', 'estatuto',
1, 'p_estatuto', 'lexAndSyn.py', 373), (
'estatuto -> BREAK generaCuadbreak SEMICOLON', 'estatuto', 3,
'p_estatuto', 'lexAndSyn.py', 374), ('estatuto -> transpuesta',
'estatuto', 1, 'p_estatuto', 'lexAndSyn.py', 375), (
'estatuto -> inversa', 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py', 376
), ('transpuesta -> ID push_id TRANSPUESTA creaTrans SEMICOLON',
'transpuesta', 5, 'p_transpuesta', 'lexAndSyn.py', 380), (
'inversa -> ID push_id INVERSA creaInversa SEMICOLON', 'inversa', 5,
'p_inversa', 'lexAndSyn.py', 383), ('creaInversa -> <empty>',
'creaInversa', 0, 'p_creaInversa', 'lexAndSyn.py', 387), (
'creaTrans -> <empty>', 'creaTrans', 0, 'p_creaTrans', 'lexAndSyn.py',
391), ('generaCuadbreak -> <empty>', 'generaCuadbreak', 0,
'p_generaCuadbreak', 'lexAndSyn.py', 395), (
'llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion'
, 'llamadaAFuncion', 8, 'p_llamadaAFuncion', 'lexAndSyn.py', 399), (
'llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN'
, 'llamadaAFuncion', 7, 'p_llamadaAFuncion', 'lexAndSyn.py', 400), (
'actualizaFuncion -> <empty>', 'actualizaFuncion', 0,
'p_actualizaFuncion', 'lexAndSyn.py', 404), ('gosub -> <empty>',
'gosub', 0, 'p_gosub', 'lexAndSyn.py', 409), ('generarEra -> <empty>',
'generarEra', 0, 'p_generarEra', 'lexAndSyn.py', 421), (
'paramFuncion -> ID push_id2 paramFuncionAux', 'paramFuncion', 3,
'p_paramFuncion', 'lexAndSyn.py', 429), (
'paramFuncion -> ID push_id2 paramFuncionAux COMA paramFuncion',
'paramFuncion', 5, 'p_paramFuncion', 'lexAndSyn.py', 430), (
'paramFuncion -> exp paramFuncionAux', 'paramFuncion', 2,
'p_paramFuncion', 'lexAndSyn.py', 431), (
'paramFuncion -> exp paramFuncionAux COMA paramFuncion', 'paramFuncion',
4, 'p_paramFuncion', 'lexAndSyn.py', 432), ('paramFuncion -> empty',
'paramFuncion', 1, 'p_paramFuncion', 'lexAndSyn.py', 433), (
'paramFuncionAux -> <empty>', 'paramFuncionAux', 0, 'p_paramFuncionAux',
'lexAndSyn.py', 437), ('push_id2 -> <empty>', 'push_id2', 0,
'p_push_id2', 'lexAndSyn.py', 441), (
'arreglo -> ID push_id LCORCH exp RCORCH ver_dim1', 'arreglo', 6,
'p_array', 'lexAndSyn.py', 445), (
'matrix -> ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2',
'matrix', 9, 'p_matrix', 'lexAndSyn.py', 449), ('ver_dim2 -> <empty>',
'ver_dim2', 0, 'p_ver_dim2', 'lexAndSyn.py', 453), (
'asignacion -> ID push_id EQUAL push_poper expresion create_asign SEMICOLON'
, 'asignacion', 7, 'p_asignacion', 'lexAndSyn.py', 457), (
'asignacion -> arreglo EQUAL push_poper exp create_asign SEMICOLON',
'asignacion', 6, 'p_asignacion', 'lexAndSyn.py', 458), (
'asignacion -> matrix EQUAL push_poper exp create_asign SEMICOLON',
'asignacion', 6, 'p_asignacion', 'lexAndSyn.py', 459), (
'asignacion -> ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON'
, 'asignacion', 7, 'p_asignacion', 'lexAndSyn.py', 460), (
'asignacion -> ID push_id EQUAL push_poper determinante SEMICOLON',
'asignacion', 6, 'p_asignacion', 'lexAndSyn.py', 461), (
'determinante -> ID push_id DETERMINANT', 'determinante', 3,
'p_determinante', 'lexAndSyn.py', 465), (
'push_id_dimensionada -> <empty>', 'push_id_dimensionada', 0,
'p_push_id_dimensionada', 'lexAndSyn.py', 470), (
'create_asign_dim -> <empty>', 'create_asign_dim', 0,
'p_create_asign_dim', 'lexAndSyn.py', 473), ('ver_dim1 -> <empty>',
'ver_dim1', 0, 'p_ver_dim1', 'lexAndSyn.py', 477), (
'create_asign -> <empty>', 'create_asign', 0, 'p_create_asign',
'lexAndSyn.py', 481), (
'comparacion -> ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON',
'comparacion', 6, 'p_comparacion', 'lexAndSyn.py', 485), (
'condicion -> IF LPAREN expresion RPAREN cond bloque condFinal',
'condicion', 7, 'p_condicion', 'lexAndSyn.py', 489), (
'condicion -> IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal'
, 'condicion', 10, 'p_condicion', 'lexAndSyn.py', 490), (
'cond -> <empty>', 'cond', 0, 'p_quad_cond', 'lexAndSyn.py', 494), (
'condElse -> <empty>', 'condElse', 0, 'p_quad_condElse', 'lexAndSyn.py',
498), ('condFinal -> <empty>', 'condFinal', 0, 'p_quad_condFinal',
'lexAndSyn.py', 502), (
'escritura -> PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON'
, 'escritura', 7, 'p_escritura', 'lexAndSyn.py', 506), (
'escritura -> PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON'
, 'escritura', 7, 'p_escritura', 'lexAndSyn.py', 507), (
'lectura -> INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON'
, 'lectura', 8, 'p_lectura', 'lexAndSyn.py', 511), (
'quad_print -> <empty>', 'quad_print', 0, 'p_quad_print',
'lexAndSyn.py', 515), ('escrituraAux -> expresion', 'escrituraAux', 1,
'p_escrituraAux', 'lexAndSyn.py', 519), (
'escrituraAux -> CTE_STRING push_cte', 'escrituraAux', 2,
'p_escrituraAux', 'lexAndSyn.py', 520), (
'escrituraAux -> expresion COMA escrituraAux', 'escrituraAux', 3,
'p_escrituraAux', 'lexAndSyn.py', 521), (
'escrituraAux -> CTE_STRING push_cte COMA escrituraAux', 'escrituraAux',
4, 'p_escrituraAux', 'lexAndSyn.py', 522), (
'escrituraAux -> llamadaAFuncion', 'escrituraAux', 1, 'p_escrituraAux',
'lexAndSyn.py', 523), ('expresion -> exp', 'expresion', 1,
'p_expresion', 'lexAndSyn.py', 527), (
'expresion -> exp comp exp quad_comp', 'expresion', 4, 'p_expresion',
'lexAndSyn.py', 528), ('comp -> LOWERTHAN push_poper', 'comp', 2,
'p_comp', 'lexAndSyn.py', 532), ('comp -> MORETHAN push_poper', 'comp',
2, 'p_comp', 'lexAndSyn.py', 533), ('comp -> DIFFERENT push_poper',
'comp', 2, 'p_comp', 'lexAndSyn.py', 534), (
'comp -> DOUBLEEQUAL push_poper', 'comp', 2, 'p_comp', 'lexAndSyn.py',
535), ('comp -> LOWEREQUAL push_poper', 'comp', 2, 'p_comp',
'lexAndSyn.py', 536), ('comp -> MOREEQUAL push_poper', 'comp', 2,
'p_comp', 'lexAndSyn.py', 537), ('quad_comp -> <empty>', 'quad_comp', 0,
'p_quad_comp', 'lexAndSyn.py', 541), ('exp -> termino quad_term', 'exp',
2, 'p_exp', 'lexAndSyn.py', 545), ('exp -> termino quad_term exp1',
'exp', 3, 'p_exp', 'lexAndSyn.py', 546), ('exp1 -> PLUS push_poper exp',
'exp1', 3, 'p_exp1', 'lexAndSyn.py', 550), (
'exp1 -> MINUS push_poper exp', 'exp1', 3, 'p_exp1', 'lexAndSyn.py',
551), ('quad_term -> <empty>', 'quad_term', 0, 'p_quad_term',
'lexAndSyn.py', 555), ('quad_fact -> <empty>', 'quad_fact', 0,
'p_quad_fact', 'lexAndSyn.py', 559), ('termino -> factor quad_fact',
'termino', 2, 'p_termino', 'lexAndSyn.py', 563), (
'termino -> factor quad_fact termino1', 'termino', 3, 'p_termino',
'lexAndSyn.py', 564), ('termino1 -> TIMES push_poper termino',
'termino1', 3, 'p_termino1', 'lexAndSyn.py', 568), (
'termino1 -> DIVIDE push_poper termino', 'termino1', 3, 'p_termino1',
'lexAndSyn.py', 569), ('factor -> LPAREN expresion RPAREN', 'factor', 3,
'p_factor', 'lexAndSyn.py', 573), ('factor -> factorAux', 'factor', 1,
'p_factor', 'lexAndSyn.py', 574), (
'factorAux -> PLUS push_poper var_cte', 'factorAux', 3, 'p_factorAux',
'lexAndSyn.py', 578), ('factorAux -> MINUS push_poper var_cte',
'factorAux', 3, 'p_factorAux', 'lexAndSyn.py', 579), (
'factorAux -> var_cte', 'factorAux', 1, 'p_factorAux', 'lexAndSyn.py',
580), ('push_id -> <empty>', 'push_id', 0, 'p_push_id', 'lexAndSyn.py',
584), ('push_cte -> <empty>', 'push_cte', 0, 'p_push_cte',
'lexAndSyn.py', 588), ('push_poper -> <empty>', 'push_poper', 0,
'p_push_poper', 'lexAndSyn.py', 598), ('var_cte -> ID push_id',
'var_cte', 2, 'p_var_cte', 'lexAndSyn.py', 602), (
'var_cte -> CTE_I push_cte', 'var_cte', 2, 'p_var_cte', 'lexAndSyn.py',
603), ('var_cte -> CTE_F push_cte', 'var_cte', 2, 'p_var_cte',
'lexAndSyn.py', 604), ('var_cte -> CTE_STRING push_cte', 'var_cte', 2,
'p_var_cte', 'lexAndSyn.py', 605), ('var_cte -> arreglo', 'var_cte', 1,
'p_var_cte', 'lexAndSyn.py', 606), ('var_cte -> matrix', 'var_cte', 1,
'p_var_cte', 'lexAndSyn.py', 607)]
<|reserved_special_token_1|>
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'AND BREAK CHAR COLON COMA CTE_F CTE_I CTE_STRING DETERMINANT DIFFERENT DIVIDE DO DOUBLEEQUAL ELSE EQUAL FLOAT FROM FUNCTION ID IF INPUT INT INVERSA LBRACE LCORCH LOWEREQUAL LOWERTHAN LPAREN MAIN MINUS MOREEQUAL MORETHAN OR PLUS PRINT PROGRAM RBRACE RCORCH RETURN RPAREN SEMICOLON TIMES TO TRANSPUESTA VAR VOID WHILEprogram : PROGRAM ID COLON varsGlobal function main endPrograma\n | PROGRAM ID COLON function main endPrograma\n | PROGRAM ID COLON varsGlobal main endPrograma\n | PROGRAM ID COLON main endPrograma\n endPrograma :varsGlobal : VAR varAuxGlobal1\n varAuxGlobal1 : tipo varAuxGlobal2 SEMICOLON\n | tipo varAuxGlobal2 SEMICOLON varAuxGlobal1\n varAuxGlobal2 : ID\n | ID COMA varAuxGlobal2\n | ID LCORCH CTE_I RCORCH\n | ID LCORCH CTE_I RCORCH COMA varAuxGlobal2\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2\n main : nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE\n | nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE\n | nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE\n nomMain : MAIN\n vars : VAR varAux1\n varAux1 : tipo varAux2 SEMICOLON\n | tipo varAux2 SEMICOLON varAux1\n varAux2 : ID push_var\n | ID push_var COMA varAux2\n | ID LCORCH CTE_I RCORCH push_arreglo\n | ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2\n push_var :push_arreglo :push_matriz :tipo : INT\n | FLOAT\n | CHAR\n tipoFunc : INT\n | FLOAT\n | CHAR\n | VOID\n bloque : LBRACE RBRACE\n | LBRACE bloqueAux RBRACE\n function : FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function \n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc \n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function\n functionReturn : RETURN exp creaCuadReturn SEMICOLON\n | empty\n creaCuadReturn :\n endProc :\n param : tipo ID paramAvarTable\n | tipo ID paramAvarTable COMA param\n | empty\n paramAvarTable : empty : \n push_function :nomFunc : ID push_function\n bloqueAux : estatuto\n | estatuto bloqueAux\n while : WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3\n while1 :while2 :while3 :loopFromDo : FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE\n estatuto : asignacion\n | condicion\n | escritura\n | while\n | loopFromDo\n | comparacion\n | llamadaAFuncion SEMICOLON\n | lectura\n | BREAK generaCuadbreak SEMICOLON\n | transpuesta\n | inversa\n transpuesta : ID push_id TRANSPUESTA creaTrans SEMICOLON\n inversa : ID push_id INVERSA creaInversa SEMICOLON\n creaInversa : creaTrans : generaCuadbreak : llamadaAFuncion : ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion\n | ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN\n actualizaFuncion : gosub :\n generarEra :\n paramFuncion : ID push_id2 paramFuncionAux\n | ID push_id2 paramFuncionAux COMA paramFuncion\n | exp paramFuncionAux\n | exp paramFuncionAux COMA paramFuncion\n | empty\n paramFuncionAux : push_id2 :arreglo : ID push_id LCORCH exp RCORCH ver_dim1\n matrix : ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2\n ver_dim2 : asignacion : ID push_id EQUAL push_poper expresion create_asign SEMICOLON\n | arreglo EQUAL push_poper exp create_asign SEMICOLON\n | matrix EQUAL push_poper exp create_asign SEMICOLON\n | ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON\n | ID push_id EQUAL push_poper determinante SEMICOLON\n determinante : ID push_id DETERMINANT\n push_id_dimensionada :create_asign_dim :ver_dim1 :create_asign :comparacion : ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON\n condicion : IF LPAREN expresion RPAREN cond bloque condFinal\n | IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal\n cond :condElse :condFinal :escritura : PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON\n | PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON\n lectura : INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON\n quad_print :escrituraAux : expresion\n | CTE_STRING push_cte\n | expresion COMA escrituraAux\n | CTE_STRING push_cte COMA escrituraAux\n | llamadaAFuncion\n expresion : exp\n | exp comp exp quad_comp\n comp : LOWERTHAN push_poper\n | MORETHAN push_poper\n | DIFFERENT push_poper\n | DOUBLEEQUAL push_poper\n | LOWEREQUAL push_poper\n | MOREEQUAL push_poper\n quad_comp :exp : termino quad_term\n | termino quad_term exp1\n exp1 : PLUS push_poper exp\n | MINUS push_poper exp\n quad_term :quad_fact :termino : factor quad_fact\n | factor quad_fact termino1\n termino1 : TIMES push_poper termino\n | DIVIDE push_poper termino\n factor : LPAREN expresion RPAREN\n | factorAux\n factorAux : PLUS push_poper var_cte\n | MINUS push_poper var_cte\n | var_cte \n push_id :push_cte :push_poper :var_cte : ID push_id\n | CTE_I push_cte\n | CTE_F push_cte\n | CTE_STRING push_cte\n | arreglo\n | matrix\n '
_lr_action_items = {'MOREEQUAL':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,160,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'CTE_STRING':([78,80,82,95,103,104,105,109,111,116,124,126,127,131,151,152,160,161,162,163,164,165,166,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,239,245,246,247,248,256,291,293,307,309,],[-152,-152,114,114,114,144,114,-152,-152,114,-152,114,-152,114,114,114,-152,-152,-152,-152,114,-152,-152,114,114,114,114,144,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,144,114,114,114,114,114,114,114,114,114,]),'LCORCH':([34,57,75,86,94,117,122,146,158,218,219,226,252,258,],[40,-150,-150,126,133,-150,168,-150,126,256,-150,-150,284,126,]),'RETURN':([50,52,53,54,58,61,62,66,67,68,72,81,89,99,100,132,136,141,185,217,223,238,244,250,255,261,274,275,280,282,289,290,300,304,312,318,319,322,328,],[-63,-77,-79,-71,-74,-70,-80,-73,-75,-72,95,-64,-76,95,95,-78,95,95,95,-82,-81,-102,-103,-116,-111,-105,-117,-118,-38,-112,-101,-104,-39,-119,-116,-68,-113,-65,-69,]),'DO':([321,],[324,]),'VOID':([5,],[13,]),'EQUAL':([47,49,57,75,86,130,218,257,305,315,],[78,80,-150,-150,127,177,-109,-98,-100,-99,]),'CHAR':([5,10,35,39,55,142,167,],[15,25,25,25,25,25,25,]),'VAR':([4,37,72,100,],[10,55,55,55,]),'WHILE':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[63,63,63,-77,-79,-71,-74,-70,-80,-73,-75,-72,63,-19,-76,63,63,-78,63,-20,-21,-82,-81,-102,-103,63,-116,-111,-105,-117,-118,-38,-112,-101,-104,63,-39,-119,-116,-68,-113,-65,63,-69,]),'PROGRAM':([0,],[2,]),'PRINT':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[48,48,48,-77,-79,-71,-74,-70,-80,-73,-75,-72,48,-19,-76,48,48,-78,48,-20,-21,-82,-81,-102,-103,48,-116,-111,-105,-117,-118,-38,-112,-101,-104,48,-39,-119,-116,-68,-113,-65,48,-69,]),'MORETHAN':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,166,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'MINUS':([78,80,82,95,103,104,105,106,107,108,110,112,113,114,115,116,117,120,124,126,127,131,144,146,150,153,154,155,156,158,160,161,162,163,164,165,166,171,174,176,177,190,191,196,197,198,199,200,201,202,203,205,206,207,208,210,211,218,219,226,239,245,246,247,248,256,257,258,278,279,291,293,305,307,309,315,],[-152,-152,109,109,109,109,109,-149,-157,-139,-158,-140,-151,-151,-151,109,-150,-146,-152,109,-152,109,-151,-150,197,-141,-155,-156,-154,-153,-152,-152,-152,-152,109,-152,-152,109,109,109,109,-156,109,-152,-152,-148,-147,-152,-142,-152,-145,-133,-130,-131,-128,-132,-129,-109,-150,-150,109,109,109,109,109,109,-98,-153,-144,-143,109,109,-100,109,109,-99,]),'DIVIDE':([106,107,110,112,113,114,115,117,120,144,146,153,154,155,156,158,190,198,199,203,218,219,226,257,258,305,315,],[-149,-157,-158,-140,-151,-151,-151,-150,-146,-151,-150,200,-155,-156,-154,-153,-156,-148,-147,-145,-109,-150,-150,-98,-153,-100,-99,]),'RCORCH':([70,106,107,108,110,112,113,114,115,117,120,150,153,154,155,156,158,173,179,195,198,199,201,203,213,218,257,276,277,278,279,287,302,305,315,],[94,-149,-157,-139,-158,-140,-151,-151,-151,-150,-146,-135,-141,-155,-156,-154,-153,218,230,-136,-148,-147,-142,-145,252,-109,-98,-137,-138,-144,-143,305,313,-100,-99,]),'DETERMINANT':([219,258,],[-150,288,]),'RPAREN':([17,35,43,44,74,101,106,107,108,110,112,113,114,115,117,118,119,120,142,144,145,146,147,148,150,153,154,155,156,157,158,170,176,178,188,190,195,198,199,201,203,209,215,218,224,225,226,227,228,240,241,251,257,262,263,264,273,276,277,278,279,291,292,293,305,306,307,308,315,316,317,],[29,42,73,-58,-59,-56,-149,-157,-139,-158,-140,-151,-151,-151,-150,159,-126,-146,-60,-151,-121,-150,192,193,-135,-141,-155,-156,-154,203,-153,-150,-60,229,-57,-122,-136,-148,-147,-142,-145,-134,254,-109,-89,-95,-97,-96,265,-123,-125,-127,-98,291,-96,-93,-124,-137,-138,-144,-143,-87,-91,-60,-100,-86,-60,-94,-99,-92,321,]),'SEMICOLON':([33,34,59,65,71,76,93,94,106,107,108,110,112,113,114,115,117,119,120,121,122,125,128,135,143,149,150,153,154,155,156,158,169,172,175,180,181,189,192,193,194,195,198,199,201,203,209,216,218,219,220,221,222,230,242,243,251,252,253,254,257,258,259,260,276,277,278,279,285,286,288,291,296,305,306,313,314,315,320,325,],[39,-9,89,-85,-10,89,132,-11,-149,-157,-139,-158,-140,-151,-151,-151,-150,-126,-146,167,-28,-83,-84,-54,-110,-110,-135,-141,-155,-156,-154,-153,-22,217,223,-12,231,238,-120,-120,244,-136,-148,-147,-142,-145,-134,255,-109,-150,-110,-110,261,-13,274,275,-127,-29,-23,-120,-98,-153,289,290,-137,-138,-144,-143,-24,304,-106,-87,-14,-100,-86,-30,-25,-99,-26,-27,]),'LOWERTHAN':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,163,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'LOWEREQUAL':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,165,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'TO':([265,],[294,]),'COLON':([3,],[4,]),'CTE_I':([40,78,80,82,95,103,104,105,109,111,116,124,126,127,131,133,151,152,160,161,162,163,164,165,166,168,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,239,245,246,247,248,256,284,291,293,307,309,],[70,-152,-152,115,115,115,115,115,-152,-152,115,-152,115,-152,115,179,115,115,-152,-152,-152,-152,115,-152,-152,213,115,115,115,115,115,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,115,115,115,115,115,115,302,115,115,115,115,]),'CTE_F':([78,80,82,95,103,104,105,109,111,116,124,126,127,131,151,152,160,161,162,163,164,165,166,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,239,245,246,247,248,256,291,293,307,309,],[-152,-152,113,113,113,113,113,-152,-152,113,-152,113,-152,113,113,113,-152,-152,-152,-152,113,-152,-152,113,113,113,113,113,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,113,113,113,113,113,113,113,113,113,113,]),'PLUS':([78,80,82,95,103,104,105,106,107,108,110,112,113,114,115,116,117,120,124,126,127,131,144,146,150,153,154,155,156,158,160,161,162,163,164,165,166,171,174,176,177,190,191,196,197,198,199,200,201,202,203,205,206,207,208,210,211,218,219,226,239,245,246,247,248,256,257,258,278,279,291,293,305,307,309,315,],[-152,-152,111,111,111,111,111,-149,-157,-139,-158,-140,-151,-151,-151,111,-150,-146,-152,111,-152,111,-151,-150,196,-141,-155,-156,-154,-153,-152,-152,-152,-152,111,-152,-152,111,111,111,111,-156,111,-152,-152,-148,-147,-152,-142,-152,-145,-133,-130,-131,-128,-132,-129,-109,-150,-150,111,111,111,111,111,111,-98,-153,-144,-143,111,111,-100,111,111,-99,]),'$end':([1,8,18,20,21,30,31,32,38,88,92,102,],[0,-5,-5,-4,-5,-3,-5,-2,-1,-17,-15,-16,]),'FUNCTION':([4,7,26,39,69,137,183,184,186,232,234,236,237,268,270,272,298,],[5,5,-6,-7,-8,-55,5,-55,-55,-55,5,5,-55,5,-55,5,5,]),'DIFFERENT':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,161,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'RBRACE':([50,52,53,54,58,59,61,62,64,66,67,68,72,77,81,89,97,98,99,100,106,107,108,110,112,113,114,115,117,119,120,132,136,138,140,141,150,153,154,155,156,158,182,185,187,195,198,199,201,203,209,217,218,223,231,235,238,244,249,250,251,255,257,261,274,275,276,277,278,279,280,281,282,289,290,291,300,304,305,306,310,312,315,318,319,322,327,328,],[-63,-77,-79,-71,-74,88,-70,-80,92,-73,-75,-72,-60,102,-64,-76,137,-53,-60,-60,-149,-157,-139,-158,-140,-151,-151,-151,-150,-126,-146,-78,-60,184,186,-60,-135,-141,-155,-156,-154,-153,232,-60,237,-136,-148,-147,-142,-145,-134,-82,-109,-81,-52,270,-102,-103,280,-116,-127,-111,-98,-105,-117,-118,-137,-138,-144,-143,-38,300,-112,-101,-104,-87,-39,-119,-100,-86,318,-116,-99,-68,-113,-65,328,-69,]),'DOUBLEEQUAL':([57,75,86,106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-150,-150,124,-149,-157,-139,-158,-140,-151,-151,-151,-150,162,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'INVERSA':([57,75,86,],[-150,-150,125,]),'TIMES':([106,107,110,112,113,114,115,117,120,144,146,153,154,155,156,158,190,198,199,203,218,219,226,257,258,305,315,],[-149,-157,-158,-140,-151,-151,-151,-150,-146,-151,-150,202,-155,-156,-154,-153,-156,-148,-147,-145,-109,-150,-150,-98,-153,-100,-99,]),'LPAREN':([6,11,27,28,36,48,51,56,57,60,63,75,78,79,80,82,85,87,91,95,103,104,105,116,124,126,127,129,131,146,160,161,162,163,164,165,166,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,219,239,245,246,247,248,256,291,293,294,307,309,],[17,-18,35,-61,-62,-152,82,-152,-88,90,-66,-88,-152,104,-152,116,123,-90,131,116,116,116,116,116,-152,116,-152,176,116,-88,-152,-152,-152,-152,116,-152,-152,116,116,116,116,116,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,-88,116,116,116,116,116,116,116,116,309,116,116,]),'COMA':([34,74,94,101,106,107,108,110,112,113,114,115,117,119,120,122,144,145,146,150,153,154,155,156,158,169,190,195,198,199,201,203,209,218,226,227,230,251,252,257,263,264,276,277,278,279,285,292,305,313,315,320,],[41,-59,134,142,-149,-157,-139,-158,-140,-151,-151,-151,-150,-126,-146,-28,-151,191,-150,-135,-141,-155,-156,-154,-153,214,239,-136,-148,-147,-142,-145,-134,-109,-97,-96,267,-127,-29,-98,-96,293,-137,-138,-144,-143,303,307,-100,-30,-99,323,]),'INPUT':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[56,56,56,-77,-79,-71,-74,-70,-80,-73,-75,-72,56,-19,-76,56,56,-78,56,-20,-21,-82,-81,-102,-103,56,-116,-111,-105,-117,-118,-38,-112,-101,-104,56,-39,-119,-116,-68,-113,-65,56,-69,]),'ELSE':([250,280,300,],[283,-38,-39,]),'ID':([2,12,13,14,15,16,22,23,24,25,37,41,45,46,50,52,53,54,58,61,62,66,67,68,72,78,80,82,83,84,89,90,95,96,100,103,104,105,109,111,116,123,124,126,127,131,132,134,139,151,152,160,161,162,163,164,165,166,167,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,212,214,217,223,238,239,244,245,246,247,248,249,250,255,256,261,267,274,275,280,282,289,290,291,293,295,300,303,304,307,309,312,318,319,322,323,326,328,],[3,-34,-37,-35,-36,28,34,-31,-32,-33,57,34,74,75,75,-77,-79,-71,-74,-70,-80,-73,-75,-72,75,-152,-152,117,122,-19,-76,130,117,75,75,117,146,117,-152,-152,117,170,-152,117,-152,117,-78,34,75,117,117,-152,-152,-152,-152,117,-152,-152,-20,117,219,226,117,146,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,-21,122,-82,-81,-102,146,-103,117,117,117,117,75,-116,-111,117,-105,34,-117,-118,-38,-112,-101,-104,117,226,75,-39,122,-119,226,117,-116,-68,-113,-65,122,75,-69,]),'IF':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[51,51,51,-77,-79,-71,-74,-70,-80,-73,-75,-72,51,-19,-76,51,51,-78,51,-20,-21,-82,-81,-102,-103,51,-116,-111,-105,-117,-118,-38,-112,-101,-104,51,-39,-119,-116,-68,-113,-65,51,-69,]),'LBRACE':([29,42,73,159,204,229,266,283,301,324,],[37,72,100,-114,249,-67,295,-115,249,326,]),'FROM':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[60,60,60,-77,-79,-71,-74,-70,-80,-73,-75,-72,60,-19,-76,60,60,-78,60,-20,-21,-82,-81,-102,-103,60,-116,-111,-105,-117,-118,-38,-112,-101,-104,60,-39,-119,-116,-68,-113,-65,60,-69,]),'INT':([5,10,35,39,55,142,167,],[12,23,23,23,23,23,23,]),'FLOAT':([5,10,35,39,55,142,167,],[14,24,24,24,24,24,24,]),'BREAK':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[65,65,65,-77,-79,-71,-74,-70,-80,-73,-75,-72,65,-19,-76,65,65,-78,65,-20,-21,-82,-81,-102,-103,65,-116,-111,-105,-117,-118,-38,-112,-101,-104,65,-39,-119,-116,-68,-113,-65,65,-69,]),'TRANSPUESTA':([57,75,86,],[-150,-150,128,]),'MAIN':([4,7,9,19,26,39,69,137,183,184,186,232,233,234,236,237,268,269,270,271,272,297,298,299,311,],[11,11,11,11,-6,-7,-8,-55,-40,-55,-55,-55,-42,-44,-46,-55,-41,-45,-55,-50,-47,-43,-49,-48,-51,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'creaTrans':([128,],[175,]),'creaCuadReturn':([135,],[181,]),'quad_fact':([112,],[153,]),'creaInversa':([125,],[172,]),'vars':([37,72,100,],[46,96,139,]),'condFinal':([250,312,],[282,319,]),'paramFuncion':([176,293,307,],[224,308,316,]),'push_function':([28,],[36,]),'push_arreglo':([252,],[285,]),'endProc':([137,184,186,232,237,270,],[183,234,236,268,272,298,]),'var_cte':([82,95,103,104,105,116,126,131,151,152,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[106,106,106,106,106,106,106,106,198,199,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,]),'while3':([318,],[322,]),'arreglo':([37,46,50,72,82,95,96,100,103,104,105,116,126,131,139,151,152,164,171,174,176,177,191,239,245,246,247,248,249,256,291,293,295,307,309,326,],[47,47,47,47,107,107,47,47,107,107,107,107,107,107,47,107,107,107,107,107,107,107,107,107,107,107,107,107,47,107,107,107,47,107,107,47,]),'nomMain':([4,7,9,19,],[6,6,6,6,]),'cond':([159,],[204,]),'termino':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,278,279,108,108,108,108,108,]),'create_asign':([143,149,220,221,],[189,194,259,260,]),'tipoFunc':([5,],[16,]),'bloque':([204,301,],[250,312,]),'push_id':([57,75,117,146,170,219,226,],[86,86,158,158,215,258,158,]),'quad_print':([192,193,254,],[242,243,286,]),'varsGlobal':([4,],[7,]),'matrix':([37,46,50,72,82,95,96,100,103,104,105,116,126,131,139,151,152,164,171,174,176,177,191,239,245,246,247,248,249,256,291,293,295,307,309,326,],[49,49,49,49,110,110,49,49,110,110,110,110,110,110,49,110,110,110,110,110,110,110,110,110,110,110,110,110,49,110,110,110,49,110,110,49,]),'tipo':([10,35,39,55,142,167,],[22,45,22,83,45,83,]),'inversa':([37,46,50,72,96,100,139,249,295,326,],[62,62,62,62,62,62,62,62,62,62,]),'exp1':([150,],[195,]),'estatuto':([37,46,50,72,96,100,139,249,295,326,],[50,50,50,50,50,50,50,50,50,50,]),'determinante':([174,],[222,]),'param':([35,142,],[43,188,]),'varAux2':([83,214,303,323,],[121,253,314,325,]),'varAuxGlobal2':([22,41,134,267,],[33,71,180,296,]),'varAuxGlobal1':([10,39,],[26,69,]),'program':([0,],[1,]),'functionReturn':([72,99,100,136,141,185,],[97,138,140,182,187,235,]),'varAux1':([55,167,],[84,212,]),'paramAvarTable':([74,],[101,]),'main':([4,7,9,19,],[8,18,21,31,]),'lectura':([37,46,50,72,96,100,139,249,295,326,],[52,52,52,52,52,52,52,52,52,52,]),'empty':([35,72,99,100,136,141,142,176,185,293,307,],[44,98,98,98,98,98,44,225,98,225,225,]),'function':([4,7,183,234,236,268,272,298,],[9,19,233,269,271,297,299,311,]),'escrituraAux':([104,191,239,],[147,240,273,]),'push_poper':([48,56,78,80,109,111,124,127,160,161,162,163,165,166,196,197,200,202,],[79,85,103,105,151,152,171,174,205,206,207,208,210,211,245,246,247,248,]),'push_var':([122,],[169,]),'gosub':([224,],[262,]),'ver_dim2':([305,],[315,]),'comp':([119,],[164,]),'factor':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,]),'actualizaFuncion':([57,75,146,219,],[87,87,87,87,]),'transpuesta':([37,46,50,72,96,100,139,249,295,326,],[53,53,53,53,53,53,53,53,53,53,]),'condElse':([283,],[301,]),'condicion':([37,46,50,72,96,100,139,249,295,326,],[54,54,54,54,54,54,54,54,54,54,]),'quad_term':([108,],[150,]),'push_cte':([113,114,115,144,],[154,155,156,190,]),'quad_comp':([209,],[251,]),'generarEra':([87,],[129,]),'loopFromDo':([37,46,50,72,96,100,139,249,295,326,],[58,58,58,58,58,58,58,58,58,58,]),'expresion':([82,104,116,131,171,174,177,191,239,291,309,],[118,145,157,178,216,220,228,145,145,306,317,]),'endPrograma':([8,18,21,31,],[20,30,32,38,]),'llamadaAFuncion':([37,46,50,72,96,100,104,139,174,191,239,249,295,326,],[59,76,76,76,76,76,148,76,221,241,241,76,76,76,]),'push_matriz':([313,],[320,]),'asignacion':([37,46,50,72,96,100,139,249,295,326,],[61,61,61,61,61,61,61,61,61,61,]),'while2':([229,],[266,]),'generaCuadbreak':([65,],[93,]),'while1':([63,],[91,]),'push_id2':([226,],[263,]),'bloqueAux':([37,46,50,72,96,100,139,249,295,326,],[64,77,81,99,136,141,185,281,310,327,]),'ver_dim1':([218,],[257,]),'while':([37,46,50,72,96,100,139,249,295,326,],[66,66,66,66,66,66,66,66,66,66,]),'termino1':([153,],[201,]),'exp':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,256,291,293,307,309,],[119,135,143,119,149,119,173,119,209,119,119,227,119,119,119,276,277,287,119,227,227,119,]),'nomFunc':([16,],[27,]),'factorAux':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,]),'comparacion':([37,46,50,72,96,100,139,249,295,326,],[67,67,67,67,67,67,67,67,67,67,]),'paramFuncionAux':([227,263,],[264,292,]),'escritura':([37,46,50,72,96,100,139,249,295,326,],[68,68,68,68,68,68,68,68,68,68,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> program","S'",1,None,None,None),
('program -> PROGRAM ID COLON varsGlobal function main endPrograma','program',7,'p_program','lexAndSyn.py',144),
('program -> PROGRAM ID COLON function main endPrograma','program',6,'p_program','lexAndSyn.py',145),
('program -> PROGRAM ID COLON varsGlobal main endPrograma','program',6,'p_program','lexAndSyn.py',146),
('program -> PROGRAM ID COLON main endPrograma','program',5,'p_program','lexAndSyn.py',147),
('endPrograma -> <empty>','endPrograma',0,'p_endPrograma','lexAndSyn.py',153),
('varsGlobal -> VAR varAuxGlobal1','varsGlobal',2,'p_varsGlobal','lexAndSyn.py',158),
('varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON','varAuxGlobal1',3,'p_varAuxGlobal1','lexAndSyn.py',162),
('varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON varAuxGlobal1','varAuxGlobal1',4,'p_varAuxGlobal1','lexAndSyn.py',163),
('varAuxGlobal2 -> ID','varAuxGlobal2',1,'p_varAuxGlobal2','lexAndSyn.py',167),
('varAuxGlobal2 -> ID COMA varAuxGlobal2','varAuxGlobal2',3,'p_varAuxGlobal2','lexAndSyn.py',168),
('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH','varAuxGlobal2',4,'p_varAuxGlobal2','lexAndSyn.py',169),
('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH COMA varAuxGlobal2','varAuxGlobal2',6,'p_varAuxGlobal2','lexAndSyn.py',170),
('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH','varAuxGlobal2',7,'p_varAuxGlobal2','lexAndSyn.py',171),
('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2','varAuxGlobal2',9,'p_varAuxGlobal2','lexAndSyn.py',172),
('main -> nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE','main',6,'p_main','lexAndSyn.py',180),
('main -> nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE','main',7,'p_main','lexAndSyn.py',181),
('main -> nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE','main',6,'p_main','lexAndSyn.py',182),
('nomMain -> MAIN','nomMain',1,'p_nomMain','lexAndSyn.py',186),
('vars -> VAR varAux1','vars',2,'p_vars','lexAndSyn.py',196),
('varAux1 -> tipo varAux2 SEMICOLON','varAux1',3,'p_varAux1','lexAndSyn.py',200),
('varAux1 -> tipo varAux2 SEMICOLON varAux1','varAux1',4,'p_varAux1','lexAndSyn.py',201),
('varAux2 -> ID push_var','varAux2',2,'p_varAux2','lexAndSyn.py',205),
('varAux2 -> ID push_var COMA varAux2','varAux2',4,'p_varAux2','lexAndSyn.py',206),
('varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo','varAux2',5,'p_varAux2','lexAndSyn.py',207),
('varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2','varAux2',7,'p_varAux2','lexAndSyn.py',208),
('varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz','varAux2',8,'p_varAux2','lexAndSyn.py',209),
('varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2','varAux2',10,'p_varAux2','lexAndSyn.py',210),
('push_var -> <empty>','push_var',0,'p_pushVariable','lexAndSyn.py',214),
('push_arreglo -> <empty>','push_arreglo',0,'p_arreglo','lexAndSyn.py',220),
('push_matriz -> <empty>','push_matriz',0,'p_matriz','lexAndSyn.py',231),
('tipo -> INT','tipo',1,'p_tipo','lexAndSyn.py',246),
('tipo -> FLOAT','tipo',1,'p_tipo','lexAndSyn.py',247),
('tipo -> CHAR','tipo',1,'p_tipo','lexAndSyn.py',248),
('tipoFunc -> INT','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',253),
('tipoFunc -> FLOAT','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',254),
('tipoFunc -> CHAR','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',255),
('tipoFunc -> VOID','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',256),
('bloque -> LBRACE RBRACE','bloque',2,'p_bloque','lexAndSyn.py',261),
('bloque -> LBRACE bloqueAux RBRACE','bloque',3,'p_bloque','lexAndSyn.py',262),
('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc','function',9,'p_function','lexAndSyn.py',268),
('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc','function',11,'p_function','lexAndSyn.py',269),
('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function','function',10,'p_function','lexAndSyn.py',270),
('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function','function',12,'p_function','lexAndSyn.py',271),
('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc','function',10,'p_function','lexAndSyn.py',272),
('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function','function',11,'p_function','lexAndSyn.py',273),
('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc','function',10,'p_function','lexAndSyn.py',274),
('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc','function',11,'p_function','lexAndSyn.py',275),
('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function','function',12,'p_function','lexAndSyn.py',276),
('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc','function',12,'p_function','lexAndSyn.py',277),
('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function','function',11,'p_function','lexAndSyn.py',278),
('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function','function',13,'p_function','lexAndSyn.py',279),
('functionReturn -> RETURN exp creaCuadReturn SEMICOLON','functionReturn',4,'p_functionReturn','lexAndSyn.py',283),
('functionReturn -> empty','functionReturn',1,'p_functionReturn','lexAndSyn.py',284),
('creaCuadReturn -> <empty>','creaCuadReturn',0,'p_creaCuadReturn','lexAndSyn.py',288),
('endProc -> <empty>','endProc',0,'p_endProc','lexAndSyn.py',293),
('param -> tipo ID paramAvarTable','param',3,'p_param','lexAndSyn.py',298),
('param -> tipo ID paramAvarTable COMA param','param',5,'p_param','lexAndSyn.py',299),
('param -> empty','param',1,'p_param','lexAndSyn.py',300),
('paramAvarTable -> <empty>','paramAvarTable',0,'p_paramAvarTable','lexAndSyn.py',305),
('empty -> <empty>','empty',0,'p_empty','lexAndSyn.py',311),
('push_function -> <empty>','push_function',0,'p_push_function','lexAndSyn.py',315),
('nomFunc -> ID push_function','nomFunc',2,'p_nomFunc','lexAndSyn.py',324),
('bloqueAux -> estatuto','bloqueAux',1,'p_bloqueAux','lexAndSyn.py',333),
('bloqueAux -> estatuto bloqueAux','bloqueAux',2,'p_bloqueAux','lexAndSyn.py',334),
('while -> WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3','while',10,'p_while','lexAndSyn.py',338),
('while1 -> <empty>','while1',0,'p_while1','lexAndSyn.py',342),
('while2 -> <empty>','while2',0,'p_while2','lexAndSyn.py',346),
('while3 -> <empty>','while3',0,'p_while3','lexAndSyn.py',350),
('loopFromDo -> FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE','loopFromDo',14,'p_loopFromDo','lexAndSyn.py',354),
('estatuto -> asignacion','estatuto',1,'p_estatuto','lexAndSyn.py',366),
('estatuto -> condicion','estatuto',1,'p_estatuto','lexAndSyn.py',367),
('estatuto -> escritura','estatuto',1,'p_estatuto','lexAndSyn.py',368),
('estatuto -> while','estatuto',1,'p_estatuto','lexAndSyn.py',369),
('estatuto -> loopFromDo','estatuto',1,'p_estatuto','lexAndSyn.py',370),
('estatuto -> comparacion','estatuto',1,'p_estatuto','lexAndSyn.py',371),
('estatuto -> llamadaAFuncion SEMICOLON','estatuto',2,'p_estatuto','lexAndSyn.py',372),
('estatuto -> lectura','estatuto',1,'p_estatuto','lexAndSyn.py',373),
('estatuto -> BREAK generaCuadbreak SEMICOLON','estatuto',3,'p_estatuto','lexAndSyn.py',374),
('estatuto -> transpuesta','estatuto',1,'p_estatuto','lexAndSyn.py',375),
('estatuto -> inversa','estatuto',1,'p_estatuto','lexAndSyn.py',376),
('transpuesta -> ID push_id TRANSPUESTA creaTrans SEMICOLON','transpuesta',5,'p_transpuesta','lexAndSyn.py',380),
('inversa -> ID push_id INVERSA creaInversa SEMICOLON','inversa',5,'p_inversa','lexAndSyn.py',383),
('creaInversa -> <empty>','creaInversa',0,'p_creaInversa','lexAndSyn.py',387),
('creaTrans -> <empty>','creaTrans',0,'p_creaTrans','lexAndSyn.py',391),
('generaCuadbreak -> <empty>','generaCuadbreak',0,'p_generaCuadbreak','lexAndSyn.py',395),
('llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion','llamadaAFuncion',8,'p_llamadaAFuncion','lexAndSyn.py',399),
('llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN','llamadaAFuncion',7,'p_llamadaAFuncion','lexAndSyn.py',400),
('actualizaFuncion -> <empty>','actualizaFuncion',0,'p_actualizaFuncion','lexAndSyn.py',404),
('gosub -> <empty>','gosub',0,'p_gosub','lexAndSyn.py',409),
('generarEra -> <empty>','generarEra',0,'p_generarEra','lexAndSyn.py',421),
('paramFuncion -> ID push_id2 paramFuncionAux','paramFuncion',3,'p_paramFuncion','lexAndSyn.py',429),
('paramFuncion -> ID push_id2 paramFuncionAux COMA paramFuncion','paramFuncion',5,'p_paramFuncion','lexAndSyn.py',430),
('paramFuncion -> exp paramFuncionAux','paramFuncion',2,'p_paramFuncion','lexAndSyn.py',431),
('paramFuncion -> exp paramFuncionAux COMA paramFuncion','paramFuncion',4,'p_paramFuncion','lexAndSyn.py',432),
('paramFuncion -> empty','paramFuncion',1,'p_paramFuncion','lexAndSyn.py',433),
('paramFuncionAux -> <empty>','paramFuncionAux',0,'p_paramFuncionAux','lexAndSyn.py',437),
('push_id2 -> <empty>','push_id2',0,'p_push_id2','lexAndSyn.py',441),
('arreglo -> ID push_id LCORCH exp RCORCH ver_dim1','arreglo',6,'p_array','lexAndSyn.py',445),
('matrix -> ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2','matrix',9,'p_matrix','lexAndSyn.py',449),
('ver_dim2 -> <empty>','ver_dim2',0,'p_ver_dim2','lexAndSyn.py',453),
('asignacion -> ID push_id EQUAL push_poper expresion create_asign SEMICOLON','asignacion',7,'p_asignacion','lexAndSyn.py',457),
('asignacion -> arreglo EQUAL push_poper exp create_asign SEMICOLON','asignacion',6,'p_asignacion','lexAndSyn.py',458),
('asignacion -> matrix EQUAL push_poper exp create_asign SEMICOLON','asignacion',6,'p_asignacion','lexAndSyn.py',459),
('asignacion -> ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON','asignacion',7,'p_asignacion','lexAndSyn.py',460),
('asignacion -> ID push_id EQUAL push_poper determinante SEMICOLON','asignacion',6,'p_asignacion','lexAndSyn.py',461),
('determinante -> ID push_id DETERMINANT','determinante',3,'p_determinante','lexAndSyn.py',465),
('push_id_dimensionada -> <empty>','push_id_dimensionada',0,'p_push_id_dimensionada','lexAndSyn.py',470),
('create_asign_dim -> <empty>','create_asign_dim',0,'p_create_asign_dim','lexAndSyn.py',473),
('ver_dim1 -> <empty>','ver_dim1',0,'p_ver_dim1','lexAndSyn.py',477),
('create_asign -> <empty>','create_asign',0,'p_create_asign','lexAndSyn.py',481),
('comparacion -> ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON','comparacion',6,'p_comparacion','lexAndSyn.py',485),
('condicion -> IF LPAREN expresion RPAREN cond bloque condFinal','condicion',7,'p_condicion','lexAndSyn.py',489),
('condicion -> IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal','condicion',10,'p_condicion','lexAndSyn.py',490),
('cond -> <empty>','cond',0,'p_quad_cond','lexAndSyn.py',494),
('condElse -> <empty>','condElse',0,'p_quad_condElse','lexAndSyn.py',498),
('condFinal -> <empty>','condFinal',0,'p_quad_condFinal','lexAndSyn.py',502),
('escritura -> PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON','escritura',7,'p_escritura','lexAndSyn.py',506),
('escritura -> PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON','escritura',7,'p_escritura','lexAndSyn.py',507),
('lectura -> INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON','lectura',8,'p_lectura','lexAndSyn.py',511),
('quad_print -> <empty>','quad_print',0,'p_quad_print','lexAndSyn.py',515),
('escrituraAux -> expresion','escrituraAux',1,'p_escrituraAux','lexAndSyn.py',519),
('escrituraAux -> CTE_STRING push_cte','escrituraAux',2,'p_escrituraAux','lexAndSyn.py',520),
('escrituraAux -> expresion COMA escrituraAux','escrituraAux',3,'p_escrituraAux','lexAndSyn.py',521),
('escrituraAux -> CTE_STRING push_cte COMA escrituraAux','escrituraAux',4,'p_escrituraAux','lexAndSyn.py',522),
('escrituraAux -> llamadaAFuncion','escrituraAux',1,'p_escrituraAux','lexAndSyn.py',523),
('expresion -> exp','expresion',1,'p_expresion','lexAndSyn.py',527),
('expresion -> exp comp exp quad_comp','expresion',4,'p_expresion','lexAndSyn.py',528),
('comp -> LOWERTHAN push_poper','comp',2,'p_comp','lexAndSyn.py',532),
('comp -> MORETHAN push_poper','comp',2,'p_comp','lexAndSyn.py',533),
('comp -> DIFFERENT push_poper','comp',2,'p_comp','lexAndSyn.py',534),
('comp -> DOUBLEEQUAL push_poper','comp',2,'p_comp','lexAndSyn.py',535),
('comp -> LOWEREQUAL push_poper','comp',2,'p_comp','lexAndSyn.py',536),
('comp -> MOREEQUAL push_poper','comp',2,'p_comp','lexAndSyn.py',537),
('quad_comp -> <empty>','quad_comp',0,'p_quad_comp','lexAndSyn.py',541),
('exp -> termino quad_term','exp',2,'p_exp','lexAndSyn.py',545),
('exp -> termino quad_term exp1','exp',3,'p_exp','lexAndSyn.py',546),
('exp1 -> PLUS push_poper exp','exp1',3,'p_exp1','lexAndSyn.py',550),
('exp1 -> MINUS push_poper exp','exp1',3,'p_exp1','lexAndSyn.py',551),
('quad_term -> <empty>','quad_term',0,'p_quad_term','lexAndSyn.py',555),
('quad_fact -> <empty>','quad_fact',0,'p_quad_fact','lexAndSyn.py',559),
('termino -> factor quad_fact','termino',2,'p_termino','lexAndSyn.py',563),
('termino -> factor quad_fact termino1','termino',3,'p_termino','lexAndSyn.py',564),
('termino1 -> TIMES push_poper termino','termino1',3,'p_termino1','lexAndSyn.py',568),
('termino1 -> DIVIDE push_poper termino','termino1',3,'p_termino1','lexAndSyn.py',569),
('factor -> LPAREN expresion RPAREN','factor',3,'p_factor','lexAndSyn.py',573),
('factor -> factorAux','factor',1,'p_factor','lexAndSyn.py',574),
('factorAux -> PLUS push_poper var_cte','factorAux',3,'p_factorAux','lexAndSyn.py',578),
('factorAux -> MINUS push_poper var_cte','factorAux',3,'p_factorAux','lexAndSyn.py',579),
('factorAux -> var_cte','factorAux',1,'p_factorAux','lexAndSyn.py',580),
('push_id -> <empty>','push_id',0,'p_push_id','lexAndSyn.py',584),
('push_cte -> <empty>','push_cte',0,'p_push_cte','lexAndSyn.py',588),
('push_poper -> <empty>','push_poper',0,'p_push_poper','lexAndSyn.py',598),
('var_cte -> ID push_id','var_cte',2,'p_var_cte','lexAndSyn.py',602),
('var_cte -> CTE_I push_cte','var_cte',2,'p_var_cte','lexAndSyn.py',603),
('var_cte -> CTE_F push_cte','var_cte',2,'p_var_cte','lexAndSyn.py',604),
('var_cte -> CTE_STRING push_cte','var_cte',2,'p_var_cte','lexAndSyn.py',605),
('var_cte -> arreglo','var_cte',1,'p_var_cte','lexAndSyn.py',606),
('var_cte -> matrix','var_cte',1,'p_var_cte','lexAndSyn.py',607),
]
|
flexible
|
{
"blob_id": "160f272edd8283ea561552f22c71967db4a1660a",
"index": 7983,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor _k, _v in _lr_action_items.items():\n for _x, _y in zip(_v[0], _v[1]):\n if not _x in _lr_action:\n _lr_action[_x] = {}\n _lr_action[_x][_k] = _y\ndel _lr_action_items\n<mask token>\nfor _k, _v in _lr_goto_items.items():\n for _x, _y in zip(_v[0], _v[1]):\n if not _x in _lr_goto:\n _lr_goto[_x] = {}\n _lr_goto[_x][_k] = _y\ndel _lr_goto_items\n<mask token>\n",
"step-3": "_tabversion = '3.10'\n_lr_method = 'LALR'\n_lr_signature = \"\"\"AND BREAK CHAR COLON COMA CTE_F CTE_I CTE_STRING DETERMINANT DIFFERENT DIVIDE DO DOUBLEEQUAL ELSE EQUAL FLOAT FROM FUNCTION ID IF INPUT INT INVERSA LBRACE LCORCH LOWEREQUAL LOWERTHAN LPAREN MAIN MINUS MOREEQUAL MORETHAN OR PLUS PRINT PROGRAM RBRACE RCORCH RETURN RPAREN SEMICOLON TIMES TO TRANSPUESTA VAR VOID WHILEprogram : PROGRAM ID COLON varsGlobal function main endPrograma\n | PROGRAM ID COLON function main endPrograma\n | PROGRAM ID COLON varsGlobal main endPrograma\n | PROGRAM ID COLON main endPrograma\n endPrograma :varsGlobal : VAR varAuxGlobal1\n varAuxGlobal1 : tipo varAuxGlobal2 SEMICOLON\n | tipo varAuxGlobal2 SEMICOLON varAuxGlobal1\n varAuxGlobal2 : ID\n | ID COMA varAuxGlobal2\n | ID LCORCH CTE_I RCORCH\n | ID LCORCH CTE_I RCORCH COMA varAuxGlobal2\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2\n main : nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE\n | nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE\n | nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE\n nomMain : MAIN\n vars : VAR varAux1\n varAux1 : tipo varAux2 SEMICOLON\n | tipo varAux2 SEMICOLON varAux1\n varAux2 : ID push_var\n | ID push_var COMA varAux2\n | ID LCORCH CTE_I RCORCH push_arreglo\n | ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2\n push_var :push_arreglo :push_matriz :tipo : INT\n | FLOAT\n | CHAR\n tipoFunc : INT\n | FLOAT\n | CHAR\n | VOID\n bloque : LBRACE RBRACE\n | LBRACE bloqueAux RBRACE\n function : FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function \n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc \n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function\n functionReturn : RETURN exp creaCuadReturn SEMICOLON\n | empty\n creaCuadReturn :\n endProc :\n param : tipo ID paramAvarTable\n | tipo ID paramAvarTable COMA param\n | empty\n paramAvarTable : empty : \n push_function :nomFunc : ID push_function\n bloqueAux : estatuto\n | estatuto bloqueAux\n while : WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3\n while1 :while2 :while3 :loopFromDo : FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE\n estatuto : asignacion\n | condicion\n | escritura\n | while\n | loopFromDo\n | comparacion\n | llamadaAFuncion SEMICOLON\n | lectura\n | BREAK generaCuadbreak SEMICOLON\n | transpuesta\n | inversa\n transpuesta : ID push_id TRANSPUESTA creaTrans SEMICOLON\n inversa : ID push_id INVERSA creaInversa SEMICOLON\n creaInversa : creaTrans : generaCuadbreak : llamadaAFuncion : ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion\n | ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN\n actualizaFuncion : gosub :\n generarEra :\n paramFuncion : ID push_id2 paramFuncionAux\n | ID push_id2 paramFuncionAux COMA paramFuncion\n | exp paramFuncionAux\n | exp paramFuncionAux COMA paramFuncion\n | empty\n paramFuncionAux : push_id2 :arreglo : ID push_id LCORCH exp RCORCH ver_dim1\n matrix : ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2\n ver_dim2 : asignacion : ID push_id EQUAL push_poper expresion create_asign SEMICOLON\n | arreglo EQUAL push_poper exp create_asign SEMICOLON\n | matrix EQUAL push_poper exp create_asign SEMICOLON\n | ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON\n | ID push_id EQUAL push_poper determinante SEMICOLON\n determinante : ID push_id DETERMINANT\n push_id_dimensionada :create_asign_dim :ver_dim1 :create_asign :comparacion : ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON\n condicion : IF LPAREN expresion RPAREN cond bloque condFinal\n | IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal\n cond :condElse :condFinal :escritura : PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON\n | PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON\n lectura : INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON\n quad_print :escrituraAux : expresion\n | CTE_STRING push_cte\n | expresion COMA escrituraAux\n | CTE_STRING push_cte COMA escrituraAux\n | llamadaAFuncion\n expresion : exp\n | exp comp exp quad_comp\n comp : LOWERTHAN push_poper\n | MORETHAN push_poper\n | DIFFERENT push_poper\n | DOUBLEEQUAL push_poper\n | LOWEREQUAL push_poper\n | MOREEQUAL push_poper\n quad_comp :exp : termino quad_term\n | termino quad_term exp1\n exp1 : PLUS push_poper exp\n | MINUS push_poper exp\n quad_term :quad_fact :termino : factor quad_fact\n | factor quad_fact termino1\n termino1 : TIMES push_poper termino\n | DIVIDE push_poper termino\n factor : LPAREN expresion RPAREN\n | factorAux\n factorAux : PLUS push_poper var_cte\n | MINUS push_poper var_cte\n | var_cte \n push_id :push_cte :push_poper :var_cte : ID push_id\n | CTE_I push_cte\n | CTE_F push_cte\n | CTE_STRING push_cte\n | arreglo\n | matrix\n \"\"\"\n_lr_action_items = {'MOREEQUAL': ([106, 107, 108, 110, 112, 113, 114, 115, \n 117, 119, 120, 144, 146, 150, 153, 154, 155, 156, 158, 190, 195, 198, \n 199, 201, 203, 218, 219, 257, 258, 276, 277, 278, 279, 305, 315], [-149,\n -157, -139, -158, -140, -151, -151, -151, -150, 160, -146, -151, -150, \n -135, -141, -155, -156, -154, -153, -156, -136, -148, -147, -142, -145,\n -109, -150, -98, -153, -137, -138, -144, -143, -100, -99]),\n 'CTE_STRING': ([78, 80, 82, 95, 103, 104, 105, 109, 111, 116, 124, 126,\n 127, 131, 151, 152, 160, 161, 162, 163, 164, 165, 166, 171, 174, 176, \n 177, 191, 196, 197, 200, 202, 205, 206, 207, 208, 210, 211, 239, 245, \n 246, 247, 248, 256, 291, 293, 307, 309], [-152, -152, 114, 114, 114, \n 144, 114, -152, -152, 114, -152, 114, -152, 114, 114, 114, -152, -152, \n -152, -152, 114, -152, -152, 114, 114, 114, 114, 144, -152, -152, -152,\n -152, -133, -130, -131, -128, -132, -129, 144, 114, 114, 114, 114, 114,\n 114, 114, 114, 114]), 'LCORCH': ([34, 57, 75, 86, 94, 117, 122, 146, \n 158, 218, 219, 226, 252, 258], [40, -150, -150, 126, 133, -150, 168, -\n 150, 126, 256, -150, -150, 284, 126]), 'RETURN': ([50, 52, 53, 54, 58, \n 61, 62, 66, 67, 68, 72, 81, 89, 99, 100, 132, 136, 141, 185, 217, 223, \n 238, 244, 250, 255, 261, 274, 275, 280, 282, 289, 290, 300, 304, 312, \n 318, 319, 322, 328], [-63, -77, -79, -71, -74, -70, -80, -73, -75, -72,\n 95, -64, -76, 95, 95, -78, 95, 95, 95, -82, -81, -102, -103, -116, -111,\n -105, -117, -118, -38, -112, -101, -104, -39, -119, -116, -68, -113, -\n 65, -69]), 'DO': ([321], [324]), 'VOID': ([5], [13]), 'EQUAL': ([47, 49,\n 57, 75, 86, 130, 218, 257, 305, 315], [78, 80, -150, -150, 127, 177, -\n 109, -98, -100, -99]), 'CHAR': ([5, 10, 35, 39, 55, 142, 167], [15, 25,\n 25, 25, 25, 25, 25]), 'VAR': ([4, 37, 72, 100], [10, 55, 55, 55]),\n 'WHILE': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68, 72, 84, 89, \n 96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250, 255, 261, \n 274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319, 322, 326, \n 328], [63, 63, 63, -77, -79, -71, -74, -70, -80, -73, -75, -72, 63, -19,\n -76, 63, 63, -78, 63, -20, -21, -82, -81, -102, -103, 63, -116, -111, -\n 105, -117, -118, -38, -112, -101, -104, 63, -39, -119, -116, -68, -113,\n -65, 63, -69]), 'PROGRAM': ([0], [2]), 'PRINT': ([37, 46, 50, 52, 53, \n 54, 58, 61, 62, 66, 67, 68, 72, 84, 89, 96, 100, 132, 139, 167, 212, \n 217, 223, 238, 244, 249, 250, 255, 261, 274, 275, 280, 282, 289, 290, \n 295, 300, 304, 312, 318, 319, 322, 326, 328], [48, 48, 48, -77, -79, -\n 71, -74, -70, -80, -73, -75, -72, 48, -19, -76, 48, 48, -78, 48, -20, -\n 21, -82, -81, -102, -103, 48, -116, -111, -105, -117, -118, -38, -112, \n -101, -104, 48, -39, -119, -116, -68, -113, -65, 48, -69]), 'MORETHAN':\n ([106, 107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 144, 146, 150,\n 153, 154, 155, 156, 158, 190, 195, 198, 199, 201, 203, 218, 219, 257, \n 258, 276, 277, 278, 279, 305, 315], [-149, -157, -139, -158, -140, -151,\n -151, -151, -150, 166, -146, -151, -150, -135, -141, -155, -156, -154, \n -153, -156, -136, -148, -147, -142, -145, -109, -150, -98, -153, -137, \n -138, -144, -143, -100, -99]), 'MINUS': ([78, 80, 82, 95, 103, 104, 105,\n 106, 107, 108, 110, 112, 113, 114, 115, 116, 117, 120, 124, 126, 127, \n 131, 144, 146, 150, 153, 154, 155, 156, 158, 160, 161, 162, 163, 164, \n 165, 166, 171, 174, 176, 177, 190, 191, 196, 197, 198, 199, 200, 201, \n 202, 203, 205, 206, 207, 208, 210, 211, 218, 219, 226, 239, 245, 246, \n 247, 248, 256, 257, 258, 278, 279, 291, 293, 305, 307, 309, 315], [-152,\n -152, 109, 109, 109, 109, 109, -149, -157, -139, -158, -140, -151, -151,\n -151, 109, -150, -146, -152, 109, -152, 109, -151, -150, 197, -141, -\n 155, -156, -154, -153, -152, -152, -152, -152, 109, -152, -152, 109, \n 109, 109, 109, -156, 109, -152, -152, -148, -147, -152, -142, -152, -\n 145, -133, -130, -131, -128, -132, -129, -109, -150, -150, 109, 109, \n 109, 109, 109, 109, -98, -153, -144, -143, 109, 109, -100, 109, 109, -\n 99]), 'DIVIDE': ([106, 107, 110, 112, 113, 114, 115, 117, 120, 144, 146,\n 153, 154, 155, 156, 158, 190, 198, 199, 203, 218, 219, 226, 257, 258, \n 305, 315], [-149, -157, -158, -140, -151, -151, -151, -150, -146, -151,\n -150, 200, -155, -156, -154, -153, -156, -148, -147, -145, -109, -150, \n -150, -98, -153, -100, -99]), 'RCORCH': ([70, 106, 107, 108, 110, 112, \n 113, 114, 115, 117, 120, 150, 153, 154, 155, 156, 158, 173, 179, 195, \n 198, 199, 201, 203, 213, 218, 257, 276, 277, 278, 279, 287, 302, 305, \n 315], [94, -149, -157, -139, -158, -140, -151, -151, -151, -150, -146, \n -135, -141, -155, -156, -154, -153, 218, 230, -136, -148, -147, -142, -\n 145, 252, -109, -98, -137, -138, -144, -143, 305, 313, -100, -99]),\n 'DETERMINANT': ([219, 258], [-150, 288]), 'RPAREN': ([17, 35, 43, 44, \n 74, 101, 106, 107, 108, 110, 112, 113, 114, 115, 117, 118, 119, 120, \n 142, 144, 145, 146, 147, 148, 150, 153, 154, 155, 156, 157, 158, 170, \n 176, 178, 188, 190, 195, 198, 199, 201, 203, 209, 215, 218, 224, 225, \n 226, 227, 228, 240, 241, 251, 257, 262, 263, 264, 273, 276, 277, 278, \n 279, 291, 292, 293, 305, 306, 307, 308, 315, 316, 317], [29, 42, 73, -\n 58, -59, -56, -149, -157, -139, -158, -140, -151, -151, -151, -150, 159,\n -126, -146, -60, -151, -121, -150, 192, 193, -135, -141, -155, -156, -\n 154, 203, -153, -150, -60, 229, -57, -122, -136, -148, -147, -142, -145,\n -134, 254, -109, -89, -95, -97, -96, 265, -123, -125, -127, -98, 291, -\n 96, -93, -124, -137, -138, -144, -143, -87, -91, -60, -100, -86, -60, -\n 94, -99, -92, 321]), 'SEMICOLON': ([33, 34, 59, 65, 71, 76, 93, 94, 106,\n 107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 121, 122, 125, 128, \n 135, 143, 149, 150, 153, 154, 155, 156, 158, 169, 172, 175, 180, 181, \n 189, 192, 193, 194, 195, 198, 199, 201, 203, 209, 216, 218, 219, 220, \n 221, 222, 230, 242, 243, 251, 252, 253, 254, 257, 258, 259, 260, 276, \n 277, 278, 279, 285, 286, 288, 291, 296, 305, 306, 313, 314, 315, 320, \n 325], [39, -9, 89, -85, -10, 89, 132, -11, -149, -157, -139, -158, -140,\n -151, -151, -151, -150, -126, -146, 167, -28, -83, -84, -54, -110, -110,\n -135, -141, -155, -156, -154, -153, -22, 217, 223, -12, 231, 238, -120,\n -120, 244, -136, -148, -147, -142, -145, -134, 255, -109, -150, -110, -\n 110, 261, -13, 274, 275, -127, -29, -23, -120, -98, -153, 289, 290, -\n 137, -138, -144, -143, -24, 304, -106, -87, -14, -100, -86, -30, -25, -\n 99, -26, -27]), 'LOWERTHAN': ([106, 107, 108, 110, 112, 113, 114, 115, \n 117, 119, 120, 144, 146, 150, 153, 154, 155, 156, 158, 190, 195, 198, \n 199, 201, 203, 218, 219, 257, 258, 276, 277, 278, 279, 305, 315], [-149,\n -157, -139, -158, -140, -151, -151, -151, -150, 163, -146, -151, -150, \n -135, -141, -155, -156, -154, -153, -156, -136, -148, -147, -142, -145,\n -109, -150, -98, -153, -137, -138, -144, -143, -100, -99]),\n 'LOWEREQUAL': ([106, 107, 108, 110, 112, 113, 114, 115, 117, 119, 120, \n 144, 146, 150, 153, 154, 155, 156, 158, 190, 195, 198, 199, 201, 203, \n 218, 219, 257, 258, 276, 277, 278, 279, 305, 315], [-149, -157, -139, -\n 158, -140, -151, -151, -151, -150, 165, -146, -151, -150, -135, -141, -\n 155, -156, -154, -153, -156, -136, -148, -147, -142, -145, -109, -150, \n -98, -153, -137, -138, -144, -143, -100, -99]), 'TO': ([265], [294]),\n 'COLON': ([3], [4]), 'CTE_I': ([40, 78, 80, 82, 95, 103, 104, 105, 109,\n 111, 116, 124, 126, 127, 131, 133, 151, 152, 160, 161, 162, 163, 164, \n 165, 166, 168, 171, 174, 176, 177, 191, 196, 197, 200, 202, 205, 206, \n 207, 208, 210, 211, 239, 245, 246, 247, 248, 256, 284, 291, 293, 307, \n 309], [70, -152, -152, 115, 115, 115, 115, 115, -152, -152, 115, -152, \n 115, -152, 115, 179, 115, 115, -152, -152, -152, -152, 115, -152, -152,\n 213, 115, 115, 115, 115, 115, -152, -152, -152, -152, -133, -130, -131,\n -128, -132, -129, 115, 115, 115, 115, 115, 115, 302, 115, 115, 115, 115\n ]), 'CTE_F': ([78, 80, 82, 95, 103, 104, 105, 109, 111, 116, 124, 126, \n 127, 131, 151, 152, 160, 161, 162, 163, 164, 165, 166, 171, 174, 176, \n 177, 191, 196, 197, 200, 202, 205, 206, 207, 208, 210, 211, 239, 245, \n 246, 247, 248, 256, 291, 293, 307, 309], [-152, -152, 113, 113, 113, \n 113, 113, -152, -152, 113, -152, 113, -152, 113, 113, 113, -152, -152, \n -152, -152, 113, -152, -152, 113, 113, 113, 113, 113, -152, -152, -152,\n -152, -133, -130, -131, -128, -132, -129, 113, 113, 113, 113, 113, 113,\n 113, 113, 113, 113]), 'PLUS': ([78, 80, 82, 95, 103, 104, 105, 106, 107,\n 108, 110, 112, 113, 114, 115, 116, 117, 120, 124, 126, 127, 131, 144, \n 146, 150, 153, 154, 155, 156, 158, 160, 161, 162, 163, 164, 165, 166, \n 171, 174, 176, 177, 190, 191, 196, 197, 198, 199, 200, 201, 202, 203, \n 205, 206, 207, 208, 210, 211, 218, 219, 226, 239, 245, 246, 247, 248, \n 256, 257, 258, 278, 279, 291, 293, 305, 307, 309, 315], [-152, -152, \n 111, 111, 111, 111, 111, -149, -157, -139, -158, -140, -151, -151, -151,\n 111, -150, -146, -152, 111, -152, 111, -151, -150, 196, -141, -155, -\n 156, -154, -153, -152, -152, -152, -152, 111, -152, -152, 111, 111, 111,\n 111, -156, 111, -152, -152, -148, -147, -152, -142, -152, -145, -133, -\n 130, -131, -128, -132, -129, -109, -150, -150, 111, 111, 111, 111, 111,\n 111, -98, -153, -144, -143, 111, 111, -100, 111, 111, -99]), '$end': ([\n 1, 8, 18, 20, 21, 30, 31, 32, 38, 88, 92, 102], [0, -5, -5, -4, -5, -3,\n -5, -2, -1, -17, -15, -16]), 'FUNCTION': ([4, 7, 26, 39, 69, 137, 183, \n 184, 186, 232, 234, 236, 237, 268, 270, 272, 298], [5, 5, -6, -7, -8, -\n 55, 5, -55, -55, -55, 5, 5, -55, 5, -55, 5, 5]), 'DIFFERENT': ([106, \n 107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 144, 146, 150, 153, \n 154, 155, 156, 158, 190, 195, 198, 199, 201, 203, 218, 219, 257, 258, \n 276, 277, 278, 279, 305, 315], [-149, -157, -139, -158, -140, -151, -\n 151, -151, -150, 161, -146, -151, -150, -135, -141, -155, -156, -154, -\n 153, -156, -136, -148, -147, -142, -145, -109, -150, -98, -153, -137, -\n 138, -144, -143, -100, -99]), 'RBRACE': ([50, 52, 53, 54, 58, 59, 61, \n 62, 64, 66, 67, 68, 72, 77, 81, 89, 97, 98, 99, 100, 106, 107, 108, 110,\n 112, 113, 114, 115, 117, 119, 120, 132, 136, 138, 140, 141, 150, 153, \n 154, 155, 156, 158, 182, 185, 187, 195, 198, 199, 201, 203, 209, 217, \n 218, 223, 231, 235, 238, 244, 249, 250, 251, 255, 257, 261, 274, 275, \n 276, 277, 278, 279, 280, 281, 282, 289, 290, 291, 300, 304, 305, 306, \n 310, 312, 315, 318, 319, 322, 327, 328], [-63, -77, -79, -71, -74, 88, \n -70, -80, 92, -73, -75, -72, -60, 102, -64, -76, 137, -53, -60, -60, -\n 149, -157, -139, -158, -140, -151, -151, -151, -150, -126, -146, -78, -\n 60, 184, 186, -60, -135, -141, -155, -156, -154, -153, 232, -60, 237, -\n 136, -148, -147, -142, -145, -134, -82, -109, -81, -52, 270, -102, -103,\n 280, -116, -127, -111, -98, -105, -117, -118, -137, -138, -144, -143, -\n 38, 300, -112, -101, -104, -87, -39, -119, -100, -86, 318, -116, -99, -\n 68, -113, -65, 328, -69]), 'DOUBLEEQUAL': ([57, 75, 86, 106, 107, 108, \n 110, 112, 113, 114, 115, 117, 119, 120, 144, 146, 150, 153, 154, 155, \n 156, 158, 190, 195, 198, 199, 201, 203, 218, 219, 257, 258, 276, 277, \n 278, 279, 305, 315], [-150, -150, 124, -149, -157, -139, -158, -140, -\n 151, -151, -151, -150, 162, -146, -151, -150, -135, -141, -155, -156, -\n 154, -153, -156, -136, -148, -147, -142, -145, -109, -150, -98, -153, -\n 137, -138, -144, -143, -100, -99]), 'INVERSA': ([57, 75, 86], [-150, -\n 150, 125]), 'TIMES': ([106, 107, 110, 112, 113, 114, 115, 117, 120, 144,\n 146, 153, 154, 155, 156, 158, 190, 198, 199, 203, 218, 219, 226, 257, \n 258, 305, 315], [-149, -157, -158, -140, -151, -151, -151, -150, -146, \n -151, -150, 202, -155, -156, -154, -153, -156, -148, -147, -145, -109, \n -150, -150, -98, -153, -100, -99]), 'LPAREN': ([6, 11, 27, 28, 36, 48, \n 51, 56, 57, 60, 63, 75, 78, 79, 80, 82, 85, 87, 91, 95, 103, 104, 105, \n 116, 124, 126, 127, 129, 131, 146, 160, 161, 162, 163, 164, 165, 166, \n 171, 174, 176, 177, 191, 196, 197, 200, 202, 205, 206, 207, 208, 210, \n 211, 219, 239, 245, 246, 247, 248, 256, 291, 293, 294, 307, 309], [17, \n -18, 35, -61, -62, -152, 82, -152, -88, 90, -66, -88, -152, 104, -152, \n 116, 123, -90, 131, 116, 116, 116, 116, 116, -152, 116, -152, 176, 116,\n -88, -152, -152, -152, -152, 116, -152, -152, 116, 116, 116, 116, 116, \n -152, -152, -152, -152, -133, -130, -131, -128, -132, -129, -88, 116, \n 116, 116, 116, 116, 116, 116, 116, 309, 116, 116]), 'COMA': ([34, 74, \n 94, 101, 106, 107, 108, 110, 112, 113, 114, 115, 117, 119, 120, 122, \n 144, 145, 146, 150, 153, 154, 155, 156, 158, 169, 190, 195, 198, 199, \n 201, 203, 209, 218, 226, 227, 230, 251, 252, 257, 263, 264, 276, 277, \n 278, 279, 285, 292, 305, 313, 315, 320], [41, -59, 134, 142, -149, -157,\n -139, -158, -140, -151, -151, -151, -150, -126, -146, -28, -151, 191, -\n 150, -135, -141, -155, -156, -154, -153, 214, 239, -136, -148, -147, -\n 142, -145, -134, -109, -97, -96, 267, -127, -29, -98, -96, 293, -137, -\n 138, -144, -143, 303, 307, -100, -30, -99, 323]), 'INPUT': ([37, 46, 50,\n 52, 53, 54, 58, 61, 62, 66, 67, 68, 72, 84, 89, 96, 100, 132, 139, 167,\n 212, 217, 223, 238, 244, 249, 250, 255, 261, 274, 275, 280, 282, 289, \n 290, 295, 300, 304, 312, 318, 319, 322, 326, 328], [56, 56, 56, -77, -\n 79, -71, -74, -70, -80, -73, -75, -72, 56, -19, -76, 56, 56, -78, 56, -\n 20, -21, -82, -81, -102, -103, 56, -116, -111, -105, -117, -118, -38, -\n 112, -101, -104, 56, -39, -119, -116, -68, -113, -65, 56, -69]), 'ELSE':\n ([250, 280, 300], [283, -38, -39]), 'ID': ([2, 12, 13, 14, 15, 16, 22, \n 23, 24, 25, 37, 41, 45, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68, 72,\n 78, 80, 82, 83, 84, 89, 90, 95, 96, 100, 103, 104, 105, 109, 111, 116, \n 123, 124, 126, 127, 131, 132, 134, 139, 151, 152, 160, 161, 162, 163, \n 164, 165, 166, 167, 171, 174, 176, 177, 191, 196, 197, 200, 202, 205, \n 206, 207, 208, 210, 211, 212, 214, 217, 223, 238, 239, 244, 245, 246, \n 247, 248, 249, 250, 255, 256, 261, 267, 274, 275, 280, 282, 289, 290, \n 291, 293, 295, 300, 303, 304, 307, 309, 312, 318, 319, 322, 323, 326, \n 328], [3, -34, -37, -35, -36, 28, 34, -31, -32, -33, 57, 34, 74, 75, 75,\n -77, -79, -71, -74, -70, -80, -73, -75, -72, 75, -152, -152, 117, 122, \n -19, -76, 130, 117, 75, 75, 117, 146, 117, -152, -152, 117, 170, -152, \n 117, -152, 117, -78, 34, 75, 117, 117, -152, -152, -152, -152, 117, -\n 152, -152, -20, 117, 219, 226, 117, 146, -152, -152, -152, -152, -133, \n -130, -131, -128, -132, -129, -21, 122, -82, -81, -102, 146, -103, 117,\n 117, 117, 117, 75, -116, -111, 117, -105, 34, -117, -118, -38, -112, -\n 101, -104, 117, 226, 75, -39, 122, -119, 226, 117, -116, -68, -113, -65,\n 122, 75, -69]), 'IF': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68,\n 72, 84, 89, 96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250, \n 255, 261, 274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319, \n 322, 326, 328], [51, 51, 51, -77, -79, -71, -74, -70, -80, -73, -75, -\n 72, 51, -19, -76, 51, 51, -78, 51, -20, -21, -82, -81, -102, -103, 51, \n -116, -111, -105, -117, -118, -38, -112, -101, -104, 51, -39, -119, -\n 116, -68, -113, -65, 51, -69]), 'LBRACE': ([29, 42, 73, 159, 204, 229, \n 266, 283, 301, 324], [37, 72, 100, -114, 249, -67, 295, -115, 249, 326]\n ), 'FROM': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68, 72, 84, 89,\n 96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250, 255, 261, \n 274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319, 322, 326, \n 328], [60, 60, 60, -77, -79, -71, -74, -70, -80, -73, -75, -72, 60, -19,\n -76, 60, 60, -78, 60, -20, -21, -82, -81, -102, -103, 60, -116, -111, -\n 105, -117, -118, -38, -112, -101, -104, 60, -39, -119, -116, -68, -113,\n -65, 60, -69]), 'INT': ([5, 10, 35, 39, 55, 142, 167], [12, 23, 23, 23,\n 23, 23, 23]), 'FLOAT': ([5, 10, 35, 39, 55, 142, 167], [14, 24, 24, 24,\n 24, 24, 24]), 'BREAK': ([37, 46, 50, 52, 53, 54, 58, 61, 62, 66, 67, 68,\n 72, 84, 89, 96, 100, 132, 139, 167, 212, 217, 223, 238, 244, 249, 250, \n 255, 261, 274, 275, 280, 282, 289, 290, 295, 300, 304, 312, 318, 319, \n 322, 326, 328], [65, 65, 65, -77, -79, -71, -74, -70, -80, -73, -75, -\n 72, 65, -19, -76, 65, 65, -78, 65, -20, -21, -82, -81, -102, -103, 65, \n -116, -111, -105, -117, -118, -38, -112, -101, -104, 65, -39, -119, -\n 116, -68, -113, -65, 65, -69]), 'TRANSPUESTA': ([57, 75, 86], [-150, -\n 150, 128]), 'MAIN': ([4, 7, 9, 19, 26, 39, 69, 137, 183, 184, 186, 232,\n 233, 234, 236, 237, 268, 269, 270, 271, 272, 297, 298, 299, 311], [11, \n 11, 11, 11, -6, -7, -8, -55, -40, -55, -55, -55, -42, -44, -46, -55, -\n 41, -45, -55, -50, -47, -43, -49, -48, -51])}\n_lr_action = {}\nfor _k, _v in _lr_action_items.items():\n for _x, _y in zip(_v[0], _v[1]):\n if not _x in _lr_action:\n _lr_action[_x] = {}\n _lr_action[_x][_k] = _y\ndel _lr_action_items\n_lr_goto_items = {'creaTrans': ([128], [175]), 'creaCuadReturn': ([135], [\n 181]), 'quad_fact': ([112], [153]), 'creaInversa': ([125], [172]),\n 'vars': ([37, 72, 100], [46, 96, 139]), 'condFinal': ([250, 312], [282,\n 319]), 'paramFuncion': ([176, 293, 307], [224, 308, 316]),\n 'push_function': ([28], [36]), 'push_arreglo': ([252], [285]),\n 'endProc': ([137, 184, 186, 232, 237, 270], [183, 234, 236, 268, 272, \n 298]), 'var_cte': ([82, 95, 103, 104, 105, 116, 126, 131, 151, 152, 164,\n 171, 174, 176, 177, 191, 239, 245, 246, 247, 248, 256, 291, 293, 307, \n 309], [106, 106, 106, 106, 106, 106, 106, 106, 198, 199, 106, 106, 106,\n 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106]),\n 'while3': ([318], [322]), 'arreglo': ([37, 46, 50, 72, 82, 95, 96, 100,\n 103, 104, 105, 116, 126, 131, 139, 151, 152, 164, 171, 174, 176, 177, \n 191, 239, 245, 246, 247, 248, 249, 256, 291, 293, 295, 307, 309, 326],\n [47, 47, 47, 47, 107, 107, 47, 47, 107, 107, 107, 107, 107, 107, 47, \n 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 47, \n 107, 107, 107, 47, 107, 107, 47]), 'nomMain': ([4, 7, 9, 19], [6, 6, 6,\n 6]), 'cond': ([159], [204]), 'termino': ([82, 95, 103, 104, 105, 116, \n 126, 131, 164, 171, 174, 176, 177, 191, 239, 245, 246, 247, 248, 256, \n 291, 293, 307, 309], [108, 108, 108, 108, 108, 108, 108, 108, 108, 108,\n 108, 108, 108, 108, 108, 108, 108, 278, 279, 108, 108, 108, 108, 108]),\n 'create_asign': ([143, 149, 220, 221], [189, 194, 259, 260]),\n 'tipoFunc': ([5], [16]), 'bloque': ([204, 301], [250, 312]), 'push_id':\n ([57, 75, 117, 146, 170, 219, 226], [86, 86, 158, 158, 215, 258, 158]),\n 'quad_print': ([192, 193, 254], [242, 243, 286]), 'varsGlobal': ([4], [\n 7]), 'matrix': ([37, 46, 50, 72, 82, 95, 96, 100, 103, 104, 105, 116, \n 126, 131, 139, 151, 152, 164, 171, 174, 176, 177, 191, 239, 245, 246, \n 247, 248, 249, 256, 291, 293, 295, 307, 309, 326], [49, 49, 49, 49, 110,\n 110, 49, 49, 110, 110, 110, 110, 110, 110, 49, 110, 110, 110, 110, 110,\n 110, 110, 110, 110, 110, 110, 110, 110, 49, 110, 110, 110, 49, 110, 110,\n 49]), 'tipo': ([10, 35, 39, 55, 142, 167], [22, 45, 22, 83, 45, 83]),\n 'inversa': ([37, 46, 50, 72, 96, 100, 139, 249, 295, 326], [62, 62, 62,\n 62, 62, 62, 62, 62, 62, 62]), 'exp1': ([150], [195]), 'estatuto': ([37,\n 46, 50, 72, 96, 100, 139, 249, 295, 326], [50, 50, 50, 50, 50, 50, 50, \n 50, 50, 50]), 'determinante': ([174], [222]), 'param': ([35, 142], [43,\n 188]), 'varAux2': ([83, 214, 303, 323], [121, 253, 314, 325]),\n 'varAuxGlobal2': ([22, 41, 134, 267], [33, 71, 180, 296]),\n 'varAuxGlobal1': ([10, 39], [26, 69]), 'program': ([0], [1]),\n 'functionReturn': ([72, 99, 100, 136, 141, 185], [97, 138, 140, 182, \n 187, 235]), 'varAux1': ([55, 167], [84, 212]), 'paramAvarTable': ([74],\n [101]), 'main': ([4, 7, 9, 19], [8, 18, 21, 31]), 'lectura': ([37, 46, \n 50, 72, 96, 100, 139, 249, 295, 326], [52, 52, 52, 52, 52, 52, 52, 52, \n 52, 52]), 'empty': ([35, 72, 99, 100, 136, 141, 142, 176, 185, 293, 307\n ], [44, 98, 98, 98, 98, 98, 44, 225, 98, 225, 225]), 'function': ([4, 7,\n 183, 234, 236, 268, 272, 298], [9, 19, 233, 269, 271, 297, 299, 311]),\n 'escrituraAux': ([104, 191, 239], [147, 240, 273]), 'push_poper': ([48,\n 56, 78, 80, 109, 111, 124, 127, 160, 161, 162, 163, 165, 166, 196, 197,\n 200, 202], [79, 85, 103, 105, 151, 152, 171, 174, 205, 206, 207, 208, \n 210, 211, 245, 246, 247, 248]), 'push_var': ([122], [169]), 'gosub': ([\n 224], [262]), 'ver_dim2': ([305], [315]), 'comp': ([119], [164]),\n 'factor': ([82, 95, 103, 104, 105, 116, 126, 131, 164, 171, 174, 176, \n 177, 191, 239, 245, 246, 247, 248, 256, 291, 293, 307, 309], [112, 112,\n 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, \n 112, 112, 112, 112, 112, 112, 112, 112]), 'actualizaFuncion': ([57, 75,\n 146, 219], [87, 87, 87, 87]), 'transpuesta': ([37, 46, 50, 72, 96, 100,\n 139, 249, 295, 326], [53, 53, 53, 53, 53, 53, 53, 53, 53, 53]),\n 'condElse': ([283], [301]), 'condicion': ([37, 46, 50, 72, 96, 100, 139,\n 249, 295, 326], [54, 54, 54, 54, 54, 54, 54, 54, 54, 54]), 'quad_term':\n ([108], [150]), 'push_cte': ([113, 114, 115, 144], [154, 155, 156, 190]\n ), 'quad_comp': ([209], [251]), 'generarEra': ([87], [129]),\n 'loopFromDo': ([37, 46, 50, 72, 96, 100, 139, 249, 295, 326], [58, 58, \n 58, 58, 58, 58, 58, 58, 58, 58]), 'expresion': ([82, 104, 116, 131, 171,\n 174, 177, 191, 239, 291, 309], [118, 145, 157, 178, 216, 220, 228, 145,\n 145, 306, 317]), 'endPrograma': ([8, 18, 21, 31], [20, 30, 32, 38]),\n 'llamadaAFuncion': ([37, 46, 50, 72, 96, 100, 104, 139, 174, 191, 239, \n 249, 295, 326], [59, 76, 76, 76, 76, 76, 148, 76, 221, 241, 241, 76, 76,\n 76]), 'push_matriz': ([313], [320]), 'asignacion': ([37, 46, 50, 72, 96,\n 100, 139, 249, 295, 326], [61, 61, 61, 61, 61, 61, 61, 61, 61, 61]),\n 'while2': ([229], [266]), 'generaCuadbreak': ([65], [93]), 'while1': ([\n 63], [91]), 'push_id2': ([226], [263]), 'bloqueAux': ([37, 46, 50, 72, \n 96, 100, 139, 249, 295, 326], [64, 77, 81, 99, 136, 141, 185, 281, 310,\n 327]), 'ver_dim1': ([218], [257]), 'while': ([37, 46, 50, 72, 96, 100, \n 139, 249, 295, 326], [66, 66, 66, 66, 66, 66, 66, 66, 66, 66]),\n 'termino1': ([153], [201]), 'exp': ([82, 95, 103, 104, 105, 116, 126, \n 131, 164, 171, 174, 176, 177, 191, 239, 245, 246, 256, 291, 293, 307, \n 309], [119, 135, 143, 119, 149, 119, 173, 119, 209, 119, 119, 227, 119,\n 119, 119, 276, 277, 287, 119, 227, 227, 119]), 'nomFunc': ([16], [27]),\n 'factorAux': ([82, 95, 103, 104, 105, 116, 126, 131, 164, 171, 174, 176,\n 177, 191, 239, 245, 246, 247, 248, 256, 291, 293, 307, 309], [120, 120,\n 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, \n 120, 120, 120, 120, 120, 120, 120, 120]), 'comparacion': ([37, 46, 50, \n 72, 96, 100, 139, 249, 295, 326], [67, 67, 67, 67, 67, 67, 67, 67, 67, \n 67]), 'paramFuncionAux': ([227, 263], [264, 292]), 'escritura': ([37, \n 46, 50, 72, 96, 100, 139, 249, 295, 326], [68, 68, 68, 68, 68, 68, 68, \n 68, 68, 68])}\n_lr_goto = {}\nfor _k, _v in _lr_goto_items.items():\n for _x, _y in zip(_v[0], _v[1]):\n if not _x in _lr_goto:\n _lr_goto[_x] = {}\n _lr_goto[_x][_k] = _y\ndel _lr_goto_items\n_lr_productions = [(\"S' -> program\", \"S'\", 1, None, None, None), (\n 'program -> PROGRAM ID COLON varsGlobal function main endPrograma',\n 'program', 7, 'p_program', 'lexAndSyn.py', 144), (\n 'program -> PROGRAM ID COLON function main endPrograma', 'program', 6,\n 'p_program', 'lexAndSyn.py', 145), (\n 'program -> PROGRAM ID COLON varsGlobal main endPrograma', 'program', 6,\n 'p_program', 'lexAndSyn.py', 146), (\n 'program -> PROGRAM ID COLON main endPrograma', 'program', 5,\n 'p_program', 'lexAndSyn.py', 147), ('endPrograma -> <empty>',\n 'endPrograma', 0, 'p_endPrograma', 'lexAndSyn.py', 153), (\n 'varsGlobal -> VAR varAuxGlobal1', 'varsGlobal', 2, 'p_varsGlobal',\n 'lexAndSyn.py', 158), ('varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON',\n 'varAuxGlobal1', 3, 'p_varAuxGlobal1', 'lexAndSyn.py', 162), (\n 'varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON varAuxGlobal1',\n 'varAuxGlobal1', 4, 'p_varAuxGlobal1', 'lexAndSyn.py', 163), (\n 'varAuxGlobal2 -> ID', 'varAuxGlobal2', 1, 'p_varAuxGlobal2',\n 'lexAndSyn.py', 167), ('varAuxGlobal2 -> ID COMA varAuxGlobal2',\n 'varAuxGlobal2', 3, 'p_varAuxGlobal2', 'lexAndSyn.py', 168), (\n 'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH', 'varAuxGlobal2', 4,\n 'p_varAuxGlobal2', 'lexAndSyn.py', 169), (\n 'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH COMA varAuxGlobal2',\n 'varAuxGlobal2', 6, 'p_varAuxGlobal2', 'lexAndSyn.py', 170), (\n 'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH',\n 'varAuxGlobal2', 7, 'p_varAuxGlobal2', 'lexAndSyn.py', 171), (\n 'varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2'\n , 'varAuxGlobal2', 9, 'p_varAuxGlobal2', 'lexAndSyn.py', 172), (\n 'main -> nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE', 'main', 6,\n 'p_main', 'lexAndSyn.py', 180), (\n 'main -> nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE', 'main', 7,\n 'p_main', 'lexAndSyn.py', 181), (\n 'main -> nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE', 'main', \n 6, 'p_main', 'lexAndSyn.py', 182), ('nomMain -> MAIN', 'nomMain', 1,\n 'p_nomMain', 'lexAndSyn.py', 186), ('vars -> VAR varAux1', 'vars', 2,\n 'p_vars', 'lexAndSyn.py', 196), ('varAux1 -> tipo varAux2 SEMICOLON',\n 'varAux1', 3, 'p_varAux1', 'lexAndSyn.py', 200), (\n 'varAux1 -> tipo varAux2 SEMICOLON varAux1', 'varAux1', 4, 'p_varAux1',\n 'lexAndSyn.py', 201), ('varAux2 -> ID push_var', 'varAux2', 2,\n 'p_varAux2', 'lexAndSyn.py', 205), (\n 'varAux2 -> ID push_var COMA varAux2', 'varAux2', 4, 'p_varAux2',\n 'lexAndSyn.py', 206), ('varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo',\n 'varAux2', 5, 'p_varAux2', 'lexAndSyn.py', 207), (\n 'varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2',\n 'varAux2', 7, 'p_varAux2', 'lexAndSyn.py', 208), (\n 'varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz',\n 'varAux2', 8, 'p_varAux2', 'lexAndSyn.py', 209), (\n 'varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2'\n , 'varAux2', 10, 'p_varAux2', 'lexAndSyn.py', 210), (\n 'push_var -> <empty>', 'push_var', 0, 'p_pushVariable', 'lexAndSyn.py',\n 214), ('push_arreglo -> <empty>', 'push_arreglo', 0, 'p_arreglo',\n 'lexAndSyn.py', 220), ('push_matriz -> <empty>', 'push_matriz', 0,\n 'p_matriz', 'lexAndSyn.py', 231), ('tipo -> INT', 'tipo', 1, 'p_tipo',\n 'lexAndSyn.py', 246), ('tipo -> FLOAT', 'tipo', 1, 'p_tipo',\n 'lexAndSyn.py', 247), ('tipo -> CHAR', 'tipo', 1, 'p_tipo',\n 'lexAndSyn.py', 248), ('tipoFunc -> INT', 'tipoFunc', 1, 'p_tipoFunc',\n 'lexAndSyn.py', 253), ('tipoFunc -> FLOAT', 'tipoFunc', 1, 'p_tipoFunc',\n 'lexAndSyn.py', 254), ('tipoFunc -> CHAR', 'tipoFunc', 1, 'p_tipoFunc',\n 'lexAndSyn.py', 255), ('tipoFunc -> VOID', 'tipoFunc', 1, 'p_tipoFunc',\n 'lexAndSyn.py', 256), ('bloque -> LBRACE RBRACE', 'bloque', 2,\n 'p_bloque', 'lexAndSyn.py', 261), ('bloque -> LBRACE bloqueAux RBRACE',\n 'bloque', 3, 'p_bloque', 'lexAndSyn.py', 262), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc'\n , 'function', 9, 'p_function', 'lexAndSyn.py', 268), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc'\n , 'function', 11, 'p_function', 'lexAndSyn.py', 269), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function'\n , 'function', 10, 'p_function', 'lexAndSyn.py', 270), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function'\n , 'function', 12, 'p_function', 'lexAndSyn.py', 271), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc'\n , 'function', 10, 'p_function', 'lexAndSyn.py', 272), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function'\n , 'function', 11, 'p_function', 'lexAndSyn.py', 273), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc'\n , 'function', 10, 'p_function', 'lexAndSyn.py', 274), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc'\n , 'function', 11, 'p_function', 'lexAndSyn.py', 275), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function'\n , 'function', 12, 'p_function', 'lexAndSyn.py', 276), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc'\n , 'function', 12, 'p_function', 'lexAndSyn.py', 277), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function'\n , 'function', 11, 'p_function', 'lexAndSyn.py', 278), (\n 'function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function'\n , 'function', 13, 'p_function', 'lexAndSyn.py', 279), (\n 'functionReturn -> RETURN exp creaCuadReturn SEMICOLON',\n 'functionReturn', 4, 'p_functionReturn', 'lexAndSyn.py', 283), (\n 'functionReturn -> empty', 'functionReturn', 1, 'p_functionReturn',\n 'lexAndSyn.py', 284), ('creaCuadReturn -> <empty>', 'creaCuadReturn', 0,\n 'p_creaCuadReturn', 'lexAndSyn.py', 288), ('endProc -> <empty>',\n 'endProc', 0, 'p_endProc', 'lexAndSyn.py', 293), (\n 'param -> tipo ID paramAvarTable', 'param', 3, 'p_param',\n 'lexAndSyn.py', 298), ('param -> tipo ID paramAvarTable COMA param',\n 'param', 5, 'p_param', 'lexAndSyn.py', 299), ('param -> empty', 'param',\n 1, 'p_param', 'lexAndSyn.py', 300), ('paramAvarTable -> <empty>',\n 'paramAvarTable', 0, 'p_paramAvarTable', 'lexAndSyn.py', 305), (\n 'empty -> <empty>', 'empty', 0, 'p_empty', 'lexAndSyn.py', 311), (\n 'push_function -> <empty>', 'push_function', 0, 'p_push_function',\n 'lexAndSyn.py', 315), ('nomFunc -> ID push_function', 'nomFunc', 2,\n 'p_nomFunc', 'lexAndSyn.py', 324), ('bloqueAux -> estatuto',\n 'bloqueAux', 1, 'p_bloqueAux', 'lexAndSyn.py', 333), (\n 'bloqueAux -> estatuto bloqueAux', 'bloqueAux', 2, 'p_bloqueAux',\n 'lexAndSyn.py', 334), (\n 'while -> WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3'\n , 'while', 10, 'p_while', 'lexAndSyn.py', 338), ('while1 -> <empty>',\n 'while1', 0, 'p_while1', 'lexAndSyn.py', 342), ('while2 -> <empty>',\n 'while2', 0, 'p_while2', 'lexAndSyn.py', 346), ('while3 -> <empty>',\n 'while3', 0, 'p_while3', 'lexAndSyn.py', 350), (\n 'loopFromDo -> FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE'\n , 'loopFromDo', 14, 'p_loopFromDo', 'lexAndSyn.py', 354), (\n 'estatuto -> asignacion', 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py', \n 366), ('estatuto -> condicion', 'estatuto', 1, 'p_estatuto',\n 'lexAndSyn.py', 367), ('estatuto -> escritura', 'estatuto', 1,\n 'p_estatuto', 'lexAndSyn.py', 368), ('estatuto -> while', 'estatuto', 1,\n 'p_estatuto', 'lexAndSyn.py', 369), ('estatuto -> loopFromDo',\n 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py', 370), (\n 'estatuto -> comparacion', 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py',\n 371), ('estatuto -> llamadaAFuncion SEMICOLON', 'estatuto', 2,\n 'p_estatuto', 'lexAndSyn.py', 372), ('estatuto -> lectura', 'estatuto',\n 1, 'p_estatuto', 'lexAndSyn.py', 373), (\n 'estatuto -> BREAK generaCuadbreak SEMICOLON', 'estatuto', 3,\n 'p_estatuto', 'lexAndSyn.py', 374), ('estatuto -> transpuesta',\n 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py', 375), (\n 'estatuto -> inversa', 'estatuto', 1, 'p_estatuto', 'lexAndSyn.py', 376\n ), ('transpuesta -> ID push_id TRANSPUESTA creaTrans SEMICOLON',\n 'transpuesta', 5, 'p_transpuesta', 'lexAndSyn.py', 380), (\n 'inversa -> ID push_id INVERSA creaInversa SEMICOLON', 'inversa', 5,\n 'p_inversa', 'lexAndSyn.py', 383), ('creaInversa -> <empty>',\n 'creaInversa', 0, 'p_creaInversa', 'lexAndSyn.py', 387), (\n 'creaTrans -> <empty>', 'creaTrans', 0, 'p_creaTrans', 'lexAndSyn.py', \n 391), ('generaCuadbreak -> <empty>', 'generaCuadbreak', 0,\n 'p_generaCuadbreak', 'lexAndSyn.py', 395), (\n 'llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion'\n , 'llamadaAFuncion', 8, 'p_llamadaAFuncion', 'lexAndSyn.py', 399), (\n 'llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN'\n , 'llamadaAFuncion', 7, 'p_llamadaAFuncion', 'lexAndSyn.py', 400), (\n 'actualizaFuncion -> <empty>', 'actualizaFuncion', 0,\n 'p_actualizaFuncion', 'lexAndSyn.py', 404), ('gosub -> <empty>',\n 'gosub', 0, 'p_gosub', 'lexAndSyn.py', 409), ('generarEra -> <empty>',\n 'generarEra', 0, 'p_generarEra', 'lexAndSyn.py', 421), (\n 'paramFuncion -> ID push_id2 paramFuncionAux', 'paramFuncion', 3,\n 'p_paramFuncion', 'lexAndSyn.py', 429), (\n 'paramFuncion -> ID push_id2 paramFuncionAux COMA paramFuncion',\n 'paramFuncion', 5, 'p_paramFuncion', 'lexAndSyn.py', 430), (\n 'paramFuncion -> exp paramFuncionAux', 'paramFuncion', 2,\n 'p_paramFuncion', 'lexAndSyn.py', 431), (\n 'paramFuncion -> exp paramFuncionAux COMA paramFuncion', 'paramFuncion',\n 4, 'p_paramFuncion', 'lexAndSyn.py', 432), ('paramFuncion -> empty',\n 'paramFuncion', 1, 'p_paramFuncion', 'lexAndSyn.py', 433), (\n 'paramFuncionAux -> <empty>', 'paramFuncionAux', 0, 'p_paramFuncionAux',\n 'lexAndSyn.py', 437), ('push_id2 -> <empty>', 'push_id2', 0,\n 'p_push_id2', 'lexAndSyn.py', 441), (\n 'arreglo -> ID push_id LCORCH exp RCORCH ver_dim1', 'arreglo', 6,\n 'p_array', 'lexAndSyn.py', 445), (\n 'matrix -> ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2',\n 'matrix', 9, 'p_matrix', 'lexAndSyn.py', 449), ('ver_dim2 -> <empty>',\n 'ver_dim2', 0, 'p_ver_dim2', 'lexAndSyn.py', 453), (\n 'asignacion -> ID push_id EQUAL push_poper expresion create_asign SEMICOLON'\n , 'asignacion', 7, 'p_asignacion', 'lexAndSyn.py', 457), (\n 'asignacion -> arreglo EQUAL push_poper exp create_asign SEMICOLON',\n 'asignacion', 6, 'p_asignacion', 'lexAndSyn.py', 458), (\n 'asignacion -> matrix EQUAL push_poper exp create_asign SEMICOLON',\n 'asignacion', 6, 'p_asignacion', 'lexAndSyn.py', 459), (\n 'asignacion -> ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON'\n , 'asignacion', 7, 'p_asignacion', 'lexAndSyn.py', 460), (\n 'asignacion -> ID push_id EQUAL push_poper determinante SEMICOLON',\n 'asignacion', 6, 'p_asignacion', 'lexAndSyn.py', 461), (\n 'determinante -> ID push_id DETERMINANT', 'determinante', 3,\n 'p_determinante', 'lexAndSyn.py', 465), (\n 'push_id_dimensionada -> <empty>', 'push_id_dimensionada', 0,\n 'p_push_id_dimensionada', 'lexAndSyn.py', 470), (\n 'create_asign_dim -> <empty>', 'create_asign_dim', 0,\n 'p_create_asign_dim', 'lexAndSyn.py', 473), ('ver_dim1 -> <empty>',\n 'ver_dim1', 0, 'p_ver_dim1', 'lexAndSyn.py', 477), (\n 'create_asign -> <empty>', 'create_asign', 0, 'p_create_asign',\n 'lexAndSyn.py', 481), (\n 'comparacion -> ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON',\n 'comparacion', 6, 'p_comparacion', 'lexAndSyn.py', 485), (\n 'condicion -> IF LPAREN expresion RPAREN cond bloque condFinal',\n 'condicion', 7, 'p_condicion', 'lexAndSyn.py', 489), (\n 'condicion -> IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal'\n , 'condicion', 10, 'p_condicion', 'lexAndSyn.py', 490), (\n 'cond -> <empty>', 'cond', 0, 'p_quad_cond', 'lexAndSyn.py', 494), (\n 'condElse -> <empty>', 'condElse', 0, 'p_quad_condElse', 'lexAndSyn.py',\n 498), ('condFinal -> <empty>', 'condFinal', 0, 'p_quad_condFinal',\n 'lexAndSyn.py', 502), (\n 'escritura -> PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON'\n , 'escritura', 7, 'p_escritura', 'lexAndSyn.py', 506), (\n 'escritura -> PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON'\n , 'escritura', 7, 'p_escritura', 'lexAndSyn.py', 507), (\n 'lectura -> INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON'\n , 'lectura', 8, 'p_lectura', 'lexAndSyn.py', 511), (\n 'quad_print -> <empty>', 'quad_print', 0, 'p_quad_print',\n 'lexAndSyn.py', 515), ('escrituraAux -> expresion', 'escrituraAux', 1,\n 'p_escrituraAux', 'lexAndSyn.py', 519), (\n 'escrituraAux -> CTE_STRING push_cte', 'escrituraAux', 2,\n 'p_escrituraAux', 'lexAndSyn.py', 520), (\n 'escrituraAux -> expresion COMA escrituraAux', 'escrituraAux', 3,\n 'p_escrituraAux', 'lexAndSyn.py', 521), (\n 'escrituraAux -> CTE_STRING push_cte COMA escrituraAux', 'escrituraAux',\n 4, 'p_escrituraAux', 'lexAndSyn.py', 522), (\n 'escrituraAux -> llamadaAFuncion', 'escrituraAux', 1, 'p_escrituraAux',\n 'lexAndSyn.py', 523), ('expresion -> exp', 'expresion', 1,\n 'p_expresion', 'lexAndSyn.py', 527), (\n 'expresion -> exp comp exp quad_comp', 'expresion', 4, 'p_expresion',\n 'lexAndSyn.py', 528), ('comp -> LOWERTHAN push_poper', 'comp', 2,\n 'p_comp', 'lexAndSyn.py', 532), ('comp -> MORETHAN push_poper', 'comp',\n 2, 'p_comp', 'lexAndSyn.py', 533), ('comp -> DIFFERENT push_poper',\n 'comp', 2, 'p_comp', 'lexAndSyn.py', 534), (\n 'comp -> DOUBLEEQUAL push_poper', 'comp', 2, 'p_comp', 'lexAndSyn.py', \n 535), ('comp -> LOWEREQUAL push_poper', 'comp', 2, 'p_comp',\n 'lexAndSyn.py', 536), ('comp -> MOREEQUAL push_poper', 'comp', 2,\n 'p_comp', 'lexAndSyn.py', 537), ('quad_comp -> <empty>', 'quad_comp', 0,\n 'p_quad_comp', 'lexAndSyn.py', 541), ('exp -> termino quad_term', 'exp',\n 2, 'p_exp', 'lexAndSyn.py', 545), ('exp -> termino quad_term exp1',\n 'exp', 3, 'p_exp', 'lexAndSyn.py', 546), ('exp1 -> PLUS push_poper exp',\n 'exp1', 3, 'p_exp1', 'lexAndSyn.py', 550), (\n 'exp1 -> MINUS push_poper exp', 'exp1', 3, 'p_exp1', 'lexAndSyn.py', \n 551), ('quad_term -> <empty>', 'quad_term', 0, 'p_quad_term',\n 'lexAndSyn.py', 555), ('quad_fact -> <empty>', 'quad_fact', 0,\n 'p_quad_fact', 'lexAndSyn.py', 559), ('termino -> factor quad_fact',\n 'termino', 2, 'p_termino', 'lexAndSyn.py', 563), (\n 'termino -> factor quad_fact termino1', 'termino', 3, 'p_termino',\n 'lexAndSyn.py', 564), ('termino1 -> TIMES push_poper termino',\n 'termino1', 3, 'p_termino1', 'lexAndSyn.py', 568), (\n 'termino1 -> DIVIDE push_poper termino', 'termino1', 3, 'p_termino1',\n 'lexAndSyn.py', 569), ('factor -> LPAREN expresion RPAREN', 'factor', 3,\n 'p_factor', 'lexAndSyn.py', 573), ('factor -> factorAux', 'factor', 1,\n 'p_factor', 'lexAndSyn.py', 574), (\n 'factorAux -> PLUS push_poper var_cte', 'factorAux', 3, 'p_factorAux',\n 'lexAndSyn.py', 578), ('factorAux -> MINUS push_poper var_cte',\n 'factorAux', 3, 'p_factorAux', 'lexAndSyn.py', 579), (\n 'factorAux -> var_cte', 'factorAux', 1, 'p_factorAux', 'lexAndSyn.py', \n 580), ('push_id -> <empty>', 'push_id', 0, 'p_push_id', 'lexAndSyn.py',\n 584), ('push_cte -> <empty>', 'push_cte', 0, 'p_push_cte',\n 'lexAndSyn.py', 588), ('push_poper -> <empty>', 'push_poper', 0,\n 'p_push_poper', 'lexAndSyn.py', 598), ('var_cte -> ID push_id',\n 'var_cte', 2, 'p_var_cte', 'lexAndSyn.py', 602), (\n 'var_cte -> CTE_I push_cte', 'var_cte', 2, 'p_var_cte', 'lexAndSyn.py',\n 603), ('var_cte -> CTE_F push_cte', 'var_cte', 2, 'p_var_cte',\n 'lexAndSyn.py', 604), ('var_cte -> CTE_STRING push_cte', 'var_cte', 2,\n 'p_var_cte', 'lexAndSyn.py', 605), ('var_cte -> arreglo', 'var_cte', 1,\n 'p_var_cte', 'lexAndSyn.py', 606), ('var_cte -> matrix', 'var_cte', 1,\n 'p_var_cte', 'lexAndSyn.py', 607)]\n",
"step-4": "\n# parsetab.py\n# This file is automatically generated. Do not edit.\n# pylint: disable=W,C,R\n_tabversion = '3.10'\n\n_lr_method = 'LALR'\n\n_lr_signature = 'AND BREAK CHAR COLON COMA CTE_F CTE_I CTE_STRING DETERMINANT DIFFERENT DIVIDE DO DOUBLEEQUAL ELSE EQUAL FLOAT FROM FUNCTION ID IF INPUT INT INVERSA LBRACE LCORCH LOWEREQUAL LOWERTHAN LPAREN MAIN MINUS MOREEQUAL MORETHAN OR PLUS PRINT PROGRAM RBRACE RCORCH RETURN RPAREN SEMICOLON TIMES TO TRANSPUESTA VAR VOID WHILEprogram : PROGRAM ID COLON varsGlobal function main endPrograma\\n | PROGRAM ID COLON function main endPrograma\\n | PROGRAM ID COLON varsGlobal main endPrograma\\n | PROGRAM ID COLON main endPrograma\\n endPrograma :varsGlobal : VAR varAuxGlobal1\\n varAuxGlobal1 : tipo varAuxGlobal2 SEMICOLON\\n | tipo varAuxGlobal2 SEMICOLON varAuxGlobal1\\n varAuxGlobal2 : ID\\n | ID COMA varAuxGlobal2\\n | ID LCORCH CTE_I RCORCH\\n | ID LCORCH CTE_I RCORCH COMA varAuxGlobal2\\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH\\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2\\n main : nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE\\n | nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE\\n | nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE\\n nomMain : MAIN\\n vars : VAR varAux1\\n varAux1 : tipo varAux2 SEMICOLON\\n | tipo varAux2 SEMICOLON varAux1\\n varAux2 : ID push_var\\n | ID push_var COMA varAux2\\n | ID LCORCH CTE_I RCORCH push_arreglo\\n | ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2\\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz\\n | ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2\\n push_var :push_arreglo :push_matriz :tipo : INT\\n | FLOAT\\n | CHAR\\n tipoFunc : INT\\n | FLOAT\\n | CHAR\\n | VOID\\n bloque : LBRACE RBRACE\\n | LBRACE bloqueAux RBRACE\\n function : FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc\\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc\\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function \\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function\\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc\\n | FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function\\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc \\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc\\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function\\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc\\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function\\n | FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function\\n functionReturn : RETURN exp creaCuadReturn SEMICOLON\\n | empty\\n creaCuadReturn :\\n endProc :\\n param : tipo ID paramAvarTable\\n | tipo ID paramAvarTable COMA param\\n | empty\\n paramAvarTable : empty : \\n push_function :nomFunc : ID push_function\\n bloqueAux : estatuto\\n | estatuto bloqueAux\\n while : WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3\\n while1 :while2 :while3 :loopFromDo : FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE\\n estatuto : asignacion\\n | condicion\\n | escritura\\n | while\\n | loopFromDo\\n | comparacion\\n | llamadaAFuncion SEMICOLON\\n | lectura\\n | BREAK generaCuadbreak SEMICOLON\\n | transpuesta\\n | inversa\\n transpuesta : ID push_id TRANSPUESTA creaTrans SEMICOLON\\n inversa : ID push_id INVERSA creaInversa SEMICOLON\\n creaInversa : creaTrans : generaCuadbreak : llamadaAFuncion : ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion\\n | ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN\\n actualizaFuncion : gosub :\\n generarEra :\\n paramFuncion : ID push_id2 paramFuncionAux\\n | ID push_id2 paramFuncionAux COMA paramFuncion\\n | exp paramFuncionAux\\n | exp paramFuncionAux COMA paramFuncion\\n | empty\\n paramFuncionAux : push_id2 :arreglo : ID push_id LCORCH exp RCORCH ver_dim1\\n matrix : ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2\\n ver_dim2 : asignacion : ID push_id EQUAL push_poper expresion create_asign SEMICOLON\\n | arreglo EQUAL push_poper exp create_asign SEMICOLON\\n | matrix EQUAL push_poper exp create_asign SEMICOLON\\n | ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON\\n | ID push_id EQUAL push_poper determinante SEMICOLON\\n determinante : ID push_id DETERMINANT\\n push_id_dimensionada :create_asign_dim :ver_dim1 :create_asign :comparacion : ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON\\n condicion : IF LPAREN expresion RPAREN cond bloque condFinal\\n | IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal\\n cond :condElse :condFinal :escritura : PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON\\n | PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON\\n lectura : INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON\\n quad_print :escrituraAux : expresion\\n | CTE_STRING push_cte\\n | expresion COMA escrituraAux\\n | CTE_STRING push_cte COMA escrituraAux\\n | llamadaAFuncion\\n expresion : exp\\n | exp comp exp quad_comp\\n comp : LOWERTHAN push_poper\\n | MORETHAN push_poper\\n | DIFFERENT push_poper\\n | DOUBLEEQUAL push_poper\\n | LOWEREQUAL push_poper\\n | MOREEQUAL push_poper\\n quad_comp :exp : termino quad_term\\n | termino quad_term exp1\\n exp1 : PLUS push_poper exp\\n | MINUS push_poper exp\\n quad_term :quad_fact :termino : factor quad_fact\\n | factor quad_fact termino1\\n termino1 : TIMES push_poper termino\\n | DIVIDE push_poper termino\\n factor : LPAREN expresion RPAREN\\n | factorAux\\n factorAux : PLUS push_poper var_cte\\n | MINUS push_poper var_cte\\n | var_cte \\n push_id :push_cte :push_poper :var_cte : ID push_id\\n | CTE_I push_cte\\n | CTE_F push_cte\\n | CTE_STRING push_cte\\n | arreglo\\n | matrix\\n '\n \n_lr_action_items = {'MOREEQUAL':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,160,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'CTE_STRING':([78,80,82,95,103,104,105,109,111,116,124,126,127,131,151,152,160,161,162,163,164,165,166,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,239,245,246,247,248,256,291,293,307,309,],[-152,-152,114,114,114,144,114,-152,-152,114,-152,114,-152,114,114,114,-152,-152,-152,-152,114,-152,-152,114,114,114,114,144,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,144,114,114,114,114,114,114,114,114,114,]),'LCORCH':([34,57,75,86,94,117,122,146,158,218,219,226,252,258,],[40,-150,-150,126,133,-150,168,-150,126,256,-150,-150,284,126,]),'RETURN':([50,52,53,54,58,61,62,66,67,68,72,81,89,99,100,132,136,141,185,217,223,238,244,250,255,261,274,275,280,282,289,290,300,304,312,318,319,322,328,],[-63,-77,-79,-71,-74,-70,-80,-73,-75,-72,95,-64,-76,95,95,-78,95,95,95,-82,-81,-102,-103,-116,-111,-105,-117,-118,-38,-112,-101,-104,-39,-119,-116,-68,-113,-65,-69,]),'DO':([321,],[324,]),'VOID':([5,],[13,]),'EQUAL':([47,49,57,75,86,130,218,257,305,315,],[78,80,-150,-150,127,177,-109,-98,-100,-99,]),'CHAR':([5,10,35,39,55,142,167,],[15,25,25,25,25,25,25,]),'VAR':([4,37,72,100,],[10,55,55,55,]),'WHILE':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[63,63,63,-77,-79,-71,-74,-70,-80,-73,-75,-72,63,-19,-76,63,63,-78,63,-20,-21,-82,-81,-102,-103,63,-116,-111,-105,-117,-118,-38,-112,-101,-104,63,-39,-119,-116,-68,-113,-65,63,-69,]),'PROGRAM':([0,],[2,]),'PRINT':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[48,48,48,-77,-79,-71,-74,-70,-80,-73,-75,-72,48,-19,-76,48,48,-78,48,-20,-21,-82,-81,-102,-103,48,-116,-111,-105,-117,-118,-38,-112,-101,-104,48,-39,-119,-116,-68,-113,-65,48,-69,]),'MORETHAN':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,166,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'MINUS':([78,80,82,95,103,104,105,106,107,108,110,112,113,114,115,116,117,120,124,126,127,131,144,146,150,153,154,155,156,158,160,161,162,163,164,165,166,171,174,176,177,190,191,196,197,198,199,200,201,202,203,205,206,207,208,210,211,218,219,226,239,245,246,247,248,256,257,258,278,279,291,293,305,307,309,315,],[-152,-152,109,109,109,109,109,-149,-157,-139,-158,-140,-151,-151,-151,109,-150,-146,-152,109,-152,109,-151,-150,197,-141,-155,-156,-154,-153,-152,-152,-152,-152,109,-152,-152,109,109,109,109,-156,109,-152,-152,-148,-147,-152,-142,-152,-145,-133,-130,-131,-128,-132,-129,-109,-150,-150,109,109,109,109,109,109,-98,-153,-144,-143,109,109,-100,109,109,-99,]),'DIVIDE':([106,107,110,112,113,114,115,117,120,144,146,153,154,155,156,158,190,198,199,203,218,219,226,257,258,305,315,],[-149,-157,-158,-140,-151,-151,-151,-150,-146,-151,-150,200,-155,-156,-154,-153,-156,-148,-147,-145,-109,-150,-150,-98,-153,-100,-99,]),'RCORCH':([70,106,107,108,110,112,113,114,115,117,120,150,153,154,155,156,158,173,179,195,198,199,201,203,213,218,257,276,277,278,279,287,302,305,315,],[94,-149,-157,-139,-158,-140,-151,-151,-151,-150,-146,-135,-141,-155,-156,-154,-153,218,230,-136,-148,-147,-142,-145,252,-109,-98,-137,-138,-144,-143,305,313,-100,-99,]),'DETERMINANT':([219,258,],[-150,288,]),'RPAREN':([17,35,43,44,74,101,106,107,108,110,112,113,114,115,117,118,119,120,142,144,145,146,147,148,150,153,154,155,156,157,158,170,176,178,188,190,195,198,199,201,203,209,215,218,224,225,226,227,228,240,241,251,257,262,263,264,273,276,277,278,279,291,292,293,305,306,307,308,315,316,317,],[29,42,73,-58,-59,-56,-149,-157,-139,-158,-140,-151,-151,-151,-150,159,-126,-146,-60,-151,-121,-150,192,193,-135,-141,-155,-156,-154,203,-153,-150,-60,229,-57,-122,-136,-148,-147,-142,-145,-134,254,-109,-89,-95,-97,-96,265,-123,-125,-127,-98,291,-96,-93,-124,-137,-138,-144,-143,-87,-91,-60,-100,-86,-60,-94,-99,-92,321,]),'SEMICOLON':([33,34,59,65,71,76,93,94,106,107,108,110,112,113,114,115,117,119,120,121,122,125,128,135,143,149,150,153,154,155,156,158,169,172,175,180,181,189,192,193,194,195,198,199,201,203,209,216,218,219,220,221,222,230,242,243,251,252,253,254,257,258,259,260,276,277,278,279,285,286,288,291,296,305,306,313,314,315,320,325,],[39,-9,89,-85,-10,89,132,-11,-149,-157,-139,-158,-140,-151,-151,-151,-150,-126,-146,167,-28,-83,-84,-54,-110,-110,-135,-141,-155,-156,-154,-153,-22,217,223,-12,231,238,-120,-120,244,-136,-148,-147,-142,-145,-134,255,-109,-150,-110,-110,261,-13,274,275,-127,-29,-23,-120,-98,-153,289,290,-137,-138,-144,-143,-24,304,-106,-87,-14,-100,-86,-30,-25,-99,-26,-27,]),'LOWERTHAN':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,163,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'LOWEREQUAL':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,165,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'TO':([265,],[294,]),'COLON':([3,],[4,]),'CTE_I':([40,78,80,82,95,103,104,105,109,111,116,124,126,127,131,133,151,152,160,161,162,163,164,165,166,168,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,239,245,246,247,248,256,284,291,293,307,309,],[70,-152,-152,115,115,115,115,115,-152,-152,115,-152,115,-152,115,179,115,115,-152,-152,-152,-152,115,-152,-152,213,115,115,115,115,115,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,115,115,115,115,115,115,302,115,115,115,115,]),'CTE_F':([78,80,82,95,103,104,105,109,111,116,124,126,127,131,151,152,160,161,162,163,164,165,166,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,239,245,246,247,248,256,291,293,307,309,],[-152,-152,113,113,113,113,113,-152,-152,113,-152,113,-152,113,113,113,-152,-152,-152,-152,113,-152,-152,113,113,113,113,113,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,113,113,113,113,113,113,113,113,113,113,]),'PLUS':([78,80,82,95,103,104,105,106,107,108,110,112,113,114,115,116,117,120,124,126,127,131,144,146,150,153,154,155,156,158,160,161,162,163,164,165,166,171,174,176,177,190,191,196,197,198,199,200,201,202,203,205,206,207,208,210,211,218,219,226,239,245,246,247,248,256,257,258,278,279,291,293,305,307,309,315,],[-152,-152,111,111,111,111,111,-149,-157,-139,-158,-140,-151,-151,-151,111,-150,-146,-152,111,-152,111,-151,-150,196,-141,-155,-156,-154,-153,-152,-152,-152,-152,111,-152,-152,111,111,111,111,-156,111,-152,-152,-148,-147,-152,-142,-152,-145,-133,-130,-131,-128,-132,-129,-109,-150,-150,111,111,111,111,111,111,-98,-153,-144,-143,111,111,-100,111,111,-99,]),'$end':([1,8,18,20,21,30,31,32,38,88,92,102,],[0,-5,-5,-4,-5,-3,-5,-2,-1,-17,-15,-16,]),'FUNCTION':([4,7,26,39,69,137,183,184,186,232,234,236,237,268,270,272,298,],[5,5,-6,-7,-8,-55,5,-55,-55,-55,5,5,-55,5,-55,5,5,]),'DIFFERENT':([106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-149,-157,-139,-158,-140,-151,-151,-151,-150,161,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'RBRACE':([50,52,53,54,58,59,61,62,64,66,67,68,72,77,81,89,97,98,99,100,106,107,108,110,112,113,114,115,117,119,120,132,136,138,140,141,150,153,154,155,156,158,182,185,187,195,198,199,201,203,209,217,218,223,231,235,238,244,249,250,251,255,257,261,274,275,276,277,278,279,280,281,282,289,290,291,300,304,305,306,310,312,315,318,319,322,327,328,],[-63,-77,-79,-71,-74,88,-70,-80,92,-73,-75,-72,-60,102,-64,-76,137,-53,-60,-60,-149,-157,-139,-158,-140,-151,-151,-151,-150,-126,-146,-78,-60,184,186,-60,-135,-141,-155,-156,-154,-153,232,-60,237,-136,-148,-147,-142,-145,-134,-82,-109,-81,-52,270,-102,-103,280,-116,-127,-111,-98,-105,-117,-118,-137,-138,-144,-143,-38,300,-112,-101,-104,-87,-39,-119,-100,-86,318,-116,-99,-68,-113,-65,328,-69,]),'DOUBLEEQUAL':([57,75,86,106,107,108,110,112,113,114,115,117,119,120,144,146,150,153,154,155,156,158,190,195,198,199,201,203,218,219,257,258,276,277,278,279,305,315,],[-150,-150,124,-149,-157,-139,-158,-140,-151,-151,-151,-150,162,-146,-151,-150,-135,-141,-155,-156,-154,-153,-156,-136,-148,-147,-142,-145,-109,-150,-98,-153,-137,-138,-144,-143,-100,-99,]),'INVERSA':([57,75,86,],[-150,-150,125,]),'TIMES':([106,107,110,112,113,114,115,117,120,144,146,153,154,155,156,158,190,198,199,203,218,219,226,257,258,305,315,],[-149,-157,-158,-140,-151,-151,-151,-150,-146,-151,-150,202,-155,-156,-154,-153,-156,-148,-147,-145,-109,-150,-150,-98,-153,-100,-99,]),'LPAREN':([6,11,27,28,36,48,51,56,57,60,63,75,78,79,80,82,85,87,91,95,103,104,105,116,124,126,127,129,131,146,160,161,162,163,164,165,166,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,219,239,245,246,247,248,256,291,293,294,307,309,],[17,-18,35,-61,-62,-152,82,-152,-88,90,-66,-88,-152,104,-152,116,123,-90,131,116,116,116,116,116,-152,116,-152,176,116,-88,-152,-152,-152,-152,116,-152,-152,116,116,116,116,116,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,-88,116,116,116,116,116,116,116,116,309,116,116,]),'COMA':([34,74,94,101,106,107,108,110,112,113,114,115,117,119,120,122,144,145,146,150,153,154,155,156,158,169,190,195,198,199,201,203,209,218,226,227,230,251,252,257,263,264,276,277,278,279,285,292,305,313,315,320,],[41,-59,134,142,-149,-157,-139,-158,-140,-151,-151,-151,-150,-126,-146,-28,-151,191,-150,-135,-141,-155,-156,-154,-153,214,239,-136,-148,-147,-142,-145,-134,-109,-97,-96,267,-127,-29,-98,-96,293,-137,-138,-144,-143,303,307,-100,-30,-99,323,]),'INPUT':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[56,56,56,-77,-79,-71,-74,-70,-80,-73,-75,-72,56,-19,-76,56,56,-78,56,-20,-21,-82,-81,-102,-103,56,-116,-111,-105,-117,-118,-38,-112,-101,-104,56,-39,-119,-116,-68,-113,-65,56,-69,]),'ELSE':([250,280,300,],[283,-38,-39,]),'ID':([2,12,13,14,15,16,22,23,24,25,37,41,45,46,50,52,53,54,58,61,62,66,67,68,72,78,80,82,83,84,89,90,95,96,100,103,104,105,109,111,116,123,124,126,127,131,132,134,139,151,152,160,161,162,163,164,165,166,167,171,174,176,177,191,196,197,200,202,205,206,207,208,210,211,212,214,217,223,238,239,244,245,246,247,248,249,250,255,256,261,267,274,275,280,282,289,290,291,293,295,300,303,304,307,309,312,318,319,322,323,326,328,],[3,-34,-37,-35,-36,28,34,-31,-32,-33,57,34,74,75,75,-77,-79,-71,-74,-70,-80,-73,-75,-72,75,-152,-152,117,122,-19,-76,130,117,75,75,117,146,117,-152,-152,117,170,-152,117,-152,117,-78,34,75,117,117,-152,-152,-152,-152,117,-152,-152,-20,117,219,226,117,146,-152,-152,-152,-152,-133,-130,-131,-128,-132,-129,-21,122,-82,-81,-102,146,-103,117,117,117,117,75,-116,-111,117,-105,34,-117,-118,-38,-112,-101,-104,117,226,75,-39,122,-119,226,117,-116,-68,-113,-65,122,75,-69,]),'IF':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[51,51,51,-77,-79,-71,-74,-70,-80,-73,-75,-72,51,-19,-76,51,51,-78,51,-20,-21,-82,-81,-102,-103,51,-116,-111,-105,-117,-118,-38,-112,-101,-104,51,-39,-119,-116,-68,-113,-65,51,-69,]),'LBRACE':([29,42,73,159,204,229,266,283,301,324,],[37,72,100,-114,249,-67,295,-115,249,326,]),'FROM':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[60,60,60,-77,-79,-71,-74,-70,-80,-73,-75,-72,60,-19,-76,60,60,-78,60,-20,-21,-82,-81,-102,-103,60,-116,-111,-105,-117,-118,-38,-112,-101,-104,60,-39,-119,-116,-68,-113,-65,60,-69,]),'INT':([5,10,35,39,55,142,167,],[12,23,23,23,23,23,23,]),'FLOAT':([5,10,35,39,55,142,167,],[14,24,24,24,24,24,24,]),'BREAK':([37,46,50,52,53,54,58,61,62,66,67,68,72,84,89,96,100,132,139,167,212,217,223,238,244,249,250,255,261,274,275,280,282,289,290,295,300,304,312,318,319,322,326,328,],[65,65,65,-77,-79,-71,-74,-70,-80,-73,-75,-72,65,-19,-76,65,65,-78,65,-20,-21,-82,-81,-102,-103,65,-116,-111,-105,-117,-118,-38,-112,-101,-104,65,-39,-119,-116,-68,-113,-65,65,-69,]),'TRANSPUESTA':([57,75,86,],[-150,-150,128,]),'MAIN':([4,7,9,19,26,39,69,137,183,184,186,232,233,234,236,237,268,269,270,271,272,297,298,299,311,],[11,11,11,11,-6,-7,-8,-55,-40,-55,-55,-55,-42,-44,-46,-55,-41,-45,-55,-50,-47,-43,-49,-48,-51,]),}\n\n_lr_action = {}\nfor _k, _v in _lr_action_items.items():\n for _x,_y in zip(_v[0],_v[1]):\n if not _x in _lr_action: _lr_action[_x] = {}\n _lr_action[_x][_k] = _y\ndel _lr_action_items\n\n_lr_goto_items = {'creaTrans':([128,],[175,]),'creaCuadReturn':([135,],[181,]),'quad_fact':([112,],[153,]),'creaInversa':([125,],[172,]),'vars':([37,72,100,],[46,96,139,]),'condFinal':([250,312,],[282,319,]),'paramFuncion':([176,293,307,],[224,308,316,]),'push_function':([28,],[36,]),'push_arreglo':([252,],[285,]),'endProc':([137,184,186,232,237,270,],[183,234,236,268,272,298,]),'var_cte':([82,95,103,104,105,116,126,131,151,152,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[106,106,106,106,106,106,106,106,198,199,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,]),'while3':([318,],[322,]),'arreglo':([37,46,50,72,82,95,96,100,103,104,105,116,126,131,139,151,152,164,171,174,176,177,191,239,245,246,247,248,249,256,291,293,295,307,309,326,],[47,47,47,47,107,107,47,47,107,107,107,107,107,107,47,107,107,107,107,107,107,107,107,107,107,107,107,107,47,107,107,107,47,107,107,47,]),'nomMain':([4,7,9,19,],[6,6,6,6,]),'cond':([159,],[204,]),'termino':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,278,279,108,108,108,108,108,]),'create_asign':([143,149,220,221,],[189,194,259,260,]),'tipoFunc':([5,],[16,]),'bloque':([204,301,],[250,312,]),'push_id':([57,75,117,146,170,219,226,],[86,86,158,158,215,258,158,]),'quad_print':([192,193,254,],[242,243,286,]),'varsGlobal':([4,],[7,]),'matrix':([37,46,50,72,82,95,96,100,103,104,105,116,126,131,139,151,152,164,171,174,176,177,191,239,245,246,247,248,249,256,291,293,295,307,309,326,],[49,49,49,49,110,110,49,49,110,110,110,110,110,110,49,110,110,110,110,110,110,110,110,110,110,110,110,110,49,110,110,110,49,110,110,49,]),'tipo':([10,35,39,55,142,167,],[22,45,22,83,45,83,]),'inversa':([37,46,50,72,96,100,139,249,295,326,],[62,62,62,62,62,62,62,62,62,62,]),'exp1':([150,],[195,]),'estatuto':([37,46,50,72,96,100,139,249,295,326,],[50,50,50,50,50,50,50,50,50,50,]),'determinante':([174,],[222,]),'param':([35,142,],[43,188,]),'varAux2':([83,214,303,323,],[121,253,314,325,]),'varAuxGlobal2':([22,41,134,267,],[33,71,180,296,]),'varAuxGlobal1':([10,39,],[26,69,]),'program':([0,],[1,]),'functionReturn':([72,99,100,136,141,185,],[97,138,140,182,187,235,]),'varAux1':([55,167,],[84,212,]),'paramAvarTable':([74,],[101,]),'main':([4,7,9,19,],[8,18,21,31,]),'lectura':([37,46,50,72,96,100,139,249,295,326,],[52,52,52,52,52,52,52,52,52,52,]),'empty':([35,72,99,100,136,141,142,176,185,293,307,],[44,98,98,98,98,98,44,225,98,225,225,]),'function':([4,7,183,234,236,268,272,298,],[9,19,233,269,271,297,299,311,]),'escrituraAux':([104,191,239,],[147,240,273,]),'push_poper':([48,56,78,80,109,111,124,127,160,161,162,163,165,166,196,197,200,202,],[79,85,103,105,151,152,171,174,205,206,207,208,210,211,245,246,247,248,]),'push_var':([122,],[169,]),'gosub':([224,],[262,]),'ver_dim2':([305,],[315,]),'comp':([119,],[164,]),'factor':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,]),'actualizaFuncion':([57,75,146,219,],[87,87,87,87,]),'transpuesta':([37,46,50,72,96,100,139,249,295,326,],[53,53,53,53,53,53,53,53,53,53,]),'condElse':([283,],[301,]),'condicion':([37,46,50,72,96,100,139,249,295,326,],[54,54,54,54,54,54,54,54,54,54,]),'quad_term':([108,],[150,]),'push_cte':([113,114,115,144,],[154,155,156,190,]),'quad_comp':([209,],[251,]),'generarEra':([87,],[129,]),'loopFromDo':([37,46,50,72,96,100,139,249,295,326,],[58,58,58,58,58,58,58,58,58,58,]),'expresion':([82,104,116,131,171,174,177,191,239,291,309,],[118,145,157,178,216,220,228,145,145,306,317,]),'endPrograma':([8,18,21,31,],[20,30,32,38,]),'llamadaAFuncion':([37,46,50,72,96,100,104,139,174,191,239,249,295,326,],[59,76,76,76,76,76,148,76,221,241,241,76,76,76,]),'push_matriz':([313,],[320,]),'asignacion':([37,46,50,72,96,100,139,249,295,326,],[61,61,61,61,61,61,61,61,61,61,]),'while2':([229,],[266,]),'generaCuadbreak':([65,],[93,]),'while1':([63,],[91,]),'push_id2':([226,],[263,]),'bloqueAux':([37,46,50,72,96,100,139,249,295,326,],[64,77,81,99,136,141,185,281,310,327,]),'ver_dim1':([218,],[257,]),'while':([37,46,50,72,96,100,139,249,295,326,],[66,66,66,66,66,66,66,66,66,66,]),'termino1':([153,],[201,]),'exp':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,256,291,293,307,309,],[119,135,143,119,149,119,173,119,209,119,119,227,119,119,119,276,277,287,119,227,227,119,]),'nomFunc':([16,],[27,]),'factorAux':([82,95,103,104,105,116,126,131,164,171,174,176,177,191,239,245,246,247,248,256,291,293,307,309,],[120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,120,]),'comparacion':([37,46,50,72,96,100,139,249,295,326,],[67,67,67,67,67,67,67,67,67,67,]),'paramFuncionAux':([227,263,],[264,292,]),'escritura':([37,46,50,72,96,100,139,249,295,326,],[68,68,68,68,68,68,68,68,68,68,]),}\n\n_lr_goto = {}\nfor _k, _v in _lr_goto_items.items():\n for _x, _y in zip(_v[0], _v[1]):\n if not _x in _lr_goto: _lr_goto[_x] = {}\n _lr_goto[_x][_k] = _y\ndel _lr_goto_items\n_lr_productions = [\n (\"S' -> program\",\"S'\",1,None,None,None),\n ('program -> PROGRAM ID COLON varsGlobal function main endPrograma','program',7,'p_program','lexAndSyn.py',144),\n ('program -> PROGRAM ID COLON function main endPrograma','program',6,'p_program','lexAndSyn.py',145),\n ('program -> PROGRAM ID COLON varsGlobal main endPrograma','program',6,'p_program','lexAndSyn.py',146),\n ('program -> PROGRAM ID COLON main endPrograma','program',5,'p_program','lexAndSyn.py',147),\n ('endPrograma -> <empty>','endPrograma',0,'p_endPrograma','lexAndSyn.py',153),\n ('varsGlobal -> VAR varAuxGlobal1','varsGlobal',2,'p_varsGlobal','lexAndSyn.py',158),\n ('varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON','varAuxGlobal1',3,'p_varAuxGlobal1','lexAndSyn.py',162),\n ('varAuxGlobal1 -> tipo varAuxGlobal2 SEMICOLON varAuxGlobal1','varAuxGlobal1',4,'p_varAuxGlobal1','lexAndSyn.py',163),\n ('varAuxGlobal2 -> ID','varAuxGlobal2',1,'p_varAuxGlobal2','lexAndSyn.py',167),\n ('varAuxGlobal2 -> ID COMA varAuxGlobal2','varAuxGlobal2',3,'p_varAuxGlobal2','lexAndSyn.py',168),\n ('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH','varAuxGlobal2',4,'p_varAuxGlobal2','lexAndSyn.py',169),\n ('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH COMA varAuxGlobal2','varAuxGlobal2',6,'p_varAuxGlobal2','lexAndSyn.py',170),\n ('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH','varAuxGlobal2',7,'p_varAuxGlobal2','lexAndSyn.py',171),\n ('varAuxGlobal2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH COMA varAuxGlobal2','varAuxGlobal2',9,'p_varAuxGlobal2','lexAndSyn.py',172),\n ('main -> nomMain LPAREN RPAREN LBRACE bloqueAux RBRACE','main',6,'p_main','lexAndSyn.py',180),\n ('main -> nomMain LPAREN RPAREN LBRACE vars bloqueAux RBRACE','main',7,'p_main','lexAndSyn.py',181),\n ('main -> nomMain LPAREN RPAREN LBRACE llamadaAFuncion RBRACE','main',6,'p_main','lexAndSyn.py',182),\n ('nomMain -> MAIN','nomMain',1,'p_nomMain','lexAndSyn.py',186),\n ('vars -> VAR varAux1','vars',2,'p_vars','lexAndSyn.py',196),\n ('varAux1 -> tipo varAux2 SEMICOLON','varAux1',3,'p_varAux1','lexAndSyn.py',200),\n ('varAux1 -> tipo varAux2 SEMICOLON varAux1','varAux1',4,'p_varAux1','lexAndSyn.py',201),\n ('varAux2 -> ID push_var','varAux2',2,'p_varAux2','lexAndSyn.py',205),\n ('varAux2 -> ID push_var COMA varAux2','varAux2',4,'p_varAux2','lexAndSyn.py',206),\n ('varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo','varAux2',5,'p_varAux2','lexAndSyn.py',207),\n ('varAux2 -> ID LCORCH CTE_I RCORCH push_arreglo COMA varAux2','varAux2',7,'p_varAux2','lexAndSyn.py',208),\n ('varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz','varAux2',8,'p_varAux2','lexAndSyn.py',209),\n ('varAux2 -> ID LCORCH CTE_I RCORCH LCORCH CTE_I RCORCH push_matriz COMA varAux2','varAux2',10,'p_varAux2','lexAndSyn.py',210),\n ('push_var -> <empty>','push_var',0,'p_pushVariable','lexAndSyn.py',214),\n ('push_arreglo -> <empty>','push_arreglo',0,'p_arreglo','lexAndSyn.py',220),\n ('push_matriz -> <empty>','push_matriz',0,'p_matriz','lexAndSyn.py',231),\n ('tipo -> INT','tipo',1,'p_tipo','lexAndSyn.py',246),\n ('tipo -> FLOAT','tipo',1,'p_tipo','lexAndSyn.py',247),\n ('tipo -> CHAR','tipo',1,'p_tipo','lexAndSyn.py',248),\n ('tipoFunc -> INT','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',253),\n ('tipoFunc -> FLOAT','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',254),\n ('tipoFunc -> CHAR','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',255),\n ('tipoFunc -> VOID','tipoFunc',1,'p_tipoFunc','lexAndSyn.py',256),\n ('bloque -> LBRACE RBRACE','bloque',2,'p_bloque','lexAndSyn.py',261),\n ('bloque -> LBRACE bloqueAux RBRACE','bloque',3,'p_bloque','lexAndSyn.py',262),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc','function',9,'p_function','lexAndSyn.py',268),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc','function',11,'p_function','lexAndSyn.py',269),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE functionReturn RBRACE endProc function','function',10,'p_function','lexAndSyn.py',270),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function','function',12,'p_function','lexAndSyn.py',271),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc','function',10,'p_function','lexAndSyn.py',272),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function','function',11,'p_function','lexAndSyn.py',273),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc','function',10,'p_function','lexAndSyn.py',274),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc','function',11,'p_function','lexAndSyn.py',275),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE bloqueAux functionReturn RBRACE endProc function','function',12,'p_function','lexAndSyn.py',276),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc','function',12,'p_function','lexAndSyn.py',277),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE functionReturn RBRACE endProc function','function',11,'p_function','lexAndSyn.py',278),\n ('function -> FUNCTION tipoFunc nomFunc LPAREN param RPAREN LBRACE vars bloqueAux functionReturn RBRACE endProc function','function',13,'p_function','lexAndSyn.py',279),\n ('functionReturn -> RETURN exp creaCuadReturn SEMICOLON','functionReturn',4,'p_functionReturn','lexAndSyn.py',283),\n ('functionReturn -> empty','functionReturn',1,'p_functionReturn','lexAndSyn.py',284),\n ('creaCuadReturn -> <empty>','creaCuadReturn',0,'p_creaCuadReturn','lexAndSyn.py',288),\n ('endProc -> <empty>','endProc',0,'p_endProc','lexAndSyn.py',293),\n ('param -> tipo ID paramAvarTable','param',3,'p_param','lexAndSyn.py',298),\n ('param -> tipo ID paramAvarTable COMA param','param',5,'p_param','lexAndSyn.py',299),\n ('param -> empty','param',1,'p_param','lexAndSyn.py',300),\n ('paramAvarTable -> <empty>','paramAvarTable',0,'p_paramAvarTable','lexAndSyn.py',305),\n ('empty -> <empty>','empty',0,'p_empty','lexAndSyn.py',311),\n ('push_function -> <empty>','push_function',0,'p_push_function','lexAndSyn.py',315),\n ('nomFunc -> ID push_function','nomFunc',2,'p_nomFunc','lexAndSyn.py',324),\n ('bloqueAux -> estatuto','bloqueAux',1,'p_bloqueAux','lexAndSyn.py',333),\n ('bloqueAux -> estatuto bloqueAux','bloqueAux',2,'p_bloqueAux','lexAndSyn.py',334),\n ('while -> WHILE while1 LPAREN expresion RPAREN while2 LBRACE bloqueAux RBRACE while3','while',10,'p_while','lexAndSyn.py',338),\n ('while1 -> <empty>','while1',0,'p_while1','lexAndSyn.py',342),\n ('while2 -> <empty>','while2',0,'p_while2','lexAndSyn.py',346),\n ('while3 -> <empty>','while3',0,'p_while3','lexAndSyn.py',350),\n ('loopFromDo -> FROM LPAREN ID EQUAL expresion RPAREN TO LPAREN expresion RPAREN DO LBRACE bloqueAux RBRACE','loopFromDo',14,'p_loopFromDo','lexAndSyn.py',354),\n ('estatuto -> asignacion','estatuto',1,'p_estatuto','lexAndSyn.py',366),\n ('estatuto -> condicion','estatuto',1,'p_estatuto','lexAndSyn.py',367),\n ('estatuto -> escritura','estatuto',1,'p_estatuto','lexAndSyn.py',368),\n ('estatuto -> while','estatuto',1,'p_estatuto','lexAndSyn.py',369),\n ('estatuto -> loopFromDo','estatuto',1,'p_estatuto','lexAndSyn.py',370),\n ('estatuto -> comparacion','estatuto',1,'p_estatuto','lexAndSyn.py',371),\n ('estatuto -> llamadaAFuncion SEMICOLON','estatuto',2,'p_estatuto','lexAndSyn.py',372),\n ('estatuto -> lectura','estatuto',1,'p_estatuto','lexAndSyn.py',373),\n ('estatuto -> BREAK generaCuadbreak SEMICOLON','estatuto',3,'p_estatuto','lexAndSyn.py',374),\n ('estatuto -> transpuesta','estatuto',1,'p_estatuto','lexAndSyn.py',375),\n ('estatuto -> inversa','estatuto',1,'p_estatuto','lexAndSyn.py',376),\n ('transpuesta -> ID push_id TRANSPUESTA creaTrans SEMICOLON','transpuesta',5,'p_transpuesta','lexAndSyn.py',380),\n ('inversa -> ID push_id INVERSA creaInversa SEMICOLON','inversa',5,'p_inversa','lexAndSyn.py',383),\n ('creaInversa -> <empty>','creaInversa',0,'p_creaInversa','lexAndSyn.py',387),\n ('creaTrans -> <empty>','creaTrans',0,'p_creaTrans','lexAndSyn.py',391),\n ('generaCuadbreak -> <empty>','generaCuadbreak',0,'p_generaCuadbreak','lexAndSyn.py',395),\n ('llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN expresion','llamadaAFuncion',8,'p_llamadaAFuncion','lexAndSyn.py',399),\n ('llamadaAFuncion -> ID actualizaFuncion generarEra LPAREN paramFuncion gosub RPAREN','llamadaAFuncion',7,'p_llamadaAFuncion','lexAndSyn.py',400),\n ('actualizaFuncion -> <empty>','actualizaFuncion',0,'p_actualizaFuncion','lexAndSyn.py',404),\n ('gosub -> <empty>','gosub',0,'p_gosub','lexAndSyn.py',409),\n ('generarEra -> <empty>','generarEra',0,'p_generarEra','lexAndSyn.py',421),\n ('paramFuncion -> ID push_id2 paramFuncionAux','paramFuncion',3,'p_paramFuncion','lexAndSyn.py',429),\n ('paramFuncion -> ID push_id2 paramFuncionAux COMA paramFuncion','paramFuncion',5,'p_paramFuncion','lexAndSyn.py',430),\n ('paramFuncion -> exp paramFuncionAux','paramFuncion',2,'p_paramFuncion','lexAndSyn.py',431),\n ('paramFuncion -> exp paramFuncionAux COMA paramFuncion','paramFuncion',4,'p_paramFuncion','lexAndSyn.py',432),\n ('paramFuncion -> empty','paramFuncion',1,'p_paramFuncion','lexAndSyn.py',433),\n ('paramFuncionAux -> <empty>','paramFuncionAux',0,'p_paramFuncionAux','lexAndSyn.py',437),\n ('push_id2 -> <empty>','push_id2',0,'p_push_id2','lexAndSyn.py',441),\n ('arreglo -> ID push_id LCORCH exp RCORCH ver_dim1','arreglo',6,'p_array','lexAndSyn.py',445),\n ('matrix -> ID push_id LCORCH exp RCORCH LCORCH exp RCORCH ver_dim2','matrix',9,'p_matrix','lexAndSyn.py',449),\n ('ver_dim2 -> <empty>','ver_dim2',0,'p_ver_dim2','lexAndSyn.py',453),\n ('asignacion -> ID push_id EQUAL push_poper expresion create_asign SEMICOLON','asignacion',7,'p_asignacion','lexAndSyn.py',457),\n ('asignacion -> arreglo EQUAL push_poper exp create_asign SEMICOLON','asignacion',6,'p_asignacion','lexAndSyn.py',458),\n ('asignacion -> matrix EQUAL push_poper exp create_asign SEMICOLON','asignacion',6,'p_asignacion','lexAndSyn.py',459),\n ('asignacion -> ID push_id EQUAL push_poper llamadaAFuncion create_asign SEMICOLON','asignacion',7,'p_asignacion','lexAndSyn.py',460),\n ('asignacion -> ID push_id EQUAL push_poper determinante SEMICOLON','asignacion',6,'p_asignacion','lexAndSyn.py',461),\n ('determinante -> ID push_id DETERMINANT','determinante',3,'p_determinante','lexAndSyn.py',465),\n ('push_id_dimensionada -> <empty>','push_id_dimensionada',0,'p_push_id_dimensionada','lexAndSyn.py',470),\n ('create_asign_dim -> <empty>','create_asign_dim',0,'p_create_asign_dim','lexAndSyn.py',473),\n ('ver_dim1 -> <empty>','ver_dim1',0,'p_ver_dim1','lexAndSyn.py',477),\n ('create_asign -> <empty>','create_asign',0,'p_create_asign','lexAndSyn.py',481),\n ('comparacion -> ID push_id DOUBLEEQUAL push_poper expresion SEMICOLON','comparacion',6,'p_comparacion','lexAndSyn.py',485),\n ('condicion -> IF LPAREN expresion RPAREN cond bloque condFinal','condicion',7,'p_condicion','lexAndSyn.py',489),\n ('condicion -> IF LPAREN expresion RPAREN cond bloque ELSE condElse bloque condFinal','condicion',10,'p_condicion','lexAndSyn.py',490),\n ('cond -> <empty>','cond',0,'p_quad_cond','lexAndSyn.py',494),\n ('condElse -> <empty>','condElse',0,'p_quad_condElse','lexAndSyn.py',498),\n ('condFinal -> <empty>','condFinal',0,'p_quad_condFinal','lexAndSyn.py',502),\n ('escritura -> PRINT push_poper LPAREN escrituraAux RPAREN quad_print SEMICOLON','escritura',7,'p_escritura','lexAndSyn.py',506),\n ('escritura -> PRINT push_poper LPAREN llamadaAFuncion RPAREN quad_print SEMICOLON','escritura',7,'p_escritura','lexAndSyn.py',507),\n ('lectura -> INPUT push_poper LPAREN ID push_id RPAREN quad_print SEMICOLON','lectura',8,'p_lectura','lexAndSyn.py',511),\n ('quad_print -> <empty>','quad_print',0,'p_quad_print','lexAndSyn.py',515),\n ('escrituraAux -> expresion','escrituraAux',1,'p_escrituraAux','lexAndSyn.py',519),\n ('escrituraAux -> CTE_STRING push_cte','escrituraAux',2,'p_escrituraAux','lexAndSyn.py',520),\n ('escrituraAux -> expresion COMA escrituraAux','escrituraAux',3,'p_escrituraAux','lexAndSyn.py',521),\n ('escrituraAux -> CTE_STRING push_cte COMA escrituraAux','escrituraAux',4,'p_escrituraAux','lexAndSyn.py',522),\n ('escrituraAux -> llamadaAFuncion','escrituraAux',1,'p_escrituraAux','lexAndSyn.py',523),\n ('expresion -> exp','expresion',1,'p_expresion','lexAndSyn.py',527),\n ('expresion -> exp comp exp quad_comp','expresion',4,'p_expresion','lexAndSyn.py',528),\n ('comp -> LOWERTHAN push_poper','comp',2,'p_comp','lexAndSyn.py',532),\n ('comp -> MORETHAN push_poper','comp',2,'p_comp','lexAndSyn.py',533),\n ('comp -> DIFFERENT push_poper','comp',2,'p_comp','lexAndSyn.py',534),\n ('comp -> DOUBLEEQUAL push_poper','comp',2,'p_comp','lexAndSyn.py',535),\n ('comp -> LOWEREQUAL push_poper','comp',2,'p_comp','lexAndSyn.py',536),\n ('comp -> MOREEQUAL push_poper','comp',2,'p_comp','lexAndSyn.py',537),\n ('quad_comp -> <empty>','quad_comp',0,'p_quad_comp','lexAndSyn.py',541),\n ('exp -> termino quad_term','exp',2,'p_exp','lexAndSyn.py',545),\n ('exp -> termino quad_term exp1','exp',3,'p_exp','lexAndSyn.py',546),\n ('exp1 -> PLUS push_poper exp','exp1',3,'p_exp1','lexAndSyn.py',550),\n ('exp1 -> MINUS push_poper exp','exp1',3,'p_exp1','lexAndSyn.py',551),\n ('quad_term -> <empty>','quad_term',0,'p_quad_term','lexAndSyn.py',555),\n ('quad_fact -> <empty>','quad_fact',0,'p_quad_fact','lexAndSyn.py',559),\n ('termino -> factor quad_fact','termino',2,'p_termino','lexAndSyn.py',563),\n ('termino -> factor quad_fact termino1','termino',3,'p_termino','lexAndSyn.py',564),\n ('termino1 -> TIMES push_poper termino','termino1',3,'p_termino1','lexAndSyn.py',568),\n ('termino1 -> DIVIDE push_poper termino','termino1',3,'p_termino1','lexAndSyn.py',569),\n ('factor -> LPAREN expresion RPAREN','factor',3,'p_factor','lexAndSyn.py',573),\n ('factor -> factorAux','factor',1,'p_factor','lexAndSyn.py',574),\n ('factorAux -> PLUS push_poper var_cte','factorAux',3,'p_factorAux','lexAndSyn.py',578),\n ('factorAux -> MINUS push_poper var_cte','factorAux',3,'p_factorAux','lexAndSyn.py',579),\n ('factorAux -> var_cte','factorAux',1,'p_factorAux','lexAndSyn.py',580),\n ('push_id -> <empty>','push_id',0,'p_push_id','lexAndSyn.py',584),\n ('push_cte -> <empty>','push_cte',0,'p_push_cte','lexAndSyn.py',588),\n ('push_poper -> <empty>','push_poper',0,'p_push_poper','lexAndSyn.py',598),\n ('var_cte -> ID push_id','var_cte',2,'p_var_cte','lexAndSyn.py',602),\n ('var_cte -> CTE_I push_cte','var_cte',2,'p_var_cte','lexAndSyn.py',603),\n ('var_cte -> CTE_F push_cte','var_cte',2,'p_var_cte','lexAndSyn.py',604),\n ('var_cte -> CTE_STRING push_cte','var_cte',2,'p_var_cte','lexAndSyn.py',605),\n ('var_cte -> arreglo','var_cte',1,'p_var_cte','lexAndSyn.py',606),\n ('var_cte -> matrix','var_cte',1,'p_var_cte','lexAndSyn.py',607),\n]\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import glob
def next_batch(num, data, labels):
'''
Return a total of `num` random samples and labels.
'''
idx = np.arange(0 , len(data))
np.random.shuffle(idx)
idx = idx[:num]
data_shuffle = [data[ i] for i in idx]
labels_shuffle = [labels[ i] for i in idx]
return np.asarray(data_shuffle), np.asarray(labels_shuffle)
def dataX(features, set):
data_x = np.array([])
count = 0
for filepath in glob.iglob(set):
globpath = filepath + '\*.jpg'
for filepath in glob.iglob(r'' + globpath):
count = count + 1
img = Image.open(filepath).convert('L') # convert image to 8-bit grayscale
data = list(img.getdata())
x = np.array(data)
data_x = np.append(data_x, x)
data_x = data_x.reshape(count, features)
# return data_x
return data_x.astype(int)
def dataY(categories, set):
data_y = np.array([])
count = 0
for filepath in glob.iglob(set):
path = filepath.split("\\")
globpath = filepath + '\*.jpg'
for filepath in glob.iglob(r'' + globpath):
count = count + 1
y = np.array([])
t = [int(path[2])]
y = np.append(y, t)
data_y = np.append(data_y, y)
# data_y = data_y.reshape(count, categories)
# return data_y
return data_y.astype(int)
def model():
print(' model')
batch_size = 50
features = 32 * 32
categories = 5
filter1 = 32
filter2 = 64
train_path = r'dataset\train\[0-4]'
test_path = r'dataset\test\[0-4]'
validation_path = r'dataset\validation\[0-4]'
data_x = dataX(features, train_path)
print("datax: ", data_x)
data_y = dataY(categories, train_path)
print("datay: ", data_y)
data_x_test = dataX(features, test_path)
data_y_test = dataY(categories, test_path)
data_x_validation = dataX(features, validation_path)
data_y_validation = dataY(categories, validation_path)
x_image = tf.reshape(data_x, [-1, 32, 32, 1])
x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])
x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])
model = models.Sequential()
model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding='SAME', input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding='SAME', input_shape=(filter1, 16, 16, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(filter2, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(categories))
model.summary()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(x=x_image, y=data_y, epochs=10,
validation_data=(x_image_validation, data_y_validation))
# Show results in graph view
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
# plt.show()
test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)
plt.show()
if __name__ == '__main__':
model()
|
normal
|
{
"blob_id": "f8d815bcdc74452b66a1b3b33bf0fbe976e728c8",
"index": 231,
"step-1": "<mask token>\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef next_batch(num, data, labels):\n \"\"\"\n Return a total of `num` random samples and labels.\n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef next_batch(num, data, labels):\n \"\"\"\n Return a total of `num` random samples and labels.\n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\nif __name__ == '__main__':\n model()\n",
"step-4": "import tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport glob\n\n\ndef next_batch(num, data, labels):\n \"\"\"\n Return a total of `num` random samples and labels.\n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\nif __name__ == '__main__':\n model()\n",
"step-5": "# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport glob\n\n\ndef next_batch(num, data, labels):\n '''\n Return a total of `num` random samples and labels.\n '''\n idx = np.arange(0 , len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[ i] for i in idx]\n labels_shuffle = [labels[ i] for i in idx]\n\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\*.jpg'\n for filepath in glob.iglob(r'' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L') # convert image to 8-bit grayscale\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n # return data_x\n return data_x.astype(int)\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split(\"\\\\\")\n globpath = filepath + '\\*.jpg'\n for filepath in glob.iglob(r'' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n # data_y = data_y.reshape(count, categories)\n # return data_y\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n\n train_path = r'dataset\\train\\[0-4]'\n test_path = r'dataset\\test\\[0-4]'\n validation_path = r'dataset\\validation\\[0-4]'\n\n\n\n data_x = dataX(features, train_path)\n print(\"datax: \", data_x)\n data_y = dataY(categories, train_path)\n print(\"datay: \", data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding='SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding='SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n\n model.summary()\n\n model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n history = model.fit(x=x_image, y=data_y, epochs=10,\n validation_data=(x_image_validation, data_y_validation))\n\n # Show results in graph view\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n # plt.show()\n\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n\n plt.show()\n\nif __name__ == '__main__':\n model()\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
class Consignor(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
indents = db.relationship('Indent', lazy='dynamic')
def __init__(self):
pass
def __repr__(self):
return '<Consignor %s>' % str(self.id)
class Convoy(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Convoy %s>' % str(self.id)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Account(db.Model):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __repr__(self):
return '<Account %s %s>' % (str(self.id), self.acc)
class Transporter(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
d_lic = db.Column(db.String(50))
v_lic = db.Column(db.String(50))
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Transporter %s>' % str(self.id)
class Consignor(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
indents = db.relationship('Indent', lazy='dynamic')
def __init__(self):
pass
def __repr__(self):
return '<Consignor %s>' % str(self.id)
class Convoy(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Convoy %s>' % str(self.id)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Account(db.Model):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __init__(self, acc, pwd):
self.acc = acc
self.pwd = pwd
def __repr__(self):
return '<Account %s %s>' % (str(self.id), self.acc)
class Transporter(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
d_lic = db.Column(db.String(50))
v_lic = db.Column(db.String(50))
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Transporter %s>' % str(self.id)
class Consignor(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
indents = db.relationship('Indent', lazy='dynamic')
def __init__(self):
pass
def __repr__(self):
return '<Consignor %s>' % str(self.id)
class Convoy(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Convoy %s>' % str(self.id)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Account(db.Model):
id = db.Column(db.Integer, primary_key=True)
acc = db.Column(db.String(50), unique=True)
pwd = db.Column(db.String(50))
name = db.Column(db.String(20))
sex = db.Column(db.SmallInteger)
idno = db.Column(db.String(20))
phone = db.Column(db.String(20))
crttime = db.Column(db.TIMESTAMP)
crtip = db.Column(db.String(50))
crtmac = db.Column(db.String(50))
crtplat = db.Column(db.SmallInteger)
crtrole = db.Column(db.SmallInteger)
lasttime = db.Column(db.TIMESTAMP)
lastip = db.Column(db.String(50))
lastmac = db.Column(db.String(50))
lastplat = db.Column(db.SmallInteger)
lastrole = db.Column(db.SmallInteger)
transporter = db.relationship('Transporter', uselist=False)
consignor = db.relationship('Consignor', uselist=False)
def __init__(self, acc, pwd):
self.acc = acc
self.pwd = pwd
def __repr__(self):
return '<Account %s %s>' % (str(self.id), self.acc)
class Transporter(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
d_lic = db.Column(db.String(50))
v_lic = db.Column(db.String(50))
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Transporter %s>' % str(self.id)
class Consignor(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
indents = db.relationship('Indent', lazy='dynamic')
def __init__(self):
pass
def __repr__(self):
return '<Consignor %s>' % str(self.id)
class Convoy(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Convoy %s>' % str(self.id)
<|reserved_special_token_1|>
from .. import db
class Account(db.Model):
id = db.Column(db.Integer, primary_key=True)
acc = db.Column(db.String(50), unique=True)#TODO 调整长度
pwd = db.Column(db.String(50))#TODO 调整长度
name = db.Column(db.String(20))
sex = db.Column(db.SmallInteger)
idno = db.Column(db.String(20))
phone = db.Column(db.String(20))
crttime = db.Column(db.TIMESTAMP)
crtip = db.Column(db.String(50))
crtmac = db.Column(db.String(50))
crtplat = db.Column(db.SmallInteger)
crtrole = db.Column(db.SmallInteger)
lasttime = db.Column(db.TIMESTAMP)
lastip = db.Column(db.String(50))
lastmac = db.Column(db.String(50))
lastplat = db.Column(db.SmallInteger)
lastrole = db.Column(db.SmallInteger)
transporter = db.relationship('Transporter', uselist=False)
consignor = db.relationship('Consignor', uselist=False)
def __init__(self, acc, pwd):
self.acc = acc
self.pwd = pwd
def __repr__(self):
return '<Account %s %s>'%(str(self.id), self.acc)
class Transporter(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
d_lic = db.Column(db.String(50)) #TODO 长度
v_lic = db.Column(db.String(50))
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Transporter %s>'%str(self.id)
class Consignor(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
indents = db.relationship('Indent', lazy='dynamic')
def __init__(self):
pass
def __repr__(self):
return '<Consignor %s>'%str(self.id)
class Convoy(db.Model):
id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)
account = db.relationship('Account', uselist=False)
def __init__(self):
pass
def __repr__(self):
return '<Convoy %s>'%str(self.id)
|
flexible
|
{
"blob_id": "b6824251b1165ca6c66049d40c79fccee6bc7d3a",
"index": 159,
"step-1": "<mask token>\n\n\nclass Consignor(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n indents = db.relationship('Indent', lazy='dynamic')\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Consignor %s>' % str(self.id)\n\n\nclass Convoy(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Convoy %s>' % str(self.id)\n",
"step-2": "<mask token>\n\n\nclass Account(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '<Account %s %s>' % (str(self.id), self.acc)\n\n\nclass Transporter(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n d_lic = db.Column(db.String(50))\n v_lic = db.Column(db.String(50))\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Transporter %s>' % str(self.id)\n\n\nclass Consignor(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n indents = db.relationship('Indent', lazy='dynamic')\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Consignor %s>' % str(self.id)\n\n\nclass Convoy(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Convoy %s>' % str(self.id)\n",
"step-3": "<mask token>\n\n\nclass Account(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, acc, pwd):\n self.acc = acc\n self.pwd = pwd\n\n def __repr__(self):\n return '<Account %s %s>' % (str(self.id), self.acc)\n\n\nclass Transporter(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n d_lic = db.Column(db.String(50))\n v_lic = db.Column(db.String(50))\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Transporter %s>' % str(self.id)\n\n\nclass Consignor(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n indents = db.relationship('Indent', lazy='dynamic')\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Consignor %s>' % str(self.id)\n\n\nclass Convoy(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Convoy %s>' % str(self.id)\n",
"step-4": "<mask token>\n\n\nclass Account(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n acc = db.Column(db.String(50), unique=True)\n pwd = db.Column(db.String(50))\n name = db.Column(db.String(20))\n sex = db.Column(db.SmallInteger)\n idno = db.Column(db.String(20))\n phone = db.Column(db.String(20))\n crttime = db.Column(db.TIMESTAMP)\n crtip = db.Column(db.String(50))\n crtmac = db.Column(db.String(50))\n crtplat = db.Column(db.SmallInteger)\n crtrole = db.Column(db.SmallInteger)\n lasttime = db.Column(db.TIMESTAMP)\n lastip = db.Column(db.String(50))\n lastmac = db.Column(db.String(50))\n lastplat = db.Column(db.SmallInteger)\n lastrole = db.Column(db.SmallInteger)\n transporter = db.relationship('Transporter', uselist=False)\n consignor = db.relationship('Consignor', uselist=False)\n\n def __init__(self, acc, pwd):\n self.acc = acc\n self.pwd = pwd\n\n def __repr__(self):\n return '<Account %s %s>' % (str(self.id), self.acc)\n\n\nclass Transporter(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n d_lic = db.Column(db.String(50))\n v_lic = db.Column(db.String(50))\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Transporter %s>' % str(self.id)\n\n\nclass Consignor(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n indents = db.relationship('Indent', lazy='dynamic')\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Consignor %s>' % str(self.id)\n\n\nclass Convoy(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Convoy %s>' % str(self.id)\n",
"step-5": "from .. import db\n\n\nclass Account(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n acc = db.Column(db.String(50), unique=True)#TODO 调整长度\n pwd = db.Column(db.String(50))#TODO 调整长度\n name = db.Column(db.String(20))\n sex = db.Column(db.SmallInteger)\n idno = db.Column(db.String(20))\n phone = db.Column(db.String(20))\n crttime = db.Column(db.TIMESTAMP)\n crtip = db.Column(db.String(50))\n crtmac = db.Column(db.String(50))\n crtplat = db.Column(db.SmallInteger)\n crtrole = db.Column(db.SmallInteger)\n lasttime = db.Column(db.TIMESTAMP)\n lastip = db.Column(db.String(50))\n lastmac = db.Column(db.String(50))\n lastplat = db.Column(db.SmallInteger)\n lastrole = db.Column(db.SmallInteger)\n\n transporter = db.relationship('Transporter', uselist=False)\n consignor = db.relationship('Consignor', uselist=False)\n\n def __init__(self, acc, pwd):\n self.acc = acc\n self.pwd = pwd\n\n def __repr__(self):\n return '<Account %s %s>'%(str(self.id), self.acc)\n\n\nclass Transporter(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n d_lic = db.Column(db.String(50)) #TODO 长度\n v_lic = db.Column(db.String(50))\n\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Transporter %s>'%str(self.id)\n\n\nclass Consignor(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n\n account = db.relationship('Account', uselist=False)\n indents = db.relationship('Indent', lazy='dynamic')\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Consignor %s>'%str(self.id)\n\n\nclass Convoy(db.Model):\n id = db.Column(db.Integer, db.ForeignKey('account.id'), primary_key=True)\n\n account = db.relationship('Account', uselist=False)\n\n def __init__(self):\n pass\n\n def __repr__(self):\n return '<Convoy %s>'%str(self.id)\n",
"step-ids": [
8,
14,
15,
16,
18
]
}
|
[
8,
14,
15,
16,
18
] |
#!/usr/bin/env python
"""
Power calculation based for admixture mapping.
@ref: Design and Analysis of admixture mapping studies, (2004).
@Author: wavefancy@gmail.com
Usage:
PowerCalculation.py -r aratio -n nhap
PowerCalculation.py -h | --help | -v | --version | -f | --format
Notes:
1. Read parameters from stdin, and output to stdout.
Options:
-r aratio Ancestry risk ratio. aratio = f2/f0 for multiplicative model.
-n nhap Number of haplotypes, n = 2*N, N for sample size.
-h --help Show this screen.
-v --version Show version.
-f --format Show input/output file format example.
"""
import sys
from docopt import docopt
from signal import signal, SIGPIPE, SIG_DFL
def ShowFormat():
'''File format example'''
print('''
#rfmix output, 3 person, 2 snps
------------------------
1 1 2 1 2 2
1 2 2 1 2 2
#id average:
------------------------
0.8
0.5
0.1
#output:
------------------------
0.40 0.00 -0.20
-0.60 0.00 -0.20
''');
if __name__ == '__main__':
args = docopt(__doc__, version='1.0')
# print(args)
# sys.exit(0)
if(args['--format']):
ShowFormat()
sys.exit(-1)
idav = [] # 2*ID_average
with open(args['-a'],'r') as ifile:
for line in ifile:
line = line.strip()
if line:
idav.append(2 * float(line))
checkLen = True
for line in sys.stdin:
line = line.strip()
if line:
ss = line.split()
ss = [2-int(x) for x in ss] #number of pop1 copy for each haplotype.
obs = []
for i in range(0, len(ss), 2):
obs.append(ss[i] + ss[i+1])
if checkLen:
if len(obs) != len(idav):
sys.stderr.write('Error: numbr of individuals in ID_average file is not the same as that in sys.stdin.\n')
sys.exit(-1)
else:
checkLen = False
out = [ '%.2f'%(y-x) for x,y in zip(idav, obs)]
sys.stdout.write('%s\n'%('\t'.join(out)))
sys.stdout.flush()
sys.stdout.close()
sys.stderr.flush()
sys.stderr.close()
|
normal
|
{
"blob_id": "7f9046582ff03d1c72d191a8f78c911cbc8a0650",
"index": 5907,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef ShowFormat():\n \"\"\"File format example\"\"\"\n print(\n \"\"\"\n #rfmix output, 3 person, 2 snps\n ------------------------\n1 1 2 1 2 2\n1 2 2 1 2 2\n\n #id average:\n ------------------------\n0.8\n0.5\n0.1\n\n #output:\n ------------------------\n0.40 0.00 -0.20\n-0.60 0.00 -0.20\n \"\"\"\n )\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef ShowFormat():\n \"\"\"File format example\"\"\"\n print(\n \"\"\"\n #rfmix output, 3 person, 2 snps\n ------------------------\n1 1 2 1 2 2\n1 2 2 1 2 2\n\n #id average:\n ------------------------\n0.8\n0.5\n0.1\n\n #output:\n ------------------------\n0.40 0.00 -0.20\n-0.60 0.00 -0.20\n \"\"\"\n )\n\n\nif __name__ == '__main__':\n args = docopt(__doc__, version='1.0')\n if args['--format']:\n ShowFormat()\n sys.exit(-1)\n idav = []\n with open(args['-a'], 'r') as ifile:\n for line in ifile:\n line = line.strip()\n if line:\n idav.append(2 * float(line))\n checkLen = True\n for line in sys.stdin:\n line = line.strip()\n if line:\n ss = line.split()\n ss = [(2 - int(x)) for x in ss]\n obs = []\n for i in range(0, len(ss), 2):\n obs.append(ss[i] + ss[i + 1])\n if checkLen:\n if len(obs) != len(idav):\n sys.stderr.write(\n \"\"\"Error: numbr of individuals in ID_average file is not the same as that in sys.stdin.\n\"\"\"\n )\n sys.exit(-1)\n else:\n checkLen = False\n out = [('%.2f' % (y - x)) for x, y in zip(idav, obs)]\n sys.stdout.write('%s\\n' % '\\t'.join(out))\nsys.stdout.flush()\nsys.stdout.close()\nsys.stderr.flush()\nsys.stderr.close()\n",
"step-4": "<mask token>\nimport sys\nfrom docopt import docopt\nfrom signal import signal, SIGPIPE, SIG_DFL\n\n\ndef ShowFormat():\n \"\"\"File format example\"\"\"\n print(\n \"\"\"\n #rfmix output, 3 person, 2 snps\n ------------------------\n1 1 2 1 2 2\n1 2 2 1 2 2\n\n #id average:\n ------------------------\n0.8\n0.5\n0.1\n\n #output:\n ------------------------\n0.40 0.00 -0.20\n-0.60 0.00 -0.20\n \"\"\"\n )\n\n\nif __name__ == '__main__':\n args = docopt(__doc__, version='1.0')\n if args['--format']:\n ShowFormat()\n sys.exit(-1)\n idav = []\n with open(args['-a'], 'r') as ifile:\n for line in ifile:\n line = line.strip()\n if line:\n idav.append(2 * float(line))\n checkLen = True\n for line in sys.stdin:\n line = line.strip()\n if line:\n ss = line.split()\n ss = [(2 - int(x)) for x in ss]\n obs = []\n for i in range(0, len(ss), 2):\n obs.append(ss[i] + ss[i + 1])\n if checkLen:\n if len(obs) != len(idav):\n sys.stderr.write(\n \"\"\"Error: numbr of individuals in ID_average file is not the same as that in sys.stdin.\n\"\"\"\n )\n sys.exit(-1)\n else:\n checkLen = False\n out = [('%.2f' % (y - x)) for x, y in zip(idav, obs)]\n sys.stdout.write('%s\\n' % '\\t'.join(out))\nsys.stdout.flush()\nsys.stdout.close()\nsys.stderr.flush()\nsys.stderr.close()\n",
"step-5": "#!/usr/bin/env python\n\n\"\"\"\n\n Power calculation based for admixture mapping.\n @ref: Design and Analysis of admixture mapping studies, (2004).\n\n @Author: wavefancy@gmail.com\n\n Usage:\n PowerCalculation.py -r aratio -n nhap\n PowerCalculation.py -h | --help | -v | --version | -f | --format\n\n Notes:\n 1. Read parameters from stdin, and output to stdout.\n\n Options:\n -r aratio Ancestry risk ratio. aratio = f2/f0 for multiplicative model.\n -n nhap Number of haplotypes, n = 2*N, N for sample size.\n -h --help Show this screen.\n -v --version Show version.\n -f --format Show input/output file format example.\n\n\"\"\"\nimport sys\nfrom docopt import docopt\nfrom signal import signal, SIGPIPE, SIG_DFL\n\ndef ShowFormat():\n '''File format example'''\n print('''\n #rfmix output, 3 person, 2 snps\n ------------------------\n1 1 2 1 2 2\n1 2 2 1 2 2\n\n #id average:\n ------------------------\n0.8\n0.5\n0.1\n\n #output:\n ------------------------\n0.40 0.00 -0.20\n-0.60 0.00 -0.20\n ''');\n\nif __name__ == '__main__':\n args = docopt(__doc__, version='1.0')\n # print(args)\n # sys.exit(0)\n\n if(args['--format']):\n ShowFormat()\n sys.exit(-1)\n\n idav = [] # 2*ID_average\n with open(args['-a'],'r') as ifile:\n for line in ifile:\n line = line.strip()\n if line:\n idav.append(2 * float(line))\n\n checkLen = True\n for line in sys.stdin:\n line = line.strip()\n if line:\n ss = line.split()\n ss = [2-int(x) for x in ss] #number of pop1 copy for each haplotype.\n obs = []\n for i in range(0, len(ss), 2):\n obs.append(ss[i] + ss[i+1])\n\n if checkLen:\n if len(obs) != len(idav):\n sys.stderr.write('Error: numbr of individuals in ID_average file is not the same as that in sys.stdin.\\n')\n sys.exit(-1)\n else:\n checkLen = False\n out = [ '%.2f'%(y-x) for x,y in zip(idav, obs)]\n sys.stdout.write('%s\\n'%('\\t'.join(out)))\n\nsys.stdout.flush()\nsys.stdout.close()\nsys.stderr.flush()\nsys.stderr.close()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
app = Flask(__name__)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from flask import *
app = Flask(__name__)
from app import views
from app import admin_views
from app import usr_reg
from app import cookie
from app import db_connect
|
flexible
|
{
"blob_id": "e736991f364ba9ff709348e4b1f612b1e9673281",
"index": 252,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp = Flask(__name__)\n<mask token>\n",
"step-3": "from flask import *\napp = Flask(__name__)\nfrom app import views\nfrom app import admin_views\nfrom app import usr_reg\nfrom app import cookie\nfrom app import db_connect\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
class MinHeap:
<|reserved_special_token_0|>
def __init__(self):
pass
def insert(self, value):
self.__heap.append(value)
self.__sift_up()
def pop(self):
if len(self.__heap) == 1:
return None
minimum = self.__heap[1]
if len(self.__heap) == 2:
self.__heap.pop()
else:
self.__heap[1] = self.__heap.pop()
self.__sift_down()
return minimum
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class MinHeap:
<|reserved_special_token_0|>
def __init__(self):
pass
def insert(self, value):
self.__heap.append(value)
self.__sift_up()
def pop(self):
if len(self.__heap) == 1:
return None
minimum = self.__heap[1]
if len(self.__heap) == 2:
self.__heap.pop()
else:
self.__heap[1] = self.__heap.pop()
self.__sift_down()
return minimum
<|reserved_special_token_0|>
def __sift_down(self):
idx = 1
size = len(self.__heap)
while idx < size:
minimum = self.__heap[idx]
left = idx << 1
right = left + 1
swap = None
if left < size and self.__heap[left] < minimum:
minimum = self.__heap[left]
swap = left
if right < size and self.__heap[right] < minimum:
swap = right
if swap is None:
break
tmp = self.__heap[swap]
self.__heap[swap] = self.__heap[idx]
self.__heap[idx] = tmp
idx = swap
<|reserved_special_token_1|>
class MinHeap:
<|reserved_special_token_0|>
def __init__(self):
pass
def insert(self, value):
self.__heap.append(value)
self.__sift_up()
def pop(self):
if len(self.__heap) == 1:
return None
minimum = self.__heap[1]
if len(self.__heap) == 2:
self.__heap.pop()
else:
self.__heap[1] = self.__heap.pop()
self.__sift_down()
return minimum
def __sift_up(self):
idx = len(self.__heap) - 1
parent = idx >> 1
while idx > 1 and self.__heap[idx] < self.__heap[parent]:
tmp = self.__heap[idx]
self.__heap[idx] = self.__heap[parent]
self.__heap[parent] = tmp
idx = parent
parent = idx >> 1
def __sift_down(self):
idx = 1
size = len(self.__heap)
while idx < size:
minimum = self.__heap[idx]
left = idx << 1
right = left + 1
swap = None
if left < size and self.__heap[left] < minimum:
minimum = self.__heap[left]
swap = left
if right < size and self.__heap[right] < minimum:
swap = right
if swap is None:
break
tmp = self.__heap[swap]
self.__heap[swap] = self.__heap[idx]
self.__heap[idx] = tmp
idx = swap
<|reserved_special_token_1|>
class MinHeap:
__heap = [-0]
def __init__(self):
pass
def insert(self, value):
self.__heap.append(value)
self.__sift_up()
def pop(self):
if len(self.__heap) == 1:
return None
minimum = self.__heap[1]
if len(self.__heap) == 2:
self.__heap.pop()
else:
self.__heap[1] = self.__heap.pop()
self.__sift_down()
return minimum
def __sift_up(self):
idx = len(self.__heap) - 1
parent = idx >> 1
while idx > 1 and self.__heap[idx] < self.__heap[parent]:
tmp = self.__heap[idx]
self.__heap[idx] = self.__heap[parent]
self.__heap[parent] = tmp
idx = parent
parent = idx >> 1
def __sift_down(self):
idx = 1
size = len(self.__heap)
while idx < size:
minimum = self.__heap[idx]
left = idx << 1
right = left + 1
swap = None
if left < size and self.__heap[left] < minimum:
minimum = self.__heap[left]
swap = left
if right < size and self.__heap[right] < minimum:
swap = right
if swap is None:
break
tmp = self.__heap[swap]
self.__heap[swap] = self.__heap[idx]
self.__heap[idx] = tmp
idx = swap
|
flexible
|
{
"blob_id": "d412e5768b23b8bbb8f72e2ae204650bbc1f0550",
"index": 8979,
"step-1": "class MinHeap:\n <mask token>\n\n def __init__(self):\n pass\n\n def insert(self, value):\n self.__heap.append(value)\n self.__sift_up()\n\n def pop(self):\n if len(self.__heap) == 1:\n return None\n minimum = self.__heap[1]\n if len(self.__heap) == 2:\n self.__heap.pop()\n else:\n self.__heap[1] = self.__heap.pop()\n self.__sift_down()\n return minimum\n <mask token>\n <mask token>\n",
"step-2": "class MinHeap:\n <mask token>\n\n def __init__(self):\n pass\n\n def insert(self, value):\n self.__heap.append(value)\n self.__sift_up()\n\n def pop(self):\n if len(self.__heap) == 1:\n return None\n minimum = self.__heap[1]\n if len(self.__heap) == 2:\n self.__heap.pop()\n else:\n self.__heap[1] = self.__heap.pop()\n self.__sift_down()\n return minimum\n <mask token>\n\n def __sift_down(self):\n idx = 1\n size = len(self.__heap)\n while idx < size:\n minimum = self.__heap[idx]\n left = idx << 1\n right = left + 1\n swap = None\n if left < size and self.__heap[left] < minimum:\n minimum = self.__heap[left]\n swap = left\n if right < size and self.__heap[right] < minimum:\n swap = right\n if swap is None:\n break\n tmp = self.__heap[swap]\n self.__heap[swap] = self.__heap[idx]\n self.__heap[idx] = tmp\n idx = swap\n",
"step-3": "class MinHeap:\n <mask token>\n\n def __init__(self):\n pass\n\n def insert(self, value):\n self.__heap.append(value)\n self.__sift_up()\n\n def pop(self):\n if len(self.__heap) == 1:\n return None\n minimum = self.__heap[1]\n if len(self.__heap) == 2:\n self.__heap.pop()\n else:\n self.__heap[1] = self.__heap.pop()\n self.__sift_down()\n return minimum\n\n def __sift_up(self):\n idx = len(self.__heap) - 1\n parent = idx >> 1\n while idx > 1 and self.__heap[idx] < self.__heap[parent]:\n tmp = self.__heap[idx]\n self.__heap[idx] = self.__heap[parent]\n self.__heap[parent] = tmp\n idx = parent\n parent = idx >> 1\n\n def __sift_down(self):\n idx = 1\n size = len(self.__heap)\n while idx < size:\n minimum = self.__heap[idx]\n left = idx << 1\n right = left + 1\n swap = None\n if left < size and self.__heap[left] < minimum:\n minimum = self.__heap[left]\n swap = left\n if right < size and self.__heap[right] < minimum:\n swap = right\n if swap is None:\n break\n tmp = self.__heap[swap]\n self.__heap[swap] = self.__heap[idx]\n self.__heap[idx] = tmp\n idx = swap\n",
"step-4": "class MinHeap:\n __heap = [-0]\n\n def __init__(self):\n pass\n\n def insert(self, value):\n self.__heap.append(value)\n self.__sift_up()\n\n def pop(self):\n if len(self.__heap) == 1:\n return None\n minimum = self.__heap[1]\n if len(self.__heap) == 2:\n self.__heap.pop()\n else:\n self.__heap[1] = self.__heap.pop()\n self.__sift_down()\n return minimum\n\n def __sift_up(self):\n idx = len(self.__heap) - 1\n parent = idx >> 1\n while idx > 1 and self.__heap[idx] < self.__heap[parent]:\n tmp = self.__heap[idx]\n self.__heap[idx] = self.__heap[parent]\n self.__heap[parent] = tmp\n idx = parent\n parent = idx >> 1\n\n def __sift_down(self):\n idx = 1\n size = len(self.__heap)\n while idx < size:\n minimum = self.__heap[idx]\n left = idx << 1\n right = left + 1\n swap = None\n if left < size and self.__heap[left] < minimum:\n minimum = self.__heap[left]\n swap = left\n if right < size and self.__heap[right] < minimum:\n swap = right\n if swap is None:\n break\n tmp = self.__heap[swap]\n self.__heap[swap] = self.__heap[idx]\n self.__heap[idx] = tmp\n idx = swap\n",
"step-5": null,
"step-ids": [
4,
5,
6,
7
]
}
|
[
4,
5,
6,
7
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print('Width x: ', width, ' Height y: ', height)
print('Frame Number,x coordinate of ROI,Weidth,Height,Width/Height')
<|reserved_special_token_0|>
while True:
j += 1
if j % 1000 != 0:
continue
totalframesampled += 1
frame = vs.read()
frame = frame[1]
text = 'Unoccupied'
if frame is None:
break
frame = imutils.resize(frame, width=500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if firstFrame is None:
firstFrame = gray
continue
frameDelta = cv2.absdiff(firstFrame, gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.
CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
minarea = 250
if area <= minarea:
continue
x, y, w, h = cv2.boundingRect(c)
condition_center_inlet = x > 440 and x < 450
condition_deformation = y > 240 and y < 300
if condition_center_inlet:
totalcelldetected += 1
print('totalcelldetected:', totalcelldetected)
print(j, x, y, w, h, w / h)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = 'Occupied'
k = 0
frameskip = 10
while k < frameskip:
k += 1
temp = vs.read()
break
cv2.putText(frame, 'Room Status: {}'.format(text), (10, 20), cv2.
FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame, datetime.datetime.now().strftime(
'%A %d %B %Y %I:%M:%S%p'), (10, frame.shape[0] - 10), cv2.
FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
cv2.imshow('Security Feed', frame)
cv2.imshow('Thresh', thresh)
cv2.imshow('Frame Delta', frameDelta)
key = cv2.waitKey(1) & 255
if key == ord('q'):
break
vs.release()
cv2.destroyAllWindows()
print('Total frame: ', j - 1)
print('Frame sampled: ', totalframesampled)
print('Total object detected: ', totalcelldetected)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
b = 'blood.mp4'
c = 'Center.avi'
d = 'Deformed.avi'
i = 'Inlet.avi'
videofile = c
vs = cv2.VideoCapture(videofile)
width = vs.get(3)
height = vs.get(4)
print('Width x: ', width, ' Height y: ', height)
print('Frame Number,x coordinate of ROI,Weidth,Height,Width/Height')
firstFrame = None
j = 0
totalframesampled = 0
totalcelldetected = 0
while True:
j += 1
if j % 1000 != 0:
continue
totalframesampled += 1
frame = vs.read()
frame = frame[1]
text = 'Unoccupied'
if frame is None:
break
frame = imutils.resize(frame, width=500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if firstFrame is None:
firstFrame = gray
continue
frameDelta = cv2.absdiff(firstFrame, gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.
CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
minarea = 250
if area <= minarea:
continue
x, y, w, h = cv2.boundingRect(c)
condition_center_inlet = x > 440 and x < 450
condition_deformation = y > 240 and y < 300
if condition_center_inlet:
totalcelldetected += 1
print('totalcelldetected:', totalcelldetected)
print(j, x, y, w, h, w / h)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = 'Occupied'
k = 0
frameskip = 10
while k < frameskip:
k += 1
temp = vs.read()
break
cv2.putText(frame, 'Room Status: {}'.format(text), (10, 20), cv2.
FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame, datetime.datetime.now().strftime(
'%A %d %B %Y %I:%M:%S%p'), (10, frame.shape[0] - 10), cv2.
FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
cv2.imshow('Security Feed', frame)
cv2.imshow('Thresh', thresh)
cv2.imshow('Frame Delta', frameDelta)
key = cv2.waitKey(1) & 255
if key == ord('q'):
break
vs.release()
cv2.destroyAllWindows()
print('Total frame: ', j - 1)
print('Frame sampled: ', totalframesampled)
print('Total object detected: ', totalcelldetected)
<|reserved_special_token_1|>
from imutils.video import VideoStream
import argparse
import datetime
import imutils
import time
import cv2
b = 'blood.mp4'
c = 'Center.avi'
d = 'Deformed.avi'
i = 'Inlet.avi'
videofile = c
vs = cv2.VideoCapture(videofile)
width = vs.get(3)
height = vs.get(4)
print('Width x: ', width, ' Height y: ', height)
print('Frame Number,x coordinate of ROI,Weidth,Height,Width/Height')
firstFrame = None
j = 0
totalframesampled = 0
totalcelldetected = 0
while True:
j += 1
if j % 1000 != 0:
continue
totalframesampled += 1
frame = vs.read()
frame = frame[1]
text = 'Unoccupied'
if frame is None:
break
frame = imutils.resize(frame, width=500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if firstFrame is None:
firstFrame = gray
continue
frameDelta = cv2.absdiff(firstFrame, gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.
CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
minarea = 250
if area <= minarea:
continue
x, y, w, h = cv2.boundingRect(c)
condition_center_inlet = x > 440 and x < 450
condition_deformation = y > 240 and y < 300
if condition_center_inlet:
totalcelldetected += 1
print('totalcelldetected:', totalcelldetected)
print(j, x, y, w, h, w / h)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = 'Occupied'
k = 0
frameskip = 10
while k < frameskip:
k += 1
temp = vs.read()
break
cv2.putText(frame, 'Room Status: {}'.format(text), (10, 20), cv2.
FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame, datetime.datetime.now().strftime(
'%A %d %B %Y %I:%M:%S%p'), (10, frame.shape[0] - 10), cv2.
FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
cv2.imshow('Security Feed', frame)
cv2.imshow('Thresh', thresh)
cv2.imshow('Frame Delta', frameDelta)
key = cv2.waitKey(1) & 255
if key == ord('q'):
break
vs.release()
cv2.destroyAllWindows()
print('Total frame: ', j - 1)
print('Frame sampled: ', totalframesampled)
print('Total object detected: ', totalcelldetected)
<|reserved_special_token_1|>
#source: https://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/
from imutils.video import VideoStream
import argparse
import datetime
import imutils
import time
import cv2
#capture the video file
b="blood.mp4"
c="Center.avi"
d="Deformed.avi"
i="Inlet.avi"
videofile=c
vs = cv2.VideoCapture(videofile)
#width = vs.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
#height = vs.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
width = vs.get(3)
height=vs.get(4)
print("Width x: ",width, " Height y: ",height)
print("Frame Number,x coordinate of ROI,Weidth,Height,Width/Height")
# initialize the first frame in the video stream
firstFrame = None
# loop over the frames of the video
j=0
totalframesampled=0
totalcelldetected=0
while True:
j+=1
if j%1000 !=0 :
continue
totalframesampled+=1
# grab the current frame and initialize the occupied/unoccupied
# text
frame = vs.read()
frame = frame[1]
text = "Unoccupied"
# if the frame could not be grabbed, then we have reached the end
# of the video
if frame is None:
break
# resize the frame, convert it to grayscale, and blur it
frame = imutils.resize(frame, width=500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# if the first frame is None, initialize it
if firstFrame is None:
firstFrame = gray
continue
# compute the absolute difference between the current frame and
# first frame
frameDelta = cv2.absdiff(firstFrame, gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
# dilate the thresholded image to fill in holes, then find contours
# on thresholded image
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
#print(cnts)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
#print("Frame: ",j)
#print(cnts)
# loop over the contours
for c in cnts:
#print("c:",c)
area=cv2.contourArea(c)
#print("Area:",area)
minarea=250
if area<=minarea:
continue
(x, y, w, h) = cv2.boundingRect(c)# top left x,y, wid,hei
condition_center_inlet=x>440 and x<450
condition_deformation=y>240 and y<300
if condition_center_inlet:
totalcelldetected+=1
print("totalcelldetected:",totalcelldetected)
print(j,x,y,w,h,w/h)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = "Occupied"
k=0
frameskip=10 # for center and inlet skip=10
while k<frameskip:
k+=1
temp=vs.read()
break
# if the contour is too small, ignore it
# compute the bounding box for the contour, draw it on the frame,
# and update the text
# draw the text and timestamp on the frame
cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
(10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
# show the frame and record if the user presses a key
cv2.imshow("Security Feed", frame)
cv2.imshow("Thresh", thresh)
cv2.imshow("Frame Delta", frameDelta)
key = cv2.waitKey(1) & 0xFF
# if the `q` key is pressed, break from the lop
if key == ord("q"):
break
# cleanup the camera and close any open windows
vs.release()
cv2.destroyAllWindows()
print("Total frame: ",j-1)
print("Frame sampled: ",totalframesampled)
print("Total object detected: ",totalcelldetected)
|
flexible
|
{
"blob_id": "4bd928c16cd0f06931aad5a478f8a911c5a7108b",
"index": 5850,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Width x: ', width, ' Height y: ', height)\nprint('Frame Number,x coordinate of ROI,Weidth,Height,Width/Height')\n<mask token>\nwhile True:\n j += 1\n if j % 1000 != 0:\n continue\n totalframesampled += 1\n frame = vs.read()\n frame = frame[1]\n text = 'Unoccupied'\n if frame is None:\n break\n frame = imutils.resize(frame, width=500)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n if firstFrame is None:\n firstFrame = gray\n continue\n frameDelta = cv2.absdiff(firstFrame, gray)\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\n thresh = cv2.dilate(thresh, None, iterations=2)\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.\n CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n for c in cnts:\n area = cv2.contourArea(c)\n minarea = 250\n if area <= minarea:\n continue\n x, y, w, h = cv2.boundingRect(c)\n condition_center_inlet = x > 440 and x < 450\n condition_deformation = y > 240 and y < 300\n if condition_center_inlet:\n totalcelldetected += 1\n print('totalcelldetected:', totalcelldetected)\n print(j, x, y, w, h, w / h)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n text = 'Occupied'\n k = 0\n frameskip = 10\n while k < frameskip:\n k += 1\n temp = vs.read()\n break\n cv2.putText(frame, 'Room Status: {}'.format(text), (10, 20), cv2.\n FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n cv2.putText(frame, datetime.datetime.now().strftime(\n '%A %d %B %Y %I:%M:%S%p'), (10, frame.shape[0] - 10), cv2.\n FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n cv2.imshow('Security Feed', frame)\n cv2.imshow('Thresh', thresh)\n cv2.imshow('Frame Delta', frameDelta)\n key = cv2.waitKey(1) & 255\n if key == ord('q'):\n break\nvs.release()\ncv2.destroyAllWindows()\nprint('Total frame: ', j - 1)\nprint('Frame sampled: ', totalframesampled)\nprint('Total object detected: ', totalcelldetected)\n",
"step-3": "<mask token>\nb = 'blood.mp4'\nc = 'Center.avi'\nd = 'Deformed.avi'\ni = 'Inlet.avi'\nvideofile = c\nvs = cv2.VideoCapture(videofile)\nwidth = vs.get(3)\nheight = vs.get(4)\nprint('Width x: ', width, ' Height y: ', height)\nprint('Frame Number,x coordinate of ROI,Weidth,Height,Width/Height')\nfirstFrame = None\nj = 0\ntotalframesampled = 0\ntotalcelldetected = 0\nwhile True:\n j += 1\n if j % 1000 != 0:\n continue\n totalframesampled += 1\n frame = vs.read()\n frame = frame[1]\n text = 'Unoccupied'\n if frame is None:\n break\n frame = imutils.resize(frame, width=500)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n if firstFrame is None:\n firstFrame = gray\n continue\n frameDelta = cv2.absdiff(firstFrame, gray)\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\n thresh = cv2.dilate(thresh, None, iterations=2)\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.\n CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n for c in cnts:\n area = cv2.contourArea(c)\n minarea = 250\n if area <= minarea:\n continue\n x, y, w, h = cv2.boundingRect(c)\n condition_center_inlet = x > 440 and x < 450\n condition_deformation = y > 240 and y < 300\n if condition_center_inlet:\n totalcelldetected += 1\n print('totalcelldetected:', totalcelldetected)\n print(j, x, y, w, h, w / h)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n text = 'Occupied'\n k = 0\n frameskip = 10\n while k < frameskip:\n k += 1\n temp = vs.read()\n break\n cv2.putText(frame, 'Room Status: {}'.format(text), (10, 20), cv2.\n FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n cv2.putText(frame, datetime.datetime.now().strftime(\n '%A %d %B %Y %I:%M:%S%p'), (10, frame.shape[0] - 10), cv2.\n FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n cv2.imshow('Security Feed', frame)\n cv2.imshow('Thresh', thresh)\n cv2.imshow('Frame Delta', frameDelta)\n key = cv2.waitKey(1) & 255\n if key == ord('q'):\n break\nvs.release()\ncv2.destroyAllWindows()\nprint('Total frame: ', j - 1)\nprint('Frame sampled: ', totalframesampled)\nprint('Total object detected: ', totalcelldetected)\n",
"step-4": "from imutils.video import VideoStream\nimport argparse\nimport datetime\nimport imutils\nimport time\nimport cv2\nb = 'blood.mp4'\nc = 'Center.avi'\nd = 'Deformed.avi'\ni = 'Inlet.avi'\nvideofile = c\nvs = cv2.VideoCapture(videofile)\nwidth = vs.get(3)\nheight = vs.get(4)\nprint('Width x: ', width, ' Height y: ', height)\nprint('Frame Number,x coordinate of ROI,Weidth,Height,Width/Height')\nfirstFrame = None\nj = 0\ntotalframesampled = 0\ntotalcelldetected = 0\nwhile True:\n j += 1\n if j % 1000 != 0:\n continue\n totalframesampled += 1\n frame = vs.read()\n frame = frame[1]\n text = 'Unoccupied'\n if frame is None:\n break\n frame = imutils.resize(frame, width=500)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n if firstFrame is None:\n firstFrame = gray\n continue\n frameDelta = cv2.absdiff(firstFrame, gray)\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\n thresh = cv2.dilate(thresh, None, iterations=2)\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.\n CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n for c in cnts:\n area = cv2.contourArea(c)\n minarea = 250\n if area <= minarea:\n continue\n x, y, w, h = cv2.boundingRect(c)\n condition_center_inlet = x > 440 and x < 450\n condition_deformation = y > 240 and y < 300\n if condition_center_inlet:\n totalcelldetected += 1\n print('totalcelldetected:', totalcelldetected)\n print(j, x, y, w, h, w / h)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n text = 'Occupied'\n k = 0\n frameskip = 10\n while k < frameskip:\n k += 1\n temp = vs.read()\n break\n cv2.putText(frame, 'Room Status: {}'.format(text), (10, 20), cv2.\n FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n cv2.putText(frame, datetime.datetime.now().strftime(\n '%A %d %B %Y %I:%M:%S%p'), (10, frame.shape[0] - 10), cv2.\n FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n cv2.imshow('Security Feed', frame)\n cv2.imshow('Thresh', thresh)\n cv2.imshow('Frame Delta', frameDelta)\n key = cv2.waitKey(1) & 255\n if key == ord('q'):\n break\nvs.release()\ncv2.destroyAllWindows()\nprint('Total frame: ', j - 1)\nprint('Frame sampled: ', totalframesampled)\nprint('Total object detected: ', totalcelldetected)\n",
"step-5": "#source: https://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/\r\n\r\nfrom imutils.video import VideoStream\r\nimport argparse\r\nimport datetime\r\nimport imutils\r\nimport time\r\nimport cv2\r\n\r\n\r\n#capture the video file\r\nb=\"blood.mp4\"\r\nc=\"Center.avi\"\r\nd=\"Deformed.avi\"\r\ni=\"Inlet.avi\"\r\nvideofile=c\r\nvs = cv2.VideoCapture(videofile)\r\n\r\n#width = vs.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)\r\n#height = vs.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)\r\nwidth = vs.get(3)\r\nheight=vs.get(4)\r\nprint(\"Width x: \",width, \" Height y: \",height)\r\nprint(\"Frame Number,x coordinate of ROI,Weidth,Height,Width/Height\")\r\n\r\n# initialize the first frame in the video stream\r\nfirstFrame = None\r\n\r\n# loop over the frames of the video\r\nj=0\r\ntotalframesampled=0\r\ntotalcelldetected=0\r\nwhile True:\r\n \r\n j+=1\r\n if j%1000 !=0 :\r\n continue\r\n totalframesampled+=1\r\n\t# grab the current frame and initialize the occupied/unoccupied\r\n\t# text\r\n frame = vs.read()\r\n frame = frame[1]\r\n text = \"Unoccupied\"\r\n \r\n\t# if the frame could not be grabbed, then we have reached the end\r\n\t# of the video\r\n if frame is None:\r\n break\r\n \r\n\t\r\n \r\n\t# resize the frame, convert it to grayscale, and blur it\r\n frame = imutils.resize(frame, width=500)\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\r\n \r\n\t# if the first frame is None, initialize it\r\n if firstFrame is None:\r\n firstFrame = gray\r\n continue\r\n \r\n\t\r\n\t\r\n\t\r\n\r\n\t\t# compute the absolute difference between the current frame and\r\n\t# first frame\r\n frameDelta = cv2.absdiff(firstFrame, gray)\r\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\r\n \r\n\t# dilate the thresholded image to fill in holes, then find contours\r\n\t# on thresholded image\r\n thresh = cv2.dilate(thresh, None, iterations=2)\r\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\r\n\t cv2.CHAIN_APPROX_SIMPLE)\r\n\t#print(cnts)\r\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\r\n #print(\"Frame: \",j)\r\n #print(cnts)\r\n \r\n\t# loop over the contours\r\n for c in cnts:\r\n #print(\"c:\",c)\r\n area=cv2.contourArea(c)\r\n #print(\"Area:\",area)\r\n minarea=250\r\n if area<=minarea:\r\n continue\r\n \r\n \r\n \r\n (x, y, w, h) = cv2.boundingRect(c)# top left x,y, wid,hei\r\n condition_center_inlet=x>440 and x<450\r\n condition_deformation=y>240 and y<300\r\n if condition_center_inlet:\r\n totalcelldetected+=1\r\n print(\"totalcelldetected:\",totalcelldetected)\r\n print(j,x,y,w,h,w/h)\r\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n text = \"Occupied\"\r\n k=0\r\n frameskip=10 # for center and inlet skip=10\r\n while k<frameskip:\r\n k+=1\r\n temp=vs.read()\r\n break\r\n\t\r\n\t\r\n\t\t# if the contour is too small, ignore it\r\n\t\r\n\t \r\n \r\n\t\t# compute the bounding box for the contour, draw it on the frame,\r\n\t\t# and update the text\r\n\t\r\n\t\r\n\t\t\t# draw the text and timestamp on the frame\r\n cv2.putText(frame, \"Room Status: {}\".format(text), (10, 20),\r\n\t cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\r\n cv2.putText(frame, datetime.datetime.now().strftime(\"%A %d %B %Y %I:%M:%S%p\"),\r\n\t (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\r\n \r\n\t# show the frame and record if the user presses a key\r\n cv2.imshow(\"Security Feed\", frame)\r\n cv2.imshow(\"Thresh\", thresh)\r\n cv2.imshow(\"Frame Delta\", frameDelta)\r\n key = cv2.waitKey(1) & 0xFF\r\n # if the `q` key is pressed, break from the lop\r\n if key == ord(\"q\"):\r\n break\r\n \r\n\t\r\n \r\n \r\n\t\r\n \r\n# cleanup the camera and close any open windows\r\nvs.release()\r\ncv2.destroyAllWindows()\r\nprint(\"Total frame: \",j-1)\r\nprint(\"Frame sampled: \",totalframesampled)\r\nprint(\"Total object detected: \",totalcelldetected)\r\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import csv
from sys import argv
import re
import sys
datasave=[]
if len(argv) is not 3: #stop usage if not correct input
print('Usage: python dna.py data.csv sequence.txt')
sys.exit()
#open CSV file and save
with open (argv[1],'r') as csv_file:
datafile = csv.reader(csv_file)
line_count = 0
for row in datafile:
datasave.insert(line_count, row)
line_count += 1
rowlength= len(datasave[0])-1
seqfile= open(argv[2],'r') #read argv2
countvector=[]
def STR(x): #choose between large or small databse
ABC = ["AGATC", "TTTTTTCT", "AATG", "TCTAG", "GATA", "TATC", "GAAA", "TCTG"]
DEF =["AGATC", "AATG", "TATC"]
A = ABC[x]
if argv[1] == 'databases/large.csv':
A= ABC[x]
elif argv[1] == 'databases/small.csv':
A= DEF[x]
return A
seqfile2 = seqfile.read()
#reminder x in count is repeated x-1 in task description , 2 occurence = repeated 1 times
for i in range(rowlength):
newcount= 0
STR1= STR(i)
while True:
Bfound = re.findall(STR1*newcount,seqfile2)
if re.findall(STR1*newcount, seqfile2) == [] :
countvector.append(newcount-1)
break
else:
newcount += 1
countvector= str(countvector)[1:-1] #some formatting lines, converting first integers to string
countvector1= countvector.replace(',','') #removing ,
search_list= countvector1.split(' ') #splitting into list cuz the database i saved as list
rowcount=0
rowplacement=0
for row in datasave:
indexcount=0
truecount=0
for i in range(rowlength):
if search_list[i] in datasave[rowcount]:
truecount+=1 #testing if index matches lists
if truecount == rowlength: #matching all in the row will start this IF line
rowplacement=rowcount
print(datasave[rowplacement][0])
break #this break doesnt work???????
indexcount+=1
rowcount+=1
if truecount is not rowlength and rowplacement == 0 :
print('No match')
|
normal
|
{
"blob_id": "1eeb7a539f43e9fb013494e2aa0d81b4eab0ae1a",
"index": 9353,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif len(argv) is not 3:\n print('Usage: python dna.py data.csv sequence.txt')\n sys.exit()\nwith open(argv[1], 'r') as csv_file:\n datafile = csv.reader(csv_file)\n line_count = 0\n for row in datafile:\n datasave.insert(line_count, row)\n line_count += 1\n<mask token>\n\n\ndef STR(x):\n ABC = ['AGATC', 'TTTTTTCT', 'AATG', 'TCTAG', 'GATA', 'TATC', 'GAAA', 'TCTG'\n ]\n DEF = ['AGATC', 'AATG', 'TATC']\n A = ABC[x]\n if argv[1] == 'databases/large.csv':\n A = ABC[x]\n elif argv[1] == 'databases/small.csv':\n A = DEF[x]\n return A\n\n\n<mask token>\nfor i in range(rowlength):\n newcount = 0\n STR1 = STR(i)\n while True:\n Bfound = re.findall(STR1 * newcount, seqfile2)\n if re.findall(STR1 * newcount, seqfile2) == []:\n countvector.append(newcount - 1)\n break\n else:\n newcount += 1\n<mask token>\nfor row in datasave:\n indexcount = 0\n truecount = 0\n for i in range(rowlength):\n if search_list[i] in datasave[rowcount]:\n truecount += 1\n if truecount == rowlength:\n rowplacement = rowcount\n print(datasave[rowplacement][0])\n break\n indexcount += 1\n rowcount += 1\nif truecount is not rowlength and rowplacement == 0:\n print('No match')\n",
"step-3": "<mask token>\ndatasave = []\nif len(argv) is not 3:\n print('Usage: python dna.py data.csv sequence.txt')\n sys.exit()\nwith open(argv[1], 'r') as csv_file:\n datafile = csv.reader(csv_file)\n line_count = 0\n for row in datafile:\n datasave.insert(line_count, row)\n line_count += 1\nrowlength = len(datasave[0]) - 1\nseqfile = open(argv[2], 'r')\ncountvector = []\n\n\ndef STR(x):\n ABC = ['AGATC', 'TTTTTTCT', 'AATG', 'TCTAG', 'GATA', 'TATC', 'GAAA', 'TCTG'\n ]\n DEF = ['AGATC', 'AATG', 'TATC']\n A = ABC[x]\n if argv[1] == 'databases/large.csv':\n A = ABC[x]\n elif argv[1] == 'databases/small.csv':\n A = DEF[x]\n return A\n\n\nseqfile2 = seqfile.read()\nfor i in range(rowlength):\n newcount = 0\n STR1 = STR(i)\n while True:\n Bfound = re.findall(STR1 * newcount, seqfile2)\n if re.findall(STR1 * newcount, seqfile2) == []:\n countvector.append(newcount - 1)\n break\n else:\n newcount += 1\ncountvector = str(countvector)[1:-1]\ncountvector1 = countvector.replace(',', '')\nsearch_list = countvector1.split(' ')\nrowcount = 0\nrowplacement = 0\nfor row in datasave:\n indexcount = 0\n truecount = 0\n for i in range(rowlength):\n if search_list[i] in datasave[rowcount]:\n truecount += 1\n if truecount == rowlength:\n rowplacement = rowcount\n print(datasave[rowplacement][0])\n break\n indexcount += 1\n rowcount += 1\nif truecount is not rowlength and rowplacement == 0:\n print('No match')\n",
"step-4": "import csv\nfrom sys import argv\nimport re\nimport sys\ndatasave = []\nif len(argv) is not 3:\n print('Usage: python dna.py data.csv sequence.txt')\n sys.exit()\nwith open(argv[1], 'r') as csv_file:\n datafile = csv.reader(csv_file)\n line_count = 0\n for row in datafile:\n datasave.insert(line_count, row)\n line_count += 1\nrowlength = len(datasave[0]) - 1\nseqfile = open(argv[2], 'r')\ncountvector = []\n\n\ndef STR(x):\n ABC = ['AGATC', 'TTTTTTCT', 'AATG', 'TCTAG', 'GATA', 'TATC', 'GAAA', 'TCTG'\n ]\n DEF = ['AGATC', 'AATG', 'TATC']\n A = ABC[x]\n if argv[1] == 'databases/large.csv':\n A = ABC[x]\n elif argv[1] == 'databases/small.csv':\n A = DEF[x]\n return A\n\n\nseqfile2 = seqfile.read()\nfor i in range(rowlength):\n newcount = 0\n STR1 = STR(i)\n while True:\n Bfound = re.findall(STR1 * newcount, seqfile2)\n if re.findall(STR1 * newcount, seqfile2) == []:\n countvector.append(newcount - 1)\n break\n else:\n newcount += 1\ncountvector = str(countvector)[1:-1]\ncountvector1 = countvector.replace(',', '')\nsearch_list = countvector1.split(' ')\nrowcount = 0\nrowplacement = 0\nfor row in datasave:\n indexcount = 0\n truecount = 0\n for i in range(rowlength):\n if search_list[i] in datasave[rowcount]:\n truecount += 1\n if truecount == rowlength:\n rowplacement = rowcount\n print(datasave[rowplacement][0])\n break\n indexcount += 1\n rowcount += 1\nif truecount is not rowlength and rowplacement == 0:\n print('No match')\n",
"step-5": "import csv\nfrom sys import argv\nimport re\nimport sys\n\n\ndatasave=[]\n\nif len(argv) is not 3: #stop usage if not correct input\n print('Usage: python dna.py data.csv sequence.txt')\n sys.exit()\n\n#open CSV file and save\nwith open (argv[1],'r') as csv_file:\n datafile = csv.reader(csv_file)\n line_count = 0\n for row in datafile:\n datasave.insert(line_count, row)\n line_count += 1\n \nrowlength= len(datasave[0])-1\nseqfile= open(argv[2],'r') #read argv2\ncountvector=[]\n\ndef STR(x): #choose between large or small databse\n\n ABC = [\"AGATC\", \"TTTTTTCT\", \"AATG\", \"TCTAG\", \"GATA\", \"TATC\", \"GAAA\", \"TCTG\"]\n DEF =[\"AGATC\", \"AATG\", \"TATC\"]\n A = ABC[x]\n \n if argv[1] == 'databases/large.csv':\n A= ABC[x]\n elif argv[1] == 'databases/small.csv':\n A= DEF[x]\n return A\n\n\nseqfile2 = seqfile.read()\n\n#reminder x in count is repeated x-1 in task description , 2 occurence = repeated 1 times\n\n\nfor i in range(rowlength):\n newcount= 0\n STR1= STR(i)\n\n while True:\n Bfound = re.findall(STR1*newcount,seqfile2)\n if re.findall(STR1*newcount, seqfile2) == [] :\n countvector.append(newcount-1)\n break\n else:\n newcount += 1\n \n\ncountvector= str(countvector)[1:-1] #some formatting lines, converting first integers to string\ncountvector1= countvector.replace(',','') #removing , \nsearch_list= countvector1.split(' ') #splitting into list cuz the database i saved as list\n\nrowcount=0\nrowplacement=0\n\nfor row in datasave:\n indexcount=0\n truecount=0\n for i in range(rowlength):\n if search_list[i] in datasave[rowcount]:\n truecount+=1 #testing if index matches lists\n if truecount == rowlength: #matching all in the row will start this IF line\n rowplacement=rowcount\n print(datasave[rowplacement][0])\n \n break #this break doesnt work???????\n \n indexcount+=1\n rowcount+=1\n \nif truecount is not rowlength and rowplacement == 0 :\n print('No match') \n\n",
"step-ids": [
0,
2,
3,
4,
5
]
}
|
[
0,
2,
3,
4,
5
] |
#公路工程工程量清单编码默认格式母节点为数字型式,子节点为-b字母形式,为使编码唯一便于数据处理,编制此脚本
import re
import pandas as pd
import os
def get_csv_path():#原编码保存为csv文件的一列,便于读取
path=input('enter csv path:')
if os.path.isfile(path):
return path
else:
print('csv file not exsit,try again:')
return get_csv_path()
def unique_code():
path=get_csv_path()
path_dir=os.path.dirname(path)
frame1=pd.read_csv(path,encoding='utf-8')
list1=list(frame1.iloc[:,0])
pat1=re.compile(r'\d+-\d+')#数字打头的母节点匹配符
pat2=re.compile(r'-\D{1}-\d+')#二级子节点,即-字母-数字形式匹配符
list2=[]
i=100
for code in list1:
if code=='':
list2.append(i)
i+=100
elif re.match(pat1,code):
cover=code
list2.append(cover)
else:
list2.append(cover+code)
frame2=pd.DataFrame(list2,)
frame2.to_csv(os.path.join(path_dir,'code_csv_out.csv'),encoding='utf-8-sig')
if __name__=='__main__':
unique_code()
|
normal
|
{
"blob_id": "857e3e04b99cb346fd89b34c0d14957d65b7ac38",
"index": 9566,
"step-1": "<mask token>\n\n\ndef get_csv_path():\n path = input('enter csv path:')\n if os.path.isfile(path):\n return path\n else:\n print('csv file not exsit,try again:')\n return get_csv_path()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_csv_path():\n path = input('enter csv path:')\n if os.path.isfile(path):\n return path\n else:\n print('csv file not exsit,try again:')\n return get_csv_path()\n\n\ndef unique_code():\n path = get_csv_path()\n path_dir = os.path.dirname(path)\n frame1 = pd.read_csv(path, encoding='utf-8')\n list1 = list(frame1.iloc[:, 0])\n pat1 = re.compile('\\\\d+-\\\\d+')\n pat2 = re.compile('-\\\\D{1}-\\\\d+')\n list2 = []\n i = 100\n for code in list1:\n if code == '':\n list2.append(i)\n i += 100\n elif re.match(pat1, code):\n cover = code\n list2.append(cover)\n else:\n list2.append(cover + code)\n frame2 = pd.DataFrame(list2)\n frame2.to_csv(os.path.join(path_dir, 'code_csv_out.csv'), encoding=\n 'utf-8-sig')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef get_csv_path():\n path = input('enter csv path:')\n if os.path.isfile(path):\n return path\n else:\n print('csv file not exsit,try again:')\n return get_csv_path()\n\n\ndef unique_code():\n path = get_csv_path()\n path_dir = os.path.dirname(path)\n frame1 = pd.read_csv(path, encoding='utf-8')\n list1 = list(frame1.iloc[:, 0])\n pat1 = re.compile('\\\\d+-\\\\d+')\n pat2 = re.compile('-\\\\D{1}-\\\\d+')\n list2 = []\n i = 100\n for code in list1:\n if code == '':\n list2.append(i)\n i += 100\n elif re.match(pat1, code):\n cover = code\n list2.append(cover)\n else:\n list2.append(cover + code)\n frame2 = pd.DataFrame(list2)\n frame2.to_csv(os.path.join(path_dir, 'code_csv_out.csv'), encoding=\n 'utf-8-sig')\n\n\nif __name__ == '__main__':\n unique_code()\n",
"step-4": "import re\nimport pandas as pd\nimport os\n\n\ndef get_csv_path():\n path = input('enter csv path:')\n if os.path.isfile(path):\n return path\n else:\n print('csv file not exsit,try again:')\n return get_csv_path()\n\n\ndef unique_code():\n path = get_csv_path()\n path_dir = os.path.dirname(path)\n frame1 = pd.read_csv(path, encoding='utf-8')\n list1 = list(frame1.iloc[:, 0])\n pat1 = re.compile('\\\\d+-\\\\d+')\n pat2 = re.compile('-\\\\D{1}-\\\\d+')\n list2 = []\n i = 100\n for code in list1:\n if code == '':\n list2.append(i)\n i += 100\n elif re.match(pat1, code):\n cover = code\n list2.append(cover)\n else:\n list2.append(cover + code)\n frame2 = pd.DataFrame(list2)\n frame2.to_csv(os.path.join(path_dir, 'code_csv_out.csv'), encoding=\n 'utf-8-sig')\n\n\nif __name__ == '__main__':\n unique_code()\n",
"step-5": "#公路工程工程量清单编码默认格式母节点为数字型式,子节点为-b字母形式,为使编码唯一便于数据处理,编制此脚本\nimport re\nimport pandas as pd\nimport os\ndef get_csv_path():#原编码保存为csv文件的一列,便于读取\n path=input('enter csv path:')\n if os.path.isfile(path):\n return path\n else:\n print('csv file not exsit,try again:')\n return get_csv_path()\ndef unique_code():\n path=get_csv_path()\n path_dir=os.path.dirname(path)\n frame1=pd.read_csv(path,encoding='utf-8')\n list1=list(frame1.iloc[:,0])\n pat1=re.compile(r'\\d+-\\d+')#数字打头的母节点匹配符\n pat2=re.compile(r'-\\D{1}-\\d+')#二级子节点,即-字母-数字形式匹配符\n list2=[]\n i=100\n for code in list1:\n if code=='':\n list2.append(i)\n i+=100\n elif re.match(pat1,code):\n cover=code\n list2.append(cover)\n else:\n list2.append(cover+code)\n frame2=pd.DataFrame(list2,)\n frame2.to_csv(os.path.join(path_dir,'code_csv_out.csv'),encoding='utf-8-sig')\nif __name__=='__main__':\n unique_code()\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
class Model:
def __init__(self, training=True):
self.classes = settings.classes_name
self.num_classes = len(settings.classes_name)
self.image_size = settings.image_size
self.cell_size = settings.cell_size
self.boxes_per_cell = settings.box_per_cell
self.output_size = self.cell_size * self.cell_size * (self.
num_classes + self.boxes_per_cell * 5)
self.scale = 1.0 * self.image_size / self.cell_size
self.boundary1 = self.cell_size * self.cell_size * self.num_classes
self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *
self.boxes_per_cell)
self.object_scale = settings.object_scale
self.no_object_scale = settings.no_object_scale
self.class_scale = settings.class_scale
self.coord_scale = settings.coordinate_scale
self.offset = np.transpose(np.reshape(np.array([np.arange(self.
cell_size)] * self.cell_size * self.boxes_per_cell), (self.
boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))
self.images = tf.placeholder(tf.float32, [None, settings.image_size,
settings.image_size, 3])
if settings.model_type == 'normal':
self.logits = self.build_network(self.images, num_outputs=self.
output_size, alpha=settings.alpha_relu, training=training)
if settings.model_type == 'fast':
self.logits = self.build_fast_network(self.images, num_outputs=
self.output_size, alpha=settings.alpha_relu, training=training)
if training:
self.batch = tf.Variable(0)
self.labels = tf.placeholder(tf.float32, [None, self.cell_size,
self.cell_size, 5 + self.num_classes])
self.loss_layer(self.logits, self.labels)
self.total_loss = tf.contrib.losses.get_total_loss()
self.learning_rate = tf.train.exponential_decay(settings.
learning_rate, self.batch * settings.batch_size, settings.
decay_step, settings.decay_rate, True)
self.optimizer = tf.train.GradientDescentOptimizer(self.
learning_rate).minimize(self.total_loss, global_step=self.batch
)
def build_network(self, images, num_outputs, alpha, keep_prob=settings.
dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 256, 1, scope='conv_8')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 256, 1, scope='conv_13')
net = slim.conv2d(net, 512, 3, scope='conv_14')
net = slim.conv2d(net, 256, 1, scope='conv_15')
net = slim.conv2d(net, 512, 3, scope='conv_16')
net = slim.conv2d(net, 256, 1, scope='conv_17')
net = slim.conv2d(net, 512, 3, scope='conv_18')
net = slim.conv2d(net, 512, 1, scope='conv_19')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 512, 1, scope='conv_24')
net = slim.conv2d(net, 1024, 3, scope='conv_25')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = slim.conv2d(net, 1024, 3, scope='conv_29')
net = slim.conv2d(net, 1024, 3, scope='conv_30')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def build_fast_network(self, images, num_outputs, alpha, keep_prob=
settings.dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def calc_iou(self, boxes1, boxes2, scope='iou'):
with tf.variable_scope(scope):
boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2
] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] /
2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0,
boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])
boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])
boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2
] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] /
2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0,
boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])
boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])
lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])
rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])
intersection = tf.maximum(0.0, rd - lu)
inter_square = intersection[:, :, :, :, 0] * intersection[:, :,
:, :, 1]
square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1
[:, :, :, :, 3] - boxes1[:, :, :, :, 1])
square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2
[:, :, :, :, 3] - boxes2[:, :, :, :, 1])
union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)
return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)
def loss_layer(self, predicts, labels, scope='loss_layer'):
with tf.variable_scope(scope):
predict_classes = tf.reshape(predicts[:, :self.boundary1], [
settings.batch_size, self.cell_size, self.cell_size, self.
num_classes])
predict_scales = tf.reshape(predicts[:, self.boundary1:self.
boundary2], [settings.batch_size, self.cell_size, self.
cell_size, self.boxes_per_cell])
predict_boxes = tf.reshape(predicts[:, self.boundary2:], [
settings.batch_size, self.cell_size, self.cell_size, self.
boxes_per_cell, 4])
response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,
self.cell_size, self.cell_size, 1])
boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,
self.cell_size, self.cell_size, 1, 4])
boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]
) / self.image_size
classes = labels[:, :, :, 5:]
offset = tf.constant(self.offset, dtype=tf.float32)
offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,
self.boxes_per_cell])
offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])
predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +
offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +
tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.
square(predict_boxes[:, :, :, :, 2]), tf.square(
predict_boxes[:, :, :, :, 3])])
predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,
4, 0])
iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)
object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)
object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32
) * response
noobject_mask = tf.ones_like(object_mask, dtype=tf.float32
) - object_mask
boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -
offset, boxes[:, :, :, :, 1] * self.cell_size - tf.
transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :,
2]), tf.sqrt(boxes[:, :, :, :, 3])])
boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])
class_delta = response * (predict_classes - classes)
class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta
), axis=[1, 2, 3]), name='class_loss') * self.class_scale
object_delta = object_mask * (predict_scales - iou_predict_truth)
object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
object_delta), axis=[1, 2, 3]), name='object_loss'
) * self.object_scale
noobject_delta = noobject_mask * predict_scales
noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
noobject_delta), axis=[1, 2, 3]), name='noobject_loss'
) * self.no_object_scale
coord_mask = tf.expand_dims(object_mask, 4)
boxes_delta = coord_mask * (predict_boxes - boxes_tran)
coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta
), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale
tf.contrib.losses.add_loss(class_loss)
tf.contrib.losses.add_loss(object_loss)
tf.contrib.losses.add_loss(noobject_loss)
tf.contrib.losses.add_loss(coord_loss)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Model:
def __init__(self, training=True):
self.classes = settings.classes_name
self.num_classes = len(settings.classes_name)
self.image_size = settings.image_size
self.cell_size = settings.cell_size
self.boxes_per_cell = settings.box_per_cell
self.output_size = self.cell_size * self.cell_size * (self.
num_classes + self.boxes_per_cell * 5)
self.scale = 1.0 * self.image_size / self.cell_size
self.boundary1 = self.cell_size * self.cell_size * self.num_classes
self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *
self.boxes_per_cell)
self.object_scale = settings.object_scale
self.no_object_scale = settings.no_object_scale
self.class_scale = settings.class_scale
self.coord_scale = settings.coordinate_scale
self.offset = np.transpose(np.reshape(np.array([np.arange(self.
cell_size)] * self.cell_size * self.boxes_per_cell), (self.
boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))
self.images = tf.placeholder(tf.float32, [None, settings.image_size,
settings.image_size, 3])
if settings.model_type == 'normal':
self.logits = self.build_network(self.images, num_outputs=self.
output_size, alpha=settings.alpha_relu, training=training)
if settings.model_type == 'fast':
self.logits = self.build_fast_network(self.images, num_outputs=
self.output_size, alpha=settings.alpha_relu, training=training)
if training:
self.batch = tf.Variable(0)
self.labels = tf.placeholder(tf.float32, [None, self.cell_size,
self.cell_size, 5 + self.num_classes])
self.loss_layer(self.logits, self.labels)
self.total_loss = tf.contrib.losses.get_total_loss()
self.learning_rate = tf.train.exponential_decay(settings.
learning_rate, self.batch * settings.batch_size, settings.
decay_step, settings.decay_rate, True)
self.optimizer = tf.train.GradientDescentOptimizer(self.
learning_rate).minimize(self.total_loss, global_step=self.batch
)
def build_network(self, images, num_outputs, alpha, keep_prob=settings.
dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 256, 1, scope='conv_8')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 256, 1, scope='conv_13')
net = slim.conv2d(net, 512, 3, scope='conv_14')
net = slim.conv2d(net, 256, 1, scope='conv_15')
net = slim.conv2d(net, 512, 3, scope='conv_16')
net = slim.conv2d(net, 256, 1, scope='conv_17')
net = slim.conv2d(net, 512, 3, scope='conv_18')
net = slim.conv2d(net, 512, 1, scope='conv_19')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 512, 1, scope='conv_24')
net = slim.conv2d(net, 1024, 3, scope='conv_25')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = slim.conv2d(net, 1024, 3, scope='conv_29')
net = slim.conv2d(net, 1024, 3, scope='conv_30')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def build_fast_network(self, images, num_outputs, alpha, keep_prob=
settings.dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def calc_iou(self, boxes1, boxes2, scope='iou'):
with tf.variable_scope(scope):
boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2
] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] /
2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0,
boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])
boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])
boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2
] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] /
2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0,
boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])
boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])
lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])
rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])
intersection = tf.maximum(0.0, rd - lu)
inter_square = intersection[:, :, :, :, 0] * intersection[:, :,
:, :, 1]
square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1
[:, :, :, :, 3] - boxes1[:, :, :, :, 1])
square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2
[:, :, :, :, 3] - boxes2[:, :, :, :, 1])
union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)
return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)
def loss_layer(self, predicts, labels, scope='loss_layer'):
with tf.variable_scope(scope):
predict_classes = tf.reshape(predicts[:, :self.boundary1], [
settings.batch_size, self.cell_size, self.cell_size, self.
num_classes])
predict_scales = tf.reshape(predicts[:, self.boundary1:self.
boundary2], [settings.batch_size, self.cell_size, self.
cell_size, self.boxes_per_cell])
predict_boxes = tf.reshape(predicts[:, self.boundary2:], [
settings.batch_size, self.cell_size, self.cell_size, self.
boxes_per_cell, 4])
response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,
self.cell_size, self.cell_size, 1])
boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,
self.cell_size, self.cell_size, 1, 4])
boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]
) / self.image_size
classes = labels[:, :, :, 5:]
offset = tf.constant(self.offset, dtype=tf.float32)
offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,
self.boxes_per_cell])
offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])
predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +
offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +
tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.
square(predict_boxes[:, :, :, :, 2]), tf.square(
predict_boxes[:, :, :, :, 3])])
predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,
4, 0])
iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)
object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)
object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32
) * response
noobject_mask = tf.ones_like(object_mask, dtype=tf.float32
) - object_mask
boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -
offset, boxes[:, :, :, :, 1] * self.cell_size - tf.
transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :,
2]), tf.sqrt(boxes[:, :, :, :, 3])])
boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])
class_delta = response * (predict_classes - classes)
class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta
), axis=[1, 2, 3]), name='class_loss') * self.class_scale
object_delta = object_mask * (predict_scales - iou_predict_truth)
object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
object_delta), axis=[1, 2, 3]), name='object_loss'
) * self.object_scale
noobject_delta = noobject_mask * predict_scales
noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
noobject_delta), axis=[1, 2, 3]), name='noobject_loss'
) * self.no_object_scale
coord_mask = tf.expand_dims(object_mask, 4)
boxes_delta = coord_mask * (predict_boxes - boxes_tran)
coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta
), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale
tf.contrib.losses.add_loss(class_loss)
tf.contrib.losses.add_loss(object_loss)
tf.contrib.losses.add_loss(noobject_loss)
tf.contrib.losses.add_loss(coord_loss)
def leaky_relu(alpha):
def op(inputs):
return tf.maximum(alpha * inputs, inputs)
return op
<|reserved_special_token_1|>
<|reserved_special_token_0|>
slim = tf.contrib.slim
class Model:
def __init__(self, training=True):
self.classes = settings.classes_name
self.num_classes = len(settings.classes_name)
self.image_size = settings.image_size
self.cell_size = settings.cell_size
self.boxes_per_cell = settings.box_per_cell
self.output_size = self.cell_size * self.cell_size * (self.
num_classes + self.boxes_per_cell * 5)
self.scale = 1.0 * self.image_size / self.cell_size
self.boundary1 = self.cell_size * self.cell_size * self.num_classes
self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *
self.boxes_per_cell)
self.object_scale = settings.object_scale
self.no_object_scale = settings.no_object_scale
self.class_scale = settings.class_scale
self.coord_scale = settings.coordinate_scale
self.offset = np.transpose(np.reshape(np.array([np.arange(self.
cell_size)] * self.cell_size * self.boxes_per_cell), (self.
boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))
self.images = tf.placeholder(tf.float32, [None, settings.image_size,
settings.image_size, 3])
if settings.model_type == 'normal':
self.logits = self.build_network(self.images, num_outputs=self.
output_size, alpha=settings.alpha_relu, training=training)
if settings.model_type == 'fast':
self.logits = self.build_fast_network(self.images, num_outputs=
self.output_size, alpha=settings.alpha_relu, training=training)
if training:
self.batch = tf.Variable(0)
self.labels = tf.placeholder(tf.float32, [None, self.cell_size,
self.cell_size, 5 + self.num_classes])
self.loss_layer(self.logits, self.labels)
self.total_loss = tf.contrib.losses.get_total_loss()
self.learning_rate = tf.train.exponential_decay(settings.
learning_rate, self.batch * settings.batch_size, settings.
decay_step, settings.decay_rate, True)
self.optimizer = tf.train.GradientDescentOptimizer(self.
learning_rate).minimize(self.total_loss, global_step=self.batch
)
def build_network(self, images, num_outputs, alpha, keep_prob=settings.
dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 256, 1, scope='conv_8')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 256, 1, scope='conv_13')
net = slim.conv2d(net, 512, 3, scope='conv_14')
net = slim.conv2d(net, 256, 1, scope='conv_15')
net = slim.conv2d(net, 512, 3, scope='conv_16')
net = slim.conv2d(net, 256, 1, scope='conv_17')
net = slim.conv2d(net, 512, 3, scope='conv_18')
net = slim.conv2d(net, 512, 1, scope='conv_19')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 512, 1, scope='conv_24')
net = slim.conv2d(net, 1024, 3, scope='conv_25')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = slim.conv2d(net, 1024, 3, scope='conv_29')
net = slim.conv2d(net, 1024, 3, scope='conv_30')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def build_fast_network(self, images, num_outputs, alpha, keep_prob=
settings.dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def calc_iou(self, boxes1, boxes2, scope='iou'):
with tf.variable_scope(scope):
boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2
] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] /
2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0,
boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])
boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])
boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2
] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] /
2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0,
boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])
boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])
lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])
rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])
intersection = tf.maximum(0.0, rd - lu)
inter_square = intersection[:, :, :, :, 0] * intersection[:, :,
:, :, 1]
square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1
[:, :, :, :, 3] - boxes1[:, :, :, :, 1])
square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2
[:, :, :, :, 3] - boxes2[:, :, :, :, 1])
union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)
return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)
def loss_layer(self, predicts, labels, scope='loss_layer'):
with tf.variable_scope(scope):
predict_classes = tf.reshape(predicts[:, :self.boundary1], [
settings.batch_size, self.cell_size, self.cell_size, self.
num_classes])
predict_scales = tf.reshape(predicts[:, self.boundary1:self.
boundary2], [settings.batch_size, self.cell_size, self.
cell_size, self.boxes_per_cell])
predict_boxes = tf.reshape(predicts[:, self.boundary2:], [
settings.batch_size, self.cell_size, self.cell_size, self.
boxes_per_cell, 4])
response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,
self.cell_size, self.cell_size, 1])
boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,
self.cell_size, self.cell_size, 1, 4])
boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]
) / self.image_size
classes = labels[:, :, :, 5:]
offset = tf.constant(self.offset, dtype=tf.float32)
offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,
self.boxes_per_cell])
offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])
predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +
offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +
tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.
square(predict_boxes[:, :, :, :, 2]), tf.square(
predict_boxes[:, :, :, :, 3])])
predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,
4, 0])
iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)
object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)
object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32
) * response
noobject_mask = tf.ones_like(object_mask, dtype=tf.float32
) - object_mask
boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -
offset, boxes[:, :, :, :, 1] * self.cell_size - tf.
transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :,
2]), tf.sqrt(boxes[:, :, :, :, 3])])
boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])
class_delta = response * (predict_classes - classes)
class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta
), axis=[1, 2, 3]), name='class_loss') * self.class_scale
object_delta = object_mask * (predict_scales - iou_predict_truth)
object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
object_delta), axis=[1, 2, 3]), name='object_loss'
) * self.object_scale
noobject_delta = noobject_mask * predict_scales
noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
noobject_delta), axis=[1, 2, 3]), name='noobject_loss'
) * self.no_object_scale
coord_mask = tf.expand_dims(object_mask, 4)
boxes_delta = coord_mask * (predict_boxes - boxes_tran)
coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta
), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale
tf.contrib.losses.add_loss(class_loss)
tf.contrib.losses.add_loss(object_loss)
tf.contrib.losses.add_loss(noobject_loss)
tf.contrib.losses.add_loss(coord_loss)
def leaky_relu(alpha):
def op(inputs):
return tf.maximum(alpha * inputs, inputs)
return op
<|reserved_special_token_1|>
import tensorflow as tf
import settings
import numpy as np
slim = tf.contrib.slim
class Model:
def __init__(self, training=True):
self.classes = settings.classes_name
self.num_classes = len(settings.classes_name)
self.image_size = settings.image_size
self.cell_size = settings.cell_size
self.boxes_per_cell = settings.box_per_cell
self.output_size = self.cell_size * self.cell_size * (self.
num_classes + self.boxes_per_cell * 5)
self.scale = 1.0 * self.image_size / self.cell_size
self.boundary1 = self.cell_size * self.cell_size * self.num_classes
self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *
self.boxes_per_cell)
self.object_scale = settings.object_scale
self.no_object_scale = settings.no_object_scale
self.class_scale = settings.class_scale
self.coord_scale = settings.coordinate_scale
self.offset = np.transpose(np.reshape(np.array([np.arange(self.
cell_size)] * self.cell_size * self.boxes_per_cell), (self.
boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))
self.images = tf.placeholder(tf.float32, [None, settings.image_size,
settings.image_size, 3])
if settings.model_type == 'normal':
self.logits = self.build_network(self.images, num_outputs=self.
output_size, alpha=settings.alpha_relu, training=training)
if settings.model_type == 'fast':
self.logits = self.build_fast_network(self.images, num_outputs=
self.output_size, alpha=settings.alpha_relu, training=training)
if training:
self.batch = tf.Variable(0)
self.labels = tf.placeholder(tf.float32, [None, self.cell_size,
self.cell_size, 5 + self.num_classes])
self.loss_layer(self.logits, self.labels)
self.total_loss = tf.contrib.losses.get_total_loss()
self.learning_rate = tf.train.exponential_decay(settings.
learning_rate, self.batch * settings.batch_size, settings.
decay_step, settings.decay_rate, True)
self.optimizer = tf.train.GradientDescentOptimizer(self.
learning_rate).minimize(self.total_loss, global_step=self.batch
)
def build_network(self, images, num_outputs, alpha, keep_prob=settings.
dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 256, 1, scope='conv_8')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 256, 1, scope='conv_13')
net = slim.conv2d(net, 512, 3, scope='conv_14')
net = slim.conv2d(net, 256, 1, scope='conv_15')
net = slim.conv2d(net, 512, 3, scope='conv_16')
net = slim.conv2d(net, 256, 1, scope='conv_17')
net = slim.conv2d(net, 512, 3, scope='conv_18')
net = slim.conv2d(net, 512, 1, scope='conv_19')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 512, 1, scope='conv_24')
net = slim.conv2d(net, 1024, 3, scope='conv_25')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = slim.conv2d(net, 1024, 3, scope='conv_29')
net = slim.conv2d(net, 1024, 3, scope='conv_30')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def build_fast_network(self, images, num_outputs, alpha, keep_prob=
settings.dropout, training=True, scope='yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=leaky_relu(alpha), weights_initializer=tf.
truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0,
0]]), name='pad_1')
net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=
'conv_2')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')
net = slim.conv2d(net, 192, 3, scope='conv_4')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')
net = slim.conv2d(net, 128, 1, scope='conv_6')
net = slim.conv2d(net, 256, 3, scope='conv_7')
net = slim.conv2d(net, 512, 3, scope='conv_9')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')
net = slim.conv2d(net, 256, 1, scope='conv_11')
net = slim.conv2d(net, 512, 3, scope='conv_12')
net = slim.conv2d(net, 1024, 3, scope='conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')
net = slim.conv2d(net, 512, 1, scope='conv_22')
net = slim.conv2d(net, 1024, 3, scope='conv_23')
net = slim.conv2d(net, 1024, 3, scope='conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]
), name='pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=
'conv_28')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope='flat_32')
net = slim.fully_connected(net, 512, scope='fc_33')
net = slim.fully_connected(net, 4096, scope='fc_34')
net = slim.dropout(net, keep_prob=keep_prob, is_training=
training, scope='dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn=
None, scope='fc_36')
return net
def calc_iou(self, boxes1, boxes2, scope='iou'):
with tf.variable_scope(scope):
boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2
] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] /
2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0,
boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])
boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])
boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2
] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] /
2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0,
boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])
boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])
lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])
rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])
intersection = tf.maximum(0.0, rd - lu)
inter_square = intersection[:, :, :, :, 0] * intersection[:, :,
:, :, 1]
square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1
[:, :, :, :, 3] - boxes1[:, :, :, :, 1])
square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2
[:, :, :, :, 3] - boxes2[:, :, :, :, 1])
union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)
return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)
def loss_layer(self, predicts, labels, scope='loss_layer'):
with tf.variable_scope(scope):
predict_classes = tf.reshape(predicts[:, :self.boundary1], [
settings.batch_size, self.cell_size, self.cell_size, self.
num_classes])
predict_scales = tf.reshape(predicts[:, self.boundary1:self.
boundary2], [settings.batch_size, self.cell_size, self.
cell_size, self.boxes_per_cell])
predict_boxes = tf.reshape(predicts[:, self.boundary2:], [
settings.batch_size, self.cell_size, self.cell_size, self.
boxes_per_cell, 4])
response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,
self.cell_size, self.cell_size, 1])
boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,
self.cell_size, self.cell_size, 1, 4])
boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]
) / self.image_size
classes = labels[:, :, :, 5:]
offset = tf.constant(self.offset, dtype=tf.float32)
offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,
self.boxes_per_cell])
offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])
predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +
offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +
tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.
square(predict_boxes[:, :, :, :, 2]), tf.square(
predict_boxes[:, :, :, :, 3])])
predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,
4, 0])
iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)
object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)
object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32
) * response
noobject_mask = tf.ones_like(object_mask, dtype=tf.float32
) - object_mask
boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -
offset, boxes[:, :, :, :, 1] * self.cell_size - tf.
transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :,
2]), tf.sqrt(boxes[:, :, :, :, 3])])
boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])
class_delta = response * (predict_classes - classes)
class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta
), axis=[1, 2, 3]), name='class_loss') * self.class_scale
object_delta = object_mask * (predict_scales - iou_predict_truth)
object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
object_delta), axis=[1, 2, 3]), name='object_loss'
) * self.object_scale
noobject_delta = noobject_mask * predict_scales
noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(
noobject_delta), axis=[1, 2, 3]), name='noobject_loss'
) * self.no_object_scale
coord_mask = tf.expand_dims(object_mask, 4)
boxes_delta = coord_mask * (predict_boxes - boxes_tran)
coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta
), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale
tf.contrib.losses.add_loss(class_loss)
tf.contrib.losses.add_loss(object_loss)
tf.contrib.losses.add_loss(noobject_loss)
tf.contrib.losses.add_loss(coord_loss)
def leaky_relu(alpha):
def op(inputs):
return tf.maximum(alpha * inputs, inputs)
return op
<|reserved_special_token_1|>
import tensorflow as tf
import settings
import numpy as np
slim = tf.contrib.slim
class Model:
def __init__(self, training = True):
self.classes = settings.classes_name
self.num_classes = len(settings.classes_name)
self.image_size = settings.image_size
self.cell_size = settings.cell_size
self.boxes_per_cell = settings.box_per_cell
self.output_size = (self.cell_size * self.cell_size) * (self.num_classes + self.boxes_per_cell * 5)
self.scale = 1.0 * self.image_size / self.cell_size
self.boundary1 = self.cell_size * self.cell_size * self.num_classes
self.boundary2 = self.boundary1 + self.cell_size * self.cell_size * self.boxes_per_cell
self.object_scale = settings.object_scale
self.no_object_scale = settings.no_object_scale
self.class_scale = settings.class_scale
self.coord_scale = settings.coordinate_scale
self.offset = np.transpose(np.reshape(np.array([np.arange(self.cell_size)] * self.cell_size * self.boxes_per_cell), (self.boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))
self.images = tf.placeholder(tf.float32, [None, settings.image_size, settings.image_size, 3])
if settings.model_type == 'normal':
self.logits = self.build_network(self.images, num_outputs = self.output_size, alpha = settings.alpha_relu, training = training)
if settings.model_type == 'fast':
self.logits = self.build_fast_network(self.images, num_outputs = self.output_size, alpha = settings.alpha_relu, training = training)
if training:
self.batch = tf.Variable(0)
self.labels = tf.placeholder(tf.float32, [None, self.cell_size, self.cell_size, 5 + self.num_classes])
self.loss_layer(self.logits, self.labels)
self.total_loss = tf.contrib.losses.get_total_loss()
self.learning_rate = tf.train.exponential_decay(settings.learning_rate, self.batch * settings.batch_size, settings.decay_step, settings.decay_rate, True)
self.optimizer = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.total_loss, global_step = self.batch)
def build_network(self, images, num_outputs, alpha, keep_prob = settings.dropout, training = True, scope = 'yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn = leaky_relu(alpha), weights_initializer = tf.truncated_normal_initializer(0.0, 0.01), weights_regularizer = slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, 0]]), name = 'pad_1')
net = slim.conv2d(net, 64, 7, 2, padding = 'VALID', scope = 'conv_2')
net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_3')
net = slim.conv2d(net, 192, 3, scope = 'conv_4')
net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_5')
net = slim.conv2d(net, 128, 1, scope = 'conv_6')
net = slim.conv2d(net, 256, 3, scope = 'conv_7')
net = slim.conv2d(net, 256, 1, scope = 'conv_8')
net = slim.conv2d(net, 512, 3, scope = 'conv_9')
net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_10')
net = slim.conv2d(net, 256, 1, scope = 'conv_11')
net = slim.conv2d(net, 512, 3, scope = 'conv_12')
net = slim.conv2d(net, 256, 1, scope = 'conv_13')
net = slim.conv2d(net, 512, 3, scope = 'conv_14')
net = slim.conv2d(net, 256, 1, scope = 'conv_15')
net = slim.conv2d(net, 512, 3, scope = 'conv_16')
net = slim.conv2d(net, 256, 1, scope = 'conv_17')
net = slim.conv2d(net, 512, 3, scope = 'conv_18')
net = slim.conv2d(net, 512, 1, scope = 'conv_19')
net = slim.conv2d(net, 1024, 3, scope = 'conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope = 'pool_21')
net = slim.conv2d(net, 512, 1, scope = 'conv_22')
net = slim.conv2d(net, 1024, 3, scope = 'conv_23')
net = slim.conv2d(net, 512, 1, scope = 'conv_24')
net = slim.conv2d(net, 1024, 3, scope = 'conv_25')
net = slim.conv2d(net, 1024, 3, scope = 'conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]), name = 'pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope = 'conv_28')
net = slim.conv2d(net, 1024, 3, scope = 'conv_29')
net = slim.conv2d(net, 1024, 3, scope = 'conv_30')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope = 'flat_32')
net = slim.fully_connected(net, 512, scope = 'fc_33')
net = slim.fully_connected(net, 4096, scope = 'fc_34')
net = slim.dropout(net, keep_prob = keep_prob, is_training = training, scope = 'dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn = None, scope = 'fc_36')
return net
def build_fast_network(self, images, num_outputs, alpha, keep_prob = settings.dropout, training = True, scope = 'yolo'):
with tf.variable_scope(scope):
with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn = leaky_relu(alpha), weights_initializer = tf.truncated_normal_initializer(0.0, 0.01), weights_regularizer = slim.l2_regularizer(0.0005)):
net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, 0]]), name = 'pad_1')
net = slim.conv2d(net, 64, 7, 2, padding = 'VALID', scope = 'conv_2')
net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_3')
net = slim.conv2d(net, 192, 3, scope = 'conv_4')
net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_5')
net = slim.conv2d(net, 128, 1, scope = 'conv_6')
net = slim.conv2d(net, 256, 3, scope = 'conv_7')
net = slim.conv2d(net, 512, 3, scope = 'conv_9')
net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_10')
net = slim.conv2d(net, 256, 1, scope = 'conv_11')
net = slim.conv2d(net, 512, 3, scope = 'conv_12')
net = slim.conv2d(net, 1024, 3, scope = 'conv_20')
net = slim.max_pool2d(net, 2, padding='SAME', scope = 'pool_21')
net = slim.conv2d(net, 512, 1, scope = 'conv_22')
net = slim.conv2d(net, 1024, 3, scope = 'conv_23')
net = slim.conv2d(net, 1024, 3, scope = 'conv_26')
net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]), name = 'pad_27')
net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope = 'conv_28')
net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')
net = slim.flatten(net, scope = 'flat_32')
net = slim.fully_connected(net, 512, scope = 'fc_33')
net = slim.fully_connected(net, 4096, scope = 'fc_34')
net = slim.dropout(net, keep_prob = keep_prob, is_training = training, scope = 'dropout_35')
net = slim.fully_connected(net, num_outputs, activation_fn = None, scope = 'fc_36')
return net
def calc_iou(self, boxes1, boxes2, scope = 'iou'):
with tf.variable_scope(scope):
boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2] / 2.0,
boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] / 2.0,
boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0,
boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])
boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])
boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2] / 2.0,
boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] / 2.0,
boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0,
boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])
boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])
lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])
rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])
intersection = tf.maximum(0.0, rd - lu)
inter_square = intersection[:, :, :, :, 0] * intersection[:, :, :, :, 1]
square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1[:, :, :, :, 3] - boxes1[:, :, :, :, 1])
square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2[:, :, :, :, 3] - boxes2[:, :, :, :, 1])
union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)
return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)
def loss_layer(self, predicts, labels, scope = 'loss_layer'):
with tf.variable_scope(scope):
predict_classes = tf.reshape(predicts[:, :self.boundary1], [settings.batch_size, self.cell_size, self.cell_size, self.num_classes])
predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [settings.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell])
predict_boxes = tf.reshape(predicts[:, self.boundary2:], [settings.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell, 4])
response = tf.reshape(labels[:, :, :, 0], [settings.batch_size, self.cell_size, self.cell_size, 1])
boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size, self.cell_size, self.cell_size, 1, 4])
boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]) / self.image_size
classes = labels[:, :, :, 5:]
offset = tf.constant(self.offset, dtype = tf.float32)
offset = tf.reshape(offset, [1, self.cell_size, self.cell_size, self.boxes_per_cell])
offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])
predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] + offset) / self.cell_size,
(predict_boxes[:, :, :, :, 1] + tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size,
tf.square(predict_boxes[:, :, :, :, 2]),
tf.square(predict_boxes[:, :, :, :, 3])])
predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3, 4, 0])
iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)
object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)
object_mask = tf.cast((iou_predict_truth >= object_mask), tf.float32) * response
noobject_mask = tf.ones_like(object_mask, dtype=tf.float32) - object_mask
boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size - offset,
boxes[:, :, :, :, 1] * self.cell_size - tf.transpose(offset, (0, 2, 1, 3)),
tf.sqrt(boxes[:, :, :, :, 2]),
tf.sqrt(boxes[:, :, :, :, 3])])
boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])
class_delta = response * (predict_classes - classes)
class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta), axis=[1, 2, 3]), name = 'class_loss') * self.class_scale
object_delta = object_mask * (predict_scales - iou_predict_truth)
object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(object_delta), axis=[1, 2, 3]), name = 'object_loss') * self.object_scale
noobject_delta = noobject_mask * predict_scales
noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(noobject_delta), axis=[1, 2, 3]), name = 'noobject_loss') * self.no_object_scale
coord_mask = tf.expand_dims(object_mask, 4)
boxes_delta = coord_mask * (predict_boxes - boxes_tran)
coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta), axis=[1, 2, 3, 4]), name = 'coord_loss') * self.coord_scale
tf.contrib.losses.add_loss(class_loss)
tf.contrib.losses.add_loss(object_loss)
tf.contrib.losses.add_loss(noobject_loss)
tf.contrib.losses.add_loss(coord_loss)
def leaky_relu(alpha):
def op(inputs):
return tf.maximum(alpha * inputs, inputs)
return op
|
flexible
|
{
"blob_id": "8ccec24e1a7060269ffbb376ba0c480da9eabe0a",
"index": 819,
"step-1": "<mask token>\n\n\nclass Model:\n\n def __init__(self, training=True):\n self.classes = settings.classes_name\n self.num_classes = len(settings.classes_name)\n self.image_size = settings.image_size\n self.cell_size = settings.cell_size\n self.boxes_per_cell = settings.box_per_cell\n self.output_size = self.cell_size * self.cell_size * (self.\n num_classes + self.boxes_per_cell * 5)\n self.scale = 1.0 * self.image_size / self.cell_size\n self.boundary1 = self.cell_size * self.cell_size * self.num_classes\n self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *\n self.boxes_per_cell)\n self.object_scale = settings.object_scale\n self.no_object_scale = settings.no_object_scale\n self.class_scale = settings.class_scale\n self.coord_scale = settings.coordinate_scale\n self.offset = np.transpose(np.reshape(np.array([np.arange(self.\n cell_size)] * self.cell_size * self.boxes_per_cell), (self.\n boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))\n self.images = tf.placeholder(tf.float32, [None, settings.image_size,\n settings.image_size, 3])\n if settings.model_type == 'normal':\n self.logits = self.build_network(self.images, num_outputs=self.\n output_size, alpha=settings.alpha_relu, training=training)\n if settings.model_type == 'fast':\n self.logits = self.build_fast_network(self.images, num_outputs=\n self.output_size, alpha=settings.alpha_relu, training=training)\n if training:\n self.batch = tf.Variable(0)\n self.labels = tf.placeholder(tf.float32, [None, self.cell_size,\n self.cell_size, 5 + self.num_classes])\n self.loss_layer(self.logits, self.labels)\n self.total_loss = tf.contrib.losses.get_total_loss()\n self.learning_rate = tf.train.exponential_decay(settings.\n learning_rate, self.batch * settings.batch_size, settings.\n decay_step, settings.decay_rate, True)\n self.optimizer = tf.train.GradientDescentOptimizer(self.\n learning_rate).minimize(self.total_loss, global_step=self.batch\n )\n\n def build_network(self, images, num_outputs, alpha, keep_prob=settings.\n dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 256, 1, scope='conv_8')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 256, 1, scope='conv_13')\n net = slim.conv2d(net, 512, 3, scope='conv_14')\n net = slim.conv2d(net, 256, 1, scope='conv_15')\n net = slim.conv2d(net, 512, 3, scope='conv_16')\n net = slim.conv2d(net, 256, 1, scope='conv_17')\n net = slim.conv2d(net, 512, 3, scope='conv_18')\n net = slim.conv2d(net, 512, 1, scope='conv_19')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 512, 1, scope='conv_24')\n net = slim.conv2d(net, 1024, 3, scope='conv_25')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = slim.conv2d(net, 1024, 3, scope='conv_29')\n net = slim.conv2d(net, 1024, 3, scope='conv_30')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def build_fast_network(self, images, num_outputs, alpha, keep_prob=\n settings.dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def calc_iou(self, boxes1, boxes2, scope='iou'):\n with tf.variable_scope(scope):\n boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2\n ] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] / \n 2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0, \n boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])\n boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])\n boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2\n ] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] / \n 2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0, \n boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])\n boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])\n lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])\n rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])\n intersection = tf.maximum(0.0, rd - lu)\n inter_square = intersection[:, :, :, :, 0] * intersection[:, :,\n :, :, 1]\n square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1\n [:, :, :, :, 3] - boxes1[:, :, :, :, 1])\n square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2\n [:, :, :, :, 3] - boxes2[:, :, :, :, 1])\n union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)\n return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)\n\n def loss_layer(self, predicts, labels, scope='loss_layer'):\n with tf.variable_scope(scope):\n predict_classes = tf.reshape(predicts[:, :self.boundary1], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n num_classes])\n predict_scales = tf.reshape(predicts[:, self.boundary1:self.\n boundary2], [settings.batch_size, self.cell_size, self.\n cell_size, self.boxes_per_cell])\n predict_boxes = tf.reshape(predicts[:, self.boundary2:], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n boxes_per_cell, 4])\n response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,\n self.cell_size, self.cell_size, 1])\n boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,\n self.cell_size, self.cell_size, 1, 4])\n boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]\n ) / self.image_size\n classes = labels[:, :, :, 5:]\n offset = tf.constant(self.offset, dtype=tf.float32)\n offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,\n self.boxes_per_cell])\n offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])\n predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +\n offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +\n tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.\n square(predict_boxes[:, :, :, :, 2]), tf.square(\n predict_boxes[:, :, :, :, 3])])\n predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,\n 4, 0])\n iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)\n object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)\n object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32\n ) * response\n noobject_mask = tf.ones_like(object_mask, dtype=tf.float32\n ) - object_mask\n boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -\n offset, boxes[:, :, :, :, 1] * self.cell_size - tf.\n transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, \n 2]), tf.sqrt(boxes[:, :, :, :, 3])])\n boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])\n class_delta = response * (predict_classes - classes)\n class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta\n ), axis=[1, 2, 3]), name='class_loss') * self.class_scale\n object_delta = object_mask * (predict_scales - iou_predict_truth)\n object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n object_delta), axis=[1, 2, 3]), name='object_loss'\n ) * self.object_scale\n noobject_delta = noobject_mask * predict_scales\n noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n noobject_delta), axis=[1, 2, 3]), name='noobject_loss'\n ) * self.no_object_scale\n coord_mask = tf.expand_dims(object_mask, 4)\n boxes_delta = coord_mask * (predict_boxes - boxes_tran)\n coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta\n ), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale\n tf.contrib.losses.add_loss(class_loss)\n tf.contrib.losses.add_loss(object_loss)\n tf.contrib.losses.add_loss(noobject_loss)\n tf.contrib.losses.add_loss(coord_loss)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Model:\n\n def __init__(self, training=True):\n self.classes = settings.classes_name\n self.num_classes = len(settings.classes_name)\n self.image_size = settings.image_size\n self.cell_size = settings.cell_size\n self.boxes_per_cell = settings.box_per_cell\n self.output_size = self.cell_size * self.cell_size * (self.\n num_classes + self.boxes_per_cell * 5)\n self.scale = 1.0 * self.image_size / self.cell_size\n self.boundary1 = self.cell_size * self.cell_size * self.num_classes\n self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *\n self.boxes_per_cell)\n self.object_scale = settings.object_scale\n self.no_object_scale = settings.no_object_scale\n self.class_scale = settings.class_scale\n self.coord_scale = settings.coordinate_scale\n self.offset = np.transpose(np.reshape(np.array([np.arange(self.\n cell_size)] * self.cell_size * self.boxes_per_cell), (self.\n boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))\n self.images = tf.placeholder(tf.float32, [None, settings.image_size,\n settings.image_size, 3])\n if settings.model_type == 'normal':\n self.logits = self.build_network(self.images, num_outputs=self.\n output_size, alpha=settings.alpha_relu, training=training)\n if settings.model_type == 'fast':\n self.logits = self.build_fast_network(self.images, num_outputs=\n self.output_size, alpha=settings.alpha_relu, training=training)\n if training:\n self.batch = tf.Variable(0)\n self.labels = tf.placeholder(tf.float32, [None, self.cell_size,\n self.cell_size, 5 + self.num_classes])\n self.loss_layer(self.logits, self.labels)\n self.total_loss = tf.contrib.losses.get_total_loss()\n self.learning_rate = tf.train.exponential_decay(settings.\n learning_rate, self.batch * settings.batch_size, settings.\n decay_step, settings.decay_rate, True)\n self.optimizer = tf.train.GradientDescentOptimizer(self.\n learning_rate).minimize(self.total_loss, global_step=self.batch\n )\n\n def build_network(self, images, num_outputs, alpha, keep_prob=settings.\n dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 256, 1, scope='conv_8')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 256, 1, scope='conv_13')\n net = slim.conv2d(net, 512, 3, scope='conv_14')\n net = slim.conv2d(net, 256, 1, scope='conv_15')\n net = slim.conv2d(net, 512, 3, scope='conv_16')\n net = slim.conv2d(net, 256, 1, scope='conv_17')\n net = slim.conv2d(net, 512, 3, scope='conv_18')\n net = slim.conv2d(net, 512, 1, scope='conv_19')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 512, 1, scope='conv_24')\n net = slim.conv2d(net, 1024, 3, scope='conv_25')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = slim.conv2d(net, 1024, 3, scope='conv_29')\n net = slim.conv2d(net, 1024, 3, scope='conv_30')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def build_fast_network(self, images, num_outputs, alpha, keep_prob=\n settings.dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def calc_iou(self, boxes1, boxes2, scope='iou'):\n with tf.variable_scope(scope):\n boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2\n ] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] / \n 2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0, \n boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])\n boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])\n boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2\n ] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] / \n 2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0, \n boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])\n boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])\n lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])\n rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])\n intersection = tf.maximum(0.0, rd - lu)\n inter_square = intersection[:, :, :, :, 0] * intersection[:, :,\n :, :, 1]\n square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1\n [:, :, :, :, 3] - boxes1[:, :, :, :, 1])\n square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2\n [:, :, :, :, 3] - boxes2[:, :, :, :, 1])\n union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)\n return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)\n\n def loss_layer(self, predicts, labels, scope='loss_layer'):\n with tf.variable_scope(scope):\n predict_classes = tf.reshape(predicts[:, :self.boundary1], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n num_classes])\n predict_scales = tf.reshape(predicts[:, self.boundary1:self.\n boundary2], [settings.batch_size, self.cell_size, self.\n cell_size, self.boxes_per_cell])\n predict_boxes = tf.reshape(predicts[:, self.boundary2:], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n boxes_per_cell, 4])\n response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,\n self.cell_size, self.cell_size, 1])\n boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,\n self.cell_size, self.cell_size, 1, 4])\n boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]\n ) / self.image_size\n classes = labels[:, :, :, 5:]\n offset = tf.constant(self.offset, dtype=tf.float32)\n offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,\n self.boxes_per_cell])\n offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])\n predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +\n offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +\n tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.\n square(predict_boxes[:, :, :, :, 2]), tf.square(\n predict_boxes[:, :, :, :, 3])])\n predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,\n 4, 0])\n iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)\n object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)\n object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32\n ) * response\n noobject_mask = tf.ones_like(object_mask, dtype=tf.float32\n ) - object_mask\n boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -\n offset, boxes[:, :, :, :, 1] * self.cell_size - tf.\n transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, \n 2]), tf.sqrt(boxes[:, :, :, :, 3])])\n boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])\n class_delta = response * (predict_classes - classes)\n class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta\n ), axis=[1, 2, 3]), name='class_loss') * self.class_scale\n object_delta = object_mask * (predict_scales - iou_predict_truth)\n object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n object_delta), axis=[1, 2, 3]), name='object_loss'\n ) * self.object_scale\n noobject_delta = noobject_mask * predict_scales\n noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n noobject_delta), axis=[1, 2, 3]), name='noobject_loss'\n ) * self.no_object_scale\n coord_mask = tf.expand_dims(object_mask, 4)\n boxes_delta = coord_mask * (predict_boxes - boxes_tran)\n coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta\n ), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale\n tf.contrib.losses.add_loss(class_loss)\n tf.contrib.losses.add_loss(object_loss)\n tf.contrib.losses.add_loss(noobject_loss)\n tf.contrib.losses.add_loss(coord_loss)\n\n\ndef leaky_relu(alpha):\n\n def op(inputs):\n return tf.maximum(alpha * inputs, inputs)\n return op\n",
"step-3": "<mask token>\nslim = tf.contrib.slim\n\n\nclass Model:\n\n def __init__(self, training=True):\n self.classes = settings.classes_name\n self.num_classes = len(settings.classes_name)\n self.image_size = settings.image_size\n self.cell_size = settings.cell_size\n self.boxes_per_cell = settings.box_per_cell\n self.output_size = self.cell_size * self.cell_size * (self.\n num_classes + self.boxes_per_cell * 5)\n self.scale = 1.0 * self.image_size / self.cell_size\n self.boundary1 = self.cell_size * self.cell_size * self.num_classes\n self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *\n self.boxes_per_cell)\n self.object_scale = settings.object_scale\n self.no_object_scale = settings.no_object_scale\n self.class_scale = settings.class_scale\n self.coord_scale = settings.coordinate_scale\n self.offset = np.transpose(np.reshape(np.array([np.arange(self.\n cell_size)] * self.cell_size * self.boxes_per_cell), (self.\n boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))\n self.images = tf.placeholder(tf.float32, [None, settings.image_size,\n settings.image_size, 3])\n if settings.model_type == 'normal':\n self.logits = self.build_network(self.images, num_outputs=self.\n output_size, alpha=settings.alpha_relu, training=training)\n if settings.model_type == 'fast':\n self.logits = self.build_fast_network(self.images, num_outputs=\n self.output_size, alpha=settings.alpha_relu, training=training)\n if training:\n self.batch = tf.Variable(0)\n self.labels = tf.placeholder(tf.float32, [None, self.cell_size,\n self.cell_size, 5 + self.num_classes])\n self.loss_layer(self.logits, self.labels)\n self.total_loss = tf.contrib.losses.get_total_loss()\n self.learning_rate = tf.train.exponential_decay(settings.\n learning_rate, self.batch * settings.batch_size, settings.\n decay_step, settings.decay_rate, True)\n self.optimizer = tf.train.GradientDescentOptimizer(self.\n learning_rate).minimize(self.total_loss, global_step=self.batch\n )\n\n def build_network(self, images, num_outputs, alpha, keep_prob=settings.\n dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 256, 1, scope='conv_8')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 256, 1, scope='conv_13')\n net = slim.conv2d(net, 512, 3, scope='conv_14')\n net = slim.conv2d(net, 256, 1, scope='conv_15')\n net = slim.conv2d(net, 512, 3, scope='conv_16')\n net = slim.conv2d(net, 256, 1, scope='conv_17')\n net = slim.conv2d(net, 512, 3, scope='conv_18')\n net = slim.conv2d(net, 512, 1, scope='conv_19')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 512, 1, scope='conv_24')\n net = slim.conv2d(net, 1024, 3, scope='conv_25')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = slim.conv2d(net, 1024, 3, scope='conv_29')\n net = slim.conv2d(net, 1024, 3, scope='conv_30')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def build_fast_network(self, images, num_outputs, alpha, keep_prob=\n settings.dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def calc_iou(self, boxes1, boxes2, scope='iou'):\n with tf.variable_scope(scope):\n boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2\n ] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] / \n 2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0, \n boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])\n boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])\n boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2\n ] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] / \n 2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0, \n boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])\n boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])\n lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])\n rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])\n intersection = tf.maximum(0.0, rd - lu)\n inter_square = intersection[:, :, :, :, 0] * intersection[:, :,\n :, :, 1]\n square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1\n [:, :, :, :, 3] - boxes1[:, :, :, :, 1])\n square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2\n [:, :, :, :, 3] - boxes2[:, :, :, :, 1])\n union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)\n return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)\n\n def loss_layer(self, predicts, labels, scope='loss_layer'):\n with tf.variable_scope(scope):\n predict_classes = tf.reshape(predicts[:, :self.boundary1], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n num_classes])\n predict_scales = tf.reshape(predicts[:, self.boundary1:self.\n boundary2], [settings.batch_size, self.cell_size, self.\n cell_size, self.boxes_per_cell])\n predict_boxes = tf.reshape(predicts[:, self.boundary2:], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n boxes_per_cell, 4])\n response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,\n self.cell_size, self.cell_size, 1])\n boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,\n self.cell_size, self.cell_size, 1, 4])\n boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]\n ) / self.image_size\n classes = labels[:, :, :, 5:]\n offset = tf.constant(self.offset, dtype=tf.float32)\n offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,\n self.boxes_per_cell])\n offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])\n predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +\n offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +\n tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.\n square(predict_boxes[:, :, :, :, 2]), tf.square(\n predict_boxes[:, :, :, :, 3])])\n predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,\n 4, 0])\n iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)\n object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)\n object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32\n ) * response\n noobject_mask = tf.ones_like(object_mask, dtype=tf.float32\n ) - object_mask\n boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -\n offset, boxes[:, :, :, :, 1] * self.cell_size - tf.\n transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, \n 2]), tf.sqrt(boxes[:, :, :, :, 3])])\n boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])\n class_delta = response * (predict_classes - classes)\n class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta\n ), axis=[1, 2, 3]), name='class_loss') * self.class_scale\n object_delta = object_mask * (predict_scales - iou_predict_truth)\n object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n object_delta), axis=[1, 2, 3]), name='object_loss'\n ) * self.object_scale\n noobject_delta = noobject_mask * predict_scales\n noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n noobject_delta), axis=[1, 2, 3]), name='noobject_loss'\n ) * self.no_object_scale\n coord_mask = tf.expand_dims(object_mask, 4)\n boxes_delta = coord_mask * (predict_boxes - boxes_tran)\n coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta\n ), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale\n tf.contrib.losses.add_loss(class_loss)\n tf.contrib.losses.add_loss(object_loss)\n tf.contrib.losses.add_loss(noobject_loss)\n tf.contrib.losses.add_loss(coord_loss)\n\n\ndef leaky_relu(alpha):\n\n def op(inputs):\n return tf.maximum(alpha * inputs, inputs)\n return op\n",
"step-4": "import tensorflow as tf\nimport settings\nimport numpy as np\nslim = tf.contrib.slim\n\n\nclass Model:\n\n def __init__(self, training=True):\n self.classes = settings.classes_name\n self.num_classes = len(settings.classes_name)\n self.image_size = settings.image_size\n self.cell_size = settings.cell_size\n self.boxes_per_cell = settings.box_per_cell\n self.output_size = self.cell_size * self.cell_size * (self.\n num_classes + self.boxes_per_cell * 5)\n self.scale = 1.0 * self.image_size / self.cell_size\n self.boundary1 = self.cell_size * self.cell_size * self.num_classes\n self.boundary2 = (self.boundary1 + self.cell_size * self.cell_size *\n self.boxes_per_cell)\n self.object_scale = settings.object_scale\n self.no_object_scale = settings.no_object_scale\n self.class_scale = settings.class_scale\n self.coord_scale = settings.coordinate_scale\n self.offset = np.transpose(np.reshape(np.array([np.arange(self.\n cell_size)] * self.cell_size * self.boxes_per_cell), (self.\n boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))\n self.images = tf.placeholder(tf.float32, [None, settings.image_size,\n settings.image_size, 3])\n if settings.model_type == 'normal':\n self.logits = self.build_network(self.images, num_outputs=self.\n output_size, alpha=settings.alpha_relu, training=training)\n if settings.model_type == 'fast':\n self.logits = self.build_fast_network(self.images, num_outputs=\n self.output_size, alpha=settings.alpha_relu, training=training)\n if training:\n self.batch = tf.Variable(0)\n self.labels = tf.placeholder(tf.float32, [None, self.cell_size,\n self.cell_size, 5 + self.num_classes])\n self.loss_layer(self.logits, self.labels)\n self.total_loss = tf.contrib.losses.get_total_loss()\n self.learning_rate = tf.train.exponential_decay(settings.\n learning_rate, self.batch * settings.batch_size, settings.\n decay_step, settings.decay_rate, True)\n self.optimizer = tf.train.GradientDescentOptimizer(self.\n learning_rate).minimize(self.total_loss, global_step=self.batch\n )\n\n def build_network(self, images, num_outputs, alpha, keep_prob=settings.\n dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 256, 1, scope='conv_8')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 256, 1, scope='conv_13')\n net = slim.conv2d(net, 512, 3, scope='conv_14')\n net = slim.conv2d(net, 256, 1, scope='conv_15')\n net = slim.conv2d(net, 512, 3, scope='conv_16')\n net = slim.conv2d(net, 256, 1, scope='conv_17')\n net = slim.conv2d(net, 512, 3, scope='conv_18')\n net = slim.conv2d(net, 512, 1, scope='conv_19')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 512, 1, scope='conv_24')\n net = slim.conv2d(net, 1024, 3, scope='conv_25')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = slim.conv2d(net, 1024, 3, scope='conv_29')\n net = slim.conv2d(net, 1024, 3, scope='conv_30')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def build_fast_network(self, images, num_outputs, alpha, keep_prob=\n settings.dropout, training=True, scope='yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=leaky_relu(alpha), weights_initializer=tf.\n truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, \n 0]]), name='pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding='VALID', scope=\n 'conv_2')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_3')\n net = slim.conv2d(net, 192, 3, scope='conv_4')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_5')\n net = slim.conv2d(net, 128, 1, scope='conv_6')\n net = slim.conv2d(net, 256, 3, scope='conv_7')\n net = slim.conv2d(net, 512, 3, scope='conv_9')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_10')\n net = slim.conv2d(net, 256, 1, scope='conv_11')\n net = slim.conv2d(net, 512, 3, scope='conv_12')\n net = slim.conv2d(net, 1024, 3, scope='conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope='pool_21')\n net = slim.conv2d(net, 512, 1, scope='conv_22')\n net = slim.conv2d(net, 1024, 3, scope='conv_23')\n net = slim.conv2d(net, 1024, 3, scope='conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]\n ), name='pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope=\n 'conv_28')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope='flat_32')\n net = slim.fully_connected(net, 512, scope='fc_33')\n net = slim.fully_connected(net, 4096, scope='fc_34')\n net = slim.dropout(net, keep_prob=keep_prob, is_training=\n training, scope='dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn=\n None, scope='fc_36')\n return net\n\n def calc_iou(self, boxes1, boxes2, scope='iou'):\n with tf.variable_scope(scope):\n boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2\n ] / 2.0, boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] / \n 2.0, boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0, \n boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])\n boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])\n boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2\n ] / 2.0, boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] / \n 2.0, boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0, \n boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])\n boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])\n lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])\n rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])\n intersection = tf.maximum(0.0, rd - lu)\n inter_square = intersection[:, :, :, :, 0] * intersection[:, :,\n :, :, 1]\n square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1\n [:, :, :, :, 3] - boxes1[:, :, :, :, 1])\n square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2\n [:, :, :, :, 3] - boxes2[:, :, :, :, 1])\n union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)\n return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)\n\n def loss_layer(self, predicts, labels, scope='loss_layer'):\n with tf.variable_scope(scope):\n predict_classes = tf.reshape(predicts[:, :self.boundary1], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n num_classes])\n predict_scales = tf.reshape(predicts[:, self.boundary1:self.\n boundary2], [settings.batch_size, self.cell_size, self.\n cell_size, self.boxes_per_cell])\n predict_boxes = tf.reshape(predicts[:, self.boundary2:], [\n settings.batch_size, self.cell_size, self.cell_size, self.\n boxes_per_cell, 4])\n response = tf.reshape(labels[:, :, :, 0], [settings.batch_size,\n self.cell_size, self.cell_size, 1])\n boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size,\n self.cell_size, self.cell_size, 1, 4])\n boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]\n ) / self.image_size\n classes = labels[:, :, :, 5:]\n offset = tf.constant(self.offset, dtype=tf.float32)\n offset = tf.reshape(offset, [1, self.cell_size, self.cell_size,\n self.boxes_per_cell])\n offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])\n predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] +\n offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] +\n tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.\n square(predict_boxes[:, :, :, :, 2]), tf.square(\n predict_boxes[:, :, :, :, 3])])\n predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3,\n 4, 0])\n iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)\n object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)\n object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32\n ) * response\n noobject_mask = tf.ones_like(object_mask, dtype=tf.float32\n ) - object_mask\n boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size -\n offset, boxes[:, :, :, :, 1] * self.cell_size - tf.\n transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, \n 2]), tf.sqrt(boxes[:, :, :, :, 3])])\n boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])\n class_delta = response * (predict_classes - classes)\n class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta\n ), axis=[1, 2, 3]), name='class_loss') * self.class_scale\n object_delta = object_mask * (predict_scales - iou_predict_truth)\n object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n object_delta), axis=[1, 2, 3]), name='object_loss'\n ) * self.object_scale\n noobject_delta = noobject_mask * predict_scales\n noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(\n noobject_delta), axis=[1, 2, 3]), name='noobject_loss'\n ) * self.no_object_scale\n coord_mask = tf.expand_dims(object_mask, 4)\n boxes_delta = coord_mask * (predict_boxes - boxes_tran)\n coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta\n ), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale\n tf.contrib.losses.add_loss(class_loss)\n tf.contrib.losses.add_loss(object_loss)\n tf.contrib.losses.add_loss(noobject_loss)\n tf.contrib.losses.add_loss(coord_loss)\n\n\ndef leaky_relu(alpha):\n\n def op(inputs):\n return tf.maximum(alpha * inputs, inputs)\n return op\n",
"step-5": "import tensorflow as tf\nimport settings\nimport numpy as np\n\nslim = tf.contrib.slim\n\nclass Model:\n \n def __init__(self, training = True):\n self.classes = settings.classes_name\n self.num_classes = len(settings.classes_name)\n self.image_size = settings.image_size\n self.cell_size = settings.cell_size\n self.boxes_per_cell = settings.box_per_cell\n self.output_size = (self.cell_size * self.cell_size) * (self.num_classes + self.boxes_per_cell * 5)\n self.scale = 1.0 * self.image_size / self.cell_size\n self.boundary1 = self.cell_size * self.cell_size * self.num_classes\n self.boundary2 = self.boundary1 + self.cell_size * self.cell_size * self.boxes_per_cell\n\n self.object_scale = settings.object_scale\n self.no_object_scale = settings.no_object_scale\n self.class_scale = settings.class_scale\n self.coord_scale = settings.coordinate_scale\n \n self.offset = np.transpose(np.reshape(np.array([np.arange(self.cell_size)] * self.cell_size * self.boxes_per_cell), (self.boxes_per_cell, self.cell_size, self.cell_size)), (1, 2, 0))\n\n self.images = tf.placeholder(tf.float32, [None, settings.image_size, settings.image_size, 3])\n \n if settings.model_type == 'normal':\n self.logits = self.build_network(self.images, num_outputs = self.output_size, alpha = settings.alpha_relu, training = training)\n if settings.model_type == 'fast':\n self.logits = self.build_fast_network(self.images, num_outputs = self.output_size, alpha = settings.alpha_relu, training = training)\n \n if training:\n self.batch = tf.Variable(0)\n self.labels = tf.placeholder(tf.float32, [None, self.cell_size, self.cell_size, 5 + self.num_classes])\n self.loss_layer(self.logits, self.labels)\n self.total_loss = tf.contrib.losses.get_total_loss()\n self.learning_rate = tf.train.exponential_decay(settings.learning_rate, self.batch * settings.batch_size, settings.decay_step, settings.decay_rate, True)\n self.optimizer = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.total_loss, global_step = self.batch)\n \n def build_network(self, images, num_outputs, alpha, keep_prob = settings.dropout, training = True, scope = 'yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn = leaky_relu(alpha), weights_initializer = tf.truncated_normal_initializer(0.0, 0.01), weights_regularizer = slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, 0]]), name = 'pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding = 'VALID', scope = 'conv_2')\n net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_3')\n net = slim.conv2d(net, 192, 3, scope = 'conv_4')\n net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_5')\n net = slim.conv2d(net, 128, 1, scope = 'conv_6')\n net = slim.conv2d(net, 256, 3, scope = 'conv_7')\n net = slim.conv2d(net, 256, 1, scope = 'conv_8')\n net = slim.conv2d(net, 512, 3, scope = 'conv_9')\n net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_10')\n net = slim.conv2d(net, 256, 1, scope = 'conv_11')\n net = slim.conv2d(net, 512, 3, scope = 'conv_12')\n net = slim.conv2d(net, 256, 1, scope = 'conv_13')\n net = slim.conv2d(net, 512, 3, scope = 'conv_14')\n net = slim.conv2d(net, 256, 1, scope = 'conv_15')\n net = slim.conv2d(net, 512, 3, scope = 'conv_16')\n net = slim.conv2d(net, 256, 1, scope = 'conv_17')\n net = slim.conv2d(net, 512, 3, scope = 'conv_18')\n net = slim.conv2d(net, 512, 1, scope = 'conv_19')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope = 'pool_21')\n net = slim.conv2d(net, 512, 1, scope = 'conv_22')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_23')\n net = slim.conv2d(net, 512, 1, scope = 'conv_24')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_25')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]), name = 'pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope = 'conv_28')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_29')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_30')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope = 'flat_32')\n net = slim.fully_connected(net, 512, scope = 'fc_33')\n net = slim.fully_connected(net, 4096, scope = 'fc_34')\n net = slim.dropout(net, keep_prob = keep_prob, is_training = training, scope = 'dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn = None, scope = 'fc_36')\n return net\n \n def build_fast_network(self, images, num_outputs, alpha, keep_prob = settings.dropout, training = True, scope = 'yolo'):\n with tf.variable_scope(scope):\n with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn = leaky_relu(alpha), weights_initializer = tf.truncated_normal_initializer(0.0, 0.01), weights_regularizer = slim.l2_regularizer(0.0005)):\n net = tf.pad(images, np.array([[0, 0], [3, 3], [3, 3], [0, 0]]), name = 'pad_1')\n net = slim.conv2d(net, 64, 7, 2, padding = 'VALID', scope = 'conv_2')\n net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_3')\n net = slim.conv2d(net, 192, 3, scope = 'conv_4')\n net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_5')\n net = slim.conv2d(net, 128, 1, scope = 'conv_6')\n net = slim.conv2d(net, 256, 3, scope = 'conv_7')\n net = slim.conv2d(net, 512, 3, scope = 'conv_9')\n net = slim.max_pool2d(net, 2, padding = 'SAME', scope = 'pool_10')\n net = slim.conv2d(net, 256, 1, scope = 'conv_11')\n net = slim.conv2d(net, 512, 3, scope = 'conv_12')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_20')\n net = slim.max_pool2d(net, 2, padding='SAME', scope = 'pool_21')\n net = slim.conv2d(net, 512, 1, scope = 'conv_22')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_23')\n net = slim.conv2d(net, 1024, 3, scope = 'conv_26')\n net = tf.pad(net, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]), name = 'pad_27')\n net = slim.conv2d(net, 1024, 3, 2, padding='VALID', scope = 'conv_28')\n net = tf.transpose(net, [0, 3, 1, 2], name='trans_31')\n net = slim.flatten(net, scope = 'flat_32')\n net = slim.fully_connected(net, 512, scope = 'fc_33')\n net = slim.fully_connected(net, 4096, scope = 'fc_34')\n net = slim.dropout(net, keep_prob = keep_prob, is_training = training, scope = 'dropout_35')\n net = slim.fully_connected(net, num_outputs, activation_fn = None, scope = 'fc_36')\n return net\n \n \n def calc_iou(self, boxes1, boxes2, scope = 'iou'):\n with tf.variable_scope(scope):\n boxes1 = tf.stack([boxes1[:, :, :, :, 0] - boxes1[:, :, :, :, 2] / 2.0,\n boxes1[:, :, :, :, 1] - boxes1[:, :, :, :, 3] / 2.0,\n boxes1[:, :, :, :, 0] + boxes1[:, :, :, :, 2] / 2.0,\n boxes1[:, :, :, :, 1] + boxes1[:, :, :, :, 3] / 2.0])\n boxes1 = tf.transpose(boxes1, [1, 2, 3, 4, 0])\n\n boxes2 = tf.stack([boxes2[:, :, :, :, 0] - boxes2[:, :, :, :, 2] / 2.0,\n boxes2[:, :, :, :, 1] - boxes2[:, :, :, :, 3] / 2.0,\n boxes2[:, :, :, :, 0] + boxes2[:, :, :, :, 2] / 2.0,\n boxes2[:, :, :, :, 1] + boxes2[:, :, :, :, 3] / 2.0])\n boxes2 = tf.transpose(boxes2, [1, 2, 3, 4, 0])\n\n lu = tf.maximum(boxes1[:, :, :, :, :2], boxes2[:, :, :, :, :2])\n rd = tf.minimum(boxes1[:, :, :, :, 2:], boxes2[:, :, :, :, 2:])\n\n intersection = tf.maximum(0.0, rd - lu)\n inter_square = intersection[:, :, :, :, 0] * intersection[:, :, :, :, 1]\n\n square1 = (boxes1[:, :, :, :, 2] - boxes1[:, :, :, :, 0]) * (boxes1[:, :, :, :, 3] - boxes1[:, :, :, :, 1])\n square2 = (boxes2[:, :, :, :, 2] - boxes2[:, :, :, :, 0]) * (boxes2[:, :, :, :, 3] - boxes2[:, :, :, :, 1])\n\n union_square = tf.maximum(square1 + square2 - inter_square, 1e-10)\n\n return tf.clip_by_value(inter_square / union_square, 0.0, 1.0)\n\n def loss_layer(self, predicts, labels, scope = 'loss_layer'):\n with tf.variable_scope(scope):\n predict_classes = tf.reshape(predicts[:, :self.boundary1], [settings.batch_size, self.cell_size, self.cell_size, self.num_classes])\n predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [settings.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell])\n predict_boxes = tf.reshape(predicts[:, self.boundary2:], [settings.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell, 4])\n\n response = tf.reshape(labels[:, :, :, 0], [settings.batch_size, self.cell_size, self.cell_size, 1])\n boxes = tf.reshape(labels[:, :, :, 1:5], [settings.batch_size, self.cell_size, self.cell_size, 1, 4])\n boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]) / self.image_size\n classes = labels[:, :, :, 5:]\n\n offset = tf.constant(self.offset, dtype = tf.float32)\n offset = tf.reshape(offset, [1, self.cell_size, self.cell_size, self.boxes_per_cell])\n offset = tf.tile(offset, [settings.batch_size, 1, 1, 1])\n predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] + offset) / self.cell_size,\n (predict_boxes[:, :, :, :, 1] + tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size,\n tf.square(predict_boxes[:, :, :, :, 2]),\n tf.square(predict_boxes[:, :, :, :, 3])])\n predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3, 4, 0])\n\n iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)\n\n object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)\n object_mask = tf.cast((iou_predict_truth >= object_mask), tf.float32) * response\n\n noobject_mask = tf.ones_like(object_mask, dtype=tf.float32) - object_mask\n\n boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size - offset,\n boxes[:, :, :, :, 1] * self.cell_size - tf.transpose(offset, (0, 2, 1, 3)),\n tf.sqrt(boxes[:, :, :, :, 2]),\n tf.sqrt(boxes[:, :, :, :, 3])])\n boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])\n\n class_delta = response * (predict_classes - classes)\n class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta), axis=[1, 2, 3]), name = 'class_loss') * self.class_scale\n\n object_delta = object_mask * (predict_scales - iou_predict_truth)\n object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(object_delta), axis=[1, 2, 3]), name = 'object_loss') * self.object_scale\n\n noobject_delta = noobject_mask * predict_scales\n noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(noobject_delta), axis=[1, 2, 3]), name = 'noobject_loss') * self.no_object_scale\n\n coord_mask = tf.expand_dims(object_mask, 4)\n boxes_delta = coord_mask * (predict_boxes - boxes_tran)\n coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta), axis=[1, 2, 3, 4]), name = 'coord_loss') * self.coord_scale\n\n tf.contrib.losses.add_loss(class_loss)\n tf.contrib.losses.add_loss(object_loss)\n tf.contrib.losses.add_loss(noobject_loss)\n tf.contrib.losses.add_loss(coord_loss)\n\ndef leaky_relu(alpha):\n \n def op(inputs):\n return tf.maximum(alpha * inputs, inputs)\n return op\n",
"step-ids": [
6,
7,
8,
9,
10
]
}
|
[
6,
7,
8,
9,
10
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-12 20:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('home', '0010_auto_20170512_2248'),
]
operations = [
migrations.AlterField(
model_name='classroom',
name='subject5teacher',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='home.Teacher', verbose_name='Chemistry'),
),
]
|
normal
|
{
"blob_id": "438efbaf35401a29ea5408fee3b49b85f237760e",
"index": 1089,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('home', '0010_auto_20170512_2248')]\n operations = [migrations.AlterField(model_name='classroom', name=\n 'subject5teacher', field=models.ForeignKey(default=None, on_delete=\n django.db.models.deletion.CASCADE, related_name='+', to=\n 'home.Teacher', verbose_name='Chemistry'))]\n",
"step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [('home', '0010_auto_20170512_2248')]\n operations = [migrations.AlterField(model_name='classroom', name=\n 'subject5teacher', field=models.ForeignKey(default=None, on_delete=\n django.db.models.deletion.CASCADE, related_name='+', to=\n 'home.Teacher', verbose_name='Chemistry'))]\n",
"step-5": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11 on 2017-05-12 20:48\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations, models\r\nimport django.db.models.deletion\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('home', '0010_auto_20170512_2248'),\r\n ]\r\n\r\n operations = [\r\n migrations.AlterField(\r\n model_name='classroom',\r\n name='subject5teacher',\r\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='home.Teacher', verbose_name='Chemistry'),\r\n ),\r\n ]\r\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import gc
import sys
import time
import warnings
import multiprocessing
import numpy as np
import pandas as pd
import lightgbm as lgb
from os import path, makedirs
from tqdm import tqdm
from utils import Logger
from datetime import datetime
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
# ======================================================================= Method
def load_dataframe(dataset):
return pd.read_csv(dataset)
def augment(x, y, t=2):
xs, xn = [], []
for i in range(t):
mask = y > 0
x1 = x[mask].copy()
for c in range(200):
val = x1[:, [c, c+200, c+400]]
np.random.shuffle(val)
x1[:, [c, c+200, c+400]] = val
xs.append(x1)
for i in range(t//2):
mask = y == 0
x1 = x[mask].copy()
for c in range(200):
val = x1[:, [c, c+200, c+400]]
np.random.shuffle(val)
x1[:, [c, c+200, c+400]] = val
xn.append(x1)
xs = np.vstack(xs)
xn = np.vstack(xn)
ys = np.ones(xs.shape[0])
yn = np.zeros(xn.shape[0])
x = np.vstack([x, xs, xn])
y = np.concatenate([y, ys, yn])
return x, y
# ======================================================================= Main
if __name__ == '__main__':
gc.enable()
pd.set_option('max_rows', None)
pd.set_option('max_columns', None)
warnings.simplefilter('ignore', UserWarning)
# =================================================================== Params
top_folder = './output'
today = datetime.today()
now = today.strftime('%m%d-%H%M')
log_name = now + '.txt'
sys.stdout = Logger(path.join(top_folder, log_name))
seed_np = 1011
np.random.seed(seed_np)
print('numpy seed: {}'.format(seed_np))
# =================================================================== Load Data
start = time.time()
with multiprocessing.Pool() as pool:
train, test = pool.map(load_dataframe, ['./input/train.csv', './input/test.csv'])
# === fake sample
df_test = test.drop(columns=['ID_code']).values
unique_samples = []
unique_count = np.zeros_like(df_test)
for feature in tqdm(range(df_test.shape[1])):
_, index_, count_ = np.unique(df_test[:, feature], return_counts=True, return_index=True)
unique_count[index_[count_ == 1], feature] += 1
idx_score = np.argwhere(np.sum(unique_count, axis=1) > 0)[:, 0]
idx_synthetic = np.argwhere(np.sum(unique_count, axis=1) == 0)[:, 0]
synthetic = test.loc[idx_synthetic]
test = test.loc[idx_score]
raw = pd.concat([train, test], axis=0, sort=False, ignore_index=True)
# ============================== Extra Feature
len_train = len(train)
col_var = list(raw.columns[2:])
# === replace value(frequency=1) to NA
mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)
for col in tqdm(col_var):
cnt = raw[col].value_counts()
val = cnt[cnt == 1].index
mask.loc[np.isin(raw[col], val), col] = 0
col_repeat = [col + '_repeat_2' for col in col_var]
raw[col_repeat] = raw[col_var][mask.astype(bool)]
# === replace value(frequency=1/2) to NA
mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)
for col in tqdm(col_var):
cnt = raw[col].value_counts()
val = cnt[np.isin(cnt, [1, 2])].index
mask.loc[np.isin(raw[col], val), col] = 0
col_repeat = [col + '_repeat_3' for col in col_var]
raw[col_repeat] = raw[col_var][mask.astype(bool)]
raw = pd.concat([raw, synthetic], axis=0, sort=False, ignore_index=True)
# === logging
print('data: {}'.format(raw.shape))
print('elapsed time: {:.1f} min'.format((time.time() - start)/60))
# =================================================================== PreProcess
feats = [col for col in raw.columns.values if col not in ['ID_code', 'target']]
# =================================================================== Model
train = raw[:len_train]
test = raw[len_train:].copy()
x_train = train[feats]
y_train = train['target']
x_test = test[feats]
print('trn_x: {}'.format(x_train.shape))
print('x_test: {}'.format(x_test.shape))
param = {
'objective': 'binary',
'boosting': 'gbdt',
'metric': 'auc',
'verbosity': -1,
'n_jobs': 11,
'random_state': 1993,
'learning_rate': 0.01,
'num_leaves': 8,
'max_depth': -1,
'feature_fraction': 0.05,
'bagging_freq': 5,
'bagging_fraction': 0.4,
'min_data_in_leaf': 80,
'min_sum_hessian_in_leaf': 10.0,
}
print('model params:\n{}'.format(pd.Series(list(param.values()), index=list(param.keys()))))
seed_fold = 26
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed_fold)
print('StratifiedKFold seed: {}'.format(seed_fold))
round_max = 30000
round_early_stopping = 3000
print('num_round: {}'.format(round_max))
print('early_stopping_round: {}'.format(round_early_stopping))
# === training
oof = np.zeros(len(x_train))
predictions = np.zeros(len(x_test))
start = time.time()
for fold_, (trn_idx, val_idx) in enumerate(folds.split(x_train.values, y_train.values)):
print("fold n°{}".format(fold_))
trn_x, trn_y = x_train.iloc[trn_idx], y_train.iloc[trn_idx]
val_x, val_y = x_train.iloc[val_idx], y_train.iloc[val_idx]
N = 5
for i in range(N):
X_t, y_t = augment(trn_x.values, trn_y.values)
X_t = pd.DataFrame(X_t, columns=feats)
trn_data = lgb.Dataset(X_t, label=y_t)
val_data = lgb.Dataset(val_x, label=val_y)
evals_result = {}
clf = lgb.train(param,
trn_data,
round_max,
valid_sets=[trn_data, val_data],
early_stopping_rounds=round_early_stopping,
verbose_eval=1000,
evals_result=evals_result)
oof[val_idx] += clf.predict(val_x, num_iteration=clf.best_iteration) / N
predictions += clf.predict(x_test, num_iteration=clf.best_iteration) / folds.n_splits / N
fold_score = roc_auc_score(val_y, oof[val_idx])
print('fold {} auc score: {:.5f}'.format(fold_, fold_score))
cv_score = roc_auc_score(y_train, oof)
print('elapsed time: {:.1f} min'.format((time.time() - start)/60))
print('auc score: {:.5f}'.format(cv_score))
# =================================================================== Saving File
sub_folder = path.join(top_folder, 'cv_' + now + '_' + str(np.round(cv_score, 5)))
makedirs(sub_folder, exist_ok=True)
test['target'] = predictions
test[['ID_code', 'target']].to_csv(path.join(sub_folder, 'submission.csv'), index=False)
raw['oof'] = np.concatenate([oof, predictions], axis=0)
raw[['ID_code', 'oof']].to_csv(path.join(sub_folder, 'oof.csv'), index=False)
|
normal
|
{
"blob_id": "74c875d00c665aabbcad4e23e6059c3445d5e7bd",
"index": 1597,
"step-1": "<mask token>\n\n\ndef load_dataframe(dataset):\n return pd.read_csv(dataset)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef load_dataframe(dataset):\n return pd.read_csv(dataset)\n\n\ndef augment(x, y, t=2):\n xs, xn = [], []\n for i in range(t):\n mask = y > 0\n x1 = x[mask].copy()\n for c in range(200):\n val = x1[:, [c, c + 200, c + 400]]\n np.random.shuffle(val)\n x1[:, [c, c + 200, c + 400]] = val\n xs.append(x1)\n for i in range(t // 2):\n mask = y == 0\n x1 = x[mask].copy()\n for c in range(200):\n val = x1[:, [c, c + 200, c + 400]]\n np.random.shuffle(val)\n x1[:, [c, c + 200, c + 400]] = val\n xn.append(x1)\n xs = np.vstack(xs)\n xn = np.vstack(xn)\n ys = np.ones(xs.shape[0])\n yn = np.zeros(xn.shape[0])\n x = np.vstack([x, xs, xn])\n y = np.concatenate([y, ys, yn])\n return x, y\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef load_dataframe(dataset):\n return pd.read_csv(dataset)\n\n\ndef augment(x, y, t=2):\n xs, xn = [], []\n for i in range(t):\n mask = y > 0\n x1 = x[mask].copy()\n for c in range(200):\n val = x1[:, [c, c + 200, c + 400]]\n np.random.shuffle(val)\n x1[:, [c, c + 200, c + 400]] = val\n xs.append(x1)\n for i in range(t // 2):\n mask = y == 0\n x1 = x[mask].copy()\n for c in range(200):\n val = x1[:, [c, c + 200, c + 400]]\n np.random.shuffle(val)\n x1[:, [c, c + 200, c + 400]] = val\n xn.append(x1)\n xs = np.vstack(xs)\n xn = np.vstack(xn)\n ys = np.ones(xs.shape[0])\n yn = np.zeros(xn.shape[0])\n x = np.vstack([x, xs, xn])\n y = np.concatenate([y, ys, yn])\n return x, y\n\n\nif __name__ == '__main__':\n gc.enable()\n pd.set_option('max_rows', None)\n pd.set_option('max_columns', None)\n warnings.simplefilter('ignore', UserWarning)\n top_folder = './output'\n today = datetime.today()\n now = today.strftime('%m%d-%H%M')\n log_name = now + '.txt'\n sys.stdout = Logger(path.join(top_folder, log_name))\n seed_np = 1011\n np.random.seed(seed_np)\n print('numpy seed: {}'.format(seed_np))\n start = time.time()\n with multiprocessing.Pool() as pool:\n train, test = pool.map(load_dataframe, ['./input/train.csv',\n './input/test.csv'])\n df_test = test.drop(columns=['ID_code']).values\n unique_samples = []\n unique_count = np.zeros_like(df_test)\n for feature in tqdm(range(df_test.shape[1])):\n _, index_, count_ = np.unique(df_test[:, feature], return_counts=\n True, return_index=True)\n unique_count[index_[count_ == 1], feature] += 1\n idx_score = np.argwhere(np.sum(unique_count, axis=1) > 0)[:, 0]\n idx_synthetic = np.argwhere(np.sum(unique_count, axis=1) == 0)[:, 0]\n synthetic = test.loc[idx_synthetic]\n test = test.loc[idx_score]\n raw = pd.concat([train, test], axis=0, sort=False, ignore_index=True)\n len_train = len(train)\n col_var = list(raw.columns[2:])\n mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)\n for col in tqdm(col_var):\n cnt = raw[col].value_counts()\n val = cnt[cnt == 1].index\n mask.loc[np.isin(raw[col], val), col] = 0\n col_repeat = [(col + '_repeat_2') for col in col_var]\n raw[col_repeat] = raw[col_var][mask.astype(bool)]\n mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)\n for col in tqdm(col_var):\n cnt = raw[col].value_counts()\n val = cnt[np.isin(cnt, [1, 2])].index\n mask.loc[np.isin(raw[col], val), col] = 0\n col_repeat = [(col + '_repeat_3') for col in col_var]\n raw[col_repeat] = raw[col_var][mask.astype(bool)]\n raw = pd.concat([raw, synthetic], axis=0, sort=False, ignore_index=True)\n print('data: {}'.format(raw.shape))\n print('elapsed time: {:.1f} min'.format((time.time() - start) / 60))\n feats = [col for col in raw.columns.values if col not in ['ID_code',\n 'target']]\n train = raw[:len_train]\n test = raw[len_train:].copy()\n x_train = train[feats]\n y_train = train['target']\n x_test = test[feats]\n print('trn_x: {}'.format(x_train.shape))\n print('x_test: {}'.format(x_test.shape))\n param = {'objective': 'binary', 'boosting': 'gbdt', 'metric': 'auc',\n 'verbosity': -1, 'n_jobs': 11, 'random_state': 1993,\n 'learning_rate': 0.01, 'num_leaves': 8, 'max_depth': -1,\n 'feature_fraction': 0.05, 'bagging_freq': 5, 'bagging_fraction': \n 0.4, 'min_data_in_leaf': 80, 'min_sum_hessian_in_leaf': 10.0}\n print('model params:\\n{}'.format(pd.Series(list(param.values()), index=\n list(param.keys()))))\n seed_fold = 26\n folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed_fold)\n print('StratifiedKFold seed: {}'.format(seed_fold))\n round_max = 30000\n round_early_stopping = 3000\n print('num_round: {}'.format(round_max))\n print('early_stopping_round: {}'.format(round_early_stopping))\n oof = np.zeros(len(x_train))\n predictions = np.zeros(len(x_test))\n start = time.time()\n for fold_, (trn_idx, val_idx) in enumerate(folds.split(x_train.values,\n y_train.values)):\n print('fold n°{}'.format(fold_))\n trn_x, trn_y = x_train.iloc[trn_idx], y_train.iloc[trn_idx]\n val_x, val_y = x_train.iloc[val_idx], y_train.iloc[val_idx]\n N = 5\n for i in range(N):\n X_t, y_t = augment(trn_x.values, trn_y.values)\n X_t = pd.DataFrame(X_t, columns=feats)\n trn_data = lgb.Dataset(X_t, label=y_t)\n val_data = lgb.Dataset(val_x, label=val_y)\n evals_result = {}\n clf = lgb.train(param, trn_data, round_max, valid_sets=[\n trn_data, val_data], early_stopping_rounds=\n round_early_stopping, verbose_eval=1000, evals_result=\n evals_result)\n oof[val_idx] += clf.predict(val_x, num_iteration=clf.best_iteration\n ) / N\n predictions += clf.predict(x_test, num_iteration=clf.best_iteration\n ) / folds.n_splits / N\n fold_score = roc_auc_score(val_y, oof[val_idx])\n print('fold {} auc score: {:.5f}'.format(fold_, fold_score))\n cv_score = roc_auc_score(y_train, oof)\n print('elapsed time: {:.1f} min'.format((time.time() - start) / 60))\n print('auc score: {:.5f}'.format(cv_score))\n sub_folder = path.join(top_folder, 'cv_' + now + '_' + str(np.round(\n cv_score, 5)))\n makedirs(sub_folder, exist_ok=True)\n test['target'] = predictions\n test[['ID_code', 'target']].to_csv(path.join(sub_folder,\n 'submission.csv'), index=False)\n raw['oof'] = np.concatenate([oof, predictions], axis=0)\n raw[['ID_code', 'oof']].to_csv(path.join(sub_folder, 'oof.csv'), index=\n False)\n",
"step-4": "import gc\nimport sys\nimport time\nimport warnings\nimport multiprocessing\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgb\nfrom os import path, makedirs\nfrom tqdm import tqdm\nfrom utils import Logger\nfrom datetime import datetime\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import StratifiedKFold\n\n\ndef load_dataframe(dataset):\n return pd.read_csv(dataset)\n\n\ndef augment(x, y, t=2):\n xs, xn = [], []\n for i in range(t):\n mask = y > 0\n x1 = x[mask].copy()\n for c in range(200):\n val = x1[:, [c, c + 200, c + 400]]\n np.random.shuffle(val)\n x1[:, [c, c + 200, c + 400]] = val\n xs.append(x1)\n for i in range(t // 2):\n mask = y == 0\n x1 = x[mask].copy()\n for c in range(200):\n val = x1[:, [c, c + 200, c + 400]]\n np.random.shuffle(val)\n x1[:, [c, c + 200, c + 400]] = val\n xn.append(x1)\n xs = np.vstack(xs)\n xn = np.vstack(xn)\n ys = np.ones(xs.shape[0])\n yn = np.zeros(xn.shape[0])\n x = np.vstack([x, xs, xn])\n y = np.concatenate([y, ys, yn])\n return x, y\n\n\nif __name__ == '__main__':\n gc.enable()\n pd.set_option('max_rows', None)\n pd.set_option('max_columns', None)\n warnings.simplefilter('ignore', UserWarning)\n top_folder = './output'\n today = datetime.today()\n now = today.strftime('%m%d-%H%M')\n log_name = now + '.txt'\n sys.stdout = Logger(path.join(top_folder, log_name))\n seed_np = 1011\n np.random.seed(seed_np)\n print('numpy seed: {}'.format(seed_np))\n start = time.time()\n with multiprocessing.Pool() as pool:\n train, test = pool.map(load_dataframe, ['./input/train.csv',\n './input/test.csv'])\n df_test = test.drop(columns=['ID_code']).values\n unique_samples = []\n unique_count = np.zeros_like(df_test)\n for feature in tqdm(range(df_test.shape[1])):\n _, index_, count_ = np.unique(df_test[:, feature], return_counts=\n True, return_index=True)\n unique_count[index_[count_ == 1], feature] += 1\n idx_score = np.argwhere(np.sum(unique_count, axis=1) > 0)[:, 0]\n idx_synthetic = np.argwhere(np.sum(unique_count, axis=1) == 0)[:, 0]\n synthetic = test.loc[idx_synthetic]\n test = test.loc[idx_score]\n raw = pd.concat([train, test], axis=0, sort=False, ignore_index=True)\n len_train = len(train)\n col_var = list(raw.columns[2:])\n mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)\n for col in tqdm(col_var):\n cnt = raw[col].value_counts()\n val = cnt[cnt == 1].index\n mask.loc[np.isin(raw[col], val), col] = 0\n col_repeat = [(col + '_repeat_2') for col in col_var]\n raw[col_repeat] = raw[col_var][mask.astype(bool)]\n mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)\n for col in tqdm(col_var):\n cnt = raw[col].value_counts()\n val = cnt[np.isin(cnt, [1, 2])].index\n mask.loc[np.isin(raw[col], val), col] = 0\n col_repeat = [(col + '_repeat_3') for col in col_var]\n raw[col_repeat] = raw[col_var][mask.astype(bool)]\n raw = pd.concat([raw, synthetic], axis=0, sort=False, ignore_index=True)\n print('data: {}'.format(raw.shape))\n print('elapsed time: {:.1f} min'.format((time.time() - start) / 60))\n feats = [col for col in raw.columns.values if col not in ['ID_code',\n 'target']]\n train = raw[:len_train]\n test = raw[len_train:].copy()\n x_train = train[feats]\n y_train = train['target']\n x_test = test[feats]\n print('trn_x: {}'.format(x_train.shape))\n print('x_test: {}'.format(x_test.shape))\n param = {'objective': 'binary', 'boosting': 'gbdt', 'metric': 'auc',\n 'verbosity': -1, 'n_jobs': 11, 'random_state': 1993,\n 'learning_rate': 0.01, 'num_leaves': 8, 'max_depth': -1,\n 'feature_fraction': 0.05, 'bagging_freq': 5, 'bagging_fraction': \n 0.4, 'min_data_in_leaf': 80, 'min_sum_hessian_in_leaf': 10.0}\n print('model params:\\n{}'.format(pd.Series(list(param.values()), index=\n list(param.keys()))))\n seed_fold = 26\n folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed_fold)\n print('StratifiedKFold seed: {}'.format(seed_fold))\n round_max = 30000\n round_early_stopping = 3000\n print('num_round: {}'.format(round_max))\n print('early_stopping_round: {}'.format(round_early_stopping))\n oof = np.zeros(len(x_train))\n predictions = np.zeros(len(x_test))\n start = time.time()\n for fold_, (trn_idx, val_idx) in enumerate(folds.split(x_train.values,\n y_train.values)):\n print('fold n°{}'.format(fold_))\n trn_x, trn_y = x_train.iloc[trn_idx], y_train.iloc[trn_idx]\n val_x, val_y = x_train.iloc[val_idx], y_train.iloc[val_idx]\n N = 5\n for i in range(N):\n X_t, y_t = augment(trn_x.values, trn_y.values)\n X_t = pd.DataFrame(X_t, columns=feats)\n trn_data = lgb.Dataset(X_t, label=y_t)\n val_data = lgb.Dataset(val_x, label=val_y)\n evals_result = {}\n clf = lgb.train(param, trn_data, round_max, valid_sets=[\n trn_data, val_data], early_stopping_rounds=\n round_early_stopping, verbose_eval=1000, evals_result=\n evals_result)\n oof[val_idx] += clf.predict(val_x, num_iteration=clf.best_iteration\n ) / N\n predictions += clf.predict(x_test, num_iteration=clf.best_iteration\n ) / folds.n_splits / N\n fold_score = roc_auc_score(val_y, oof[val_idx])\n print('fold {} auc score: {:.5f}'.format(fold_, fold_score))\n cv_score = roc_auc_score(y_train, oof)\n print('elapsed time: {:.1f} min'.format((time.time() - start) / 60))\n print('auc score: {:.5f}'.format(cv_score))\n sub_folder = path.join(top_folder, 'cv_' + now + '_' + str(np.round(\n cv_score, 5)))\n makedirs(sub_folder, exist_ok=True)\n test['target'] = predictions\n test[['ID_code', 'target']].to_csv(path.join(sub_folder,\n 'submission.csv'), index=False)\n raw['oof'] = np.concatenate([oof, predictions], axis=0)\n raw[['ID_code', 'oof']].to_csv(path.join(sub_folder, 'oof.csv'), index=\n False)\n",
"step-5": "import gc\r\nimport sys\r\nimport time\r\nimport warnings\r\nimport multiprocessing\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport lightgbm as lgb\r\n\r\nfrom os import path, makedirs\r\nfrom tqdm import tqdm\r\nfrom utils import Logger\r\nfrom datetime import datetime\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.model_selection import StratifiedKFold\r\n\r\n\r\n# ======================================================================= Method\r\ndef load_dataframe(dataset):\r\n return pd.read_csv(dataset)\r\n\r\n\r\ndef augment(x, y, t=2):\r\n xs, xn = [], []\r\n for i in range(t):\r\n mask = y > 0\r\n x1 = x[mask].copy()\r\n for c in range(200):\r\n val = x1[:, [c, c+200, c+400]]\r\n np.random.shuffle(val)\r\n x1[:, [c, c+200, c+400]] = val\r\n xs.append(x1)\r\n\r\n for i in range(t//2):\r\n mask = y == 0\r\n x1 = x[mask].copy()\r\n for c in range(200):\r\n val = x1[:, [c, c+200, c+400]]\r\n np.random.shuffle(val)\r\n x1[:, [c, c+200, c+400]] = val\r\n xn.append(x1)\r\n\r\n xs = np.vstack(xs)\r\n xn = np.vstack(xn)\r\n ys = np.ones(xs.shape[0])\r\n yn = np.zeros(xn.shape[0])\r\n x = np.vstack([x, xs, xn])\r\n y = np.concatenate([y, ys, yn])\r\n return x, y\r\n\r\n\r\n# ======================================================================= Main\r\nif __name__ == '__main__':\r\n gc.enable()\r\n pd.set_option('max_rows', None)\r\n pd.set_option('max_columns', None)\r\n warnings.simplefilter('ignore', UserWarning)\r\n\r\n # =================================================================== Params\r\n top_folder = './output'\r\n\r\n today = datetime.today()\r\n now = today.strftime('%m%d-%H%M')\r\n log_name = now + '.txt'\r\n sys.stdout = Logger(path.join(top_folder, log_name))\r\n\r\n seed_np = 1011\r\n np.random.seed(seed_np)\r\n print('numpy seed: {}'.format(seed_np))\r\n\r\n # =================================================================== Load Data\r\n start = time.time()\r\n with multiprocessing.Pool() as pool:\r\n train, test = pool.map(load_dataframe, ['./input/train.csv', './input/test.csv'])\r\n\r\n # === fake sample\r\n df_test = test.drop(columns=['ID_code']).values\r\n\r\n unique_samples = []\r\n unique_count = np.zeros_like(df_test)\r\n for feature in tqdm(range(df_test.shape[1])):\r\n _, index_, count_ = np.unique(df_test[:, feature], return_counts=True, return_index=True)\r\n unique_count[index_[count_ == 1], feature] += 1\r\n\r\n idx_score = np.argwhere(np.sum(unique_count, axis=1) > 0)[:, 0]\r\n idx_synthetic = np.argwhere(np.sum(unique_count, axis=1) == 0)[:, 0]\r\n\r\n synthetic = test.loc[idx_synthetic]\r\n test = test.loc[idx_score]\r\n\r\n raw = pd.concat([train, test], axis=0, sort=False, ignore_index=True)\r\n\r\n # ============================== Extra Feature\r\n len_train = len(train)\r\n col_var = list(raw.columns[2:])\r\n\r\n # === replace value(frequency=1) to NA\r\n mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)\r\n for col in tqdm(col_var):\r\n cnt = raw[col].value_counts()\r\n val = cnt[cnt == 1].index\r\n mask.loc[np.isin(raw[col], val), col] = 0\r\n col_repeat = [col + '_repeat_2' for col in col_var]\r\n raw[col_repeat] = raw[col_var][mask.astype(bool)]\r\n\r\n # === replace value(frequency=1/2) to NA\r\n mask = pd.DataFrame(np.ones([raw.shape[0], len(col_var)]), columns=col_var)\r\n for col in tqdm(col_var):\r\n cnt = raw[col].value_counts()\r\n val = cnt[np.isin(cnt, [1, 2])].index\r\n mask.loc[np.isin(raw[col], val), col] = 0\r\n col_repeat = [col + '_repeat_3' for col in col_var]\r\n raw[col_repeat] = raw[col_var][mask.astype(bool)]\r\n\r\n raw = pd.concat([raw, synthetic], axis=0, sort=False, ignore_index=True)\r\n\r\n # === logging\r\n print('data: {}'.format(raw.shape))\r\n print('elapsed time: {:.1f} min'.format((time.time() - start)/60))\r\n\r\n # =================================================================== PreProcess\r\n feats = [col for col in raw.columns.values if col not in ['ID_code', 'target']]\r\n\r\n # =================================================================== Model\r\n train = raw[:len_train]\r\n test = raw[len_train:].copy()\r\n\r\n x_train = train[feats]\r\n y_train = train['target']\r\n x_test = test[feats]\r\n\r\n print('trn_x: {}'.format(x_train.shape))\r\n print('x_test: {}'.format(x_test.shape))\r\n\r\n param = {\r\n 'objective': 'binary',\r\n 'boosting': 'gbdt',\r\n 'metric': 'auc',\r\n 'verbosity': -1,\r\n 'n_jobs': 11,\r\n 'random_state': 1993,\r\n 'learning_rate': 0.01,\r\n\r\n 'num_leaves': 8,\r\n 'max_depth': -1,\r\n 'feature_fraction': 0.05,\r\n 'bagging_freq': 5,\r\n 'bagging_fraction': 0.4,\r\n 'min_data_in_leaf': 80,\r\n 'min_sum_hessian_in_leaf': 10.0,\r\n }\r\n print('model params:\\n{}'.format(pd.Series(list(param.values()), index=list(param.keys()))))\r\n\r\n seed_fold = 26\r\n folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed_fold)\r\n print('StratifiedKFold seed: {}'.format(seed_fold))\r\n\r\n round_max = 30000\r\n round_early_stopping = 3000\r\n print('num_round: {}'.format(round_max))\r\n print('early_stopping_round: {}'.format(round_early_stopping))\r\n\r\n # === training\r\n oof = np.zeros(len(x_train))\r\n predictions = np.zeros(len(x_test))\r\n\r\n start = time.time()\r\n for fold_, (trn_idx, val_idx) in enumerate(folds.split(x_train.values, y_train.values)):\r\n print(\"fold n°{}\".format(fold_))\r\n\r\n trn_x, trn_y = x_train.iloc[trn_idx], y_train.iloc[trn_idx]\r\n val_x, val_y = x_train.iloc[val_idx], y_train.iloc[val_idx]\r\n\r\n N = 5\r\n for i in range(N):\r\n X_t, y_t = augment(trn_x.values, trn_y.values)\r\n X_t = pd.DataFrame(X_t, columns=feats)\r\n\r\n trn_data = lgb.Dataset(X_t, label=y_t)\r\n val_data = lgb.Dataset(val_x, label=val_y)\r\n\r\n evals_result = {}\r\n clf = lgb.train(param,\r\n trn_data,\r\n round_max,\r\n valid_sets=[trn_data, val_data],\r\n early_stopping_rounds=round_early_stopping,\r\n verbose_eval=1000,\r\n evals_result=evals_result)\r\n\r\n oof[val_idx] += clf.predict(val_x, num_iteration=clf.best_iteration) / N\r\n predictions += clf.predict(x_test, num_iteration=clf.best_iteration) / folds.n_splits / N\r\n\r\n fold_score = roc_auc_score(val_y, oof[val_idx])\r\n print('fold {} auc score: {:.5f}'.format(fold_, fold_score))\r\n\r\n cv_score = roc_auc_score(y_train, oof)\r\n print('elapsed time: {:.1f} min'.format((time.time() - start)/60))\r\n print('auc score: {:.5f}'.format(cv_score))\r\n\r\n # =================================================================== Saving File\r\n sub_folder = path.join(top_folder, 'cv_' + now + '_' + str(np.round(cv_score, 5)))\r\n makedirs(sub_folder, exist_ok=True)\r\n\r\n test['target'] = predictions\r\n test[['ID_code', 'target']].to_csv(path.join(sub_folder, 'submission.csv'), index=False)\r\n\r\n raw['oof'] = np.concatenate([oof, predictions], axis=0)\r\n raw[['ID_code', 'oof']].to_csv(path.join(sub_folder, 'oof.csv'), index=False)\r\n\r\n\r\n\r\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
yuki = list(map(int, input().split()))
S = input()
enemy = [S.count('G'), S.count('C'), S.count('P')]
ans = 0
for i in range(3):
ans += min(yuki[i], enemy[(i + 1) % 3]) * 3
yuki[i], enemy[(i + 1) % 3] = max(0, yuki[i] - enemy[(i + 1) % 3]), max(
0, enemy[(i + 1) % 3] - yuki[i])
for i in range(3):
ans += min(yuki[i], enemy[i])
print(ans)
|
normal
|
{
"blob_id": "ce98c13555c474de0a9cb12e99a97b2316312b00",
"index": 979,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(3):\n ans += min(yuki[i], enemy[(i + 1) % 3]) * 3\n yuki[i], enemy[(i + 1) % 3] = max(0, yuki[i] - enemy[(i + 1) % 3]), max(\n 0, enemy[(i + 1) % 3] - yuki[i])\nfor i in range(3):\n ans += min(yuki[i], enemy[i])\nprint(ans)\n",
"step-3": "yuki = list(map(int, input().split()))\nS = input()\nenemy = [S.count('G'), S.count('C'), S.count('P')]\nans = 0\nfor i in range(3):\n ans += min(yuki[i], enemy[(i + 1) % 3]) * 3\n yuki[i], enemy[(i + 1) % 3] = max(0, yuki[i] - enemy[(i + 1) % 3]), max(\n 0, enemy[(i + 1) % 3] - yuki[i])\nfor i in range(3):\n ans += min(yuki[i], enemy[i])\nprint(ans)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def main():
grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0,
0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0,
0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0,
0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = 0, 0
end = 8, 9
path = astar(grid, start, end)
print(path)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def main():
grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0,
0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0,
0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0,
0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = 0, 0
end = 8, 9
path = astar(grid, start, end)
print(path)
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
from AStar import astar
def main():
grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0,
0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0,
0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0,
0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = 0, 0
end = 8, 9
path = astar(grid, start, end)
print(path)
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
from AStar import astar
def main():
grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = (0, 0)
end = (8, 9)
path = astar(grid, start, end)
print(path)
if __name__ == '__main__':
main()
|
flexible
|
{
"blob_id": "ba483c7eaf2f2ced7f70a14b53c781f190585024",
"index": 1257,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0,\n 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, \n 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, \n 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n start = 0, 0\n end = 8, 9\n path = astar(grid, start, end)\n print(path)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef main():\n grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0,\n 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, \n 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, \n 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n start = 0, 0\n end = 8, 9\n path = astar(grid, start, end)\n print(path)\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "from AStar import astar\n\n\ndef main():\n grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0,\n 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, \n 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, \n 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n start = 0, 0\n end = 8, 9\n path = astar(grid, start, end)\n print(path)\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "from AStar import astar\n\n\ndef main():\n grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n\n start = (0, 0)\n end = (8, 9)\n\n path = astar(grid, start, end)\n print(path)\n\n\nif __name__ == '__main__':\n main()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import nltk
from nltk import bigrams
from lm import *
# Oppgave 1:
# opretter LM klasse til aa perpleksitere news og adventure
m = LM()
# Henter news og adventure for videre bruk
news=nltk.corpus.brown.sents(categories='news')
adventure=nltk.corpus.brown.sents(categories='adventure')
# initial parametre
perpNews = 0.0
perpAdventure = 0.0
# beregner perplexitet:
perpNews = m.perplexity(news)
perpAdventure = m.perplexity(adventure)
# printer ut perplexitet.
print("Perpleksitet til news: %.2f" %perpNews)
print("Perpleksitet til adventure: %.2f" %perpAdventure)
""" Oppgave 1 - evaluering av spraakmodeller
$ python oblig2b_steinrr.py
Perpleksitet til news: 72.69
Perpleksitet til adventure: 117.41
Perpleksiteten tiil adventure er hoeyeere fordi klassifikatoren vi benytter i LM er ikke trent paa dette korpuset.
Perpleksiteten til news ville ha veart lavere hvis klassifikatoren vi benytter hadde bare veart trent paa news.
Men dette er ikke bra pga da ville perpleksiteten til adventure veare enda hoyere enn den er naa.
"""
zippy = m.zipfity(news)
for sekvens in zippy:
print("Ord: %4s Antall: %4d Sekvens: %.4f " %(sekvens[0], sekvens[1], sekvens[2]))
""" Oppgave 2 - Zipfianske distribusjon
Ord: the Antall: 6386 Sekvens: 6386.0000
Ord: , Antall: 5188 Sekvens: 2594.0000
Ord: . Antall: 4030 Sekvens: 1343.3333
Ord: of Antall: 2861 Sekvens: 715.2500
Ord: and Antall: 2186 Sekvens: 437.2000
Ord: to Antall: 2144 Sekvens: 357.3333
Ord: a Antall: 2130 Sekvens: 304.2857
Ord: in Antall: 2020 Sekvens: 252.5000
Ord: for Antall: 969 Sekvens: 107.6667
Ord: that Antall: 829 Sekvens: 82.9000
"""
brown_tagged_sents = nltk.corpus.brown.tagged_sents(categories='adventure')
adventure = [[w.lower() for w in line] for line in nltk.corpus.brown.sents(categories='adventure')]
#m.regularTagger(adventure)
checkTaggStandardAdv = m.analyseRegularTagger('adventure')
checkTaggStandardFic = m.analyseRegularTagger('fiction')
checkTaggModifiedAdv = m.analyseRegularTagger('adventure', 'modified')
checkTaggModifiedFic = m.analyseRegularTagger('fiction', 'modified')
print("Standard vs modifisert tagging ved hjelp av reguleart uttrykk")
print("Med corpus: 'adventure'")
print(" Standard: %4.2f Modifisert: %4.2f " %(checkTaggStandardFic, checkTaggModifiedAdv))
print("Med corpus: 'fiction'")
print(" Standard: %4.2f Modifisert: %4.2f " %(checkTaggStandardFic, checkTaggModifiedFic))
infile = open("test_setninger.txt")
tekst = []
for line in infile:
words = line.split(" ")
tekst.append(words)
infile.close()
# fikser at alle ord har smaa bokstaver:
tekst = [[w.lower() for w in line] for line in tekst]
taggerTekst = m.regularTagger(tekst, 'modified')
for sentence in taggerTekst:
for taggs in sentence:
print(taggs)
""" Oppgave 3 - Ordklassetagging med regulære uttrykk
Standard vs modifisert tagging ved hjelp av reguleart uttrykk
Med corpus: 'adventure'
Standard: 0.18 Modifisert: 0.41
Med corpus: 'fiction'
Standard: 0.18 Modifisert: 0.40
...
..
... skriver ut tagger som blir kopiert inn til test_setninger_m_taggs.txt
..
Kommentarer for ytterligere forbedrelser:
1. said skulle ha veart kattegorisert som verb: VBD
2. he burde veare et pronom
3. had burde veare et verb til have
oppdatere reguleare utrykk:
1 og 3: (r'(.*ed|.*id|had)$', 'VBD')
2. regler for pronoum har jeg ikke lagt inn i det hele tatt saa dette er noe som
kan tilfoeres
"""
|
normal
|
{
"blob_id": "d268f8d563aac28852457f6f130b2fb4ea6269a2",
"index": 907,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Perpleksitet til news: %.2f' % perpNews)\nprint('Perpleksitet til adventure: %.2f' % perpAdventure)\n<mask token>\nfor sekvens in zippy:\n print('Ord: %4s Antall: %4d Sekvens: %.4f ' % (sekvens[0], sekvens[1],\n sekvens[2]))\n<mask token>\nprint('Standard vs modifisert tagging ved hjelp av reguleart uttrykk')\nprint(\"Med corpus: 'adventure'\")\nprint(' Standard: %4.2f Modifisert: %4.2f ' % (checkTaggStandardFic,\n checkTaggModifiedAdv))\nprint(\"Med corpus: 'fiction'\")\nprint(' Standard: %4.2f Modifisert: %4.2f ' % (checkTaggStandardFic,\n checkTaggModifiedFic))\n<mask token>\nfor line in infile:\n words = line.split(' ')\n tekst.append(words)\ninfile.close()\n<mask token>\nfor sentence in taggerTekst:\n for taggs in sentence:\n print(taggs)\n<mask token>\n",
"step-3": "<mask token>\nm = LM()\nnews = nltk.corpus.brown.sents(categories='news')\nadventure = nltk.corpus.brown.sents(categories='adventure')\nperpNews = 0.0\nperpAdventure = 0.0\nperpNews = m.perplexity(news)\nperpAdventure = m.perplexity(adventure)\nprint('Perpleksitet til news: %.2f' % perpNews)\nprint('Perpleksitet til adventure: %.2f' % perpAdventure)\n<mask token>\nzippy = m.zipfity(news)\nfor sekvens in zippy:\n print('Ord: %4s Antall: %4d Sekvens: %.4f ' % (sekvens[0], sekvens[1],\n sekvens[2]))\n<mask token>\nbrown_tagged_sents = nltk.corpus.brown.tagged_sents(categories='adventure')\nadventure = [[w.lower() for w in line] for line in nltk.corpus.brown.sents(\n categories='adventure')]\ncheckTaggStandardAdv = m.analyseRegularTagger('adventure')\ncheckTaggStandardFic = m.analyseRegularTagger('fiction')\ncheckTaggModifiedAdv = m.analyseRegularTagger('adventure', 'modified')\ncheckTaggModifiedFic = m.analyseRegularTagger('fiction', 'modified')\nprint('Standard vs modifisert tagging ved hjelp av reguleart uttrykk')\nprint(\"Med corpus: 'adventure'\")\nprint(' Standard: %4.2f Modifisert: %4.2f ' % (checkTaggStandardFic,\n checkTaggModifiedAdv))\nprint(\"Med corpus: 'fiction'\")\nprint(' Standard: %4.2f Modifisert: %4.2f ' % (checkTaggStandardFic,\n checkTaggModifiedFic))\ninfile = open('test_setninger.txt')\ntekst = []\nfor line in infile:\n words = line.split(' ')\n tekst.append(words)\ninfile.close()\ntekst = [[w.lower() for w in line] for line in tekst]\ntaggerTekst = m.regularTagger(tekst, 'modified')\nfor sentence in taggerTekst:\n for taggs in sentence:\n print(taggs)\n<mask token>\n",
"step-4": "import nltk\nfrom nltk import bigrams\nfrom lm import *\nm = LM()\nnews = nltk.corpus.brown.sents(categories='news')\nadventure = nltk.corpus.brown.sents(categories='adventure')\nperpNews = 0.0\nperpAdventure = 0.0\nperpNews = m.perplexity(news)\nperpAdventure = m.perplexity(adventure)\nprint('Perpleksitet til news: %.2f' % perpNews)\nprint('Perpleksitet til adventure: %.2f' % perpAdventure)\n<mask token>\nzippy = m.zipfity(news)\nfor sekvens in zippy:\n print('Ord: %4s Antall: %4d Sekvens: %.4f ' % (sekvens[0], sekvens[1],\n sekvens[2]))\n<mask token>\nbrown_tagged_sents = nltk.corpus.brown.tagged_sents(categories='adventure')\nadventure = [[w.lower() for w in line] for line in nltk.corpus.brown.sents(\n categories='adventure')]\ncheckTaggStandardAdv = m.analyseRegularTagger('adventure')\ncheckTaggStandardFic = m.analyseRegularTagger('fiction')\ncheckTaggModifiedAdv = m.analyseRegularTagger('adventure', 'modified')\ncheckTaggModifiedFic = m.analyseRegularTagger('fiction', 'modified')\nprint('Standard vs modifisert tagging ved hjelp av reguleart uttrykk')\nprint(\"Med corpus: 'adventure'\")\nprint(' Standard: %4.2f Modifisert: %4.2f ' % (checkTaggStandardFic,\n checkTaggModifiedAdv))\nprint(\"Med corpus: 'fiction'\")\nprint(' Standard: %4.2f Modifisert: %4.2f ' % (checkTaggStandardFic,\n checkTaggModifiedFic))\ninfile = open('test_setninger.txt')\ntekst = []\nfor line in infile:\n words = line.split(' ')\n tekst.append(words)\ninfile.close()\ntekst = [[w.lower() for w in line] for line in tekst]\ntaggerTekst = m.regularTagger(tekst, 'modified')\nfor sentence in taggerTekst:\n for taggs in sentence:\n print(taggs)\n<mask token>\n",
"step-5": "import nltk\nfrom nltk import bigrams\nfrom lm import *\n\n# Oppgave 1:\n# opretter LM klasse til aa perpleksitere news og adventure\nm = LM()\n\n# Henter news og adventure for videre bruk\nnews=nltk.corpus.brown.sents(categories='news')\nadventure=nltk.corpus.brown.sents(categories='adventure')\n\n# initial parametre\nperpNews = 0.0\nperpAdventure = 0.0\n\n# beregner perplexitet:\nperpNews = m.perplexity(news)\nperpAdventure = m.perplexity(adventure)\n\n# printer ut perplexitet.\nprint(\"Perpleksitet til news: %.2f\" %perpNews)\nprint(\"Perpleksitet til adventure: %.2f\" %perpAdventure)\n\n\n\"\"\" Oppgave 1 - evaluering av spraakmodeller\n\n$ python oblig2b_steinrr.py\nPerpleksitet til news: 72.69\nPerpleksitet til adventure: 117.41\n\n\nPerpleksiteten tiil adventure er hoeyeere fordi klassifikatoren vi benytter i LM er ikke trent paa dette korpuset.\nPerpleksiteten til news ville ha veart lavere hvis klassifikatoren vi benytter hadde bare veart trent paa news.\nMen dette er ikke bra pga da ville perpleksiteten til adventure veare enda hoyere enn den er naa.\n\n\"\"\"\n\nzippy = m.zipfity(news)\n\nfor sekvens in zippy:\n print(\"Ord: %4s Antall: %4d Sekvens: %.4f \" %(sekvens[0], sekvens[1], sekvens[2]))\n\n\"\"\" Oppgave 2 - Zipfianske distribusjon\n \nOrd: the Antall: 6386 Sekvens: 6386.0000 \nOrd: , Antall: 5188 Sekvens: 2594.0000 \nOrd: . Antall: 4030 Sekvens: 1343.3333 \nOrd: of Antall: 2861 Sekvens: 715.2500 \nOrd: and Antall: 2186 Sekvens: 437.2000 \nOrd: to Antall: 2144 Sekvens: 357.3333 \nOrd: a Antall: 2130 Sekvens: 304.2857 \nOrd: in Antall: 2020 Sekvens: 252.5000 \nOrd: for Antall: 969 Sekvens: 107.6667 \nOrd: that Antall: 829 Sekvens: 82.9000 \n\n\"\"\"\n\nbrown_tagged_sents = nltk.corpus.brown.tagged_sents(categories='adventure')\nadventure = [[w.lower() for w in line] for line in nltk.corpus.brown.sents(categories='adventure')]\n\n#m.regularTagger(adventure)\ncheckTaggStandardAdv = m.analyseRegularTagger('adventure')\ncheckTaggStandardFic = m.analyseRegularTagger('fiction')\ncheckTaggModifiedAdv = m.analyseRegularTagger('adventure', 'modified')\ncheckTaggModifiedFic = m.analyseRegularTagger('fiction', 'modified')\n\nprint(\"Standard vs modifisert tagging ved hjelp av reguleart uttrykk\")\nprint(\"Med corpus: 'adventure'\")\nprint(\" Standard: %4.2f Modifisert: %4.2f \" %(checkTaggStandardFic, checkTaggModifiedAdv))\nprint(\"Med corpus: 'fiction'\")\nprint(\" Standard: %4.2f Modifisert: %4.2f \" %(checkTaggStandardFic, checkTaggModifiedFic))\n\ninfile = open(\"test_setninger.txt\")\ntekst = []\n\nfor line in infile:\n words = line.split(\" \")\n tekst.append(words)\ninfile.close()\n\n# fikser at alle ord har smaa bokstaver:\ntekst = [[w.lower() for w in line] for line in tekst]\n\ntaggerTekst = m.regularTagger(tekst, 'modified')\n\nfor sentence in taggerTekst:\n for taggs in sentence:\n print(taggs)\n\n\"\"\" Oppgave 3 - Ordklassetagging med regulære uttrykk\nStandard vs modifisert tagging ved hjelp av reguleart uttrykk\nMed corpus: 'adventure'\n Standard: 0.18 Modifisert: 0.41 \nMed corpus: 'fiction'\n Standard: 0.18 Modifisert: 0.40 \n...\n..\n... skriver ut tagger som blir kopiert inn til test_setninger_m_taggs.txt\n..\n\nKommentarer for ytterligere forbedrelser:\n1. said skulle ha veart kattegorisert som verb: VBD\n2. he burde veare et pronom\n3. had burde veare et verb til have\n\noppdatere reguleare utrykk:\n1 og 3: (r'(.*ed|.*id|had)$', 'VBD')\n\n2. regler for pronoum har jeg ikke lagt inn i det hele tatt saa dette er noe som\nkan tilfoeres\n\"\"\"\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print(float(num1) + float(num2))
<|reserved_special_token_0|>
print(num1 + num2)
<|reserved_special_token_1|>
num1 = input('첫 번째 실수 : ')
num2 = input('두 번째 실수 : ')
print(float(num1) + float(num2))
num1 = float(input('첫 번째 실수 : '))
num2 = float(input('두 번째 실수 : '))
print(num1 + num2)
<|reserved_special_token_1|>
num1 = input("첫 번째 실수 : ")
num2 = input("두 번째 실수 : ")
print(float(num1) + float(num2))
num1 = float(input("첫 번째 실수 : "))
num2 = float(input("두 번째 실수 : "))
print(num1 + num2)
|
flexible
|
{
"blob_id": "ee8bf681adcb07c4f79245c8f118131bbcabd2fa",
"index": 7920,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(float(num1) + float(num2))\n<mask token>\nprint(num1 + num2)\n",
"step-3": "num1 = input('첫 번째 실수 : ')\nnum2 = input('두 번째 실수 : ')\nprint(float(num1) + float(num2))\nnum1 = float(input('첫 번째 실수 : '))\nnum2 = float(input('두 번째 실수 : '))\nprint(num1 + num2)\n",
"step-4": "num1 = input(\"첫 번째 실수 : \")\r\nnum2 = input(\"두 번째 실수 : \")\r\n\r\nprint(float(num1) + float(num2))\r\n\r\nnum1 = float(input(\"첫 번째 실수 : \"))\r\nnum2 = float(input(\"두 번째 실수 : \"))\r\n\r\nprint(num1 + num2)\r\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class CvPTestCase(unittest.TestCase):
def onecompplayer_setup(self):
game1 = TicTacToe.Game()
computer1 = TicTacToe.Computer('X', game1)
player2 = TicTacToe.Player('O', game1)
return game1, computer1, player2
def test_place3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_place2(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): 'X', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)
def test_place8(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): 'X', (8): '-', (9): 'X'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',
(6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)
def test_block5(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_block7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):
'O', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',
(6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_block3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',
(6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_center_empty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_center_nonempty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):
'-', (6): 'O', (7): 'X', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',
(6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
<|reserved_special_token_0|>
def test_oppcorner1(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_oppcorner3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): 'O', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',
(6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner9(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class pVpTestCase(unittest.TestCase):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class CvPTestCase(unittest.TestCase):
def onecompplayer_setup(self):
game1 = TicTacToe.Game()
computer1 = TicTacToe.Computer('X', game1)
player2 = TicTacToe.Player('O', game1)
return game1, computer1, player2
def test_place3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_place2(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): 'X', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)
def test_place8(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): 'X', (8): '-', (9): 'X'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',
(6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)
def test_block5(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_block7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):
'O', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',
(6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_block3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',
(6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_center_empty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_center_nonempty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):
'-', (6): 'O', (7): 'X', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',
(6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):
'X', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'X',
(6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner1(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_oppcorner3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): 'O', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',
(6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner9(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class pVpTestCase(unittest.TestCase):
<|reserved_special_token_0|>
def test_mock_game1(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top left', 'middle', 'bottom right']
p2moves = ['top middle', 'bottom left', 'top right']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(player1, winner)
def test_mock_game2(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top right', 'middle', 'bottom right']
p2moves = ['top left', 'middle left', 'bottom left']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(player2, winner)
<|reserved_special_token_0|>
class CvPTestCase(unittest.TestCase):
def onecompplayer_setup(self):
game1 = TicTacToe.Game()
computer1 = TicTacToe.Computer('X', game1)
player2 = TicTacToe.Player('O', game1)
return game1, computer1, player2
def test_place3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_place2(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): 'X', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)
def test_place8(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): 'X', (8): '-', (9): 'X'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',
(6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)
def test_block5(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_block7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):
'O', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',
(6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_block3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',
(6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_center_empty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_center_nonempty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):
'-', (6): 'O', (7): 'X', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',
(6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):
'X', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'X',
(6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner1(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_oppcorner3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): 'O', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',
(6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner9(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class pVpTestCase(unittest.TestCase):
def twoplayer_setup(self):
game1 = TicTacToe.Game()
player1 = TicTacToe.Player('X', game1)
player2 = TicTacToe.Player('O', game1)
return game1, player1, player2
def test_mock_game1(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top left', 'middle', 'bottom right']
p2moves = ['top middle', 'bottom left', 'top right']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(player1, winner)
def test_mock_game2(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top right', 'middle', 'bottom right']
p2moves = ['top left', 'middle left', 'bottom left']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(player2, winner)
def test_mock_game3(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top right', 'middle top', 'middle', 'bottom right',
'middle left']
p2moves = ['top left', 'middle right', 'bottom left', 'bottom middle']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(None, winner)
class CvPTestCase(unittest.TestCase):
def onecompplayer_setup(self):
game1 = TicTacToe.Game()
computer1 = TicTacToe.Computer('X', game1)
player2 = TicTacToe.Player('O', game1)
return game1, computer1, player2
def test_place3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_place2(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): 'X', (9): '-'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)
def test_place8(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): 'X', (8): '-', (9): 'X'}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',
(6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)
def test_block5(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_block7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):
'O', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',
(6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_block3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): 'O', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',
(6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_center_empty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'-', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)
def test_center_nonempty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):
'-', (6): 'O', (7): 'X', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',
(6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):
'X', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'X',
(6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner1(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):
'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}
computer1.auto_move()
self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',
(6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)
def test_oppcorner3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): 'O', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',
(6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)
def test_oppcorner9(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):
'X', (6): '-', (7): '-', (8): '-', (9): '-'}
computer1.auto_move()
self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',
(6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)
if __name__ == '__main__':
unittest.main()
<|reserved_special_token_1|>
import unittest
import TicTacToe
class pVpTestCase(unittest.TestCase):
# def test_something(self):
# self.assertEqual(True, False)
def twoplayer_setup(self):
game1 = TicTacToe.Game()
player1 = TicTacToe.Player('X', game1)
player2 = TicTacToe.Player('O', game1)
return (game1, player1, player2)
#Player 1 wins
def test_mock_game1(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top left', 'middle', 'bottom right']
p2moves = ['top middle', 'bottom left', 'top right']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(player1, winner)
#Player 2 wins
def test_mock_game2(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top right', 'middle', 'bottom right']
p2moves = ['top left', 'middle left', 'bottom left']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(player2, winner)
#Draw
def test_mock_game3(self):
game1, player1, player2 = self.twoplayer_setup()
p1moves = ['top right', 'middle top', 'middle', 'bottom right', 'middle left']
p2moves = ['top left', 'middle right', 'bottom left', 'bottom middle']
winner = game1.play_test(player1, player2, p1moves, p2moves)
self.assertEqual(None, winner)
class CvPTestCase(unittest.TestCase):
def onecompplayer_setup(self):
game1 = TicTacToe.Game()
computer1 = TicTacToe.Computer('X', game1)
player2 = TicTacToe.Player('O', game1)
return (game1, computer1, player2)
def test_place3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1:"X", 2:"X",3:"-",
4:"-", 5:"-", 6:"-",
7:"-", 8:"-", 9:"-"}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({1:"X", 2:"X",3:"X",
4:"-", 5:"-", 6:"-",
7:"-", 8:"-", 9:"-"},
game1.game_board
)
def test_place2(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1:"-", 2:"-",3:"-",
4:"-", 5:"X", 6:"-",
7:"-", 8:"X", 9:"-"}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({1:"-", 2:"X",3:"-",
4:"-", 5:"X", 6:"-",
7:"-", 8:"X", 9:"-"},
game1.game_board
)
def test_place8(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "-",
4: "-", 5: "-", 6: "-",
7: "X", 8: "-", 9: "X"}
p2moves = []
winner = game1.play_comp_test(computer1, player2, p2moves)
self.assertEqual(computer1, winner)
self.assertEqual({1: "-", 2: "-", 3: "-",
4: "-", 5: "-", 6: "-",
7: "X", 8: "X", 9: "X"},
game1.game_board
)
def test_block5(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "-",
4: "O", 5: "-", 6: "O",
7: "-", 8: "-", 9: "-"}
computer1.auto_move()
self.assertEqual({1: "-", 2: "-", 3: "-",
4: "O", 5: "X", 6: "O",
7: "-", 8: "-", 9: "-"},
game1.game_board
)
def test_block7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "O",
4: "-", 5: "O", 6: "-",
7: "-", 8: "-", 9: "-"}
computer1.auto_move()
self.assertEqual({1: "-", 2: "-", 3: "O",
4: "-", 5: "O", 6: "-",
7: "X", 8: "-", 9: "-"},
game1.game_board
)
def test_block3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "-",
4: "-", 5: "-", 6: "O",
7: "-", 8: "-", 9: "O"}
computer1.auto_move()
self.assertEqual({1: "-", 2: "-", 3: "X",
4: "-", 5: "-", 6: "O",
7: "-", 8: "-", 9: "O"},
game1.game_board
)
def test_center_empty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "-",
4: "-", 5: "-", 6: "-",
7: "-", 8: "-", 9: "-"}
computer1.auto_move()
self.assertEqual({1: "-", 2: "-", 3: "-",
4: "-", 5: "X", 6: "-",
7: "-", 8: "-", 9: "-"},
game1.game_board
)
def test_center_nonempty(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "O", 2: "-", 3: "-",
4: "X", 5: "-", 6: "O",
7: "X", 8: "-", 9: "-"}
computer1.auto_move()
self.assertEqual({1: "O", 2: "-", 3: "-",
4: "X", 5: "X", 6: "O",
7: "X", 8: "-", 9: "-"},
game1.game_board
)
def test_oppcorner7(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "O",
4: "-", 5: "X", 6: "-",
7: "-", 8: "-", 9: "-"}
computer1.auto_move()
self.assertEqual({1: "-", 2: "-", 3: "O",
4: "-", 5: "X", 6: "-",
7: "X", 8: "-", 9: "-"},
game1.game_board
)
def test_oppcorner1(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "-",
4: "O", 5: "X", 6: "X",
7: "-", 8: "-", 9: "O"}
computer1.auto_move()
self.assertEqual({1: "X", 2: "-", 3: "-",
4: "O", 5: "X", 6: "X",
7: "-", 8: "-", 9: "O"},
game1.game_board
)
def test_oppcorner3(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "-", 2: "-", 3: "-",
4: "-", 5: "X", 6: "-",
7: "O", 8: "-", 9: "-"}
computer1.auto_move()
self.assertEqual({1: "-", 2: "-", 3: "X",
4: "-", 5: "X", 6: "-",
7: "O", 8: "-", 9: "-"},
game1.game_board
)
def test_oppcorner9(self):
game1, computer1, player2 = self.onecompplayer_setup()
game1.game_board = {1: "O", 2: "-", 3: "-",
4: "-", 5: "X", 6: "-",
7: "-", 8: "-", 9: "-"}
computer1.auto_move()
self.assertEqual({1: "O", 2: "-", 3: "-",
4: "-", 5: "X", 6: "-",
7: "-", 8: "-", 9: "X"},
game1.game_board
)
if __name__ == '__main__':
unittest.main()
|
flexible
|
{
"blob_id": "de0521db3909054c333ac3877ff0adf15ab180fb",
"index": 1732,
"step-1": "<mask token>\n\n\nclass CvPTestCase(unittest.TestCase):\n\n def onecompplayer_setup(self):\n game1 = TicTacToe.Game()\n computer1 = TicTacToe.Computer('X', game1)\n player2 = TicTacToe.Player('O', game1)\n return game1, computer1, player2\n\n def test_place3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_place2(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): 'X', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)\n\n def test_place8(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): 'X', (8): '-', (9): 'X'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',\n (6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)\n\n def test_block5(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):\n 'O', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',\n (6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',\n (6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_center_empty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_center_nonempty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):\n '-', (6): 'O', (7): 'X', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',\n (6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n <mask token>\n\n def test_oppcorner1(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n 'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_oppcorner3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): 'O', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',\n (6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner9(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass pVpTestCase(unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass CvPTestCase(unittest.TestCase):\n\n def onecompplayer_setup(self):\n game1 = TicTacToe.Game()\n computer1 = TicTacToe.Computer('X', game1)\n player2 = TicTacToe.Player('O', game1)\n return game1, computer1, player2\n\n def test_place3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_place2(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): 'X', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)\n\n def test_place8(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): 'X', (8): '-', (9): 'X'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',\n (6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)\n\n def test_block5(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):\n 'O', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',\n (6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',\n (6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_center_empty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_center_nonempty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):\n '-', (6): 'O', (7): 'X', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',\n (6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'X',\n (6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner1(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n 'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_oppcorner3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): 'O', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',\n (6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner9(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass pVpTestCase(unittest.TestCase):\n <mask token>\n\n def test_mock_game1(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top left', 'middle', 'bottom right']\n p2moves = ['top middle', 'bottom left', 'top right']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(player1, winner)\n\n def test_mock_game2(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top right', 'middle', 'bottom right']\n p2moves = ['top left', 'middle left', 'bottom left']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(player2, winner)\n <mask token>\n\n\nclass CvPTestCase(unittest.TestCase):\n\n def onecompplayer_setup(self):\n game1 = TicTacToe.Game()\n computer1 = TicTacToe.Computer('X', game1)\n player2 = TicTacToe.Player('O', game1)\n return game1, computer1, player2\n\n def test_place3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_place2(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): 'X', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)\n\n def test_place8(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): 'X', (8): '-', (9): 'X'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',\n (6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)\n\n def test_block5(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):\n 'O', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',\n (6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',\n (6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_center_empty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_center_nonempty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):\n '-', (6): 'O', (7): 'X', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',\n (6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'X',\n (6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner1(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n 'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_oppcorner3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): 'O', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',\n (6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner9(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass pVpTestCase(unittest.TestCase):\n\n def twoplayer_setup(self):\n game1 = TicTacToe.Game()\n player1 = TicTacToe.Player('X', game1)\n player2 = TicTacToe.Player('O', game1)\n return game1, player1, player2\n\n def test_mock_game1(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top left', 'middle', 'bottom right']\n p2moves = ['top middle', 'bottom left', 'top right']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(player1, winner)\n\n def test_mock_game2(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top right', 'middle', 'bottom right']\n p2moves = ['top left', 'middle left', 'bottom left']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(player2, winner)\n\n def test_mock_game3(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top right', 'middle top', 'middle', 'bottom right',\n 'middle left']\n p2moves = ['top left', 'middle right', 'bottom left', 'bottom middle']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(None, winner)\n\n\nclass CvPTestCase(unittest.TestCase):\n\n def onecompplayer_setup(self):\n game1 = TicTacToe.Game()\n computer1 = TicTacToe.Computer('X', game1)\n player2 = TicTacToe.Player('O', game1)\n return game1, computer1, player2\n\n def test_place3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'X', (2): 'X', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): 'X', (2): 'X', (3): 'X', (4): '-', (5): '-',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_place2(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): 'X', (9): '-'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): 'X', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): 'X', (9): '-'}, game1.game_board)\n\n def test_place8(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): 'X', (8): '-', (9): 'X'}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): '-',\n (6): '-', (7): 'X', (8): 'X', (9): 'X'}, game1.game_board)\n\n def test_block5(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'O', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):\n 'O', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'O',\n (6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_block3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): 'O', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): '-',\n (6): 'O', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_center_empty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n '-', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): '-'}, game1.game_board)\n\n def test_center_nonempty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): 'X', (5):\n '-', (6): 'O', (7): 'X', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): 'X', (5): 'X',\n (6): 'O', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): 'O', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'O', (4): '-', (5): 'X',\n (6): '-', (7): 'X', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner1(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): 'O', (5):\n 'X', (6): 'X', (7): '-', (8): '-', (9): 'O'}\n computer1.auto_move()\n self.assertEqual({(1): 'X', (2): '-', (3): '-', (4): 'O', (5): 'X',\n (6): 'X', (7): '-', (8): '-', (9): 'O'}, game1.game_board)\n\n def test_oppcorner3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): '-', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): 'O', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): '-', (2): '-', (3): 'X', (4): '-', (5): 'X',\n (6): '-', (7): 'O', (8): '-', (9): '-'}, game1.game_board)\n\n def test_oppcorner9(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {(1): 'O', (2): '-', (3): '-', (4): '-', (5):\n 'X', (6): '-', (7): '-', (8): '-', (9): '-'}\n computer1.auto_move()\n self.assertEqual({(1): 'O', (2): '-', (3): '-', (4): '-', (5): 'X',\n (6): '-', (7): '-', (8): '-', (9): 'X'}, game1.game_board)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"step-5": "import unittest\nimport TicTacToe\n\nclass pVpTestCase(unittest.TestCase):\n # def test_something(self):\n # self.assertEqual(True, False)\n\n def twoplayer_setup(self):\n game1 = TicTacToe.Game()\n player1 = TicTacToe.Player('X', game1)\n player2 = TicTacToe.Player('O', game1)\n return (game1, player1, player2)\n\n #Player 1 wins\n def test_mock_game1(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top left', 'middle', 'bottom right']\n p2moves = ['top middle', 'bottom left', 'top right']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(player1, winner)\n\n #Player 2 wins\n def test_mock_game2(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top right', 'middle', 'bottom right']\n p2moves = ['top left', 'middle left', 'bottom left']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(player2, winner)\n\n #Draw\n def test_mock_game3(self):\n game1, player1, player2 = self.twoplayer_setup()\n p1moves = ['top right', 'middle top', 'middle', 'bottom right', 'middle left']\n p2moves = ['top left', 'middle right', 'bottom left', 'bottom middle']\n winner = game1.play_test(player1, player2, p1moves, p2moves)\n self.assertEqual(None, winner)\n\nclass CvPTestCase(unittest.TestCase):\n\n def onecompplayer_setup(self):\n game1 = TicTacToe.Game()\n computer1 = TicTacToe.Computer('X', game1)\n player2 = TicTacToe.Player('O', game1)\n return (game1, computer1, player2)\n\n def test_place3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1:\"X\", 2:\"X\",3:\"-\",\n 4:\"-\", 5:\"-\", 6:\"-\",\n 7:\"-\", 8:\"-\", 9:\"-\"}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({1:\"X\", 2:\"X\",3:\"X\",\n 4:\"-\", 5:\"-\", 6:\"-\",\n 7:\"-\", 8:\"-\", 9:\"-\"},\n game1.game_board\n )\n\n def test_place2(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1:\"-\", 2:\"-\",3:\"-\",\n 4:\"-\", 5:\"X\", 6:\"-\",\n 7:\"-\", 8:\"X\", 9:\"-\"}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({1:\"-\", 2:\"X\",3:\"-\",\n 4:\"-\", 5:\"X\", 6:\"-\",\n 7:\"-\", 8:\"X\", 9:\"-\"},\n game1.game_board\n )\n\n def test_place8(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"-\", 6: \"-\",\n 7: \"X\", 8: \"-\", 9: \"X\"}\n p2moves = []\n winner = game1.play_comp_test(computer1, player2, p2moves)\n self.assertEqual(computer1, winner)\n self.assertEqual({1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"-\", 6: \"-\",\n 7: \"X\", 8: \"X\", 9: \"X\"},\n game1.game_board\n )\n\n def test_block5(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"O\", 5: \"-\", 6: \"O\",\n 7: \"-\", 8: \"-\", 9: \"-\"}\n computer1.auto_move()\n self.assertEqual({1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"O\", 5: \"X\", 6: \"O\",\n 7: \"-\", 8: \"-\", 9: \"-\"},\n game1.game_board\n )\n\n def test_block7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"O\",\n 4: \"-\", 5: \"O\", 6: \"-\",\n 7: \"-\", 8: \"-\", 9: \"-\"}\n computer1.auto_move()\n self.assertEqual({1: \"-\", 2: \"-\", 3: \"O\",\n 4: \"-\", 5: \"O\", 6: \"-\",\n 7: \"X\", 8: \"-\", 9: \"-\"},\n game1.game_board\n )\n\n def test_block3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"-\", 6: \"O\",\n 7: \"-\", 8: \"-\", 9: \"O\"}\n computer1.auto_move()\n self.assertEqual({1: \"-\", 2: \"-\", 3: \"X\",\n 4: \"-\", 5: \"-\", 6: \"O\",\n 7: \"-\", 8: \"-\", 9: \"O\"},\n game1.game_board\n )\n\n def test_center_empty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"-\", 6: \"-\",\n 7: \"-\", 8: \"-\", 9: \"-\"}\n computer1.auto_move()\n self.assertEqual({1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"X\", 6: \"-\",\n 7: \"-\", 8: \"-\", 9: \"-\"},\n game1.game_board\n )\n\n def test_center_nonempty(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"O\", 2: \"-\", 3: \"-\",\n 4: \"X\", 5: \"-\", 6: \"O\",\n 7: \"X\", 8: \"-\", 9: \"-\"}\n computer1.auto_move()\n self.assertEqual({1: \"O\", 2: \"-\", 3: \"-\",\n 4: \"X\", 5: \"X\", 6: \"O\",\n 7: \"X\", 8: \"-\", 9: \"-\"},\n game1.game_board\n )\n\n def test_oppcorner7(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"O\",\n 4: \"-\", 5: \"X\", 6: \"-\",\n 7: \"-\", 8: \"-\", 9: \"-\"}\n computer1.auto_move()\n self.assertEqual({1: \"-\", 2: \"-\", 3: \"O\",\n 4: \"-\", 5: \"X\", 6: \"-\",\n 7: \"X\", 8: \"-\", 9: \"-\"},\n game1.game_board\n )\n\n def test_oppcorner1(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"O\", 5: \"X\", 6: \"X\",\n 7: \"-\", 8: \"-\", 9: \"O\"}\n computer1.auto_move()\n self.assertEqual({1: \"X\", 2: \"-\", 3: \"-\",\n 4: \"O\", 5: \"X\", 6: \"X\",\n 7: \"-\", 8: \"-\", 9: \"O\"},\n game1.game_board\n )\n\n def test_oppcorner3(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"-\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"X\", 6: \"-\",\n 7: \"O\", 8: \"-\", 9: \"-\"}\n computer1.auto_move()\n self.assertEqual({1: \"-\", 2: \"-\", 3: \"X\",\n 4: \"-\", 5: \"X\", 6: \"-\",\n 7: \"O\", 8: \"-\", 9: \"-\"},\n game1.game_board\n )\n\n def test_oppcorner9(self):\n game1, computer1, player2 = self.onecompplayer_setup()\n game1.game_board = {1: \"O\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"X\", 6: \"-\",\n 7: \"-\", 8: \"-\", 9: \"-\"}\n computer1.auto_move()\n self.assertEqual({1: \"O\", 2: \"-\", 3: \"-\",\n 4: \"-\", 5: \"X\", 6: \"-\",\n 7: \"-\", 8: \"-\", 9: \"X\"},\n game1.game_board\n )\n\nif __name__ == '__main__':\n unittest.main()\n",
"step-ids": [
13,
15,
17,
20,
22
]
}
|
[
13,
15,
17,
20,
22
] |
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__,
]
|
normal
|
{
"blob_id": "acad268a228b544d60966a8767734cbf9c1237ac",
"index": 9979,
"step-1": "<mask token>\n",
"step-2": "<mask 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",
"step-3": "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",
"step-4": "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",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.EpInfo import EpInfo
from alipay.aop.api.domain.EpInfo import EpInfo
from alipay.aop.api.domain.EpInfo import EpInfo
from alipay.aop.api.domain.EpInfo import EpInfo
from alipay.aop.api.domain.EpInfo import EpInfo
from alipay.aop.api.domain.EpInfo import EpInfo
from alipay.aop.api.domain.EpInfo import EpInfo
from alipay.aop.api.domain.EpInfo import EpInfo
class CompanyInfo(object):
def __init__(self):
self._alter_list = None
self._basic_info = None
self._case_info_list = None
self._entinv_list = None
self._fr_position_list = None
self._frinv_list = None
self._person_list = None
self._share_holder_list = None
@property
def alter_list(self):
return self._alter_list
@alter_list.setter
def alter_list(self, value):
if isinstance(value, list):
self._alter_list = list()
for i in value:
if isinstance(i, EpInfo):
self._alter_list.append(i)
else:
self._alter_list.append(EpInfo.from_alipay_dict(i))
@property
def basic_info(self):
return self._basic_info
@basic_info.setter
def basic_info(self, value):
if isinstance(value, EpInfo):
self._basic_info = value
else:
self._basic_info = EpInfo.from_alipay_dict(value)
@property
def case_info_list(self):
return self._case_info_list
@case_info_list.setter
def case_info_list(self, value):
if isinstance(value, list):
self._case_info_list = list()
for i in value:
if isinstance(i, EpInfo):
self._case_info_list.append(i)
else:
self._case_info_list.append(EpInfo.from_alipay_dict(i))
@property
def entinv_list(self):
return self._entinv_list
@entinv_list.setter
def entinv_list(self, value):
if isinstance(value, list):
self._entinv_list = list()
for i in value:
if isinstance(i, EpInfo):
self._entinv_list.append(i)
else:
self._entinv_list.append(EpInfo.from_alipay_dict(i))
@property
def fr_position_list(self):
return self._fr_position_list
@fr_position_list.setter
def fr_position_list(self, value):
if isinstance(value, list):
self._fr_position_list = list()
for i in value:
if isinstance(i, EpInfo):
self._fr_position_list.append(i)
else:
self._fr_position_list.append(EpInfo.from_alipay_dict(i))
@property
def frinv_list(self):
return self._frinv_list
@frinv_list.setter
def frinv_list(self, value):
if isinstance(value, list):
self._frinv_list = list()
for i in value:
if isinstance(i, EpInfo):
self._frinv_list.append(i)
else:
self._frinv_list.append(EpInfo.from_alipay_dict(i))
@property
def person_list(self):
return self._person_list
@person_list.setter
def person_list(self, value):
if isinstance(value, list):
self._person_list = list()
for i in value:
if isinstance(i, EpInfo):
self._person_list.append(i)
else:
self._person_list.append(EpInfo.from_alipay_dict(i))
@property
def share_holder_list(self):
return self._share_holder_list
@share_holder_list.setter
def share_holder_list(self, value):
if isinstance(value, list):
self._share_holder_list = list()
for i in value:
if isinstance(i, EpInfo):
self._share_holder_list.append(i)
else:
self._share_holder_list.append(EpInfo.from_alipay_dict(i))
def to_alipay_dict(self):
params = dict()
if self.alter_list:
if isinstance(self.alter_list, list):
for i in range(0, len(self.alter_list)):
element = self.alter_list[i]
if hasattr(element, 'to_alipay_dict'):
self.alter_list[i] = element.to_alipay_dict()
if hasattr(self.alter_list, 'to_alipay_dict'):
params['alter_list'] = self.alter_list.to_alipay_dict()
else:
params['alter_list'] = self.alter_list
if self.basic_info:
if hasattr(self.basic_info, 'to_alipay_dict'):
params['basic_info'] = self.basic_info.to_alipay_dict()
else:
params['basic_info'] = self.basic_info
if self.case_info_list:
if isinstance(self.case_info_list, list):
for i in range(0, len(self.case_info_list)):
element = self.case_info_list[i]
if hasattr(element, 'to_alipay_dict'):
self.case_info_list[i] = element.to_alipay_dict()
if hasattr(self.case_info_list, 'to_alipay_dict'):
params['case_info_list'] = self.case_info_list.to_alipay_dict()
else:
params['case_info_list'] = self.case_info_list
if self.entinv_list:
if isinstance(self.entinv_list, list):
for i in range(0, len(self.entinv_list)):
element = self.entinv_list[i]
if hasattr(element, 'to_alipay_dict'):
self.entinv_list[i] = element.to_alipay_dict()
if hasattr(self.entinv_list, 'to_alipay_dict'):
params['entinv_list'] = self.entinv_list.to_alipay_dict()
else:
params['entinv_list'] = self.entinv_list
if self.fr_position_list:
if isinstance(self.fr_position_list, list):
for i in range(0, len(self.fr_position_list)):
element = self.fr_position_list[i]
if hasattr(element, 'to_alipay_dict'):
self.fr_position_list[i] = element.to_alipay_dict()
if hasattr(self.fr_position_list, 'to_alipay_dict'):
params['fr_position_list'] = self.fr_position_list.to_alipay_dict()
else:
params['fr_position_list'] = self.fr_position_list
if self.frinv_list:
if isinstance(self.frinv_list, list):
for i in range(0, len(self.frinv_list)):
element = self.frinv_list[i]
if hasattr(element, 'to_alipay_dict'):
self.frinv_list[i] = element.to_alipay_dict()
if hasattr(self.frinv_list, 'to_alipay_dict'):
params['frinv_list'] = self.frinv_list.to_alipay_dict()
else:
params['frinv_list'] = self.frinv_list
if self.person_list:
if isinstance(self.person_list, list):
for i in range(0, len(self.person_list)):
element = self.person_list[i]
if hasattr(element, 'to_alipay_dict'):
self.person_list[i] = element.to_alipay_dict()
if hasattr(self.person_list, 'to_alipay_dict'):
params['person_list'] = self.person_list.to_alipay_dict()
else:
params['person_list'] = self.person_list
if self.share_holder_list:
if isinstance(self.share_holder_list, list):
for i in range(0, len(self.share_holder_list)):
element = self.share_holder_list[i]
if hasattr(element, 'to_alipay_dict'):
self.share_holder_list[i] = element.to_alipay_dict()
if hasattr(self.share_holder_list, 'to_alipay_dict'):
params['share_holder_list'] = self.share_holder_list.to_alipay_dict()
else:
params['share_holder_list'] = self.share_holder_list
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = CompanyInfo()
if 'alter_list' in d:
o.alter_list = d['alter_list']
if 'basic_info' in d:
o.basic_info = d['basic_info']
if 'case_info_list' in d:
o.case_info_list = d['case_info_list']
if 'entinv_list' in d:
o.entinv_list = d['entinv_list']
if 'fr_position_list' in d:
o.fr_position_list = d['fr_position_list']
if 'frinv_list' in d:
o.frinv_list = d['frinv_list']
if 'person_list' in d:
o.person_list = d['person_list']
if 'share_holder_list' in d:
o.share_holder_list = d['share_holder_list']
return o
|
normal
|
{
"blob_id": "6743a4f3c9118e790e52b586a36d71a735101702",
"index": 1901,
"step-1": "<mask token>\n\n\nclass CompanyInfo(object):\n\n def __init__(self):\n self._alter_list = None\n self._basic_info = None\n self._case_info_list = None\n self._entinv_list = None\n self._fr_position_list = None\n self._frinv_list = None\n self._person_list = None\n self._share_holder_list = None\n <mask token>\n\n @alter_list.setter\n def alter_list(self, value):\n if isinstance(value, list):\n self._alter_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._alter_list.append(i)\n else:\n self._alter_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def basic_info(self):\n return self._basic_info\n <mask token>\n\n @property\n def case_info_list(self):\n return self._case_info_list\n\n @case_info_list.setter\n def case_info_list(self, value):\n if isinstance(value, list):\n self._case_info_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._case_info_list.append(i)\n else:\n self._case_info_list.append(EpInfo.from_alipay_dict(i))\n <mask token>\n <mask token>\n\n @property\n def fr_position_list(self):\n return self._fr_position_list\n <mask token>\n <mask token>\n\n @frinv_list.setter\n def frinv_list(self, value):\n if isinstance(value, list):\n self._frinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._frinv_list.append(i)\n else:\n self._frinv_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def person_list(self):\n return self._person_list\n\n @person_list.setter\n def person_list(self, value):\n if isinstance(value, list):\n self._person_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._person_list.append(i)\n else:\n self._person_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def share_holder_list(self):\n return self._share_holder_list\n\n @share_holder_list.setter\n def share_holder_list(self, value):\n if isinstance(value, list):\n self._share_holder_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._share_holder_list.append(i)\n else:\n self._share_holder_list.append(EpInfo.from_alipay_dict(i))\n\n def to_alipay_dict(self):\n params = dict()\n if self.alter_list:\n if isinstance(self.alter_list, list):\n for i in range(0, len(self.alter_list)):\n element = self.alter_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.alter_list[i] = element.to_alipay_dict()\n if hasattr(self.alter_list, 'to_alipay_dict'):\n params['alter_list'] = self.alter_list.to_alipay_dict()\n else:\n params['alter_list'] = self.alter_list\n if self.basic_info:\n if hasattr(self.basic_info, 'to_alipay_dict'):\n params['basic_info'] = self.basic_info.to_alipay_dict()\n else:\n params['basic_info'] = self.basic_info\n if self.case_info_list:\n if isinstance(self.case_info_list, list):\n for i in range(0, len(self.case_info_list)):\n element = self.case_info_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.case_info_list[i] = element.to_alipay_dict()\n if hasattr(self.case_info_list, 'to_alipay_dict'):\n params['case_info_list'] = self.case_info_list.to_alipay_dict()\n else:\n params['case_info_list'] = self.case_info_list\n if self.entinv_list:\n if isinstance(self.entinv_list, list):\n for i in range(0, len(self.entinv_list)):\n element = self.entinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.entinv_list[i] = element.to_alipay_dict()\n if hasattr(self.entinv_list, 'to_alipay_dict'):\n params['entinv_list'] = self.entinv_list.to_alipay_dict()\n else:\n params['entinv_list'] = self.entinv_list\n if self.fr_position_list:\n if isinstance(self.fr_position_list, list):\n for i in range(0, len(self.fr_position_list)):\n element = self.fr_position_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.fr_position_list[i] = element.to_alipay_dict()\n if hasattr(self.fr_position_list, 'to_alipay_dict'):\n params['fr_position_list'\n ] = self.fr_position_list.to_alipay_dict()\n else:\n params['fr_position_list'] = self.fr_position_list\n if self.frinv_list:\n if isinstance(self.frinv_list, list):\n for i in range(0, len(self.frinv_list)):\n element = self.frinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.frinv_list[i] = element.to_alipay_dict()\n if hasattr(self.frinv_list, 'to_alipay_dict'):\n params['frinv_list'] = self.frinv_list.to_alipay_dict()\n else:\n params['frinv_list'] = self.frinv_list\n if self.person_list:\n if isinstance(self.person_list, list):\n for i in range(0, len(self.person_list)):\n element = self.person_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.person_list[i] = element.to_alipay_dict()\n if hasattr(self.person_list, 'to_alipay_dict'):\n params['person_list'] = self.person_list.to_alipay_dict()\n else:\n params['person_list'] = self.person_list\n if self.share_holder_list:\n if isinstance(self.share_holder_list, list):\n for i in range(0, len(self.share_holder_list)):\n element = self.share_holder_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.share_holder_list[i] = element.to_alipay_dict()\n if hasattr(self.share_holder_list, 'to_alipay_dict'):\n params['share_holder_list'\n ] = self.share_holder_list.to_alipay_dict()\n else:\n params['share_holder_list'] = self.share_holder_list\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = CompanyInfo()\n if 'alter_list' in d:\n o.alter_list = d['alter_list']\n if 'basic_info' in d:\n o.basic_info = d['basic_info']\n if 'case_info_list' in d:\n o.case_info_list = d['case_info_list']\n if 'entinv_list' in d:\n o.entinv_list = d['entinv_list']\n if 'fr_position_list' in d:\n o.fr_position_list = d['fr_position_list']\n if 'frinv_list' in d:\n o.frinv_list = d['frinv_list']\n if 'person_list' in d:\n o.person_list = d['person_list']\n if 'share_holder_list' in d:\n o.share_holder_list = d['share_holder_list']\n return o\n",
"step-2": "<mask token>\n\n\nclass CompanyInfo(object):\n\n def __init__(self):\n self._alter_list = None\n self._basic_info = None\n self._case_info_list = None\n self._entinv_list = None\n self._fr_position_list = None\n self._frinv_list = None\n self._person_list = None\n self._share_holder_list = None\n <mask token>\n\n @alter_list.setter\n def alter_list(self, value):\n if isinstance(value, list):\n self._alter_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._alter_list.append(i)\n else:\n self._alter_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def basic_info(self):\n return self._basic_info\n\n @basic_info.setter\n def basic_info(self, value):\n if isinstance(value, EpInfo):\n self._basic_info = value\n else:\n self._basic_info = EpInfo.from_alipay_dict(value)\n\n @property\n def case_info_list(self):\n return self._case_info_list\n\n @case_info_list.setter\n def case_info_list(self, value):\n if isinstance(value, list):\n self._case_info_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._case_info_list.append(i)\n else:\n self._case_info_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def entinv_list(self):\n return self._entinv_list\n\n @entinv_list.setter\n def entinv_list(self, value):\n if isinstance(value, list):\n self._entinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._entinv_list.append(i)\n else:\n self._entinv_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def fr_position_list(self):\n return self._fr_position_list\n\n @fr_position_list.setter\n def fr_position_list(self, value):\n if isinstance(value, list):\n self._fr_position_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._fr_position_list.append(i)\n else:\n self._fr_position_list.append(EpInfo.from_alipay_dict(i))\n <mask token>\n\n @frinv_list.setter\n def frinv_list(self, value):\n if isinstance(value, list):\n self._frinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._frinv_list.append(i)\n else:\n self._frinv_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def person_list(self):\n return self._person_list\n\n @person_list.setter\n def person_list(self, value):\n if isinstance(value, list):\n self._person_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._person_list.append(i)\n else:\n self._person_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def share_holder_list(self):\n return self._share_holder_list\n\n @share_holder_list.setter\n def share_holder_list(self, value):\n if isinstance(value, list):\n self._share_holder_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._share_holder_list.append(i)\n else:\n self._share_holder_list.append(EpInfo.from_alipay_dict(i))\n\n def to_alipay_dict(self):\n params = dict()\n if self.alter_list:\n if isinstance(self.alter_list, list):\n for i in range(0, len(self.alter_list)):\n element = self.alter_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.alter_list[i] = element.to_alipay_dict()\n if hasattr(self.alter_list, 'to_alipay_dict'):\n params['alter_list'] = self.alter_list.to_alipay_dict()\n else:\n params['alter_list'] = self.alter_list\n if self.basic_info:\n if hasattr(self.basic_info, 'to_alipay_dict'):\n params['basic_info'] = self.basic_info.to_alipay_dict()\n else:\n params['basic_info'] = self.basic_info\n if self.case_info_list:\n if isinstance(self.case_info_list, list):\n for i in range(0, len(self.case_info_list)):\n element = self.case_info_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.case_info_list[i] = element.to_alipay_dict()\n if hasattr(self.case_info_list, 'to_alipay_dict'):\n params['case_info_list'] = self.case_info_list.to_alipay_dict()\n else:\n params['case_info_list'] = self.case_info_list\n if self.entinv_list:\n if isinstance(self.entinv_list, list):\n for i in range(0, len(self.entinv_list)):\n element = self.entinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.entinv_list[i] = element.to_alipay_dict()\n if hasattr(self.entinv_list, 'to_alipay_dict'):\n params['entinv_list'] = self.entinv_list.to_alipay_dict()\n else:\n params['entinv_list'] = self.entinv_list\n if self.fr_position_list:\n if isinstance(self.fr_position_list, list):\n for i in range(0, len(self.fr_position_list)):\n element = self.fr_position_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.fr_position_list[i] = element.to_alipay_dict()\n if hasattr(self.fr_position_list, 'to_alipay_dict'):\n params['fr_position_list'\n ] = self.fr_position_list.to_alipay_dict()\n else:\n params['fr_position_list'] = self.fr_position_list\n if self.frinv_list:\n if isinstance(self.frinv_list, list):\n for i in range(0, len(self.frinv_list)):\n element = self.frinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.frinv_list[i] = element.to_alipay_dict()\n if hasattr(self.frinv_list, 'to_alipay_dict'):\n params['frinv_list'] = self.frinv_list.to_alipay_dict()\n else:\n params['frinv_list'] = self.frinv_list\n if self.person_list:\n if isinstance(self.person_list, list):\n for i in range(0, len(self.person_list)):\n element = self.person_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.person_list[i] = element.to_alipay_dict()\n if hasattr(self.person_list, 'to_alipay_dict'):\n params['person_list'] = self.person_list.to_alipay_dict()\n else:\n params['person_list'] = self.person_list\n if self.share_holder_list:\n if isinstance(self.share_holder_list, list):\n for i in range(0, len(self.share_holder_list)):\n element = self.share_holder_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.share_holder_list[i] = element.to_alipay_dict()\n if hasattr(self.share_holder_list, 'to_alipay_dict'):\n params['share_holder_list'\n ] = self.share_holder_list.to_alipay_dict()\n else:\n params['share_holder_list'] = self.share_holder_list\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = CompanyInfo()\n if 'alter_list' in d:\n o.alter_list = d['alter_list']\n if 'basic_info' in d:\n o.basic_info = d['basic_info']\n if 'case_info_list' in d:\n o.case_info_list = d['case_info_list']\n if 'entinv_list' in d:\n o.entinv_list = d['entinv_list']\n if 'fr_position_list' in d:\n o.fr_position_list = d['fr_position_list']\n if 'frinv_list' in d:\n o.frinv_list = d['frinv_list']\n if 'person_list' in d:\n o.person_list = d['person_list']\n if 'share_holder_list' in d:\n o.share_holder_list = d['share_holder_list']\n return o\n",
"step-3": "<mask token>\n\n\nclass CompanyInfo(object):\n\n def __init__(self):\n self._alter_list = None\n self._basic_info = None\n self._case_info_list = None\n self._entinv_list = None\n self._fr_position_list = None\n self._frinv_list = None\n self._person_list = None\n self._share_holder_list = None\n\n @property\n def alter_list(self):\n return self._alter_list\n\n @alter_list.setter\n def alter_list(self, value):\n if isinstance(value, list):\n self._alter_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._alter_list.append(i)\n else:\n self._alter_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def basic_info(self):\n return self._basic_info\n\n @basic_info.setter\n def basic_info(self, value):\n if isinstance(value, EpInfo):\n self._basic_info = value\n else:\n self._basic_info = EpInfo.from_alipay_dict(value)\n\n @property\n def case_info_list(self):\n return self._case_info_list\n\n @case_info_list.setter\n def case_info_list(self, value):\n if isinstance(value, list):\n self._case_info_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._case_info_list.append(i)\n else:\n self._case_info_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def entinv_list(self):\n return self._entinv_list\n\n @entinv_list.setter\n def entinv_list(self, value):\n if isinstance(value, list):\n self._entinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._entinv_list.append(i)\n else:\n self._entinv_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def fr_position_list(self):\n return self._fr_position_list\n\n @fr_position_list.setter\n def fr_position_list(self, value):\n if isinstance(value, list):\n self._fr_position_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._fr_position_list.append(i)\n else:\n self._fr_position_list.append(EpInfo.from_alipay_dict(i))\n <mask token>\n\n @frinv_list.setter\n def frinv_list(self, value):\n if isinstance(value, list):\n self._frinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._frinv_list.append(i)\n else:\n self._frinv_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def person_list(self):\n return self._person_list\n\n @person_list.setter\n def person_list(self, value):\n if isinstance(value, list):\n self._person_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._person_list.append(i)\n else:\n self._person_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def share_holder_list(self):\n return self._share_holder_list\n\n @share_holder_list.setter\n def share_holder_list(self, value):\n if isinstance(value, list):\n self._share_holder_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._share_holder_list.append(i)\n else:\n self._share_holder_list.append(EpInfo.from_alipay_dict(i))\n\n def to_alipay_dict(self):\n params = dict()\n if self.alter_list:\n if isinstance(self.alter_list, list):\n for i in range(0, len(self.alter_list)):\n element = self.alter_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.alter_list[i] = element.to_alipay_dict()\n if hasattr(self.alter_list, 'to_alipay_dict'):\n params['alter_list'] = self.alter_list.to_alipay_dict()\n else:\n params['alter_list'] = self.alter_list\n if self.basic_info:\n if hasattr(self.basic_info, 'to_alipay_dict'):\n params['basic_info'] = self.basic_info.to_alipay_dict()\n else:\n params['basic_info'] = self.basic_info\n if self.case_info_list:\n if isinstance(self.case_info_list, list):\n for i in range(0, len(self.case_info_list)):\n element = self.case_info_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.case_info_list[i] = element.to_alipay_dict()\n if hasattr(self.case_info_list, 'to_alipay_dict'):\n params['case_info_list'] = self.case_info_list.to_alipay_dict()\n else:\n params['case_info_list'] = self.case_info_list\n if self.entinv_list:\n if isinstance(self.entinv_list, list):\n for i in range(0, len(self.entinv_list)):\n element = self.entinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.entinv_list[i] = element.to_alipay_dict()\n if hasattr(self.entinv_list, 'to_alipay_dict'):\n params['entinv_list'] = self.entinv_list.to_alipay_dict()\n else:\n params['entinv_list'] = self.entinv_list\n if self.fr_position_list:\n if isinstance(self.fr_position_list, list):\n for i in range(0, len(self.fr_position_list)):\n element = self.fr_position_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.fr_position_list[i] = element.to_alipay_dict()\n if hasattr(self.fr_position_list, 'to_alipay_dict'):\n params['fr_position_list'\n ] = self.fr_position_list.to_alipay_dict()\n else:\n params['fr_position_list'] = self.fr_position_list\n if self.frinv_list:\n if isinstance(self.frinv_list, list):\n for i in range(0, len(self.frinv_list)):\n element = self.frinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.frinv_list[i] = element.to_alipay_dict()\n if hasattr(self.frinv_list, 'to_alipay_dict'):\n params['frinv_list'] = self.frinv_list.to_alipay_dict()\n else:\n params['frinv_list'] = self.frinv_list\n if self.person_list:\n if isinstance(self.person_list, list):\n for i in range(0, len(self.person_list)):\n element = self.person_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.person_list[i] = element.to_alipay_dict()\n if hasattr(self.person_list, 'to_alipay_dict'):\n params['person_list'] = self.person_list.to_alipay_dict()\n else:\n params['person_list'] = self.person_list\n if self.share_holder_list:\n if isinstance(self.share_holder_list, list):\n for i in range(0, len(self.share_holder_list)):\n element = self.share_holder_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.share_holder_list[i] = element.to_alipay_dict()\n if hasattr(self.share_holder_list, 'to_alipay_dict'):\n params['share_holder_list'\n ] = self.share_holder_list.to_alipay_dict()\n else:\n params['share_holder_list'] = self.share_holder_list\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = CompanyInfo()\n if 'alter_list' in d:\n o.alter_list = d['alter_list']\n if 'basic_info' in d:\n o.basic_info = d['basic_info']\n if 'case_info_list' in d:\n o.case_info_list = d['case_info_list']\n if 'entinv_list' in d:\n o.entinv_list = d['entinv_list']\n if 'fr_position_list' in d:\n o.fr_position_list = d['fr_position_list']\n if 'frinv_list' in d:\n o.frinv_list = d['frinv_list']\n if 'person_list' in d:\n o.person_list = d['person_list']\n if 'share_holder_list' in d:\n o.share_holder_list = d['share_holder_list']\n return o\n",
"step-4": "<mask token>\n\n\nclass CompanyInfo(object):\n\n def __init__(self):\n self._alter_list = None\n self._basic_info = None\n self._case_info_list = None\n self._entinv_list = None\n self._fr_position_list = None\n self._frinv_list = None\n self._person_list = None\n self._share_holder_list = None\n\n @property\n def alter_list(self):\n return self._alter_list\n\n @alter_list.setter\n def alter_list(self, value):\n if isinstance(value, list):\n self._alter_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._alter_list.append(i)\n else:\n self._alter_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def basic_info(self):\n return self._basic_info\n\n @basic_info.setter\n def basic_info(self, value):\n if isinstance(value, EpInfo):\n self._basic_info = value\n else:\n self._basic_info = EpInfo.from_alipay_dict(value)\n\n @property\n def case_info_list(self):\n return self._case_info_list\n\n @case_info_list.setter\n def case_info_list(self, value):\n if isinstance(value, list):\n self._case_info_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._case_info_list.append(i)\n else:\n self._case_info_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def entinv_list(self):\n return self._entinv_list\n\n @entinv_list.setter\n def entinv_list(self, value):\n if isinstance(value, list):\n self._entinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._entinv_list.append(i)\n else:\n self._entinv_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def fr_position_list(self):\n return self._fr_position_list\n\n @fr_position_list.setter\n def fr_position_list(self, value):\n if isinstance(value, list):\n self._fr_position_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._fr_position_list.append(i)\n else:\n self._fr_position_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def frinv_list(self):\n return self._frinv_list\n\n @frinv_list.setter\n def frinv_list(self, value):\n if isinstance(value, list):\n self._frinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._frinv_list.append(i)\n else:\n self._frinv_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def person_list(self):\n return self._person_list\n\n @person_list.setter\n def person_list(self, value):\n if isinstance(value, list):\n self._person_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._person_list.append(i)\n else:\n self._person_list.append(EpInfo.from_alipay_dict(i))\n\n @property\n def share_holder_list(self):\n return self._share_holder_list\n\n @share_holder_list.setter\n def share_holder_list(self, value):\n if isinstance(value, list):\n self._share_holder_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._share_holder_list.append(i)\n else:\n self._share_holder_list.append(EpInfo.from_alipay_dict(i))\n\n def to_alipay_dict(self):\n params = dict()\n if self.alter_list:\n if isinstance(self.alter_list, list):\n for i in range(0, len(self.alter_list)):\n element = self.alter_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.alter_list[i] = element.to_alipay_dict()\n if hasattr(self.alter_list, 'to_alipay_dict'):\n params['alter_list'] = self.alter_list.to_alipay_dict()\n else:\n params['alter_list'] = self.alter_list\n if self.basic_info:\n if hasattr(self.basic_info, 'to_alipay_dict'):\n params['basic_info'] = self.basic_info.to_alipay_dict()\n else:\n params['basic_info'] = self.basic_info\n if self.case_info_list:\n if isinstance(self.case_info_list, list):\n for i in range(0, len(self.case_info_list)):\n element = self.case_info_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.case_info_list[i] = element.to_alipay_dict()\n if hasattr(self.case_info_list, 'to_alipay_dict'):\n params['case_info_list'] = self.case_info_list.to_alipay_dict()\n else:\n params['case_info_list'] = self.case_info_list\n if self.entinv_list:\n if isinstance(self.entinv_list, list):\n for i in range(0, len(self.entinv_list)):\n element = self.entinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.entinv_list[i] = element.to_alipay_dict()\n if hasattr(self.entinv_list, 'to_alipay_dict'):\n params['entinv_list'] = self.entinv_list.to_alipay_dict()\n else:\n params['entinv_list'] = self.entinv_list\n if self.fr_position_list:\n if isinstance(self.fr_position_list, list):\n for i in range(0, len(self.fr_position_list)):\n element = self.fr_position_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.fr_position_list[i] = element.to_alipay_dict()\n if hasattr(self.fr_position_list, 'to_alipay_dict'):\n params['fr_position_list'\n ] = self.fr_position_list.to_alipay_dict()\n else:\n params['fr_position_list'] = self.fr_position_list\n if self.frinv_list:\n if isinstance(self.frinv_list, list):\n for i in range(0, len(self.frinv_list)):\n element = self.frinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.frinv_list[i] = element.to_alipay_dict()\n if hasattr(self.frinv_list, 'to_alipay_dict'):\n params['frinv_list'] = self.frinv_list.to_alipay_dict()\n else:\n params['frinv_list'] = self.frinv_list\n if self.person_list:\n if isinstance(self.person_list, list):\n for i in range(0, len(self.person_list)):\n element = self.person_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.person_list[i] = element.to_alipay_dict()\n if hasattr(self.person_list, 'to_alipay_dict'):\n params['person_list'] = self.person_list.to_alipay_dict()\n else:\n params['person_list'] = self.person_list\n if self.share_holder_list:\n if isinstance(self.share_holder_list, list):\n for i in range(0, len(self.share_holder_list)):\n element = self.share_holder_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.share_holder_list[i] = element.to_alipay_dict()\n if hasattr(self.share_holder_list, 'to_alipay_dict'):\n params['share_holder_list'\n ] = self.share_holder_list.to_alipay_dict()\n else:\n params['share_holder_list'] = self.share_holder_list\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = CompanyInfo()\n if 'alter_list' in d:\n o.alter_list = d['alter_list']\n if 'basic_info' in d:\n o.basic_info = d['basic_info']\n if 'case_info_list' in d:\n o.case_info_list = d['case_info_list']\n if 'entinv_list' in d:\n o.entinv_list = d['entinv_list']\n if 'fr_position_list' in d:\n o.fr_position_list = d['fr_position_list']\n if 'frinv_list' in d:\n o.frinv_list = d['frinv_list']\n if 'person_list' in d:\n o.person_list = d['person_list']\n if 'share_holder_list' in d:\n o.share_holder_list = d['share_holder_list']\n return o\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\nfrom alipay.aop.api.domain.EpInfo import EpInfo\nfrom alipay.aop.api.domain.EpInfo import EpInfo\nfrom alipay.aop.api.domain.EpInfo import EpInfo\nfrom alipay.aop.api.domain.EpInfo import EpInfo\nfrom alipay.aop.api.domain.EpInfo import EpInfo\nfrom alipay.aop.api.domain.EpInfo import EpInfo\nfrom alipay.aop.api.domain.EpInfo import EpInfo\nfrom alipay.aop.api.domain.EpInfo import EpInfo\n\n\nclass CompanyInfo(object):\n\n def __init__(self):\n self._alter_list = None\n self._basic_info = None\n self._case_info_list = None\n self._entinv_list = None\n self._fr_position_list = None\n self._frinv_list = None\n self._person_list = None\n self._share_holder_list = None\n\n @property\n def alter_list(self):\n return self._alter_list\n\n @alter_list.setter\n def alter_list(self, value):\n if isinstance(value, list):\n self._alter_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._alter_list.append(i)\n else:\n self._alter_list.append(EpInfo.from_alipay_dict(i))\n @property\n def basic_info(self):\n return self._basic_info\n\n @basic_info.setter\n def basic_info(self, value):\n if isinstance(value, EpInfo):\n self._basic_info = value\n else:\n self._basic_info = EpInfo.from_alipay_dict(value)\n @property\n def case_info_list(self):\n return self._case_info_list\n\n @case_info_list.setter\n def case_info_list(self, value):\n if isinstance(value, list):\n self._case_info_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._case_info_list.append(i)\n else:\n self._case_info_list.append(EpInfo.from_alipay_dict(i))\n @property\n def entinv_list(self):\n return self._entinv_list\n\n @entinv_list.setter\n def entinv_list(self, value):\n if isinstance(value, list):\n self._entinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._entinv_list.append(i)\n else:\n self._entinv_list.append(EpInfo.from_alipay_dict(i))\n @property\n def fr_position_list(self):\n return self._fr_position_list\n\n @fr_position_list.setter\n def fr_position_list(self, value):\n if isinstance(value, list):\n self._fr_position_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._fr_position_list.append(i)\n else:\n self._fr_position_list.append(EpInfo.from_alipay_dict(i))\n @property\n def frinv_list(self):\n return self._frinv_list\n\n @frinv_list.setter\n def frinv_list(self, value):\n if isinstance(value, list):\n self._frinv_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._frinv_list.append(i)\n else:\n self._frinv_list.append(EpInfo.from_alipay_dict(i))\n @property\n def person_list(self):\n return self._person_list\n\n @person_list.setter\n def person_list(self, value):\n if isinstance(value, list):\n self._person_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._person_list.append(i)\n else:\n self._person_list.append(EpInfo.from_alipay_dict(i))\n @property\n def share_holder_list(self):\n return self._share_holder_list\n\n @share_holder_list.setter\n def share_holder_list(self, value):\n if isinstance(value, list):\n self._share_holder_list = list()\n for i in value:\n if isinstance(i, EpInfo):\n self._share_holder_list.append(i)\n else:\n self._share_holder_list.append(EpInfo.from_alipay_dict(i))\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.alter_list:\n if isinstance(self.alter_list, list):\n for i in range(0, len(self.alter_list)):\n element = self.alter_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.alter_list[i] = element.to_alipay_dict()\n if hasattr(self.alter_list, 'to_alipay_dict'):\n params['alter_list'] = self.alter_list.to_alipay_dict()\n else:\n params['alter_list'] = self.alter_list\n if self.basic_info:\n if hasattr(self.basic_info, 'to_alipay_dict'):\n params['basic_info'] = self.basic_info.to_alipay_dict()\n else:\n params['basic_info'] = self.basic_info\n if self.case_info_list:\n if isinstance(self.case_info_list, list):\n for i in range(0, len(self.case_info_list)):\n element = self.case_info_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.case_info_list[i] = element.to_alipay_dict()\n if hasattr(self.case_info_list, 'to_alipay_dict'):\n params['case_info_list'] = self.case_info_list.to_alipay_dict()\n else:\n params['case_info_list'] = self.case_info_list\n if self.entinv_list:\n if isinstance(self.entinv_list, list):\n for i in range(0, len(self.entinv_list)):\n element = self.entinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.entinv_list[i] = element.to_alipay_dict()\n if hasattr(self.entinv_list, 'to_alipay_dict'):\n params['entinv_list'] = self.entinv_list.to_alipay_dict()\n else:\n params['entinv_list'] = self.entinv_list\n if self.fr_position_list:\n if isinstance(self.fr_position_list, list):\n for i in range(0, len(self.fr_position_list)):\n element = self.fr_position_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.fr_position_list[i] = element.to_alipay_dict()\n if hasattr(self.fr_position_list, 'to_alipay_dict'):\n params['fr_position_list'] = self.fr_position_list.to_alipay_dict()\n else:\n params['fr_position_list'] = self.fr_position_list\n if self.frinv_list:\n if isinstance(self.frinv_list, list):\n for i in range(0, len(self.frinv_list)):\n element = self.frinv_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.frinv_list[i] = element.to_alipay_dict()\n if hasattr(self.frinv_list, 'to_alipay_dict'):\n params['frinv_list'] = self.frinv_list.to_alipay_dict()\n else:\n params['frinv_list'] = self.frinv_list\n if self.person_list:\n if isinstance(self.person_list, list):\n for i in range(0, len(self.person_list)):\n element = self.person_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.person_list[i] = element.to_alipay_dict()\n if hasattr(self.person_list, 'to_alipay_dict'):\n params['person_list'] = self.person_list.to_alipay_dict()\n else:\n params['person_list'] = self.person_list\n if self.share_holder_list:\n if isinstance(self.share_holder_list, list):\n for i in range(0, len(self.share_holder_list)):\n element = self.share_holder_list[i]\n if hasattr(element, 'to_alipay_dict'):\n self.share_holder_list[i] = element.to_alipay_dict()\n if hasattr(self.share_holder_list, 'to_alipay_dict'):\n params['share_holder_list'] = self.share_holder_list.to_alipay_dict()\n else:\n params['share_holder_list'] = self.share_holder_list\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = CompanyInfo()\n if 'alter_list' in d:\n o.alter_list = d['alter_list']\n if 'basic_info' in d:\n o.basic_info = d['basic_info']\n if 'case_info_list' in d:\n o.case_info_list = d['case_info_list']\n if 'entinv_list' in d:\n o.entinv_list = d['entinv_list']\n if 'fr_position_list' in d:\n o.fr_position_list = d['fr_position_list']\n if 'frinv_list' in d:\n o.frinv_list = d['frinv_list']\n if 'person_list' in d:\n o.person_list = d['person_list']\n if 'share_holder_list' in d:\n o.share_holder_list = d['share_holder_list']\n return o\n\n\n",
"step-ids": [
14,
18,
19,
20,
22
]
}
|
[
14,
18,
19,
20,
22
] |
# Generated by Django 2.0.1 on 2018-05-01 11:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rover', '0002_auto_20180501_1431'),
]
operations = [
migrations.CreateModel(
name='RoverPage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('design_review', models.FileField(blank=True, upload_to='documents/rover')),
],
options={
'verbose_name_plural': 'Rover Page',
'verbose_name': 'Rover Page',
},
),
]
|
normal
|
{
"blob_id": "fed94e0affa1fe6c705577a63fabee839aa9f05c",
"index": 5096,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('rover', '0002_auto_20180501_1431')]\n operations = [migrations.CreateModel(name='RoverPage', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('design_review', models.FileField(\n blank=True, upload_to='documents/rover'))], options={\n 'verbose_name_plural': 'Rover Page', 'verbose_name': 'Rover Page'})]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('rover', '0002_auto_20180501_1431')]\n operations = [migrations.CreateModel(name='RoverPage', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('design_review', models.FileField(\n blank=True, upload_to='documents/rover'))], options={\n 'verbose_name_plural': 'Rover Page', 'verbose_name': 'Rover Page'})]\n",
"step-5": "# Generated by Django 2.0.1 on 2018-05-01 11:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rover', '0002_auto_20180501_1431'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='RoverPage',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('design_review', models.FileField(blank=True, upload_to='documents/rover')),\n ],\n options={\n 'verbose_name_plural': 'Rover Page',\n 'verbose_name': 'Rover Page',\n },\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Calcu.py
#
import os, sys
def menuCalc():
os.system('clear')
print("Esto parece un menu:")
print("\t1 - Suma")
print("\t2 - Resta")
print("\t3 - Multiplicacion")
print("\t4 - Division")
print("\tq - Para salir")
def calculadora(calcu,):
if calcu == "1":
os.system('clear')
s1=int(input("Ingrese un numero\n"))
s2=int(input("Ingrese otro\n"))
os.system('clear')
print(f"{s1} + {s2} = {s1+s2}")
input("\nPresione una tecla para continuar.")
elif calcu == "2":
os.system('clear')
s1=int(input("Ingrese un numero\n"))
s2=int(input("Ingrese otro\n"))
os.system('clear')
print(f"{s1} - {s2} = {s1-s2}")
input("\nPresione una tecla para continuar.")
elif calcu == "3":
os.system('clear')
s1=int(input("Ingrese un numero\n"))
s2=int(input("Ingrese otro\n"))
os.system('clear')
print(f" {s1} x {s2} = {s1*s2}")
input("\nPresione una tecla para continuar.")
elif calcu == "4":
os.system('clear')
s1=int(input("Ingrese un numero\n"))
s2=int(input("Ingrese otro\n"))
os.system('clear')
print(f"{s1} / {s2} = {s1 / s2}")
input("\nPresione una tecla para continuar.")
elif calcu == "q":
print("Gracias, Vuelva Prontoss")
exit()
else:
os.system('clear')
print("Lo siento no es un numero valido!")
while True:
menuCalc()
calc = input("Ingrese su opcion: ")
calculadora(calc)
|
normal
|
{
"blob_id": "ac033e45ea61770c302be677f4dfc95945e2cca5",
"index": 6100,
"step-1": "<mask token>\n\n\ndef calculadora(calcu):\n if calcu == '1':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} + {s2} = {s1 + s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '2':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} - {s2} = {s1 - s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '3':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f' {s1} x {s2} = {s1 * s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '4':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} / {s2} = {s1 / s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == 'q':\n print('Gracias, Vuelva Prontoss')\n exit()\n else:\n os.system('clear')\n print('Lo siento no es un numero valido!')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef menuCalc():\n os.system('clear')\n print('Esto parece un menu:')\n print('\\t1 - Suma')\n print('\\t2 - Resta')\n print('\\t3 - Multiplicacion')\n print('\\t4 - Division')\n print('\\tq - Para salir')\n\n\ndef calculadora(calcu):\n if calcu == '1':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} + {s2} = {s1 + s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '2':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} - {s2} = {s1 - s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '3':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f' {s1} x {s2} = {s1 * s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '4':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} / {s2} = {s1 / s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == 'q':\n print('Gracias, Vuelva Prontoss')\n exit()\n else:\n os.system('clear')\n print('Lo siento no es un numero valido!')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef menuCalc():\n os.system('clear')\n print('Esto parece un menu:')\n print('\\t1 - Suma')\n print('\\t2 - Resta')\n print('\\t3 - Multiplicacion')\n print('\\t4 - Division')\n print('\\tq - Para salir')\n\n\ndef calculadora(calcu):\n if calcu == '1':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} + {s2} = {s1 + s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '2':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} - {s2} = {s1 - s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '3':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f' {s1} x {s2} = {s1 * s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '4':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} / {s2} = {s1 / s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == 'q':\n print('Gracias, Vuelva Prontoss')\n exit()\n else:\n os.system('clear')\n print('Lo siento no es un numero valido!')\n\n\nwhile True:\n menuCalc()\n calc = input('Ingrese su opcion: ')\n calculadora(calc)\n",
"step-4": "import os, sys\n\n\ndef menuCalc():\n os.system('clear')\n print('Esto parece un menu:')\n print('\\t1 - Suma')\n print('\\t2 - Resta')\n print('\\t3 - Multiplicacion')\n print('\\t4 - Division')\n print('\\tq - Para salir')\n\n\ndef calculadora(calcu):\n if calcu == '1':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} + {s2} = {s1 + s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '2':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} - {s2} = {s1 - s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '3':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f' {s1} x {s2} = {s1 * s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == '4':\n os.system('clear')\n s1 = int(input('Ingrese un numero\\n'))\n s2 = int(input('Ingrese otro\\n'))\n os.system('clear')\n print(f'{s1} / {s2} = {s1 / s2}')\n input('\\nPresione una tecla para continuar.')\n elif calcu == 'q':\n print('Gracias, Vuelva Prontoss')\n exit()\n else:\n os.system('clear')\n print('Lo siento no es un numero valido!')\n\n\nwhile True:\n menuCalc()\n calc = input('Ingrese su opcion: ')\n calculadora(calc)\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Calcu.py\n# \n\nimport os, sys\n\ndef menuCalc():\n\n os.system('clear')\n print(\"Esto parece un menu:\")\n print(\"\\t1 - Suma\")\n print(\"\\t2 - Resta\")\n print(\"\\t3 - Multiplicacion\")\n print(\"\\t4 - Division\")\n print(\"\\tq - Para salir\")\n \ndef calculadora(calcu,):\n\tif calcu == \"1\":\n\t\tos.system('clear')\n\t\ts1=int(input(\"Ingrese un numero\\n\"))\n\t\ts2=int(input(\"Ingrese otro\\n\"))\n\t\tos.system('clear')\n\t\tprint(f\"{s1} + {s2} = {s1+s2}\")\n\t\tinput(\"\\nPresione una tecla para continuar.\")\n\telif calcu == \"2\":\n\t\tos.system('clear')\n\t\ts1=int(input(\"Ingrese un numero\\n\"))\n\t\ts2=int(input(\"Ingrese otro\\n\"))\n\t\tos.system('clear')\n\t\tprint(f\"{s1} - {s2} = {s1-s2}\")\n\t\tinput(\"\\nPresione una tecla para continuar.\")\n\telif calcu == \"3\":\n\t\tos.system('clear')\n\t\ts1=int(input(\"Ingrese un numero\\n\"))\n\t\ts2=int(input(\"Ingrese otro\\n\"))\n\t\tos.system('clear')\n\t\tprint(f\" {s1} x {s2} = {s1*s2}\")\n\t\tinput(\"\\nPresione una tecla para continuar.\")\n\telif calcu == \"4\":\n\t\tos.system('clear')\n\t\ts1=int(input(\"Ingrese un numero\\n\"))\n\t\ts2=int(input(\"Ingrese otro\\n\"))\n\t\tos.system('clear')\n\t\tprint(f\"{s1} / {s2} = {s1 / s2}\")\n\t\tinput(\"\\nPresione una tecla para continuar.\")\n\telif calcu == \"q\":\n\t\tprint(\"Gracias, Vuelva Prontoss\")\n\t\texit()\n\telse:\n\t\tos.system('clear')\n\t\tprint(\"Lo siento no es un numero valido!\")\n\nwhile True:\n \n menuCalc()\n calc = input(\"Ingrese su opcion: \")\n calculadora(calc)\n\t\n\n\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
if a % 2 == 0:
print('Even')
else:
print('Odd')
<|reserved_special_token_1|>
a = int(raw_input())
if a % 2 == 0:
print('Even')
else:
print('Odd')
<|reserved_special_token_1|>
a=int(raw_input())
if (a%2)==0:
print("Even")
else:
print("Odd")
|
flexible
|
{
"blob_id": "00b06b5e6465bae3eab336441b283a9831bb93c0",
"index": 4531,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif a % 2 == 0:\n print('Even')\nelse:\n print('Odd')\n",
"step-3": "a = int(raw_input())\nif a % 2 == 0:\n print('Even')\nelse:\n print('Odd')\n",
"step-4": "a=int(raw_input())\nif (a%2)==0:\n\tprint(\"Even\")\nelse:\n\tprint(\"Odd\")\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def start_task(display_window, daq, exp_type, parameters, file_save,
signal_model=None, language_model=None, fake=True, auc_filename=None):
"""Creates a Task and starts execution."""
task = make_task(display_window, daq, exp_type, parameters, file_save,
signal_model, language_model, fake, auc_filename)
task.execute()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def make_task(display_window, daq, exp_type, parameters, file_save,
signal_model=None, language_model=None, fake=True, auc_filename=None
) ->Task:
"""Creates a Task based on the provided parameters.
Parameters:
-----------
display_window: pyschopy Window
daq: DataAcquisitionClient
exp_type: ExperimentType
parameters: dict
file_save: str - path to file in which to save data
signal_model
language_model - language model
fake: boolean - true if eeg stream is randomly generated
auc_filename: str
Returns:
--------
Task instance
"""
if exp_type is ExperimentType.RSVP_CALIBRATION:
return RSVPCalibrationTask(display_window, daq, parameters, file_save)
if exp_type is ExperimentType.RSVP_COPY_PHRASE:
return RSVPCopyPhraseTask(display_window, daq, parameters,
file_save, signal_model, language_model, fake=fake)
if exp_type is ExperimentType.RSVP_ICON_TO_ICON:
return RSVPIconToIconTask(display_window, daq, parameters,
file_save, signal_model, language_model, fake, False, auc_filename)
if exp_type is ExperimentType.RSVP_ICON_TO_WORD:
return RSVPIconToIconTask(display_window, daq, parameters,
file_save, signal_model, language_model, fake, True, auc_filename)
if exp_type is ExperimentType.RSVP_ALERT_TONE_CALIBRATION:
return RSVPAlertToneCalibrationTask(display_window, daq, parameters,
file_save)
if exp_type is ExperimentType.RSVP_INTER_SEQUENCE_FEEDBACK_CALIBRATION:
return RSVPInterSequenceFeedbackCalibration(display_window, daq,
parameters, file_save)
if exp_type is ExperimentType.RSVP_TIMING_VERIFICATION_CALIBRATION:
return RSVPTimingVerificationCalibration(display_window, daq,
parameters, file_save)
raise TaskRegistryException(
'The provided experiment type is not registered.')
def start_task(display_window, daq, exp_type, parameters, file_save,
signal_model=None, language_model=None, fake=True, auc_filename=None):
"""Creates a Task and starts execution."""
task = make_task(display_window, daq, exp_type, parameters, file_save,
signal_model, language_model, fake, auc_filename)
task.execute()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from bcipy.tasks.rsvp.calibration.alert_tone_calibration import RSVPAlertToneCalibrationTask
from bcipy.tasks.rsvp.calibration.inter_sequence_feedback_calibration import RSVPInterSequenceFeedbackCalibration
from bcipy.tasks.rsvp.calibration.calibration import RSVPCalibrationTask
from bcipy.tasks.rsvp.copy_phrase import RSVPCopyPhraseTask
from bcipy.tasks.rsvp.icon_to_icon import RSVPIconToIconTask
from bcipy.tasks.rsvp.calibration.timing_verification import RSVPTimingVerificationCalibration
from bcipy.tasks.task import Task
from bcipy.tasks.exceptions import TaskRegistryException
from bcipy.tasks.task_registry import ExperimentType
def make_task(display_window, daq, exp_type, parameters, file_save,
signal_model=None, language_model=None, fake=True, auc_filename=None
) ->Task:
"""Creates a Task based on the provided parameters.
Parameters:
-----------
display_window: pyschopy Window
daq: DataAcquisitionClient
exp_type: ExperimentType
parameters: dict
file_save: str - path to file in which to save data
signal_model
language_model - language model
fake: boolean - true if eeg stream is randomly generated
auc_filename: str
Returns:
--------
Task instance
"""
if exp_type is ExperimentType.RSVP_CALIBRATION:
return RSVPCalibrationTask(display_window, daq, parameters, file_save)
if exp_type is ExperimentType.RSVP_COPY_PHRASE:
return RSVPCopyPhraseTask(display_window, daq, parameters,
file_save, signal_model, language_model, fake=fake)
if exp_type is ExperimentType.RSVP_ICON_TO_ICON:
return RSVPIconToIconTask(display_window, daq, parameters,
file_save, signal_model, language_model, fake, False, auc_filename)
if exp_type is ExperimentType.RSVP_ICON_TO_WORD:
return RSVPIconToIconTask(display_window, daq, parameters,
file_save, signal_model, language_model, fake, True, auc_filename)
if exp_type is ExperimentType.RSVP_ALERT_TONE_CALIBRATION:
return RSVPAlertToneCalibrationTask(display_window, daq, parameters,
file_save)
if exp_type is ExperimentType.RSVP_INTER_SEQUENCE_FEEDBACK_CALIBRATION:
return RSVPInterSequenceFeedbackCalibration(display_window, daq,
parameters, file_save)
if exp_type is ExperimentType.RSVP_TIMING_VERIFICATION_CALIBRATION:
return RSVPTimingVerificationCalibration(display_window, daq,
parameters, file_save)
raise TaskRegistryException(
'The provided experiment type is not registered.')
def start_task(display_window, daq, exp_type, parameters, file_save,
signal_model=None, language_model=None, fake=True, auc_filename=None):
"""Creates a Task and starts execution."""
task = make_task(display_window, daq, exp_type, parameters, file_save,
signal_model, language_model, fake, auc_filename)
task.execute()
<|reserved_special_token_1|>
"""Code for constructing and executing Tasks"""
from bcipy.tasks.rsvp.calibration.alert_tone_calibration import RSVPAlertToneCalibrationTask
from bcipy.tasks.rsvp.calibration.inter_sequence_feedback_calibration import (
RSVPInterSequenceFeedbackCalibration
)
from bcipy.tasks.rsvp.calibration.calibration import RSVPCalibrationTask
from bcipy.tasks.rsvp.copy_phrase import RSVPCopyPhraseTask
from bcipy.tasks.rsvp.icon_to_icon import RSVPIconToIconTask
from bcipy.tasks.rsvp.calibration.timing_verification import RSVPTimingVerificationCalibration
from bcipy.tasks.task import Task
from bcipy.tasks.exceptions import TaskRegistryException
from bcipy.tasks.task_registry import ExperimentType
def make_task(display_window, daq, exp_type, parameters, file_save,
signal_model=None, language_model=None, fake=True,
auc_filename=None) -> Task:
"""Creates a Task based on the provided parameters.
Parameters:
-----------
display_window: pyschopy Window
daq: DataAcquisitionClient
exp_type: ExperimentType
parameters: dict
file_save: str - path to file in which to save data
signal_model
language_model - language model
fake: boolean - true if eeg stream is randomly generated
auc_filename: str
Returns:
--------
Task instance
"""
# NORMAL RSVP MODES
if exp_type is ExperimentType.RSVP_CALIBRATION:
return RSVPCalibrationTask(
display_window, daq, parameters, file_save)
if exp_type is ExperimentType.RSVP_COPY_PHRASE:
return RSVPCopyPhraseTask(
display_window, daq, parameters, file_save, signal_model,
language_model, fake=fake)
# ICON TASKS
if exp_type is ExperimentType.RSVP_ICON_TO_ICON:
return RSVPIconToIconTask(display_window, daq,
parameters, file_save, signal_model,
language_model, fake, False, auc_filename)
if exp_type is ExperimentType.RSVP_ICON_TO_WORD:
# pylint: disable=fixme
# TODO: consider a new class for this scenario.
return RSVPIconToIconTask(display_window, daq,
parameters, file_save, signal_model,
language_model, fake, True, auc_filename)
# CALIBRATION FEEDBACK TASKS
if exp_type is ExperimentType.RSVP_ALERT_TONE_CALIBRATION:
return RSVPAlertToneCalibrationTask(
display_window, daq, parameters, file_save)
if exp_type is ExperimentType.RSVP_INTER_SEQUENCE_FEEDBACK_CALIBRATION:
return RSVPInterSequenceFeedbackCalibration(
display_window, daq, parameters, file_save)
if exp_type is ExperimentType.RSVP_TIMING_VERIFICATION_CALIBRATION:
return RSVPTimingVerificationCalibration(display_window, daq,
parameters, file_save)
raise TaskRegistryException(
'The provided experiment type is not registered.')
def start_task(display_window, daq, exp_type, parameters, file_save,
signal_model=None, language_model=None, fake=True, auc_filename=None):
"""Creates a Task and starts execution."""
task = make_task(display_window, daq, exp_type, parameters, file_save,
signal_model, language_model, fake, auc_filename)
task.execute()
|
flexible
|
{
"blob_id": "f2e6d23e6d8c5aa6e80a652dc6cb8bda45824d0c",
"index": 1026,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef start_task(display_window, daq, exp_type, parameters, file_save,\n signal_model=None, language_model=None, fake=True, auc_filename=None):\n \"\"\"Creates a Task and starts execution.\"\"\"\n task = make_task(display_window, daq, exp_type, parameters, file_save,\n signal_model, language_model, fake, auc_filename)\n task.execute()\n",
"step-3": "<mask token>\n\n\ndef make_task(display_window, daq, exp_type, parameters, file_save,\n signal_model=None, language_model=None, fake=True, auc_filename=None\n ) ->Task:\n \"\"\"Creates a Task based on the provided parameters.\n\n Parameters:\n -----------\n display_window: pyschopy Window\n daq: DataAcquisitionClient\n exp_type: ExperimentType\n parameters: dict\n file_save: str - path to file in which to save data\n signal_model\n language_model - language model\n fake: boolean - true if eeg stream is randomly generated\n auc_filename: str\n Returns:\n --------\n Task instance\n \"\"\"\n if exp_type is ExperimentType.RSVP_CALIBRATION:\n return RSVPCalibrationTask(display_window, daq, parameters, file_save)\n if exp_type is ExperimentType.RSVP_COPY_PHRASE:\n return RSVPCopyPhraseTask(display_window, daq, parameters,\n file_save, signal_model, language_model, fake=fake)\n if exp_type is ExperimentType.RSVP_ICON_TO_ICON:\n return RSVPIconToIconTask(display_window, daq, parameters,\n file_save, signal_model, language_model, fake, False, auc_filename)\n if exp_type is ExperimentType.RSVP_ICON_TO_WORD:\n return RSVPIconToIconTask(display_window, daq, parameters,\n file_save, signal_model, language_model, fake, True, auc_filename)\n if exp_type is ExperimentType.RSVP_ALERT_TONE_CALIBRATION:\n return RSVPAlertToneCalibrationTask(display_window, daq, parameters,\n file_save)\n if exp_type is ExperimentType.RSVP_INTER_SEQUENCE_FEEDBACK_CALIBRATION:\n return RSVPInterSequenceFeedbackCalibration(display_window, daq,\n parameters, file_save)\n if exp_type is ExperimentType.RSVP_TIMING_VERIFICATION_CALIBRATION:\n return RSVPTimingVerificationCalibration(display_window, daq,\n parameters, file_save)\n raise TaskRegistryException(\n 'The provided experiment type is not registered.')\n\n\ndef start_task(display_window, daq, exp_type, parameters, file_save,\n signal_model=None, language_model=None, fake=True, auc_filename=None):\n \"\"\"Creates a Task and starts execution.\"\"\"\n task = make_task(display_window, daq, exp_type, parameters, file_save,\n signal_model, language_model, fake, auc_filename)\n task.execute()\n",
"step-4": "<mask token>\nfrom bcipy.tasks.rsvp.calibration.alert_tone_calibration import RSVPAlertToneCalibrationTask\nfrom bcipy.tasks.rsvp.calibration.inter_sequence_feedback_calibration import RSVPInterSequenceFeedbackCalibration\nfrom bcipy.tasks.rsvp.calibration.calibration import RSVPCalibrationTask\nfrom bcipy.tasks.rsvp.copy_phrase import RSVPCopyPhraseTask\nfrom bcipy.tasks.rsvp.icon_to_icon import RSVPIconToIconTask\nfrom bcipy.tasks.rsvp.calibration.timing_verification import RSVPTimingVerificationCalibration\nfrom bcipy.tasks.task import Task\nfrom bcipy.tasks.exceptions import TaskRegistryException\nfrom bcipy.tasks.task_registry import ExperimentType\n\n\ndef make_task(display_window, daq, exp_type, parameters, file_save,\n signal_model=None, language_model=None, fake=True, auc_filename=None\n ) ->Task:\n \"\"\"Creates a Task based on the provided parameters.\n\n Parameters:\n -----------\n display_window: pyschopy Window\n daq: DataAcquisitionClient\n exp_type: ExperimentType\n parameters: dict\n file_save: str - path to file in which to save data\n signal_model\n language_model - language model\n fake: boolean - true if eeg stream is randomly generated\n auc_filename: str\n Returns:\n --------\n Task instance\n \"\"\"\n if exp_type is ExperimentType.RSVP_CALIBRATION:\n return RSVPCalibrationTask(display_window, daq, parameters, file_save)\n if exp_type is ExperimentType.RSVP_COPY_PHRASE:\n return RSVPCopyPhraseTask(display_window, daq, parameters,\n file_save, signal_model, language_model, fake=fake)\n if exp_type is ExperimentType.RSVP_ICON_TO_ICON:\n return RSVPIconToIconTask(display_window, daq, parameters,\n file_save, signal_model, language_model, fake, False, auc_filename)\n if exp_type is ExperimentType.RSVP_ICON_TO_WORD:\n return RSVPIconToIconTask(display_window, daq, parameters,\n file_save, signal_model, language_model, fake, True, auc_filename)\n if exp_type is ExperimentType.RSVP_ALERT_TONE_CALIBRATION:\n return RSVPAlertToneCalibrationTask(display_window, daq, parameters,\n file_save)\n if exp_type is ExperimentType.RSVP_INTER_SEQUENCE_FEEDBACK_CALIBRATION:\n return RSVPInterSequenceFeedbackCalibration(display_window, daq,\n parameters, file_save)\n if exp_type is ExperimentType.RSVP_TIMING_VERIFICATION_CALIBRATION:\n return RSVPTimingVerificationCalibration(display_window, daq,\n parameters, file_save)\n raise TaskRegistryException(\n 'The provided experiment type is not registered.')\n\n\ndef start_task(display_window, daq, exp_type, parameters, file_save,\n signal_model=None, language_model=None, fake=True, auc_filename=None):\n \"\"\"Creates a Task and starts execution.\"\"\"\n task = make_task(display_window, daq, exp_type, parameters, file_save,\n signal_model, language_model, fake, auc_filename)\n task.execute()\n",
"step-5": "\"\"\"Code for constructing and executing Tasks\"\"\"\nfrom bcipy.tasks.rsvp.calibration.alert_tone_calibration import RSVPAlertToneCalibrationTask\nfrom bcipy.tasks.rsvp.calibration.inter_sequence_feedback_calibration import (\n RSVPInterSequenceFeedbackCalibration\n)\nfrom bcipy.tasks.rsvp.calibration.calibration import RSVPCalibrationTask\nfrom bcipy.tasks.rsvp.copy_phrase import RSVPCopyPhraseTask\nfrom bcipy.tasks.rsvp.icon_to_icon import RSVPIconToIconTask\nfrom bcipy.tasks.rsvp.calibration.timing_verification import RSVPTimingVerificationCalibration\n\nfrom bcipy.tasks.task import Task\nfrom bcipy.tasks.exceptions import TaskRegistryException\nfrom bcipy.tasks.task_registry import ExperimentType\n\n\ndef make_task(display_window, daq, exp_type, parameters, file_save,\n signal_model=None, language_model=None, fake=True,\n auc_filename=None) -> Task:\n \"\"\"Creates a Task based on the provided parameters.\n\n Parameters:\n -----------\n display_window: pyschopy Window\n daq: DataAcquisitionClient\n exp_type: ExperimentType\n parameters: dict\n file_save: str - path to file in which to save data\n signal_model\n language_model - language model\n fake: boolean - true if eeg stream is randomly generated\n auc_filename: str\n Returns:\n --------\n Task instance\n \"\"\"\n\n # NORMAL RSVP MODES\n if exp_type is ExperimentType.RSVP_CALIBRATION:\n return RSVPCalibrationTask(\n display_window, daq, parameters, file_save)\n\n if exp_type is ExperimentType.RSVP_COPY_PHRASE:\n return RSVPCopyPhraseTask(\n display_window, daq, parameters, file_save, signal_model,\n language_model, fake=fake)\n\n # ICON TASKS\n if exp_type is ExperimentType.RSVP_ICON_TO_ICON:\n return RSVPIconToIconTask(display_window, daq,\n parameters, file_save, signal_model,\n language_model, fake, False, auc_filename)\n\n if exp_type is ExperimentType.RSVP_ICON_TO_WORD:\n # pylint: disable=fixme\n # TODO: consider a new class for this scenario.\n return RSVPIconToIconTask(display_window, daq,\n parameters, file_save, signal_model,\n language_model, fake, True, auc_filename)\n\n # CALIBRATION FEEDBACK TASKS\n if exp_type is ExperimentType.RSVP_ALERT_TONE_CALIBRATION:\n return RSVPAlertToneCalibrationTask(\n display_window, daq, parameters, file_save)\n\n if exp_type is ExperimentType.RSVP_INTER_SEQUENCE_FEEDBACK_CALIBRATION:\n return RSVPInterSequenceFeedbackCalibration(\n display_window, daq, parameters, file_save)\n\n if exp_type is ExperimentType.RSVP_TIMING_VERIFICATION_CALIBRATION:\n return RSVPTimingVerificationCalibration(display_window, daq,\n parameters, file_save)\n raise TaskRegistryException(\n 'The provided experiment type is not registered.')\n\n\ndef start_task(display_window, daq, exp_type, parameters, file_save,\n signal_model=None, language_model=None, fake=True, auc_filename=None):\n \"\"\"Creates a Task and starts execution.\"\"\"\n task = make_task(display_window, daq, exp_type, parameters, file_save,\n signal_model, language_model, fake, auc_filename)\n task.execute()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
class Member:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __init__(self, first_name, middle_name, last_name, gender):
self.fname = first_name
self.mname = middle_name
self.lname = last_name
self.gender = gender
Member.users_num += 1
<|reserved_special_token_0|>
@staticmethod
def say_hello():
print(f'Hello From Static Method')
def full_name(self):
if self.fname in Member.not_allowed_name:
raise ValueError('Name is Not Allowed')
else:
return f'{self.fname} {self.mname} {self.lname}'
def welcome(self):
if self.gender == 'Male':
return f'Hello Mr {self.fname}'
elif self.gender == 'Female':
return f'Hello Mrs {self.fname}'
else:
return f'Hello {self.fname}'
def get_all_info(self):
return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'
def delete_user(self):
Member.users_num -= 1
return f'Users {self.fname} Is Deleted'
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Member:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __init__(self, first_name, middle_name, last_name, gender):
self.fname = first_name
self.mname = middle_name
self.lname = last_name
self.gender = gender
Member.users_num += 1
@classmethod
def show_users_count(cls):
print(f'We Have {cls.users_num} Users In Our System.')
@staticmethod
def say_hello():
print(f'Hello From Static Method')
def full_name(self):
if self.fname in Member.not_allowed_name:
raise ValueError('Name is Not Allowed')
else:
return f'{self.fname} {self.mname} {self.lname}'
def welcome(self):
if self.gender == 'Male':
return f'Hello Mr {self.fname}'
elif self.gender == 'Female':
return f'Hello Mrs {self.fname}'
else:
return f'Hello {self.fname}'
def get_all_info(self):
return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'
def delete_user(self):
Member.users_num -= 1
return f'Users {self.fname} Is Deleted'
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Member:
not_allowed_name = ['Shit', 'Hell', 'Baloot']
users_num = 0
def __init__(self, first_name, middle_name, last_name, gender):
self.fname = first_name
self.mname = middle_name
self.lname = last_name
self.gender = gender
Member.users_num += 1
@classmethod
def show_users_count(cls):
print(f'We Have {cls.users_num} Users In Our System.')
@staticmethod
def say_hello():
print(f'Hello From Static Method')
def full_name(self):
if self.fname in Member.not_allowed_name:
raise ValueError('Name is Not Allowed')
else:
return f'{self.fname} {self.mname} {self.lname}'
def welcome(self):
if self.gender == 'Male':
return f'Hello Mr {self.fname}'
elif self.gender == 'Female':
return f'Hello Mrs {self.fname}'
else:
return f'Hello {self.fname}'
def get_all_info(self):
return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'
def delete_user(self):
Member.users_num -= 1
return f'Users {self.fname} Is Deleted'
print(Member.users_num)
<|reserved_special_token_0|>
print(Member.users_num)
print(member_four.delete_user())
print(Member.users_num)
print('#' * 100)
Member.show_users_count()
Member.say_hello()
<|reserved_special_token_1|>
class Member:
not_allowed_name = ['Shit', 'Hell', 'Baloot']
users_num = 0
def __init__(self, first_name, middle_name, last_name, gender):
self.fname = first_name
self.mname = middle_name
self.lname = last_name
self.gender = gender
Member.users_num += 1
@classmethod
def show_users_count(cls):
print(f'We Have {cls.users_num} Users In Our System.')
@staticmethod
def say_hello():
print(f'Hello From Static Method')
def full_name(self):
if self.fname in Member.not_allowed_name:
raise ValueError('Name is Not Allowed')
else:
return f'{self.fname} {self.mname} {self.lname}'
def welcome(self):
if self.gender == 'Male':
return f'Hello Mr {self.fname}'
elif self.gender == 'Female':
return f'Hello Mrs {self.fname}'
else:
return f'Hello {self.fname}'
def get_all_info(self):
return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'
def delete_user(self):
Member.users_num -= 1
return f'Users {self.fname} Is Deleted'
print(Member.users_num)
member_one = Member('Osama', 'Mohammed', 'Elzero', 'Male')
member_two = Member('Mohammed', 'Mohammed', 'Saad', 'Male')
member_three = Member('Hala', 'Mohammed', 'Saad', 'Female')
member_four = Member('Shit', 'Hell', 'Metal', 'DD')
print(Member.users_num)
print(member_four.delete_user())
print(Member.users_num)
print('#' * 100)
Member.show_users_count()
Member.say_hello()
<|reserved_special_token_1|>
class Member:
not_allowed_name = ["Shit", "Hell", "Baloot"]
users_num = 0
def __init__(self, first_name, middle_name, last_name, gender):
self.fname = first_name
self.mname = middle_name
self.lname = last_name
self.gender = gender
Member.users_num += 1
@classmethod
def show_users_count(cls):
print(f"We Have {cls.users_num} Users In Our System.")
@staticmethod
def say_hello(): # static method not linked to class or instances
print(f"Hello From Static Method")
def full_name(self): # instance method
if self.fname in Member.not_allowed_name:
raise ValueError("Name is Not Allowed")
else:
return f"{self.fname} {self.mname} {self.lname}"
def welcome(self):
if self.gender == "Male":
return f"Hello Mr {self.fname}"
elif self.gender == "Female":
return f"Hello Mrs {self.fname}"
else:
return f"Hello {self.fname}"
def get_all_info(self):
return f"{self.welcome()}, Your Full Name Is: {self.full_name()}"
def delete_user(self):
Member.users_num -= 1
return f"Users {self.fname} Is Deleted"
print(Member.users_num)
member_one = Member("Osama", "Mohammed", "Elzero", "Male")
member_two = Member("Mohammed", "Mohammed", "Saad", "Male")
member_three = Member("Hala", "Mohammed", "Saad", "Female")
member_four = Member("Shit", "Hell", "Metal", "DD")
# print(member_one.fname, member_one.mname, member_one.lname)
# print(member_two.mname)
# print(member_three.lname)
# print(member_one.full_name())
# print(member_three.welcome())
# print(dir(Member))
# print(member_three.get_all_info())
# print(member_four.get_all_info()) # Value Error
print(Member.users_num)
print(member_four.delete_user())
print(Member.users_num)
print("#" * 100)
Member.show_users_count()
Member.say_hello()
#print("#" * 100)
#print(member_three.full_name()) # Both same
#print(Member.full_name(member_three)) # Both same (Backend)
|
flexible
|
{
"blob_id": "f276e33cde2e043fc8f81403e499544aa816a639",
"index": 9316,
"step-1": "class Member:\n <mask token>\n <mask token>\n\n def __init__(self, first_name, middle_name, last_name, gender):\n self.fname = first_name\n self.mname = middle_name\n self.lname = last_name\n self.gender = gender\n Member.users_num += 1\n <mask token>\n\n @staticmethod\n def say_hello():\n print(f'Hello From Static Method')\n\n def full_name(self):\n if self.fname in Member.not_allowed_name:\n raise ValueError('Name is Not Allowed')\n else:\n return f'{self.fname} {self.mname} {self.lname}'\n\n def welcome(self):\n if self.gender == 'Male':\n return f'Hello Mr {self.fname}'\n elif self.gender == 'Female':\n return f'Hello Mrs {self.fname}'\n else:\n return f'Hello {self.fname}'\n\n def get_all_info(self):\n return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'\n\n def delete_user(self):\n Member.users_num -= 1\n return f'Users {self.fname} Is Deleted'\n\n\n<mask token>\n",
"step-2": "class Member:\n <mask token>\n <mask token>\n\n def __init__(self, first_name, middle_name, last_name, gender):\n self.fname = first_name\n self.mname = middle_name\n self.lname = last_name\n self.gender = gender\n Member.users_num += 1\n\n @classmethod\n def show_users_count(cls):\n print(f'We Have {cls.users_num} Users In Our System.')\n\n @staticmethod\n def say_hello():\n print(f'Hello From Static Method')\n\n def full_name(self):\n if self.fname in Member.not_allowed_name:\n raise ValueError('Name is Not Allowed')\n else:\n return f'{self.fname} {self.mname} {self.lname}'\n\n def welcome(self):\n if self.gender == 'Male':\n return f'Hello Mr {self.fname}'\n elif self.gender == 'Female':\n return f'Hello Mrs {self.fname}'\n else:\n return f'Hello {self.fname}'\n\n def get_all_info(self):\n return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'\n\n def delete_user(self):\n Member.users_num -= 1\n return f'Users {self.fname} Is Deleted'\n\n\n<mask token>\n",
"step-3": "class Member:\n not_allowed_name = ['Shit', 'Hell', 'Baloot']\n users_num = 0\n\n def __init__(self, first_name, middle_name, last_name, gender):\n self.fname = first_name\n self.mname = middle_name\n self.lname = last_name\n self.gender = gender\n Member.users_num += 1\n\n @classmethod\n def show_users_count(cls):\n print(f'We Have {cls.users_num} Users In Our System.')\n\n @staticmethod\n def say_hello():\n print(f'Hello From Static Method')\n\n def full_name(self):\n if self.fname in Member.not_allowed_name:\n raise ValueError('Name is Not Allowed')\n else:\n return f'{self.fname} {self.mname} {self.lname}'\n\n def welcome(self):\n if self.gender == 'Male':\n return f'Hello Mr {self.fname}'\n elif self.gender == 'Female':\n return f'Hello Mrs {self.fname}'\n else:\n return f'Hello {self.fname}'\n\n def get_all_info(self):\n return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'\n\n def delete_user(self):\n Member.users_num -= 1\n return f'Users {self.fname} Is Deleted'\n\n\nprint(Member.users_num)\n<mask token>\nprint(Member.users_num)\nprint(member_four.delete_user())\nprint(Member.users_num)\nprint('#' * 100)\nMember.show_users_count()\nMember.say_hello()\n",
"step-4": "class Member:\n not_allowed_name = ['Shit', 'Hell', 'Baloot']\n users_num = 0\n\n def __init__(self, first_name, middle_name, last_name, gender):\n self.fname = first_name\n self.mname = middle_name\n self.lname = last_name\n self.gender = gender\n Member.users_num += 1\n\n @classmethod\n def show_users_count(cls):\n print(f'We Have {cls.users_num} Users In Our System.')\n\n @staticmethod\n def say_hello():\n print(f'Hello From Static Method')\n\n def full_name(self):\n if self.fname in Member.not_allowed_name:\n raise ValueError('Name is Not Allowed')\n else:\n return f'{self.fname} {self.mname} {self.lname}'\n\n def welcome(self):\n if self.gender == 'Male':\n return f'Hello Mr {self.fname}'\n elif self.gender == 'Female':\n return f'Hello Mrs {self.fname}'\n else:\n return f'Hello {self.fname}'\n\n def get_all_info(self):\n return f'{self.welcome()}, Your Full Name Is: {self.full_name()}'\n\n def delete_user(self):\n Member.users_num -= 1\n return f'Users {self.fname} Is Deleted'\n\n\nprint(Member.users_num)\nmember_one = Member('Osama', 'Mohammed', 'Elzero', 'Male')\nmember_two = Member('Mohammed', 'Mohammed', 'Saad', 'Male')\nmember_three = Member('Hala', 'Mohammed', 'Saad', 'Female')\nmember_four = Member('Shit', 'Hell', 'Metal', 'DD')\nprint(Member.users_num)\nprint(member_four.delete_user())\nprint(Member.users_num)\nprint('#' * 100)\nMember.show_users_count()\nMember.say_hello()\n",
"step-5": "class Member:\n not_allowed_name = [\"Shit\", \"Hell\", \"Baloot\"]\n users_num = 0\n\n def __init__(self, first_name, middle_name, last_name, gender):\n\n self.fname = first_name\n self.mname = middle_name\n self.lname = last_name\n self.gender = gender\n\n Member.users_num += 1\n\n @classmethod\n def show_users_count(cls):\n\n print(f\"We Have {cls.users_num} Users In Our System.\")\n\n @staticmethod\n def say_hello(): # static method not linked to class or instances\n\n print(f\"Hello From Static Method\")\n\n def full_name(self): # instance method\n\n if self.fname in Member.not_allowed_name:\n raise ValueError(\"Name is Not Allowed\")\n\n else:\n return f\"{self.fname} {self.mname} {self.lname}\"\n\n def welcome(self):\n\n if self.gender == \"Male\":\n return f\"Hello Mr {self.fname}\"\n elif self.gender == \"Female\":\n return f\"Hello Mrs {self.fname}\"\n else:\n return f\"Hello {self.fname}\"\n\n def get_all_info(self):\n\n return f\"{self.welcome()}, Your Full Name Is: {self.full_name()}\"\n\n def delete_user(self):\n\n Member.users_num -= 1\n\n return f\"Users {self.fname} Is Deleted\"\n\n\nprint(Member.users_num)\nmember_one = Member(\"Osama\", \"Mohammed\", \"Elzero\", \"Male\")\nmember_two = Member(\"Mohammed\", \"Mohammed\", \"Saad\", \"Male\")\nmember_three = Member(\"Hala\", \"Mohammed\", \"Saad\", \"Female\")\nmember_four = Member(\"Shit\", \"Hell\", \"Metal\", \"DD\")\n\n# print(member_one.fname, member_one.mname, member_one.lname)\n# print(member_two.mname)\n# print(member_three.lname)\n\n# print(member_one.full_name())\n# print(member_three.welcome())\n\n# print(dir(Member))\n\n# print(member_three.get_all_info())\n# print(member_four.get_all_info()) # Value Error\nprint(Member.users_num)\nprint(member_four.delete_user())\nprint(Member.users_num)\n\nprint(\"#\" * 100)\n\nMember.show_users_count()\nMember.say_hello()\n#print(\"#\" * 100)\n\n#print(member_three.full_name()) # Both same\n#print(Member.full_name(member_three)) # Both same (Backend)\n\n\n",
"step-ids": [
7,
8,
10,
11,
12
]
}
|
[
7,
8,
10,
11,
12
] |
<|reserved_special_token_0|>
def segmentation_function(image, name, blue_mask=False, white_mask=False,
yellow_mask=False):
image = cv2.GaussianBlur(image, (11, 11), 0)
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
low_green = np.array([30, 0, 0])
high_green = np.array([86, 255, 255])
mask_final = cv2.inRange(hsv_image, low_green, high_green)
if blue_mask == True:
low_blue = np.array([80, 0, 0])
high_blue = np.array([125, 255, 255])
mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)
mask_final = mask_final + mask_blue
if white_mask == True:
low_white = np.array([0, 0, 200])
high_white = np.array([145, 60, 255])
mask_white = cv2.inRange(hsv_image, low_white, high_white)
mask_final = mask_final + mask_white
if yellow_mask == True:
low_yellow = np.array([10, 0, 0])
high_yellow = np.array([33, 255, 100])
mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)
mask_final = mask_final + mask_yellow
mask_final = 255 - mask_final
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)
segmented_image = np.zeros_like(mask_final)
for val in np.unique(mask_final)[1:]:
mask = np.uint8(mask_final == val)
labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
segmented_image[labels == largest_label] = val
return segmented_image
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def segmentation_function(image, name, blue_mask=False, white_mask=False,
yellow_mask=False):
image = cv2.GaussianBlur(image, (11, 11), 0)
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
low_green = np.array([30, 0, 0])
high_green = np.array([86, 255, 255])
mask_final = cv2.inRange(hsv_image, low_green, high_green)
if blue_mask == True:
low_blue = np.array([80, 0, 0])
high_blue = np.array([125, 255, 255])
mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)
mask_final = mask_final + mask_blue
if white_mask == True:
low_white = np.array([0, 0, 200])
high_white = np.array([145, 60, 255])
mask_white = cv2.inRange(hsv_image, low_white, high_white)
mask_final = mask_final + mask_white
if yellow_mask == True:
low_yellow = np.array([10, 0, 0])
high_yellow = np.array([33, 255, 100])
mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)
mask_final = mask_final + mask_yellow
mask_final = 255 - mask_final
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)
segmented_image = np.zeros_like(mask_final)
for val in np.unique(mask_final)[1:]:
mask = np.uint8(mask_final == val)
labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
segmented_image[labels == largest_label] = val
return segmented_image
<|reserved_special_token_0|>
cv2.imwrite('the3_B1_output.png', segmented_image)
<|reserved_special_token_0|>
cv2.imwrite('the3_B2_output.png', segmented_image)
<|reserved_special_token_0|>
cv2.imwrite('the3_B3_output.png', segmented_image)
<|reserved_special_token_0|>
cv2.imwrite('the3_B4_output.png', segmented_image)
<|reserved_special_token_0|>
cv2.imwrite('the3_B5_output.png', segmented_image)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
B1 = 'THE3-Images/B1.jpg'
B2 = 'THE3-Images/B2.jpg'
B3 = 'THE3-Images/B3.jpg'
B4 = 'THE3-Images/B4.jpg'
B5 = 'THE3-Images/B5.jpg'
def segmentation_function(image, name, blue_mask=False, white_mask=False,
yellow_mask=False):
image = cv2.GaussianBlur(image, (11, 11), 0)
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
low_green = np.array([30, 0, 0])
high_green = np.array([86, 255, 255])
mask_final = cv2.inRange(hsv_image, low_green, high_green)
if blue_mask == True:
low_blue = np.array([80, 0, 0])
high_blue = np.array([125, 255, 255])
mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)
mask_final = mask_final + mask_blue
if white_mask == True:
low_white = np.array([0, 0, 200])
high_white = np.array([145, 60, 255])
mask_white = cv2.inRange(hsv_image, low_white, high_white)
mask_final = mask_final + mask_white
if yellow_mask == True:
low_yellow = np.array([10, 0, 0])
high_yellow = np.array([33, 255, 100])
mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)
mask_final = mask_final + mask_yellow
mask_final = 255 - mask_final
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)
segmented_image = np.zeros_like(mask_final)
for val in np.unique(mask_final)[1:]:
mask = np.uint8(mask_final == val)
labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
segmented_image[labels == largest_label] = val
return segmented_image
image_bgr = cv2.imread(B1)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B1', blue_mask=False,
white_mask=False, yellow_mask=False)
cv2.imwrite('the3_B1_output.png', segmented_image)
image_bgr = cv2.imread(B2)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B2', blue_mask=True,
white_mask=True, yellow_mask=True)
cv2.imwrite('the3_B2_output.png', segmented_image)
image_bgr = cv2.imread(B3)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B3', blue_mask=True,
white_mask=False, yellow_mask=False)
cv2.imwrite('the3_B3_output.png', segmented_image)
image_bgr = cv2.imread(B4)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B4', blue_mask=True,
white_mask=False, yellow_mask=False)
cv2.imwrite('the3_B4_output.png', segmented_image)
image_bgr = cv2.imread(B5)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B5', blue_mask=True,
white_mask=False, yellow_mask=True)
cv2.imwrite('the3_B5_output.png', segmented_image)
<|reserved_special_token_1|>
import numpy as np
import cv2
B1 = 'THE3-Images/B1.jpg'
B2 = 'THE3-Images/B2.jpg'
B3 = 'THE3-Images/B3.jpg'
B4 = 'THE3-Images/B4.jpg'
B5 = 'THE3-Images/B5.jpg'
def segmentation_function(image, name, blue_mask=False, white_mask=False,
yellow_mask=False):
image = cv2.GaussianBlur(image, (11, 11), 0)
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
low_green = np.array([30, 0, 0])
high_green = np.array([86, 255, 255])
mask_final = cv2.inRange(hsv_image, low_green, high_green)
if blue_mask == True:
low_blue = np.array([80, 0, 0])
high_blue = np.array([125, 255, 255])
mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)
mask_final = mask_final + mask_blue
if white_mask == True:
low_white = np.array([0, 0, 200])
high_white = np.array([145, 60, 255])
mask_white = cv2.inRange(hsv_image, low_white, high_white)
mask_final = mask_final + mask_white
if yellow_mask == True:
low_yellow = np.array([10, 0, 0])
high_yellow = np.array([33, 255, 100])
mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)
mask_final = mask_final + mask_yellow
mask_final = 255 - mask_final
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)
segmented_image = np.zeros_like(mask_final)
for val in np.unique(mask_final)[1:]:
mask = np.uint8(mask_final == val)
labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
segmented_image[labels == largest_label] = val
return segmented_image
image_bgr = cv2.imread(B1)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B1', blue_mask=False,
white_mask=False, yellow_mask=False)
cv2.imwrite('the3_B1_output.png', segmented_image)
image_bgr = cv2.imread(B2)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B2', blue_mask=True,
white_mask=True, yellow_mask=True)
cv2.imwrite('the3_B2_output.png', segmented_image)
image_bgr = cv2.imread(B3)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B3', blue_mask=True,
white_mask=False, yellow_mask=False)
cv2.imwrite('the3_B3_output.png', segmented_image)
image_bgr = cv2.imread(B4)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B4', blue_mask=True,
white_mask=False, yellow_mask=False)
cv2.imwrite('the3_B4_output.png', segmented_image)
image_bgr = cv2.imread(B5)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
segmented_image = segmentation_function(image, 'B5', blue_mask=True,
white_mask=False, yellow_mask=True)
cv2.imwrite('the3_B5_output.png', segmented_image)
<|reserved_special_token_1|>
# Bengisu Ayan - 2236974
# Ceren Gürsoy - 2237485
import numpy as np
import cv2
B1 = "THE3-Images/B1.jpg"
B2 = "THE3-Images/B2.jpg"
B3 = "THE3-Images/B3.jpg"
B4 = "THE3-Images/B4.jpg"
B5 = "THE3-Images/B5.jpg"
def segmentation_function(image, name, blue_mask=False, white_mask=False, yellow_mask=False):
# Smooth the image
image = cv2.GaussianBlur(image,(11,11),0)
# convert to HSV color system
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
# define green mask
# green is applied to all the images as the dogs are all in grass
low_green = np.array([30, 0, 0])
high_green = np.array([86, 255, 255])
mask_final = cv2.inRange(hsv_image, low_green, high_green)
# define blue mask and apply it
if blue_mask == True:
low_blue = np.array([80, 0, 0])
high_blue = np.array([125, 255, 255])
mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)
mask_final = mask_final + mask_blue
# define white mask and apply it
if white_mask == True:
low_white = np.array([0, 0, 200])
high_white = np.array([145,60,255])
mask_white = cv2.inRange(hsv_image, low_white, high_white)
mask_final = mask_final + mask_white
# define yellow mask and apply it
if yellow_mask == True:
low_yellow = np.array([10, 0, 0])
high_yellow = np.array([33, 255, 100])
mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)
mask_final = mask_final + mask_yellow
# make object white and background black
mask_final = 255 - mask_final
# apply opening to final mask
# define 27*27 elliptical structuring element for opening
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(27,27))
# apply opening
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)
# apply closing to final mask
# define 41*41 elliptical structuring element for opening
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(41,41))
# apply closing
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)
# get biggest connected component
segmented_image = np.zeros_like(mask_final)
for val in np.unique(mask_final)[1:]:
mask = np.uint8(mask_final == val)
labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
segmented_image[labels == largest_label] = val
return segmented_image
# Read B1
image_bgr = cv2.imread(B1)
# convert B1 from bgr to rgb
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# Apply segmentation to B1 with only green mask
segmented_image = segmentation_function(image, 'B1', blue_mask=False, white_mask=False, yellow_mask=False)
cv2.imwrite("the3_B1_output.png", segmented_image)
# Read B2
image_bgr = cv2.imread(B2)
# convert B2 from bgr to rgb
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# Apply segmentation to B2 with green, white, yellow and blue masks
segmented_image = segmentation_function(image,'B2', blue_mask=True, white_mask=True, yellow_mask=True)
cv2.imwrite("the3_B2_output.png", segmented_image)
# Read B3
image_bgr = cv2.imread(B3)
# convert B3 from bgr to rgb
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# Apply segmentation to B3 with green and blue masks
segmented_image = segmentation_function(image,'B3', blue_mask=True, white_mask=False, yellow_mask=False)
cv2.imwrite("the3_B3_output.png", segmented_image)
# Read B4
image_bgr = cv2.imread(B4)
# convert B4 from bgr to rgb
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# Apply segmentation to B4 with green and blue masks
segmented_image = segmentation_function(image,'B4', blue_mask=True, white_mask=False, yellow_mask=False)
cv2.imwrite("the3_B4_output.png", segmented_image)
# Read B5
image_bgr = cv2.imread(B5)
# convert B5 from bgr to rgb
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# Apply segmentation to B2 with green ,yellow and blue masks
segmented_image = segmentation_function(image,'B5', blue_mask=True, white_mask=False, yellow_mask=True)
cv2.imwrite("the3_B5_output.png", segmented_image)
|
flexible
|
{
"blob_id": "1614157c57b3d1b30087c42cb840d617dc91eecb",
"index": 493,
"step-1": "<mask token>\n\n\ndef segmentation_function(image, name, blue_mask=False, white_mask=False,\n yellow_mask=False):\n image = cv2.GaussianBlur(image, (11, 11), 0)\n hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n low_green = np.array([30, 0, 0])\n high_green = np.array([86, 255, 255])\n mask_final = cv2.inRange(hsv_image, low_green, high_green)\n if blue_mask == True:\n low_blue = np.array([80, 0, 0])\n high_blue = np.array([125, 255, 255])\n mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)\n mask_final = mask_final + mask_blue\n if white_mask == True:\n low_white = np.array([0, 0, 200])\n high_white = np.array([145, 60, 255])\n mask_white = cv2.inRange(hsv_image, low_white, high_white)\n mask_final = mask_final + mask_white\n if yellow_mask == True:\n low_yellow = np.array([10, 0, 0])\n high_yellow = np.array([33, 255, 100])\n mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)\n mask_final = mask_final + mask_yellow\n mask_final = 255 - mask_final\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)\n segmented_image = np.zeros_like(mask_final)\n for val in np.unique(mask_final)[1:]:\n mask = np.uint8(mask_final == val)\n labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]\n largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])\n segmented_image[labels == largest_label] = val\n return segmented_image\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef segmentation_function(image, name, blue_mask=False, white_mask=False,\n yellow_mask=False):\n image = cv2.GaussianBlur(image, (11, 11), 0)\n hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n low_green = np.array([30, 0, 0])\n high_green = np.array([86, 255, 255])\n mask_final = cv2.inRange(hsv_image, low_green, high_green)\n if blue_mask == True:\n low_blue = np.array([80, 0, 0])\n high_blue = np.array([125, 255, 255])\n mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)\n mask_final = mask_final + mask_blue\n if white_mask == True:\n low_white = np.array([0, 0, 200])\n high_white = np.array([145, 60, 255])\n mask_white = cv2.inRange(hsv_image, low_white, high_white)\n mask_final = mask_final + mask_white\n if yellow_mask == True:\n low_yellow = np.array([10, 0, 0])\n high_yellow = np.array([33, 255, 100])\n mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)\n mask_final = mask_final + mask_yellow\n mask_final = 255 - mask_final\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)\n segmented_image = np.zeros_like(mask_final)\n for val in np.unique(mask_final)[1:]:\n mask = np.uint8(mask_final == val)\n labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]\n largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])\n segmented_image[labels == largest_label] = val\n return segmented_image\n\n\n<mask token>\ncv2.imwrite('the3_B1_output.png', segmented_image)\n<mask token>\ncv2.imwrite('the3_B2_output.png', segmented_image)\n<mask token>\ncv2.imwrite('the3_B3_output.png', segmented_image)\n<mask token>\ncv2.imwrite('the3_B4_output.png', segmented_image)\n<mask token>\ncv2.imwrite('the3_B5_output.png', segmented_image)\n",
"step-3": "<mask token>\nB1 = 'THE3-Images/B1.jpg'\nB2 = 'THE3-Images/B2.jpg'\nB3 = 'THE3-Images/B3.jpg'\nB4 = 'THE3-Images/B4.jpg'\nB5 = 'THE3-Images/B5.jpg'\n\n\ndef segmentation_function(image, name, blue_mask=False, white_mask=False,\n yellow_mask=False):\n image = cv2.GaussianBlur(image, (11, 11), 0)\n hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n low_green = np.array([30, 0, 0])\n high_green = np.array([86, 255, 255])\n mask_final = cv2.inRange(hsv_image, low_green, high_green)\n if blue_mask == True:\n low_blue = np.array([80, 0, 0])\n high_blue = np.array([125, 255, 255])\n mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)\n mask_final = mask_final + mask_blue\n if white_mask == True:\n low_white = np.array([0, 0, 200])\n high_white = np.array([145, 60, 255])\n mask_white = cv2.inRange(hsv_image, low_white, high_white)\n mask_final = mask_final + mask_white\n if yellow_mask == True:\n low_yellow = np.array([10, 0, 0])\n high_yellow = np.array([33, 255, 100])\n mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)\n mask_final = mask_final + mask_yellow\n mask_final = 255 - mask_final\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)\n segmented_image = np.zeros_like(mask_final)\n for val in np.unique(mask_final)[1:]:\n mask = np.uint8(mask_final == val)\n labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]\n largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])\n segmented_image[labels == largest_label] = val\n return segmented_image\n\n\nimage_bgr = cv2.imread(B1)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B1', blue_mask=False,\n white_mask=False, yellow_mask=False)\ncv2.imwrite('the3_B1_output.png', segmented_image)\nimage_bgr = cv2.imread(B2)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B2', blue_mask=True,\n white_mask=True, yellow_mask=True)\ncv2.imwrite('the3_B2_output.png', segmented_image)\nimage_bgr = cv2.imread(B3)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B3', blue_mask=True,\n white_mask=False, yellow_mask=False)\ncv2.imwrite('the3_B3_output.png', segmented_image)\nimage_bgr = cv2.imread(B4)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B4', blue_mask=True,\n white_mask=False, yellow_mask=False)\ncv2.imwrite('the3_B4_output.png', segmented_image)\nimage_bgr = cv2.imread(B5)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B5', blue_mask=True,\n white_mask=False, yellow_mask=True)\ncv2.imwrite('the3_B5_output.png', segmented_image)\n",
"step-4": "import numpy as np\nimport cv2\nB1 = 'THE3-Images/B1.jpg'\nB2 = 'THE3-Images/B2.jpg'\nB3 = 'THE3-Images/B3.jpg'\nB4 = 'THE3-Images/B4.jpg'\nB5 = 'THE3-Images/B5.jpg'\n\n\ndef segmentation_function(image, name, blue_mask=False, white_mask=False,\n yellow_mask=False):\n image = cv2.GaussianBlur(image, (11, 11), 0)\n hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n low_green = np.array([30, 0, 0])\n high_green = np.array([86, 255, 255])\n mask_final = cv2.inRange(hsv_image, low_green, high_green)\n if blue_mask == True:\n low_blue = np.array([80, 0, 0])\n high_blue = np.array([125, 255, 255])\n mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)\n mask_final = mask_final + mask_blue\n if white_mask == True:\n low_white = np.array([0, 0, 200])\n high_white = np.array([145, 60, 255])\n mask_white = cv2.inRange(hsv_image, low_white, high_white)\n mask_final = mask_final + mask_white\n if yellow_mask == True:\n low_yellow = np.array([10, 0, 0])\n high_yellow = np.array([33, 255, 100])\n mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)\n mask_final = mask_final + mask_yellow\n mask_final = 255 - mask_final\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (27, 27))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)\n segmented_image = np.zeros_like(mask_final)\n for val in np.unique(mask_final)[1:]:\n mask = np.uint8(mask_final == val)\n labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]\n largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])\n segmented_image[labels == largest_label] = val\n return segmented_image\n\n\nimage_bgr = cv2.imread(B1)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B1', blue_mask=False,\n white_mask=False, yellow_mask=False)\ncv2.imwrite('the3_B1_output.png', segmented_image)\nimage_bgr = cv2.imread(B2)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B2', blue_mask=True,\n white_mask=True, yellow_mask=True)\ncv2.imwrite('the3_B2_output.png', segmented_image)\nimage_bgr = cv2.imread(B3)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B3', blue_mask=True,\n white_mask=False, yellow_mask=False)\ncv2.imwrite('the3_B3_output.png', segmented_image)\nimage_bgr = cv2.imread(B4)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B4', blue_mask=True,\n white_mask=False, yellow_mask=False)\ncv2.imwrite('the3_B4_output.png', segmented_image)\nimage_bgr = cv2.imread(B5)\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\nsegmented_image = segmentation_function(image, 'B5', blue_mask=True,\n white_mask=False, yellow_mask=True)\ncv2.imwrite('the3_B5_output.png', segmented_image)\n",
"step-5": "# Bengisu Ayan - 2236974\n# Ceren Gürsoy - 2237485\n\nimport numpy as np \nimport cv2 \n\nB1 = \"THE3-Images/B1.jpg\"\nB2 = \"THE3-Images/B2.jpg\"\nB3 = \"THE3-Images/B3.jpg\"\nB4 = \"THE3-Images/B4.jpg\"\nB5 = \"THE3-Images/B5.jpg\"\n\n\ndef segmentation_function(image, name, blue_mask=False, white_mask=False, yellow_mask=False):\n # Smooth the image\n image = cv2.GaussianBlur(image,(11,11),0)\n\n # convert to HSV color system\n hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n\n # define green mask\n # green is applied to all the images as the dogs are all in grass\n low_green = np.array([30, 0, 0])\n high_green = np.array([86, 255, 255])\n mask_final = cv2.inRange(hsv_image, low_green, high_green)\n\n # define blue mask and apply it\n if blue_mask == True:\n low_blue = np.array([80, 0, 0])\n high_blue = np.array([125, 255, 255])\n mask_blue = cv2.inRange(hsv_image, low_blue, high_blue)\n mask_final = mask_final + mask_blue\n\n # define white mask and apply it\n if white_mask == True:\n low_white = np.array([0, 0, 200])\n high_white = np.array([145,60,255])\n mask_white = cv2.inRange(hsv_image, low_white, high_white)\n mask_final = mask_final + mask_white\n\n # define yellow mask and apply it\n if yellow_mask == True:\n low_yellow = np.array([10, 0, 0])\n high_yellow = np.array([33, 255, 100])\n mask_yellow = cv2.inRange(hsv_image, low_yellow, high_yellow)\n mask_final = mask_final + mask_yellow\n\n # make object white and background black\n mask_final = 255 - mask_final\n\n # apply opening to final mask\n # define 27*27 elliptical structuring element for opening\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(27,27))\n # apply opening\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel)\n\n # apply closing to final mask\n # define 41*41 elliptical structuring element for opening\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(41,41))\n # apply closing\n mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_CLOSE, kernel)\n\n # get biggest connected component\n segmented_image = np.zeros_like(mask_final) \n for val in np.unique(mask_final)[1:]: \n mask = np.uint8(mask_final == val) \n labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3] \n largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]) \n segmented_image[labels == largest_label] = val \n\n return segmented_image\n\n\n \n \n# Read B1\nimage_bgr = cv2.imread(B1)\n# convert B1 from bgr to rgb\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n# Apply segmentation to B1 with only green mask\nsegmented_image = segmentation_function(image, 'B1', blue_mask=False, white_mask=False, yellow_mask=False)\ncv2.imwrite(\"the3_B1_output.png\", segmented_image)\n\n# Read B2\nimage_bgr = cv2.imread(B2)\n# convert B2 from bgr to rgb\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n# Apply segmentation to B2 with green, white, yellow and blue masks\nsegmented_image = segmentation_function(image,'B2', blue_mask=True, white_mask=True, yellow_mask=True)\ncv2.imwrite(\"the3_B2_output.png\", segmented_image)\n\n# Read B3\nimage_bgr = cv2.imread(B3)\n# convert B3 from bgr to rgb\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n# Apply segmentation to B3 with green and blue masks\nsegmented_image = segmentation_function(image,'B3', blue_mask=True, white_mask=False, yellow_mask=False)\ncv2.imwrite(\"the3_B3_output.png\", segmented_image)\n\n# Read B4\nimage_bgr = cv2.imread(B4)\n# convert B4 from bgr to rgb\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n# Apply segmentation to B4 with green and blue masks\nsegmented_image = segmentation_function(image,'B4', blue_mask=True, white_mask=False, yellow_mask=False)\ncv2.imwrite(\"the3_B4_output.png\", segmented_image)\n\n# Read B5\nimage_bgr = cv2.imread(B5)\n# convert B5 from bgr to rgb\nimage = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n# Apply segmentation to B2 with green ,yellow and blue masks\nsegmented_image = segmentation_function(image,'B5', blue_mask=True, white_mask=False, yellow_mask=True)\ncv2.imwrite(\"the3_B5_output.png\", segmented_image)\n\n\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
import gym
import os
import sys
import numpy as np
import theano
import theano.tensor as T
import matplotlib.pyplot as plt
from gym import wrappers
from datetime import datetime
from mountain_car_v1_q_learning import Transformer
# so you can test different architectures
class Layer:
def __init__(self, m1, m2, f=T.nnet.relu, use_bias=True, zeros=False):
if zeros:
w = np.zeros((m1, m2))
else:
w = np.random.randn(m1, m2) * np.sqrt(2 / m1)
self.w = theano.shared(w)
self.params = [self.w]
self.use_bias = use_bias
if use_bias:
self.b = theano.shared(np.zeros(m2))
self.params += [self.b]
self.f = f
def forward(self, x):
if self.use_bias:
a = x.dot(self.w) + self.b
else:
a = x.dot(self.w)
return self.f(a)
# approximates pi(a | s)
class Policy:
def __init__(self, ft, D, layer_sizes_mean=[], layer_sizes_var=[]):
# save inputs for copy
self.ft = ft
self.D = D
self.layer_sizes_mean = layer_sizes_mean
self.layer_sizes_var = layer_sizes_var
##### model the mean #####
self.mean_layers = []
m1 = D
for m2 in layer_sizes_mean:
layer = Layer(m1, m2)
self.mean_layers.append(layer)
m1 = m2
# final layer
layer = Layer(m1, 1, lambda x: x, use_bias=False, zeros=True)
self.mean_layers.append(layer)
##### model the variance #####
self.var_layers = []
M1 = D
for M2 in layer_sizes_var:
layer = Layer(m1, m2)
self.var_layers.append(layer)
m1 = m2
# final layer
layer = Layer(m1, 1, T.nnet.softplus, use_bias=False, zeros=False)
self.var_layers.append(layer)
# get all params for gradient
params = []
for layer in (self.mean_layers + self.var_layers):
params += layer.params
self.params = params
# inputs and targets
x = T.matrix('x')
actions = T.vector('actions')
advantages = T.vector('advantages')
# calculate output and cost
def get_output(layers):
z = x
for layer in layers:
z = layer.forward(z)
return z.flatten()
mean = get_output(self.mean_layers)
var = get_output(self.var_layers) + 1e-4 # smoothing
self.predict_ = theano.function(
inputs=[x],
outputs=[mean, var],
allow_input_downcast=True
)
def predict(self, x):
x = np.atleast_2d(x)
x = self.ft.transform(x)
return self.predict_(x)
def sample_action(self, x):
pred = self.predict(x)
mu = pred[0][0]
v = pred[1][0]
a = np.random.randn()*np.sqrt(v) + mu
return min(max(a, -1), 1)
def copy(self):
clone = Policy(self.ft, self.D, self.layer_sizes_mean, self.layer_sizes_mean)
clone.copy_from(self)
return clone
def copy_from(self, other):
# self is being copied from other
for p, q in zip(self.params, other.params):
v = q.get_value()
p.set_value(v)
def perturb_params(self):
for p in self.params:
v = p.get_value()
noise = np.random.randn(*v.shape) / np.sqrt(v.shape[0]) * 5.0
if np.random.random() < 0.1:
# with probability 0.1 start completely from scratch
p.set_value(noise)
else:
p.set_value(v + noise)
def episode(env, policy, gamma):
observation = env.reset()
done = False
total_reward = 0
iterations = 0
while not done and iterations < 2000:
# if we reach 2000, just quit, don't want this going forever
# the 200 limit seems a bit early
action = policy.sample_action(observation)
# oddly, the mountain car environment requires the action to be in
# an object where the actual action is stored in object[0]
observation, reward, done, info = env.step([action])
total_reward += reward
iterations += 1
return total_reward
def series(env, T, policy, gamma, print_iters=False):
total_rewards = np.empty(T)
for i in range(T):
total_rewards[i] = episode(env, policy, gamma)
if print_iters:
print(i, "Average so far:", total_rewards[:(i+1)].mean())
avg_totalrewards = total_rewards.mean()
print("Average total rewards:", avg_totalrewards)
return avg_totalrewards
def random_search(env, policy, gamma):
total_rewards = []
best_avg_totalreward = float('-inf')
best_policy = policy
num_episodes_per_param_test = 3
for t in range(100):
tmp_model = best_policy.copy()
tmp_model.perturb_params()
avg_totalrewards = series(
env,
num_episodes_per_param_test,
tmp_model,
gamma
)
total_rewards.append(avg_totalrewards)
if avg_totalrewards > best_avg_totalreward:
best_policy = tmp_model
best_avg_totalreward = avg_totalrewards
return total_rewards, best_policy
def main():
env = gym.make('MountainCarContinuous-v0')
ft = Transformer(env, n_components=100)
D = ft.dimensions
model = Policy(ft, D, [], [])
gamma = 0.99
if 'monitor' in sys.argv:
filename = os.path.basename(__file__).split('.')[0]
monitor_dir = './' + filename + '_' + str(datetime.now())
env = wrappers.Monitor(env, monitor_dir)
total_rewards, model = random_search(env, model, gamma)
print("max reward:", np.max(total_rewards))
# play 100 episodes and check the average
avg_totalrewards = series(env, 100, model, gamma, print_iters=True)
print("avg reward over 100 episodes with best models:", avg_totalrewards)
plt.plot(total_rewards)
plt.title("Rewards")
plt.show()
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "63ee25791177ead5389c14990ce6da3e2c11b683",
"index": 6356,
"step-1": "<mask token>\n\n\nclass Layer:\n\n def __init__(self, m1, m2, f=T.nnet.relu, use_bias=True, zeros=False):\n if zeros:\n w = np.zeros((m1, m2))\n else:\n w = np.random.randn(m1, m2) * np.sqrt(2 / m1)\n self.w = theano.shared(w)\n self.params = [self.w]\n self.use_bias = use_bias\n if use_bias:\n self.b = theano.shared(np.zeros(m2))\n self.params += [self.b]\n self.f = f\n <mask token>\n\n\nclass Policy:\n\n def __init__(self, ft, D, layer_sizes_mean=[], layer_sizes_var=[]):\n self.ft = ft\n self.D = D\n self.layer_sizes_mean = layer_sizes_mean\n self.layer_sizes_var = layer_sizes_var\n self.mean_layers = []\n m1 = D\n for m2 in layer_sizes_mean:\n layer = Layer(m1, m2)\n self.mean_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, lambda x: x, use_bias=False, zeros=True)\n self.mean_layers.append(layer)\n self.var_layers = []\n M1 = D\n for M2 in layer_sizes_var:\n layer = Layer(m1, m2)\n self.var_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, T.nnet.softplus, use_bias=False, zeros=False)\n self.var_layers.append(layer)\n params = []\n for layer in (self.mean_layers + self.var_layers):\n params += layer.params\n self.params = params\n x = T.matrix('x')\n actions = T.vector('actions')\n advantages = T.vector('advantages')\n\n def get_output(layers):\n z = x\n for layer in layers:\n z = layer.forward(z)\n return z.flatten()\n mean = get_output(self.mean_layers)\n var = get_output(self.var_layers) + 0.0001\n self.predict_ = theano.function(inputs=[x], outputs=[mean, var],\n allow_input_downcast=True)\n\n def predict(self, x):\n x = np.atleast_2d(x)\n x = self.ft.transform(x)\n return self.predict_(x)\n\n def sample_action(self, x):\n pred = self.predict(x)\n mu = pred[0][0]\n v = pred[1][0]\n a = np.random.randn() * np.sqrt(v) + mu\n return min(max(a, -1), 1)\n\n def copy(self):\n clone = Policy(self.ft, self.D, self.layer_sizes_mean, self.\n layer_sizes_mean)\n clone.copy_from(self)\n return clone\n\n def copy_from(self, other):\n for p, q in zip(self.params, other.params):\n v = q.get_value()\n p.set_value(v)\n\n def perturb_params(self):\n for p in self.params:\n v = p.get_value()\n noise = np.random.randn(*v.shape) / np.sqrt(v.shape[0]) * 5.0\n if np.random.random() < 0.1:\n p.set_value(noise)\n else:\n p.set_value(v + noise)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Layer:\n\n def __init__(self, m1, m2, f=T.nnet.relu, use_bias=True, zeros=False):\n if zeros:\n w = np.zeros((m1, m2))\n else:\n w = np.random.randn(m1, m2) * np.sqrt(2 / m1)\n self.w = theano.shared(w)\n self.params = [self.w]\n self.use_bias = use_bias\n if use_bias:\n self.b = theano.shared(np.zeros(m2))\n self.params += [self.b]\n self.f = f\n\n def forward(self, x):\n if self.use_bias:\n a = x.dot(self.w) + self.b\n else:\n a = x.dot(self.w)\n return self.f(a)\n\n\nclass Policy:\n\n def __init__(self, ft, D, layer_sizes_mean=[], layer_sizes_var=[]):\n self.ft = ft\n self.D = D\n self.layer_sizes_mean = layer_sizes_mean\n self.layer_sizes_var = layer_sizes_var\n self.mean_layers = []\n m1 = D\n for m2 in layer_sizes_mean:\n layer = Layer(m1, m2)\n self.mean_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, lambda x: x, use_bias=False, zeros=True)\n self.mean_layers.append(layer)\n self.var_layers = []\n M1 = D\n for M2 in layer_sizes_var:\n layer = Layer(m1, m2)\n self.var_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, T.nnet.softplus, use_bias=False, zeros=False)\n self.var_layers.append(layer)\n params = []\n for layer in (self.mean_layers + self.var_layers):\n params += layer.params\n self.params = params\n x = T.matrix('x')\n actions = T.vector('actions')\n advantages = T.vector('advantages')\n\n def get_output(layers):\n z = x\n for layer in layers:\n z = layer.forward(z)\n return z.flatten()\n mean = get_output(self.mean_layers)\n var = get_output(self.var_layers) + 0.0001\n self.predict_ = theano.function(inputs=[x], outputs=[mean, var],\n allow_input_downcast=True)\n\n def predict(self, x):\n x = np.atleast_2d(x)\n x = self.ft.transform(x)\n return self.predict_(x)\n\n def sample_action(self, x):\n pred = self.predict(x)\n mu = pred[0][0]\n v = pred[1][0]\n a = np.random.randn() * np.sqrt(v) + mu\n return min(max(a, -1), 1)\n\n def copy(self):\n clone = Policy(self.ft, self.D, self.layer_sizes_mean, self.\n layer_sizes_mean)\n clone.copy_from(self)\n return clone\n\n def copy_from(self, other):\n for p, q in zip(self.params, other.params):\n v = q.get_value()\n p.set_value(v)\n\n def perturb_params(self):\n for p in self.params:\n v = p.get_value()\n noise = np.random.randn(*v.shape) / np.sqrt(v.shape[0]) * 5.0\n if np.random.random() < 0.1:\n p.set_value(noise)\n else:\n p.set_value(v + noise)\n\n\n<mask token>\n\n\ndef series(env, T, policy, gamma, print_iters=False):\n total_rewards = np.empty(T)\n for i in range(T):\n total_rewards[i] = episode(env, policy, gamma)\n if print_iters:\n print(i, 'Average so far:', total_rewards[:i + 1].mean())\n avg_totalrewards = total_rewards.mean()\n print('Average total rewards:', avg_totalrewards)\n return avg_totalrewards\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Layer:\n\n def __init__(self, m1, m2, f=T.nnet.relu, use_bias=True, zeros=False):\n if zeros:\n w = np.zeros((m1, m2))\n else:\n w = np.random.randn(m1, m2) * np.sqrt(2 / m1)\n self.w = theano.shared(w)\n self.params = [self.w]\n self.use_bias = use_bias\n if use_bias:\n self.b = theano.shared(np.zeros(m2))\n self.params += [self.b]\n self.f = f\n\n def forward(self, x):\n if self.use_bias:\n a = x.dot(self.w) + self.b\n else:\n a = x.dot(self.w)\n return self.f(a)\n\n\nclass Policy:\n\n def __init__(self, ft, D, layer_sizes_mean=[], layer_sizes_var=[]):\n self.ft = ft\n self.D = D\n self.layer_sizes_mean = layer_sizes_mean\n self.layer_sizes_var = layer_sizes_var\n self.mean_layers = []\n m1 = D\n for m2 in layer_sizes_mean:\n layer = Layer(m1, m2)\n self.mean_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, lambda x: x, use_bias=False, zeros=True)\n self.mean_layers.append(layer)\n self.var_layers = []\n M1 = D\n for M2 in layer_sizes_var:\n layer = Layer(m1, m2)\n self.var_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, T.nnet.softplus, use_bias=False, zeros=False)\n self.var_layers.append(layer)\n params = []\n for layer in (self.mean_layers + self.var_layers):\n params += layer.params\n self.params = params\n x = T.matrix('x')\n actions = T.vector('actions')\n advantages = T.vector('advantages')\n\n def get_output(layers):\n z = x\n for layer in layers:\n z = layer.forward(z)\n return z.flatten()\n mean = get_output(self.mean_layers)\n var = get_output(self.var_layers) + 0.0001\n self.predict_ = theano.function(inputs=[x], outputs=[mean, var],\n allow_input_downcast=True)\n\n def predict(self, x):\n x = np.atleast_2d(x)\n x = self.ft.transform(x)\n return self.predict_(x)\n\n def sample_action(self, x):\n pred = self.predict(x)\n mu = pred[0][0]\n v = pred[1][0]\n a = np.random.randn() * np.sqrt(v) + mu\n return min(max(a, -1), 1)\n\n def copy(self):\n clone = Policy(self.ft, self.D, self.layer_sizes_mean, self.\n layer_sizes_mean)\n clone.copy_from(self)\n return clone\n\n def copy_from(self, other):\n for p, q in zip(self.params, other.params):\n v = q.get_value()\n p.set_value(v)\n\n def perturb_params(self):\n for p in self.params:\n v = p.get_value()\n noise = np.random.randn(*v.shape) / np.sqrt(v.shape[0]) * 5.0\n if np.random.random() < 0.1:\n p.set_value(noise)\n else:\n p.set_value(v + noise)\n\n\n<mask token>\n\n\ndef series(env, T, policy, gamma, print_iters=False):\n total_rewards = np.empty(T)\n for i in range(T):\n total_rewards[i] = episode(env, policy, gamma)\n if print_iters:\n print(i, 'Average so far:', total_rewards[:i + 1].mean())\n avg_totalrewards = total_rewards.mean()\n print('Average total rewards:', avg_totalrewards)\n return avg_totalrewards\n\n\n<mask token>\n\n\ndef main():\n env = gym.make('MountainCarContinuous-v0')\n ft = Transformer(env, n_components=100)\n D = ft.dimensions\n model = Policy(ft, D, [], [])\n gamma = 0.99\n if 'monitor' in sys.argv:\n filename = os.path.basename(__file__).split('.')[0]\n monitor_dir = './' + filename + '_' + str(datetime.now())\n env = wrappers.Monitor(env, monitor_dir)\n total_rewards, model = random_search(env, model, gamma)\n print('max reward:', np.max(total_rewards))\n avg_totalrewards = series(env, 100, model, gamma, print_iters=True)\n print('avg reward over 100 episodes with best models:', avg_totalrewards)\n plt.plot(total_rewards)\n plt.title('Rewards')\n plt.show()\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass Layer:\n\n def __init__(self, m1, m2, f=T.nnet.relu, use_bias=True, zeros=False):\n if zeros:\n w = np.zeros((m1, m2))\n else:\n w = np.random.randn(m1, m2) * np.sqrt(2 / m1)\n self.w = theano.shared(w)\n self.params = [self.w]\n self.use_bias = use_bias\n if use_bias:\n self.b = theano.shared(np.zeros(m2))\n self.params += [self.b]\n self.f = f\n\n def forward(self, x):\n if self.use_bias:\n a = x.dot(self.w) + self.b\n else:\n a = x.dot(self.w)\n return self.f(a)\n\n\nclass Policy:\n\n def __init__(self, ft, D, layer_sizes_mean=[], layer_sizes_var=[]):\n self.ft = ft\n self.D = D\n self.layer_sizes_mean = layer_sizes_mean\n self.layer_sizes_var = layer_sizes_var\n self.mean_layers = []\n m1 = D\n for m2 in layer_sizes_mean:\n layer = Layer(m1, m2)\n self.mean_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, lambda x: x, use_bias=False, zeros=True)\n self.mean_layers.append(layer)\n self.var_layers = []\n M1 = D\n for M2 in layer_sizes_var:\n layer = Layer(m1, m2)\n self.var_layers.append(layer)\n m1 = m2\n layer = Layer(m1, 1, T.nnet.softplus, use_bias=False, zeros=False)\n self.var_layers.append(layer)\n params = []\n for layer in (self.mean_layers + self.var_layers):\n params += layer.params\n self.params = params\n x = T.matrix('x')\n actions = T.vector('actions')\n advantages = T.vector('advantages')\n\n def get_output(layers):\n z = x\n for layer in layers:\n z = layer.forward(z)\n return z.flatten()\n mean = get_output(self.mean_layers)\n var = get_output(self.var_layers) + 0.0001\n self.predict_ = theano.function(inputs=[x], outputs=[mean, var],\n allow_input_downcast=True)\n\n def predict(self, x):\n x = np.atleast_2d(x)\n x = self.ft.transform(x)\n return self.predict_(x)\n\n def sample_action(self, x):\n pred = self.predict(x)\n mu = pred[0][0]\n v = pred[1][0]\n a = np.random.randn() * np.sqrt(v) + mu\n return min(max(a, -1), 1)\n\n def copy(self):\n clone = Policy(self.ft, self.D, self.layer_sizes_mean, self.\n layer_sizes_mean)\n clone.copy_from(self)\n return clone\n\n def copy_from(self, other):\n for p, q in zip(self.params, other.params):\n v = q.get_value()\n p.set_value(v)\n\n def perturb_params(self):\n for p in self.params:\n v = p.get_value()\n noise = np.random.randn(*v.shape) / np.sqrt(v.shape[0]) * 5.0\n if np.random.random() < 0.1:\n p.set_value(noise)\n else:\n p.set_value(v + noise)\n\n\ndef episode(env, policy, gamma):\n observation = env.reset()\n done = False\n total_reward = 0\n iterations = 0\n while not done and iterations < 2000:\n action = policy.sample_action(observation)\n observation, reward, done, info = env.step([action])\n total_reward += reward\n iterations += 1\n return total_reward\n\n\ndef series(env, T, policy, gamma, print_iters=False):\n total_rewards = np.empty(T)\n for i in range(T):\n total_rewards[i] = episode(env, policy, gamma)\n if print_iters:\n print(i, 'Average so far:', total_rewards[:i + 1].mean())\n avg_totalrewards = total_rewards.mean()\n print('Average total rewards:', avg_totalrewards)\n return avg_totalrewards\n\n\n<mask token>\n\n\ndef main():\n env = gym.make('MountainCarContinuous-v0')\n ft = Transformer(env, n_components=100)\n D = ft.dimensions\n model = Policy(ft, D, [], [])\n gamma = 0.99\n if 'monitor' in sys.argv:\n filename = os.path.basename(__file__).split('.')[0]\n monitor_dir = './' + filename + '_' + str(datetime.now())\n env = wrappers.Monitor(env, monitor_dir)\n total_rewards, model = random_search(env, model, gamma)\n print('max reward:', np.max(total_rewards))\n avg_totalrewards = series(env, 100, model, gamma, print_iters=True)\n print('avg reward over 100 episodes with best models:', avg_totalrewards)\n plt.plot(total_rewards)\n plt.title('Rewards')\n plt.show()\n\n\n<mask token>\n",
"step-5": "import gym\nimport os\nimport sys\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport matplotlib.pyplot as plt\nfrom gym import wrappers\nfrom datetime import datetime\n\nfrom mountain_car_v1_q_learning import Transformer\n\n\n\n# so you can test different architectures\nclass Layer:\n\n def __init__(self, m1, m2, f=T.nnet.relu, use_bias=True, zeros=False):\n\n if zeros:\n w = np.zeros((m1, m2))\n else:\n w = np.random.randn(m1, m2) * np.sqrt(2 / m1)\n\n self.w = theano.shared(w)\n self.params = [self.w]\n self.use_bias = use_bias\n\n if use_bias:\n self.b = theano.shared(np.zeros(m2))\n self.params += [self.b]\n\n self.f = f\n\n def forward(self, x):\n\n if self.use_bias:\n a = x.dot(self.w) + self.b\n else:\n a = x.dot(self.w)\n\n return self.f(a)\n\n\n# approximates pi(a | s)\nclass Policy:\n\n\n def __init__(self, ft, D, layer_sizes_mean=[], layer_sizes_var=[]):\n # save inputs for copy\n self.ft = ft\n self.D = D\n self.layer_sizes_mean = layer_sizes_mean\n self.layer_sizes_var = layer_sizes_var\n\n ##### model the mean #####\n\n self.mean_layers = []\n m1 = D\n for m2 in layer_sizes_mean:\n layer = Layer(m1, m2)\n self.mean_layers.append(layer)\n m1 = m2\n\n # final layer\n layer = Layer(m1, 1, lambda x: x, use_bias=False, zeros=True)\n self.mean_layers.append(layer)\n\n\n ##### model the variance #####\n self.var_layers = []\n M1 = D\n for M2 in layer_sizes_var:\n layer = Layer(m1, m2)\n self.var_layers.append(layer)\n m1 = m2\n\n # final layer\n layer = Layer(m1, 1, T.nnet.softplus, use_bias=False, zeros=False)\n self.var_layers.append(layer)\n\n # get all params for gradient\n params = []\n for layer in (self.mean_layers + self.var_layers):\n params += layer.params\n self.params = params\n\n # inputs and targets\n x = T.matrix('x')\n actions = T.vector('actions')\n advantages = T.vector('advantages')\n\n # calculate output and cost\n def get_output(layers):\n z = x\n for layer in layers:\n z = layer.forward(z)\n return z.flatten()\n\n mean = get_output(self.mean_layers)\n var = get_output(self.var_layers) + 1e-4 # smoothing\n\n\n self.predict_ = theano.function(\n inputs=[x],\n outputs=[mean, var],\n allow_input_downcast=True\n )\n\n def predict(self, x):\n\n x = np.atleast_2d(x)\n x = self.ft.transform(x)\n\n return self.predict_(x)\n\n def sample_action(self, x):\n\n pred = self.predict(x)\n mu = pred[0][0]\n v = pred[1][0]\n a = np.random.randn()*np.sqrt(v) + mu\n\n return min(max(a, -1), 1)\n\n def copy(self):\n\n clone = Policy(self.ft, self.D, self.layer_sizes_mean, self.layer_sizes_mean)\n clone.copy_from(self)\n return clone\n\n def copy_from(self, other):\n # self is being copied from other\n for p, q in zip(self.params, other.params):\n v = q.get_value()\n p.set_value(v)\n\n def perturb_params(self):\n\n for p in self.params:\n v = p.get_value()\n noise = np.random.randn(*v.shape) / np.sqrt(v.shape[0]) * 5.0\n if np.random.random() < 0.1:\n # with probability 0.1 start completely from scratch\n p.set_value(noise)\n else:\n p.set_value(v + noise)\n\n\ndef episode(env, policy, gamma):\n\n observation = env.reset()\n done = False\n total_reward = 0\n iterations = 0\n\n while not done and iterations < 2000:\n # if we reach 2000, just quit, don't want this going forever\n # the 200 limit seems a bit early\n action = policy.sample_action(observation)\n # oddly, the mountain car environment requires the action to be in\n # an object where the actual action is stored in object[0]\n observation, reward, done, info = env.step([action])\n\n total_reward += reward\n iterations += 1\n\n return total_reward\n\n\ndef series(env, T, policy, gamma, print_iters=False):\n\n total_rewards = np.empty(T)\n\n for i in range(T):\n total_rewards[i] = episode(env, policy, gamma)\n\n if print_iters:\n print(i, \"Average so far:\", total_rewards[:(i+1)].mean())\n\n avg_totalrewards = total_rewards.mean()\n print(\"Average total rewards:\", avg_totalrewards)\n return avg_totalrewards\n\n\ndef random_search(env, policy, gamma):\n\n total_rewards = []\n best_avg_totalreward = float('-inf')\n best_policy = policy\n num_episodes_per_param_test = 3\n\n for t in range(100):\n tmp_model = best_policy.copy()\n\n tmp_model.perturb_params()\n\n avg_totalrewards = series(\n env,\n num_episodes_per_param_test,\n tmp_model,\n gamma\n )\n total_rewards.append(avg_totalrewards)\n\n if avg_totalrewards > best_avg_totalreward:\n best_policy = tmp_model\n best_avg_totalreward = avg_totalrewards\n\n return total_rewards, best_policy\n\n\ndef main():\n env = gym.make('MountainCarContinuous-v0')\n ft = Transformer(env, n_components=100)\n D = ft.dimensions\n model = Policy(ft, D, [], [])\n gamma = 0.99\n\n if 'monitor' in sys.argv:\n filename = os.path.basename(__file__).split('.')[0]\n monitor_dir = './' + filename + '_' + str(datetime.now())\n env = wrappers.Monitor(env, monitor_dir)\n\n\n total_rewards, model = random_search(env, model, gamma)\n\n print(\"max reward:\", np.max(total_rewards))\n\n # play 100 episodes and check the average\n avg_totalrewards = series(env, 100, model, gamma, print_iters=True)\n print(\"avg reward over 100 episodes with best models:\", avg_totalrewards)\n\n plt.plot(total_rewards)\n plt.title(\"Rewards\")\n plt.show()\n\n\nif __name__ == '__main__':\n main()",
"step-ids": [
9,
11,
12,
13,
17
]
}
|
[
9,
11,
12,
13,
17
] |
<|reserved_special_token_0|>
class KeyValueRedis:
<|reserved_special_token_0|>
def __init__(self, context, redis_client):
"""Initialize the Class properties."""
self._context = context
self._redis_client = redis_client
<|reserved_special_token_0|>
@context.setter
def context(self, context):
"""Set or update the current context."""
self._context = context
def create(self, key, value):
"""Create key/value pair in Redis.
Args:
key (str): The field name (key) for the kv pair in Redis.
value (any): The value for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hset(self.context, key, value)
def delete(self, key):
"""Alias for hdel method.
Args:
key (str): The field name (key) for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hdel(self.context, key)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class KeyValueRedis:
<|reserved_special_token_0|>
def __init__(self, context, redis_client):
"""Initialize the Class properties."""
self._context = context
self._redis_client = redis_client
<|reserved_special_token_0|>
@context.setter
def context(self, context):
"""Set or update the current context."""
self._context = context
def create(self, key, value):
"""Create key/value pair in Redis.
Args:
key (str): The field name (key) for the kv pair in Redis.
value (any): The value for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hset(self.context, key, value)
def delete(self, key):
"""Alias for hdel method.
Args:
key (str): The field name (key) for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hdel(self.context, key)
def hgetall(self):
"""Read data from Redis for the current context.
Returns:
list: The response data from Redis.
"""
return self._redis_client.hgetall(self.context)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class KeyValueRedis:
<|reserved_special_token_0|>
def __init__(self, context, redis_client):
"""Initialize the Class properties."""
self._context = context
self._redis_client = redis_client
@property
def context(self):
"""Return the current context."""
return self._context
@context.setter
def context(self, context):
"""Set or update the current context."""
self._context = context
def create(self, key, value):
"""Create key/value pair in Redis.
Args:
key (str): The field name (key) for the kv pair in Redis.
value (any): The value for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hset(self.context, key, value)
def delete(self, key):
"""Alias for hdel method.
Args:
key (str): The field name (key) for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hdel(self.context, key)
def hgetall(self):
"""Read data from Redis for the current context.
Returns:
list: The response data from Redis.
"""
return self._redis_client.hgetall(self.context)
def read(self, key):
"""Read data from Redis for the provided key.
Returns:
str: The response data from Redis.
"""
value = self._redis_client.hget(self.context, key)
if isinstance(value, bytes):
value = value.decode('utf-8')
return value
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class KeyValueRedis:
"""TcEx Key Value Redis Module.
Args:
context (str): The Redis context (hash) for hashed based operations.
redis_client (redis.Client): An instance of redis client.
"""
def __init__(self, context, redis_client):
"""Initialize the Class properties."""
self._context = context
self._redis_client = redis_client
@property
def context(self):
"""Return the current context."""
return self._context
@context.setter
def context(self, context):
"""Set or update the current context."""
self._context = context
def create(self, key, value):
"""Create key/value pair in Redis.
Args:
key (str): The field name (key) for the kv pair in Redis.
value (any): The value for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hset(self.context, key, value)
def delete(self, key):
"""Alias for hdel method.
Args:
key (str): The field name (key) for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hdel(self.context, key)
def hgetall(self):
"""Read data from Redis for the current context.
Returns:
list: The response data from Redis.
"""
return self._redis_client.hgetall(self.context)
def read(self, key):
"""Read data from Redis for the provided key.
Returns:
str: The response data from Redis.
"""
value = self._redis_client.hget(self.context, key)
if isinstance(value, bytes):
value = value.decode('utf-8')
return value
<|reserved_special_token_1|>
"""TcEx Framework Key Value Redis Module"""
class KeyValueRedis:
"""TcEx Key Value Redis Module.
Args:
context (str): The Redis context (hash) for hashed based operations.
redis_client (redis.Client): An instance of redis client.
"""
def __init__(self, context, redis_client):
"""Initialize the Class properties."""
self._context = context
self._redis_client = redis_client
@property
def context(self):
"""Return the current context."""
return self._context
@context.setter
def context(self, context):
"""Set or update the current context."""
self._context = context
def create(self, key, value):
"""Create key/value pair in Redis.
Args:
key (str): The field name (key) for the kv pair in Redis.
value (any): The value for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hset(self.context, key, value)
def delete(self, key):
"""Alias for hdel method.
Args:
key (str): The field name (key) for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self._redis_client.hdel(self.context, key)
def hgetall(self):
"""Read data from Redis for the current context.
Returns:
list: The response data from Redis.
"""
return self._redis_client.hgetall(self.context)
def read(self, key):
"""Read data from Redis for the provided key.
Returns:
str: The response data from Redis.
"""
value = self._redis_client.hget(self.context, key)
# convert retrieved bytes to string
if isinstance(value, bytes):
value = value.decode('utf-8')
return value
|
flexible
|
{
"blob_id": "a5b74c31aed103b55404afc538af60c3eb18cb1b",
"index": 9738,
"step-1": "<mask token>\n\n\nclass KeyValueRedis:\n <mask token>\n\n def __init__(self, context, redis_client):\n \"\"\"Initialize the Class properties.\"\"\"\n self._context = context\n self._redis_client = redis_client\n <mask token>\n\n @context.setter\n def context(self, context):\n \"\"\"Set or update the current context.\"\"\"\n self._context = context\n\n def create(self, key, value):\n \"\"\"Create key/value pair in Redis.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n value (any): The value for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hset(self.context, key, value)\n\n def delete(self, key):\n \"\"\"Alias for hdel method.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hdel(self.context, key)\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass KeyValueRedis:\n <mask token>\n\n def __init__(self, context, redis_client):\n \"\"\"Initialize the Class properties.\"\"\"\n self._context = context\n self._redis_client = redis_client\n <mask token>\n\n @context.setter\n def context(self, context):\n \"\"\"Set or update the current context.\"\"\"\n self._context = context\n\n def create(self, key, value):\n \"\"\"Create key/value pair in Redis.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n value (any): The value for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hset(self.context, key, value)\n\n def delete(self, key):\n \"\"\"Alias for hdel method.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hdel(self.context, key)\n\n def hgetall(self):\n \"\"\"Read data from Redis for the current context.\n\n Returns:\n list: The response data from Redis.\n \"\"\"\n return self._redis_client.hgetall(self.context)\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass KeyValueRedis:\n <mask token>\n\n def __init__(self, context, redis_client):\n \"\"\"Initialize the Class properties.\"\"\"\n self._context = context\n self._redis_client = redis_client\n\n @property\n def context(self):\n \"\"\"Return the current context.\"\"\"\n return self._context\n\n @context.setter\n def context(self, context):\n \"\"\"Set or update the current context.\"\"\"\n self._context = context\n\n def create(self, key, value):\n \"\"\"Create key/value pair in Redis.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n value (any): The value for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hset(self.context, key, value)\n\n def delete(self, key):\n \"\"\"Alias for hdel method.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hdel(self.context, key)\n\n def hgetall(self):\n \"\"\"Read data from Redis for the current context.\n\n Returns:\n list: The response data from Redis.\n \"\"\"\n return self._redis_client.hgetall(self.context)\n\n def read(self, key):\n \"\"\"Read data from Redis for the provided key.\n\n Returns:\n str: The response data from Redis.\n \"\"\"\n value = self._redis_client.hget(self.context, key)\n if isinstance(value, bytes):\n value = value.decode('utf-8')\n return value\n",
"step-4": "<mask token>\n\n\nclass KeyValueRedis:\n \"\"\"TcEx Key Value Redis Module.\n\n Args:\n context (str): The Redis context (hash) for hashed based operations.\n redis_client (redis.Client): An instance of redis client.\n \"\"\"\n\n def __init__(self, context, redis_client):\n \"\"\"Initialize the Class properties.\"\"\"\n self._context = context\n self._redis_client = redis_client\n\n @property\n def context(self):\n \"\"\"Return the current context.\"\"\"\n return self._context\n\n @context.setter\n def context(self, context):\n \"\"\"Set or update the current context.\"\"\"\n self._context = context\n\n def create(self, key, value):\n \"\"\"Create key/value pair in Redis.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n value (any): The value for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hset(self.context, key, value)\n\n def delete(self, key):\n \"\"\"Alias for hdel method.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hdel(self.context, key)\n\n def hgetall(self):\n \"\"\"Read data from Redis for the current context.\n\n Returns:\n list: The response data from Redis.\n \"\"\"\n return self._redis_client.hgetall(self.context)\n\n def read(self, key):\n \"\"\"Read data from Redis for the provided key.\n\n Returns:\n str: The response data from Redis.\n \"\"\"\n value = self._redis_client.hget(self.context, key)\n if isinstance(value, bytes):\n value = value.decode('utf-8')\n return value\n",
"step-5": "\"\"\"TcEx Framework Key Value Redis Module\"\"\"\n\n\nclass KeyValueRedis:\n \"\"\"TcEx Key Value Redis Module.\n\n Args:\n context (str): The Redis context (hash) for hashed based operations.\n redis_client (redis.Client): An instance of redis client.\n \"\"\"\n\n def __init__(self, context, redis_client):\n \"\"\"Initialize the Class properties.\"\"\"\n self._context = context\n self._redis_client = redis_client\n\n @property\n def context(self):\n \"\"\"Return the current context.\"\"\"\n return self._context\n\n @context.setter\n def context(self, context):\n \"\"\"Set or update the current context.\"\"\"\n self._context = context\n\n def create(self, key, value):\n \"\"\"Create key/value pair in Redis.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n value (any): The value for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hset(self.context, key, value)\n\n def delete(self, key):\n \"\"\"Alias for hdel method.\n\n Args:\n key (str): The field name (key) for the kv pair in Redis.\n\n Returns:\n str: The response from Redis.\n \"\"\"\n return self._redis_client.hdel(self.context, key)\n\n def hgetall(self):\n \"\"\"Read data from Redis for the current context.\n\n Returns:\n list: The response data from Redis.\n \"\"\"\n return self._redis_client.hgetall(self.context)\n\n def read(self, key):\n \"\"\"Read data from Redis for the provided key.\n\n Returns:\n str: The response data from Redis.\n \"\"\"\n value = self._redis_client.hget(self.context, key)\n # convert retrieved bytes to string\n if isinstance(value, bytes):\n value = value.decode('utf-8')\n return value\n",
"step-ids": [
5,
6,
8,
9,
10
]
}
|
[
5,
6,
8,
9,
10
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.