Пример #1
0
    def onClick(self, sender):
        self.check_adjusts(sender)
        if sender == self.reset_constants:
            self.TD_CONSTS = self.ONES_CONSTS
            self.sync_consts()

        if sender == self.increase_depth:
            self.depth_limit += 1
            self.depth_label.setText("Current depth is " +
                                     str(self.depth_limit) + ".")

        if sender == self.decrease_depth:
            self.depth_limit -= 1
            self.depth_label.setText("Current depth is " +
                                     str(self.depth_limit) + ".")

        if sender == self.train_td:
            self.state = State()

            self.static_ai_str = '2'
            self.td_ai_str = '1'

            self.state.next_piece = [1, 1, 1]
            Timer(250, notify=self.td_ai_turn)

        if sender == self.train_static:
            self.state = State()

            self.static_ai_str = '1'
            self.td_ai_str = '2'

            self.state.next_piece = [1, 1, 1]
            Timer(250, notify=self.static_ai_turn)
Пример #2
0
    def td_ai_turn(self):
        print "\n\nTD AI player starting turn. TD AI places the piece:", self.state.next_piece[
            2]
        print "TD_CONSTS after being adjusted are: ", self.TD_CONSTS

        # print, alpha-beta search etc.:
        (expectedUtility, state) = ab(self.state,
                                      self.TD_CONSTS,
                                      depth_limit=self.depth_limit)
        terminal_state = expectedUtility.terminal
        self.TD_CONSTS = td_learning(terminal_state, self.TD_CONSTS,
                                     self.state)
        self.sync_consts()  # reflect the new TD_CONSTS in the game.

        last_position = find_last_move(self.state, state)

        self.state = state

        state.printInfo()

        print "TD_CONSTS after being adjusted are: ", self.TD_CONSTS

        over = self.check_is_win(last_position)
        print "back in td"
        print "Is over ", over
        if not over:
            return Timer(250, notify=self.static_ai_turn)
        else:
            return True
Пример #3
0
    def __init__(self, **kwargs):
        """ setMatchPattern - defaults to '' to match everything
            match pattern examples: '^[0-9]*$' is for digits only
                                    '^[0-9,A-Z]*$' is for digits and uppercase
            setMaxLength
            setText
OB        """

        kwargs['MatchPattern'] = kwargs.pop('MatchPattern', '')
        cs = kwargs.pop('CursorStyle', "inputbox-cursor")
        gs = kwargs.pop('StyleName', 'gwt-inputbox')

        ap = AbsolutePanel(StyleName="inputbox")
        self.tp = Grid(StyleName=gs, Width="100%", Height="100%",
                       CellPadding=0, CellSpacing=0)
        self.cursor = HTML(StyleName=cs)
        ap.add(self.tp)
        ap.add(self.cursor, 0, 0)
        self.cf = self.tp.getCellFormatter()

        FocusPanel.__init__(self, Widget=ap, **kwargs)

        self.addTableListener(self)
        self.addKeyboardListener(self)
        self.addFocusListener(self)

        self.word_selected_pos = 0
        self.ctimer = Timer(notify=self.cursorFlash)
        self.focusset = False
        self.cstate = False
        self._keypressListeners = []
Пример #4
0
    def __init__(self, widget, action, fps=50):
        self.widget = widget
        self.action = action
        self.fps = fps

        self.timer = Timer(0, self)
        self.timer.scheduleRepeating(int(1000.0 / fps))
Пример #5
0
 def initElement(self):
     # Most browsers don't like setting designMode until slightly _after_
     # the iframe becomes attached to the DOM. Any non-zero timeout will do
     # just fine.
     print "initElement"
     self.onElementInitializing()
     Timer(50, self)
Пример #6
0
    def draw(self):
        colour = "#000000"
        beta = 2 * math.pi / self.numSectors

        pathParams = {
            'stroke': colour,
            'stroke-width': self.width,
            'stroke-linecap': "round"
        }

        for i in range(self.numSectors):
            alpha = beta * i - math.pi / 2
            cos = math.cos(alpha)
            sin = math.sin(alpha)
            data = ','.join([
                'M',
                str(self.cx + self.r1 * cos),
                str(self.cy + self.r1 * sin), 'L',
                str(self.cx + self.r2 * cos),
                str(self.cy + self.r2 * sin)
            ])
            path = self.canvas.path(data=data, attrs=pathParams)
            self.opacity.append(1.0 * i / self.numSectors)
            self.sectors.append(path)

        period = 1000 / self.numSectors
        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)
Пример #7
0
    def onDrop(self, event):
        dt = event.dataTransfer

        item = dt.getData("Text")
        data = json.decode(item)
        if 'name' in data and 'age' in data:
            age = data['age']
            name = data['name']
            self.removeStyleName('dragover')
            if self.age_is_ok(age):
                self.addStudent(name, age)
                dt.dropEffect = 'copy'

                self.addStyleName('flash')

                def removeFlash(timer):
                    self.removeStyleName('flash')

                Timer(250, notify=removeFlash)
            else:
                dt.dropEffect = 'none'
                self.addMessage('student could not be added')
                # setting dropEffect to 'none' should be sufficient to notify
                # that the drop failed, but
                # we need to cheat a bit for now...
                # this is the only reason for parent id in data
                item_parent_id = data['parent']
                item_parent = self.parent.containerFromId(item_parent_id)
                item_parent.addStyleName('drop_fail')
            # prevent default allows onDragEnd to see the dropEffect we set here
        DOM.eventPreventDefault(event)
Пример #8
0
    def __init__(self):

        # create the label and slider
        self.__label = Label('OFF')
        self.slider = slider = HorizontalSlider(0,
                                                5,
                                                step=1,
                                                StyleName="slider")
        slider.setDragable(True)
        slider.addControlValueListener(self)

        # put them in a hpanel
        self.hpanel = hpanel = HorizontalPanel(Spacing=10)
        hpanel.add(slider)
        hpanel.add(self.__label)

        # create the color panel and give it color
        self.colorpanel = CaptionPanel('Color:',
                                       SimplePanel(StyleName='colorpanel'))
        self.randomcolor()

        # we're initially off
        self.value = 0
        # create our timer
        self.timer = Timer(notify=self)
Пример #9
0
 def __init__(self, symbol_shape, message_symbol_coder,
              symbol_signal_coder):
     self.timer = Timer(notify=self)
     self.setTimer(self.timer)
     self.symbol_shape = symbol_shape
     self.message_symbol_coder = message_symbol_coder
     self.symbol_signal_coder = symbol_signal_coder
     self.decoded = {}
Пример #10
0
    def start_game(self, view):
        self.view = view
        self.model.start_game(view)
        self.model.reset()

        #setup a timer
        self.timer = Timer(notify=self.update)
        self.timer.scheduleRepeating(1000 / FPS)
Пример #11
0
 def onTimer(self, t):
     count = 0
     while count < 10 and self.index < len(self.items):
         self._add_items(self.index)
         self.index += 1
         count += 1
     if self.index < len(self.items):
         Timer(1, self)
Пример #12
0
 def onSplitterResize(self, px):
     """ IE6/7 has event priority issues that will prevent
         the repaints from happening quickly enough causing the
         interaction to seem unresponsive.  The following is simply
         a poor man's mouse event coalescing.
     """
     resizeUpdatePeriod = 20  # ms
     if not self.isResizeInProgress:
         self.isResizeInProgress = True
         Timer(resizeUpdatePeriod, self)
     self.splitPosition = px
 def run(self):
     self.getTestMethods()
     if not IN_BROWSER:
         for test_method_name in self.test_methods:
             self._run_test(test_method_name)
         self.displayStats()
         if hasattr(self, "start_next_test"):
             self.start_next_test()
         return
     self.test_idx = 0
     Timer(10, self)
Пример #14
0
    def onDragEnd(self, event):
        dt = event.dataTransfer
        self.addMessage('Drop effect is "%s"' % dt.dropEffect)
        if dt.dropEffect != 'none':
            self.remove(self.movingWidget)
        else:
            # Restore widget visibility. Allow 0.5 seconds for the fly-back.
            def ontimer(timer):
                self.movingWidget.removeStyleName('invisible')

            Timer(500, notify=ontimer)
Пример #15
0
 def check_start_next_test(self):
     if self.tests_outstanding is None:
         return
     if self.tests_outstanding == 0:
         if hasattr(self, 'lastTestsCheck'):
             self.lastTestsCheck()
         self.displayStats()
         self.start_next_test()
         return
     # do it again.
     Timer(100, self)
Пример #16
0
    def onTimer(self, tid):
        for i in range(10):
            if self.test_idx >= len(self.test_methods):
                self.displayStats()
                self.test_idx = 'DONE'
                self.start_next_test()
                return

            self._run_test(self.test_methods[self.test_idx])
            self.test_idx += 1
        Timer(1, self)
Пример #17
0
    def __init__(self):

        # the button
        self.button = Button(listener=self)
        # set an attr on the button to keep track of its state
        self.button.stop = False
        # date label
        self.datelabel = Label(StyleName='clock')
        # the timer
        self.timer = Timer(notify=self.updateclock)
        # kick start
        self.onClick(self.button)
Пример #18
0
 def onTimer(self, target):
     if not self.started or self.first_click:
         return
     Timer(1000, self)
     self.time += 1
     if self.time <= 999:
         str_time = str(self.time)
         str_time = '000'[:-len(str_time)] + str_time
         self.timer.setText(str_time)
     else:
         self.started = False
         self.face.setStyleName('faceclock')
Пример #19
0
    def __init__(self, sender, offsetX, offsetY, contents,
                       show_delay, hide_delay, styleName, **kwargs):
        """ contents may be a text string or it may be a widget
        """
        PopupPanel.__init__(self, True, **kwargs)
        self.show_delay = show_delay
        self.hide_delay = hide_delay
        
        if isinstance(contents, basestring):
            contents = HTML(contents)
        self.add(contents)

        left = sender.getAbsoluteLeft() + offsetX
        top = sender.getAbsoluteTop() + offsetY

        self.setPopupPosition(left, top)
        self.setStyleName(styleName)

        if tooltip_hide_timer:
            self.tooltip_show_timer = Timer(1, self)
        else:
            self.tooltip_show_timer = Timer(self.show_delay, self)
Пример #20
0
    def drawDemo(self):
        self.canvas.resize(self.width, self.height)

        self.particles = []

        for i in range(self.numParticles):
            self.particles.append( Particle(self) )

        self.canvas.saveContext()
        self.canvas.setLineWidth(2)
        self.canvas.setStrokeStyle(Color(255,0,0))
        self.run = True
        Timer(10, self)
Пример #21
0
	def __init__(self):
		self.DPanel = DockPanel(HorizontalAlignment = HasAlignment.ALIGN_CENTER,
						Spacing=10) # Creates the Docker Panel Instance
		self.VPanel = VerticalPanel() # Creates the Vertical Panel Instance
		self.VPanel1 = VerticalPanel() # Creates the Vertical Panel Instance
		self.HPanel = HorizontalPanel() # Creates a Horizontal Panel Instance
		self.HPanel1 = HorizontalPanel()# Creates a Horizontal Panel Instance


		self.image=Image()#Creates the Image instance to embed the images of dice
		self.DummyUrl = self.image.getUrl() 
		self.timer = Timer(notify=self.StillImage)#Timer for display of gif animation
		self.timerRButton =  Timer(notify=self.OneAlert)#Timer for controlling states of Roll button 
													#whenever the output of the dice is 1

		self.RollButton = Button("Roll", getattr(self, "RollButtonPressed")) #Initially Disabled 
		self.RollButton.setEnabled(False)
		self.BankButton = Button("Bank", getattr(self, "BankButtonPressed")) #Initially Disabled 
		self.BankButton.setEnabled(False)
		#The start button controls both the number players as well the winning score
		self.StartButton = Button("Start", getattr(self, "StartButtonPressed")) #Intially Enabled
		self.StartButton.setEnabled(True)


		self.PlayerNum = TextBox() #Enter the Number of Players
		self.WinScore = TextBox() #Enter the Target Score
		self.PlayerNum.setText("0")
		self.WinScore.setText("0")
		# self.OK = Button("OK", getattr(self, "okButtonPressed"))

		self.NameScore = FlexTable() #main score board
		self.NameScore.setStyleName("NameScore")
		self.TempBoard = FlexTable() #Temporary score board
		self.TempBoard.setStyleName("TempBoard")

		

		self.TxtInstructions = HTML()
Пример #22
0
def queuereduce(sender, maxlines=1000):
    showOutputMeta("Reducing...")

    outputPanel.add(HTML("&nbsp;"))
    outputPanel.add(HTML("&nbsp;"))
    outputPanel.add(
        HTML("""
    <p>Takes too long? Try the <a href="https://bitbucket.org/bgeron
    </continuation-calculus-paper/">Python evaluator.</a>.</p>
    """.strip()))

    # Schedule reduceterm(maxlines) really soon.
    timer = Timer(notify=functools.partial(reduceterm, maxlines=maxlines))
    timer.schedule(50)  # after 50 milliseconds
Пример #23
0
    def onTimer(self, sender):

        count = 0
        while count < 10:
            count += 1
            idx = self.text.find("\n", self.up_to)
            if idx < 0:
                self.text = None
                break
            self.process_line(self.text[self.up_to:idx])
            self.up_to = idx+1

        if self.text:
            Timer(1, self)
Пример #24
0
    def setChapter(self, text):
        self.loaded = True

        self.text = text + '\n'

        self.ul_stack1 = 0
        self.ul_stack2 = 0
        self.doing_code = 0
        self.custom_style = False
        self.txt = ''
        self.para = ''
        self.up_to = 0

        Timer(1, self)
Пример #25
0
 def __init__(self):
     self.dropTargets = []
     self.dragging = NOT_DRAGGING
     self.dragBusy = False
     self._currentTargetElement = None
     self.previousDropTarget = None
     self.draggingImage = None
     self.origMouseX = 0
     self.origMouseY = 0
     self.currentDragOperation = 'none'
     self.data = None
     self.returnTimer = Timer(notify=self.onReturningWidget)
     self.mouseEvent = None
     self.dragDataStore = None
Пример #26
0
    def onTimer(self, tid):
        print self.test_idx
        if self.test_idx is 'DONE':
            self.check_start_next_test()
            return

        for i in range(1):
            if self.test_idx >= len(self.test_methods):
                self.test_idx = 'DONE'
                self.check_start_next_test()
                return

            self._run_test(self.test_methods[self.test_idx])
            self.test_idx += 1
        Timer(1, self)
 def __init__(self, url, callback):
     global frameId
     frame = DOM.createElement("iframe")
     frameid = "__pygwt_feedFrame%d" % frameId
     frameId += 1
     DOM.setAttribute(frame, "id", frameid)
     DOM.setAttribute(frame, "src", url)
     #DOM.setStyleAttribute(frame, 'width', '0')
     #DOM.setStyleAttribute(frame, 'height', '0')
     #DOM.setStyleAttribute(frame, 'border', '0')
     #DOM.setStyleAttribute(frame, 'position', 'absolute')
     self.frameId = frameId
     self.frame = frame
     self.timer = Timer(notify=self)
     doc().parent.body.appendChild(frame)
     self.callback = callback
     self.timer.scheduleRepeating(100)
Пример #28
0
    def _set_history_listener(self, on, on_period=251):
        '''
        pyjamas/library/pyjamas/History.py is checking every 250ms if URL has changed
        
        By default, BuoyService checks every 250+1ms before turning its listener back on.
        An initial call in BuoyService() set-up needs to set on_period to 1 for immediate listening

        Rapid UI-interaction can lead to multiple nested calls.
        A count is kept to control when to add/remove the sole history listener.
        If a count wasn't kept then History will wobble
        '''
        if on:
            self.timer = Timer(on_period, self)
        else:
            if self.timer_count == 1:
                History.removeHistoryListener(self)
            self.timer_count -= 1
Пример #29
0
    def importDone(self):

        mod = pyjslib.get_module(self.loading_app)
        if mod is None:
            Timer(500, self)
            return

        g = mod.AppInit()
        a = self.screen.add_app(g, self.loading_desc, 400, 300)
        a.show()

        self.loading_desc = None
        self.loading_app = None

        if self.loading_apps:
            path, appname, description = self.loading_apps.pop()
            self.add_app(path, appname, description)
Пример #30
0
    def __init__(self):
        Composite.__init__(self)

        self.albums = []
        self.photos = []
        self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4)
        self.grid.addTableListener(self)
        self.drill = 0
        self.pos = 0
        self.up = Button("Up", self)
        self.next = Button("Next", self)
        self.prev = Button("Prev", self)
        self.timer = Timer(notify=self)
        self.userid = "jameskhedley"
        self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb"
        self.doRESTQuery(self.album_url, self.timer)

        self.vp = VerticalPanel()
        self.disclosure = DisclosurePanel(
            "Click for boring technical details.")
        self.disclosure.add(
            HTML(
                '''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right?
				 Well you can't because of the Same Origin Policy. Basically this means that
				 because the domain of the query and the domain of the hosted site are different,
				 then that could well be a cross-site scripting (XSS) attack. So, the workaround is to
				 do the call from a script tag so the JSON we get back is part of the document.
				 But since we don't know what URL to hit yet, once we find out then we have to inject
				 a new script tag dynamically which the browser will run as soon as we append it.
				 To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch,
				 which would be easier. Well, easier for me.'''))

        self.IDPanel = HorizontalPanel()
        self.IDPanel.add(Label("Enter google account:"))
        self.IDButton = Button("Go", self)

        self.IDBox = TextBox()
        self.IDBox.setText(self.userid)
        self.IDPanel.add(self.IDBox)
        self.IDPanel.add(self.IDButton)
        self.vp.add(self.IDPanel)
        self.vp.add(self.disclosure)
        self.vp.add(self.grid)

        self.initWidget(self.vp)