示例#1
0
    def keyHandler(self, event):
        '''Event handling function called when a key is pressed. Checks if key
        is a valid move, ends game if q is entered, otherwise makes a move on
        the dictionary board and checks if the game is over. If not,
        sets up for the next move.
        '''

        movesDict = { 'Left': 'a',
                      'Right': 'd',
                      'Up': 'w',
                      'Down': 's' }
        if event.keysym not in ['Left', 'Right', 'Up', 'Down', 'q', 'z']:
            self.displayText('Invalid move! Try again...')
            return
        if event.keysym == 'q':
            quit()
        if event.keysym == 'z':
            lastState = self.boardLastStates.pop()
            self.board = lastState.copy()
            self.updateGUIBoard()
        else:
            cmd = movesDict[event.keysym]
            self.boardLastStates.append(self.board.copy())
            # Save last state of board for undo option.
            engine.update(self.board, cmd)
            self.updateGUIBoard()
            self.displayText('Enter Move: ')
        if engine.game_over(self.board):
            self.displayText('Game over!')
            quit()
示例#2
0
def run(cycles, fact):
    # Prepare data containers
    data = {}

    # Run the loop
    for cycle in range(cycles):
        # Retrieve the important bits
        (engine, manager) = fact.createHeadless()

        # play the game once
        done = False
        while not done:
            # Prepare data-gathering
            while manager.copyState().GMState < manager.GMStates['resolve']:
                if engine.update():  # Run the game up to resolution
                    done = True
                    break  # Break the loop if someone has already won
            if done:
                break  # No more collections
            while manager.copyState().GMState == manager.GMStates['resolve']:
                if engine.update():  # Finish the resolution step
                    done = True
                    break  # Game is over, time to collect data

        # Collect winnerData
        state = manager.copyState()
        winner = state.winner

        # increase count of the most recent winner
        if winner in data:
            data[winner] += 1
        else:
            data[winner] = 0

    print(data)
示例#3
0
文件: interface.py 项目: phzixis/mp2
def update(dt):
    engine.update()
    if engine.gameStarted:
        engine.camera.update()
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, engine.camera.width, 0, engine.camera.height, -1, 1)
        glTranslatef(-engine.camera.x, -engine.camera.y, 0)
        glScalef(engine.camera.toZoom, engine.camera.toZoom, 1)
        glMatrixMode(GL_MODELVIEW)
示例#4
0
def main():
    objUser = open("USERNAME.txt", "r")
    objPassword = open("PASSWORD.txt", "r")

    flag = 0
    browser = webdriver.Firefox()

    tag = getHashtag(browser, flag)

    engine.init(browser, tag, flag)
    engine.update(browser)
示例#5
0
def cycle(margs):
    """Runs a single game cycle. Broken out of the run function to allow
    multiprocessing support.

    Takes the factory as an argument.

    Returns the dataset from the cycle.

    """
    # Retrieve the important bits, now with bake your own factory
    fact = factory.Factory(margs)
    (engine, manager) = fact.createHeadless()
        
    # Prepare game dataset
    state = manager.copyState()
    gameData = {'turn' : 0, 'winner' : None, 'players' : {}}
    for key in state.players:
        gameData['players'][key] = []

    # Do the game
    done = False
    while not done:
        # Prepare data-gathering
        while manager.copyState().GMState < manager.GMStates['resolve']:
            if engine.update(): # Run the game up to resolution
                done = True
                break # Break the loop if someone has already won
        if done:
            gameData['winner'] = state.winner
            break # No more collections
        while manager.copyState().GMState == manager.GMStates['resolve']:
            if engine.update(): # Finish the resolution step
                done = True
                break # Game is over, time to collect data
                    
        # Collect data for the turn
        state = manager.copyState()
        for key in state.players:
            gameData['players'][key].append(
                state.getPlayer(key).ship.getPos())
        gameData['winner'] = state.winner
        if not done:
            gameData['turn'] += 1

    # End
    return gameData
示例#6
0
def run():
    engine.running = True
    engine.start()
    engine.world = world.host_or_connect(engine)

    lt = time.time()
    ticks = 0
    fr = 0
    engine.screen_refresh = 1
    engine.next_screen = engine.screen_refresh

    while engine.running:
        engine.dt = engine.clock.tick(getattr(engine, "framerate", 30))
        engine.dt = min(engine.dt * .001 * 60, 100.0)
        engine.update()
        engine.next_screen -= engine.dt
        if engine.next_screen < 0:
            engine.clear_screen()
            engine.world.draw()
            engine.draw_screen()
            engine.next_screen = engine.screen_refresh
        controller.input()
    print "quit"
示例#7
0
def run(cycles, fact):
    # Prepare data containers
    data = {}

    
    # Run the loop
    for cycle in range(cycles):
        # Retrieve the important bits
        (engine, manager) = fact.createHeadless()
        
        # play the game once
        done = False
        while not done:
            # Prepare data-gathering
            while manager.copyState().GMState < manager.GMStates['resolve']:
                if engine.update(): # Run the game up to resolution
                    done = True
                    break # Break the loop if someone has already won
            if done:
                break # No more collections
            while manager.copyState().GMState == manager.GMStates['resolve']:
                if engine.update(): # Finish the resolution step
                    done = True
                    break # Game is over, time to collect data
                    
        # Collect winnerData
        state = manager.copyState()
        winner = state.winner
            
        # increase count of the most recent winner
        if winner in data:
            data[winner] += 1
        else:
            data[winner] = 0

    print(data)
示例#8
0
def run():
    engine.running = True
    engine.start()
    engine.world = world.make_world(engine)
    
    
    lt = time.time()
    ticks = 0
    fr = 0
    engine.screen_refresh = 1
    engine.next_screen = engine.screen_refresh

    while engine.running:
        engine.dt = engine.clock.tick(getattr(engine,"framerate",30))
        engine.dt = min(engine.dt*.001*60,100.0)
        engine.update()
        engine.next_screen -= engine.dt
        if engine.next_screen < 0:
            engine.clear_screen()
            engine.world.draw()
            engine.draw_screen()
            engine.next_screen = engine.screen_refresh
        controller.input()
    print "quit"
示例#9
0
 def updateGame(self):
     if self.gameRunning and not self.gameOver:
         if (self.currentFrameIndex % (setupVars.framesPerStep//(self.key[3]*setupVars.downKeyDiv+1))) == 0:
             result = engine.step(self.canvas)
             self.gameScore += {0:0,1:10,2:50,3:100,4:1000}[result[1]]
             self.printTerm("Score: {:0>5}".format(self.gameScore))
         else:
             keys = self.keyToSend()
             result = engine.update(self.canvas,keys)
         self.gameOver = result[0]
         self.currentFrameIndex += 1
         self.currentFrameLabel.configure(text="Frame: {}".format(self.currentFrameIndex))
         self.after(int(1000/setupVars.framerate),self.updateGame)
     elif self.gameRunning and self.gameOver:
         self.gameRunning = False
         self.printTerm("Game Over!")
         self.after(int(1000/setupVars.framerate),self.updateGame)
     else:
         pass
示例#10
0
(options, args) = parser.parse_args()

utils.config.init(options.config_name)

slaveType = utils.config.SlaveType
BrowserBenchmarks = utils.config.browserbenchmarks()
ShellBenchmarks = utils.config.shellbenchmarks()
KnownEngines = utils.config.engines()

# Update All engines
NumUpdated = 0
RunningEngines = []
for engine in KnownEngines:
    try:
        engine.update()
        if engine.updated:
            NumUpdated += 1
        RunningEngines.append(engine)
    except Exception, e:
        import logging
        logging.exception(e) # or pass an error message, see comment

class Slave:
    def __init__(self, machine):
        self.machine = machine
submitter = submitter.getSubmitter(options.submitter)
submit = submitter(Slave(utils.config.get('main', 'machine')))

# No updates. Report to server and wait 60 seconds, before moving on
if NumUpdated == 0 and not options.force:
示例#11
0
(options, args) = parser.parse_args()

utils.config.init(options.config_name)

slaveType = utils.config.SlaveType
BrowserBenchmarks = utils.config.browserbenchmarks()
ShellBenchmarks = utils.config.shellbenchmarks()
KnownEngines = utils.config.engines()

# Update All engines
NumUpdated = 0
RunningEngines = []
for engine in KnownEngines:
    try:
        engine.update()
        if engine.updated:
            NumUpdated += 1
        RunningEngines.append(engine)
    except Exception, e:
        import logging
        logging.exception(e)  # or pass an error message, see comment


class Slave:
    def __init__(self, machine):
        self.machine = machine


submitter = submitter.getSubmitter(options.submitter)
submit = submitter(Slave(utils.config.get('main', 'machine')))
示例#12
0
def Script(browser, hashtag):
    time_until_last_check = 0
    time_elapsed_until_check = time_elapsed.time_check()
    while (check):
        # Verificando usuarios, parar de seguir
        if time_until_last_check > time_elapsed_until_check:
            engine.update(browser)
        else:
            time_until_last_check = time_until_last_check + 1
        # Redirecionar para página inicial
        browser.get('https://www.instagram.com/explore/tags/' + hashtag + '/')
        time.sleep(3)
        # Chamada da funcao para pegar os href das imagens
        image_hrefs = getAttributesScript(browser, hashtag)
        # Variaveis
        flag = constantes.FLAG
        likeable_image = len(image_hrefs)
        previous_user_list = dbusers.get_followed_users()
        previous_user_href = dbusers.get_previous_hrefs()
        new_followers = []
        followed = 0
        likes = 0
        count = 0
        swap = 0
        # Inicio do Script
        for image_href in image_hrefs:
            if image_href not in previous_user_href:
                dbusers.add_href(image_href)
                # Começa a percorrer todas as imagens armazenadas no vetor image_hrefs
                browser.get(image_href)
                geturl = browser.current_url
                try:
                    profile_name = browser.find_element_by_xpath(
                        '/html/body/div/section/main/div/div/article/header/div[2]/div/div/span/a'
                    ).text
                    time.sleep(5)
                    if browser.find_element_by_xpath(
                            '/html/body/div/section/main/div/div/article/header/div[2]/div/div/span/a'
                    ):
                        time.sleep(3)

                except Exception:
                    print("Failed to get element, trying again.")
                    continue
                    time.sleep(5)

                print("{}".format(profile_name))
                time.sleep(3)
                countvalue, flagvalue = randomGenerator()

                print("{}".format('*'))
                time.sleep(random.randint(2, 4))

                if countvalue == constantes.VALUECONST:
                    print("{}".format('Sleeping'))
                    timedOut()
                    swap += 1
                    if swap == constantes.VALUECONST:
                        print("Swap = {}, dormindo ... ".format(swap))
                        swap = 0
                        time.sleep(random.randint(200, 600))

                else:
                    semaphore = False
                    try:
                        like = browser.find_element_by_css_selector(
                            '[aria-label="Curtir"]')
                        time.sleep(5)
                        if browser.find_element_by_css_selector(
                                '[aria-label="Curtir"]'):
                            time.sleep(3)
                    except Exception:
                        print("Failed to get element, trying again.")
                        continue
                        time.sleep(5)

                    like_limit_exist = True
                    like_limit_semaphore = True
                    while (like_limit_exist):
                        try:
                            if (browser.find_element_by_xpath(
                                    '/html/body/div/section/main/div/div/article/div[3]/section[2]/div/div[2]/button/span'
                            )):
                                like_limit = browser.find_element_by_xpath(
                                    '/html/body/div/section/main/div/div/article/div[3]/section[2]/div/div[2]/button/span'
                                ).text
                                like_limit_exist = False
                            else:
                                like_limit = browser.find_element_by_xpath(
                                    '/html/body/div/section/main/div/div/article/div[3]/section[2]/div/span/span'
                                ).text
                                like_limit_exist = False
                        except Exception:
                            print("{}".format(
                                'Não foi possível localizar nenhum elemento, continuando'
                            ))
                            like_limit_exist = False
                            like_limit = 1
                            pass

                    if like_limit_semaphore != False:
                        try:
                            for i in range(len(like_limit)):
                                if like_limit[i] == '.':
                                    aux = float(like_limit)
                                    aux = aux * (10**(i + 2))
                                    integer_like_limit = int(aux)
                                    print("Valor corrigido {}".format(
                                        integer_like_limit))
                                    semaphore = True
                        except Exception as e:
                            # Default value for handle errors
                            pass
                    else:
                        like_limit = random.randint(0, 5)

                    if semaphore != True:
                        integer_like_limit = int(like_limit)
                    print('Quantida de curtidas da imagem {}'.format(
                        integer_like_limit))
                    if integer_like_limit > constantes.LIKES_LIMIT:
                        print("{}".format(
                            'Imagem não podera ser curtidas, muito popular!'))
                    else:
                        print("{}".format('Imagem curtida'))
                        choice = [True, False]
                        if random.choice(choice) == True and likes < 10:
                            like.click()
                            likes += 1
                            time.sleep(random.randint(18, 30))
                            if likes > 10:
                                print(
                                    "Muitas curtidas, {}. Bot timeout.".format(
                                        likes))
                                time.sleep(random.randint(500, 800))
                                print(
                                    "Bot wakeup, após excesso de curtidas {}".
                                    format(likes))
                                likes = 0

                    print("Perfil de {0}".format(profile_name))
                    try:
                        if browser.find_element_by_xpath(
                                '//button[text()="Seguir"]'):
                            time.sleep(2)
                            if random.randint(1, 6) == constantes.VALUECONST:
                                dbusers.add_user((profile_name))
                                browser.find_element_by_xpath(
                                    '//button[text()="Seguir"]').click()
                                followed += 1
                                print("Seguidos: {0}, #{1}".format(
                                    profile_name, followed))
                                new_followers.append((profile_name))
                                time.sleep(random.randint(30, 240))
                            else:
                                time.sleep(3)

                    except Exception:
                        print("Perfil de {} já está sendo seguido".format(
                            profile_name))

                    print("{}".format('Nova Imagem'))
                    try:
                        if browser.find_element_by_css_selector(
                                '[aria-label="Descurtir"]'):
                            browser.find_element_by_css_selector(
                                '[aria-label="Descurtir"]').click()
                            # Curtir comentario
                            like_comment = browser.find_elements_by_css_selector(
                                '[aria-label="Curtir"]')[random.randint(
                                    0, 8)].click()
                            like_comment().click()
                            likes += 1
                            time.sleep(random.randint(5, 18))
                            # Comentar
                            comment = ["Muito bom!", "Legal!", ":)"]
                            comment_profile = browser.find_element_by_css_selector(
                                '[aria-label="Adicione um comentário..."]')
                            comment_profile.click()
                            comment_profile.sendkeys(random.choice(comment))
                        else:
                            like_comment = browser.find_elements_by_css_selector(
                                '[aria-label="Curtir"]')[random.randint(
                                    0, 8)].click()
                            like_comment().click()
                            likes += 1

                    except Exception:
                        time.sleep(3)

            else:
                print("{}".format('Imagem repetida, ignorando'))
                continue

        for l in range(0, len(new_followers)):
            previous_user_list.append(new_followers[l])

            print("Curtidas {} fotos.".format(likes))
            print("Seguidos {} novas pessoas.".format(followed))

        user_choices = dbusers.get_followed_users()

        random_profile_choice = random.choice(user_choices)
        browser.get('https://www.instagram.com/' + random_profile_choice + '/')
        time.sleep(5)
        user_hrefs = getAttributesScript(browser, profile_name)
        previous_user_href = dbusers.get_previous_hrefs()
        new_hrefs = []
        var_check = 0

        for user_href in user_hrefs:
            browser.get(user_href)
            # Não analisar mesma foto varias vezes, otimizar processo
            if user_href not in previous_user_href:
                dbusers.add_href(user_href)
                try:
                    semaphore = False
                    user_like = browser.find_element_by_css_selector(
                        '[aria-label="Curtir"]')
                    try:
                        if (browser.find_element_by_xpath(
                                '/html/body/div/section/main/div/div/article/div[3]/section[2]/div/div[2]/button/span'
                        )):
                            like_limit = browser.find_element_by_xpath(
                                '/html/body/div/section/main/div/div/article/div[3]/section[2]/div/div[2]/button/span'
                            ).text
                        else:
                            like_limit = browser.find_element_by_xpath(
                                '/html/body/div/section/main/div/div/article/div[3]/section[2]/div/span/span'
                            ).text
                    except Exception:
                        print("{}".format(
                            'Não foi possível localizar nenhum elemento, continuando'
                        ))
                        time.sleep(1)

                    for i in range(len(like_limit)):
                        if like_limit[i] == '.':
                            aux = float(like_limit)
                            aux = aux * (10**(i + 2))
                            integer_like_limit = int(aux)
                            print("Valor corrigido {}".format(
                                integer_like_limit))
                            semaphore = True

                    if semaphore != True:
                        integer_like_limit = int(like_limit)
                    print('Quantida de curtidas da imagem {}'.format(
                        integer_like_limit))

                    if integer_like_limit > constantes.LIKES_LIMIT:
                        print("{}".format('Não curtido'))
                    else:
                        print(
                            "Usuario {} curtido".format(random_profile_choice))
                        user_like.click()
                        var_check += 1
                        if var_check > 10:
                            print(
                                "Muitas curtidas {}, iniciando timeout".format(
                                    count))
                            time.sleep(500, 800)
                            var_check = 0

                except Exception:
                    time.sleep(2)
            else:
                try:
                    if browser.find_element_by_css_selector(
                            '[aria-label="Descurtir"]'):
                        browser.find_element_by_css_selector(
                            '[aria-label="Descurtir"]').click()
                        # Curtir comentario
                        like_comment = browser.find_elements_by_css_selector(
                            '[aria-label="Curtir"]')[random.randint(
                                0, 8)].click()
                        like_comment().click()
                        likes += 1
                        time.sleep(random.randint(5, 18))
                        # Comentar
                        comment = ["Muito bom!", "Legal!", ":)"]
                        comment_profile = browser.find_element_by_css_selector(
                            '[aria-label="Adicione um comentário..."]')
                        comment_profile.click()
                        comment_profile.sendkeys(random.choice(comment))
                    else:
                        like_comment = browser.find_elements_by_css_selector(
                            '[aria-label="Curtir"]')[random.randint(
                                0, 8)].click()
                        like_comment().click()
                        likes += 1

                except Exception:
                    time.sleep(3)

        print("Reiniciando tarefas ... ")
示例#13
0
def update():
    req = request.get_json(force=True)
    response = eng.update(req)

    return response
示例#14
0
from selenium import webdriver
from time import sleep
import engine

chromedriver = './chromedriver.exe'
webdriver = webdriver.Chrome(executable_path=chromedriver)

engine.init(webdriver)
engine.update(webdriver)

sleep(10)
webdriver.close()
示例#15
0
def asknextquestion(request):

    session = get_current_session()
    assessmentkey = ''

    c = session.get('studentname', -1)
    if c != -1:

        if request.method != 'POST':
            usersdict.pop(c, None)
            assessmentkey = request.GET['id']
            session['assessmentkey'] = assessmentkey
            key = ndb.Key(urlsafe=assessmentkey)
            session['assessmentkey'] = key
            logging.error(assessmentkey)
            assessment = key.get()
            listoftopics = assessment.topics_in_assessment_key
            session['listoftopics'] = listoftopics
            session['topicnumber'] = 0
            completedtopics[session['studentname']] = {}
            scorelist[session['studentname']] = []
            topictimespend[session['studentname']] = []
            readytolearn[session['studentname']] = []
            readytolearnurl[session['studentname']] = []
            readytolearnquestionkey[session['studentname']] = []
            currentstatelist[session['studentname']] = []
            nextstatelist[session['studentname']] = []
            session['score'] = 0
            usersdict[c] = UserBuffer(listoftopics[0])
    else:
        return render_to_response('Home/homepage.html', {
            'loginurl': users.create_login_url('/'),
        },
                                  context_instance=RequestContext(request))

    if request.method == 'POST':

        setcount(session['studentname'])
        answer = request.POST['answer']

        if answer == usersdict[session['studentname']].questions[nextquestion(
                session['studentname'])].answer[0]:
            update(session['studentname'], True)
        else:
            update(session['studentname'], False)
    logging.error(maxstatesize(session['studentname']))
    logging.error(maxstate(session['studentname']))
    logging.error(usersdict[session['studentname']].states[maxstatesize(
        session['studentname'])][maxstate(
            session['studentname'])].questionstuple)
    val = 0
    if session.get('studentname', -1) != -1 and (
            usersdict[session['studentname']].states[maxstatesize(
                session['studentname'])][maxstate(session['studentname'])].prob
            > 0.40 or getcount(session['studentname']) == getnumquestions(
                session['studentname'])):
        #global val
        #global readytolearn
        strknow = "You know :"
        for quest in usersdict[session['studentname']].states[maxstatesize(
                session['studentname'])][maxstate(
                    session['studentname'])].questionstuple:
            if quest == -1:
                val = 0
            else:
                strknow += usersdict[
                    session['studentname']].questions[quest].questionstring
                strknow += ",,"
                val += 1
        maxsta = maxstate(session['studentname'])
        logging.error(val)
        logging.error(getnumquestions(session['studentname']))

        if val == getnumquestions(session['studentname']):
            nextstatelist[session['studentname']].append(None)
            currentstatelist[session['studentname']].append(
                usersdict[session['studentname']].states[maxstatesize(
                    session['studentname'])][maxstate(
                        session['studentname'])].key)
            scorelist[session['studentname']].append(100)
            topictimespend[session['studentname']].append(0)
            completedtopics[session['studentname']][session['listoftopics'][
                session['topicnumber']]] = 1
            logging.error("hii")
            #readytolearn[session['studentname']]=["Congratulations!!you have completed maths donut"]
        else:
            logging.error(maxstate(session['studentname']))

            states = usersdict[session['studentname']].states[
                maxstatesize(session['studentname']) + 1]
            logging.error(states)
            if (maxstatesize(session['studentname']) != 0):
                currentstate = usersdict[session['studentname']].states[
                    maxstatesize(session['studentname'])][maxstate(
                        session['studentname'])]
                for state in states:
                    stateset = set(state.questionstuple)
                    logging.error(stateset)
                    currentstateset = set(currentstate.questionstuple)
                    if stateset.issuperset(currentstateset):
                        quetionkey = stateset.difference(currentstateset)
                        logging.error(next(iter(quetionkey)))
                        logging.error(currentstate.key)
                        score = (val / (float)(getnumquestions(
                            session['studentname']))) * 100
                        scorelist[session['studentname']].append(int(score))
                        currentstatelist[session['studentname']].append(
                            currentstate.key)
                        nextstatelist[session['studentname']].append(state.key)

                        session['score'] += score
                        #studentkey= session.get('studentkey',-1)
                        #schoolkey= session.get('schoolkey',-1)
                        #a=Query.update_assessment_detail_of_student(student_key=studentkey, assessment_key=ndb.Key(urlsafe=session['assessmentkey']),current_state_key= currentstate.key, next_state_key=currentstate.key,next_question_key=next(iter(quetionkey)),score=int(score),school_key=schoolkey,completion_date=datetime.datetime.now())
                        #logging.error(a)
                        topictimespend[session['studentname']].append(0)
                        readytolearn[session['studentname']].append(
                            usersdict[session['studentname']].questions[next(
                                iter(quetionkey))].type)
                        readytolearnurl[session['studentname']].append(
                            usersdict[session['studentname']].questions[next(
                                iter(quetionkey))].url)
                        readytolearnquestionkey[session['studentname']].append(
                            usersdict[session['studentname']].questions[next(
                                iter(quetionkey))].key)
                        break
            else:
                scorelist[session['studentname']].append(0)
                currentstatelist[session['studentname']].append(None)
                nextstatelist[session['studentname']].append(None)
                topictimespend[session['studentname']].append(0)
                for state in states:
                    questiontuple = state.questionstuple
                    readytolearn[session['studentname']].append(
                        usersdict[session['studentname']].questions[
                            questiontuple[0]].type)
                    readytolearnurl[session['studentname']].append(
                        usersdict[session['studentname']].questions[
                            questiontuple[0]].url)
                    readytolearnquestionkey[session['studentname']].append(
                        usersdict[session['studentname']].questions[
                            questiontuple[0]].key)

        if (session['topicnumber'] == len(session['listoftopics']) - 1):
            Query.update_assessment_detail_of_student(
                int(session['score'] / (len(session['listoftopics']))),
                scorelist[session['studentname']],
                topictimespend[session['studentname']], session['studentkey'],
                session['assessmentkey'],
                currentstatelist[session['studentname']],
                nextstatelist[session['studentname']],
                readytolearnquestionkey[session['studentname']],
                session['schoolkey'], datetime.datetime.now())
            del usersdict[session['studentname']]
            return render_to_response('AssessingPie_toBeremoved/pie.html', {
                'readytolearn':
                zip(readytolearn[session['studentname']],
                    readytolearnurl[session['studentname']]),
                'num_known':
                session['score'] / (len(session['listoftopics'])),
                'st':
                maxsta,
                'state':
                'completed',
                'know':
                strknow,
            },
                                      context_instance=RequestContext(request))

        else:
            del usersdict[session['studentname']]
            checknext = 1
            nexttopickey = 0
            while checknext == 1:
                session['topicnumber'] += 1
                if (session['topicnumber'] == len(session['listoftopics'])):
                    logging.error("ankur")
                    logging.error(
                        int(session['score'] / (len(session['listoftopics']))))
                    Query.update_assessment_detail_of_student(
                        int(session['score'] / (len(session['listoftopics']))),
                        scorelist[session['studentname']],
                        topictimespend[session['studentname']],
                        session['studentkey'], session['assessmentkey'],
                        currentstatelist[session['studentname']],
                        nextstatelist[session['studentname']],
                        readytolearnquestionkey[session['studentname']],
                        session['schoolkey'], datetime.datetime.now())
                    return render_to_response(
                        'AssessingPie_toBeremoved/pie.html', {
                            'student name':
                            session['studentname'],
                            'readytolearn':
                            zip(readytolearn[session['studentname']],
                                readytolearnurl[session['studentname']]),
                            'num_known':
                            session['score'] / (len(session['listoftopics'])),
                        },
                        context_instance=RequestContext(request))
                else:
                    nexttopickey = session['listoftopics'][
                        session['topicnumber']]
                    prerequisitetopiclist = Query.get_prerequisite_topics_of_topic(
                        nexttopickey)
                    checknext = 0
                    for topic in prerequisitetopiclist:
                        if completedtopics[session['studentname']].get(
                                topic, -1) == -1:
                            checknext = 1
                    if checknext == 1:
                        currentstatelist[session['studentname']].append(None)
                        scorelist[session['studentname']].append(0)
                        topictimespend[session['studentname']].append(0)
                        nextstatelist[session['studentname']].append(None)

            usersdict[session['studentname']] = UserBuffer(nexttopickey)

            return render_to_response('AssessingPie/question.html', {
                'logouturl':
                users.create_logout_url('/'),
                'logger':
                users.get_current_user(),
                'nextquestion':
                usersdict[session['studentname']].questions[nextquestion(
                    session['studentname'])].questionstring,
            },
                                      context_instance=RequestContext(request))

    else:
        return render_to_response('AssessingPie/question.html', {
            'logouturl':
            users.create_logout_url('/'),
            'logger':
            users.get_current_user(),
            'nextquestion':
            usersdict[session['studentname']].questions[nextquestion(
                session['studentname'])].questionstring,
        },
                                  context_instance=RequestContext(request))
def update_command():
    engine.update(selected_tuple[0],title_text.get(), author_text.get(), year_text.get(), isbn_text.get())
示例#17
0
def asknextquestion(request):


    session = get_current_session()
    assessmentkey=''

    c=session.get('studentname',-1)
    if c != -1:

        if request.method != 'POST':
            usersdict.pop(c, None)
            assessmentkey = request.GET['id']
            session['assessmentkey']=assessmentkey
            key = ndb.Key(urlsafe=assessmentkey)
            session['assessmentkey']=key
            logging.error(assessmentkey)
            assessment = key.get()
            listoftopics=assessment.topics_in_assessment_key
            session['listoftopics']=listoftopics
            session['topicnumber'] = 0
            completedtopics[session['studentname']] ={}
            scorelist[session['studentname']] = []
            topictimespend[session['studentname']]=[]
            readytolearn[session['studentname']]=[]
            readytolearnurl[session['studentname']]=[]
            readytolearnquestionkey[session['studentname']]=[]
            currentstatelist[session['studentname']]=[]
            nextstatelist[session['studentname']]=[]
            session['score']=0
            usersdict[c]= UserBuffer(listoftopics[0])
    else:
        return render_to_response('Home/homepage.html',{'loginurl': users.create_login_url('/'),},context_instance = RequestContext(request))


    if request.method == 'POST':

        setcount(session['studentname'])
        answer =request.POST['answer']

        if answer == usersdict[session['studentname']].questions[nextquestion(session['studentname'])].answer[0] :
             update(session['studentname'], True)
        else:
            update(session['studentname'], False)
    logging.error(maxstatesize(session['studentname']))
    logging.error(maxstate(session['studentname']))
    logging.error(usersdict[session['studentname']].states[maxstatesize(session['studentname'])][maxstate(session['studentname'])].questionstuple)
    val=0
    if  session.get('studentname',-1)!=-1 and (usersdict[session['studentname']].states[maxstatesize(session['studentname'])][maxstate(session['studentname'])].prob > 0.40 or getcount(session['studentname'])==getnumquestions(session['studentname']) ):
        #global val
        #global readytolearn
        strknow = "You know :"
        for quest in usersdict[session['studentname']].states[maxstatesize(session['studentname'])][maxstate(session['studentname'])].questionstuple:
            if quest==-1:
                val=0
            else:
                strknow+=usersdict[session['studentname']].questions[quest].questionstring
                strknow+=",,"
                val+=1
        maxsta =maxstate(session['studentname'])
        logging.error(val)
        logging.error(getnumquestions(session['studentname']))

        if val==getnumquestions(session['studentname']):
            nextstatelist[session['studentname']].append(None)
            currentstatelist[session['studentname']].append(usersdict[session['studentname']].states[maxstatesize(session['studentname'])][maxstate(session['studentname'])].key)
            scorelist[session['studentname']].append(100)
            topictimespend[session['studentname']].append(0)
            completedtopics[session['studentname']][session['listoftopics'][session['topicnumber']]]=1
            logging.error("hii")
            #readytolearn[session['studentname']]=["Congratulations!!you have completed maths donut"]
        else:
            logging.error(maxstate(session['studentname']))

            states = usersdict[session['studentname']].states[maxstatesize(session['studentname']) + 1]
            logging.error(states)
            if(maxstatesize(session['studentname'])!=0):
                currentstate= usersdict[session['studentname']].states[maxstatesize(session['studentname'])][maxstate(session['studentname'])]
                for state in states:
                    stateset = set(state.questionstuple)
                    logging.error(stateset)
                    currentstateset = set(currentstate.questionstuple)
                    if stateset.issuperset(currentstateset):
                        quetionkey = stateset.difference(currentstateset)
                        logging.error(next(iter(quetionkey)))
                        logging.error(currentstate.key)
                        score =(val/(float)(getnumquestions(session['studentname'])))*100
                        scorelist[session['studentname']].append(int(score))
                        currentstatelist[session['studentname']].append(currentstate.key)
                        nextstatelist[session['studentname']].append(state.key)

                        session['score']+=score
                        #studentkey= session.get('studentkey',-1)
                        #schoolkey= session.get('schoolkey',-1)
                        #a=Query.update_assessment_detail_of_student(student_key=studentkey, assessment_key=ndb.Key(urlsafe=session['assessmentkey']),current_state_key= currentstate.key, next_state_key=currentstate.key,next_question_key=next(iter(quetionkey)),score=int(score),school_key=schoolkey,completion_date=datetime.datetime.now())
                        #logging.error(a)
                        topictimespend[session['studentname']].append(0)
                        readytolearn[session['studentname']].append(usersdict[session['studentname']].questions[next(iter(quetionkey))].type)
                        readytolearnurl[session['studentname']].append(usersdict[session['studentname']].questions[next(iter(quetionkey))].url)
                        readytolearnquestionkey[session['studentname']].append(usersdict[session['studentname']].questions[next(iter(quetionkey))].key)
                        break
            else:
                 scorelist[session['studentname']].append(0)
                 currentstatelist[session['studentname']].append(None)
                 nextstatelist[session['studentname']].append(None);
                 topictimespend[session['studentname']].append(0)
                 for state in states:
                     questiontuple = state.questionstuple
                     readytolearn[session['studentname']].append(usersdict[session['studentname']].questions[questiontuple[0]].type)
                     readytolearnurl[session['studentname']].append(usersdict[session['studentname']].questions[questiontuple[0]].url)
                     readytolearnquestionkey[session['studentname']].append(usersdict[session['studentname']].questions[questiontuple[0]].key)


        if(session['topicnumber']==len(session['listoftopics'])-1):
            Query.update_assessment_detail_of_student(int(session['score']/(len(session['listoftopics']))) ,scorelist[session['studentname']],topictimespend[session['studentname']], session['studentkey'], session['assessmentkey'], currentstatelist[session['studentname']], nextstatelist[session['studentname']], readytolearnquestionkey[session['studentname']], session['schoolkey'], datetime.datetime.now())
            del usersdict[session['studentname']]
            return render_to_response('AssessingPie_toBeremoved/pie.html',{'readytolearn':zip(readytolearn[session['studentname']],readytolearnurl[session['studentname']]), 'num_known': session['score']/(len(session['listoftopics'])) ,'st': maxsta,'state' : 'completed','know':strknow,},context_instance = RequestContext(request))

        else:
            del usersdict[session['studentname']]
            checknext=1;
            nexttopickey=0;
            while checknext==1:
                session['topicnumber']+=1
                if(session['topicnumber']==len(session['listoftopics'])):
                   logging.error("ankur")
                   logging.error(int(session['score']/(len(session['listoftopics']))))
                   Query.update_assessment_detail_of_student(int(session['score']/(len(session['listoftopics']))) ,scorelist[session['studentname']],topictimespend[session['studentname']], session['studentkey'], session['assessmentkey'], currentstatelist[session['studentname']], nextstatelist[session['studentname']], readytolearnquestionkey[session['studentname']], session['schoolkey'], datetime.datetime.now())
                   return render_to_response('AssessingPie_toBeremoved/pie.html',{'student name':session['studentname'],'readytolearn':zip(readytolearn[session['studentname']],readytolearnurl[session['studentname']]),'num_known': session['score']/(len(session['listoftopics'])) ,},context_instance = RequestContext(request))
                else:
                    nexttopickey =session['listoftopics'][session['topicnumber']]
                    prerequisitetopiclist = Query.get_prerequisite_topics_of_topic(nexttopickey)
                    checknext=0;
                    for topic in prerequisitetopiclist:
                        if completedtopics[session['studentname']].get(topic,-1)==-1 :
                            checknext=1;
                    if checknext==1:
                        currentstatelist[session['studentname']].append(None)
                        scorelist[session['studentname']].append(0)
                        topictimespend[session['studentname']].append(0)
                        nextstatelist[session['studentname']].append(None);



            usersdict[session['studentname']]=UserBuffer(nexttopickey)

            return render_to_response('AssessingPie/question.html',{'logouturl':users.create_logout_url('/') ,'logger' : users.get_current_user() ,'nextquestion' : usersdict[session['studentname']].questions[nextquestion(session['studentname'])].questionstring,},context_instance = RequestContext(request))


    else:
        return render_to_response('AssessingPie/question.html',{'logouturl':users.create_logout_url('/') ,'logger' : users.get_current_user() ,'nextquestion' : usersdict[session['studentname']].questions[nextquestion(session['studentname'])].questionstring,},context_instance = RequestContext(request))
示例#18
0
    body.Body().draw(),
    link.Link().draw(),
    div.Div().draw(),
    navigation.Navigation().draw(),
    container.Container().draw(),
    footer.Footer().draw(),
    card.Card().draw(),
    paper.Paper().draw(),
    fabric.Fabric().draw(),
    form.Form().draw(),
    button.Button().draw(),
    planet.Planet().draw(),
    heading.Heading().draw(),
    line.Line().draw(),
    tweak.Tweak().draw(),
]

# ================================ POINTERS ================================ #
# STATUS: DONT CHANGE ANYTHING
pointers = ''

# ================================= UNPACK ================================= #
# STATUS: DONT CHANGE ANYTHING
for component in components:
    for unpack in component:
        pointers += unpack.replace('}', '} ')

# ================================= UPDATE ================================= #
# STATUS: DONT CHANGE ANYTHING
engine.update(pointers)