def reduceterm(sender, maxlines): """When the Reduce button is pressed: call cc.runfile with our input. There is a maximum number of lines that we will output, to prevent a stalling browser and an overfull document. The user can raise this limit with a link. """ input = inputArea.getText() output = "" nlines = 0 def catchoutput(s, end="\n"): output += s + end nlines += 1 if nlines > maxlines: raise OverlongOutput() cc._defs = dict() try: cc.runfile(inputfile=io.StringIO(input), verbose=False, printout=catchoutput, printerr=catchoutput) except OverlongOutput: extra = FlowPanel(StyleName="terminated") extra.add(InlineLabel("Reduction terminated after %s lines. " % (maxlines,))) extra.add(Button("Try longer", functools.partial(queuereduce, maxlines=nextmaxlines(maxlines)))) showOutput(output, extra=extra) except Exception, e: Window.alert(e)
def onRemoteResponse(self, response, request_info): # Window.alert(dir(request_info)) # Window.alert(request_info.method) # Window.alert(request_info.handler) # time.sleep( 3 ) Window.alert("inside MLAlgorithmService: compression is done") self.callback.loadImage(response)
def onClick(self): if not self.survey.is_cookie_set() and self.mturk_input.accepted == True: if not self.survey.survey_filledout(): Window.alert("Please fill out the survey") else: self.survey.set_cookie() encoded_answers = [] for i,answer in enumerate(self.survey.get_answers()): encoded_answers.append(("survey_answer%d" % i,answer)) self.mturk_output.add_data(encoded_answers) self.mturk_output.add_data(self.sentence_set.get_sentences()) self.mturk_output.add_data(self.sentence_set.get_masks()) self.mturk_output.add_data(self.sentence_set.get_annotations()) self.mturk_output.mturk_form.submit() else: self.mturk_output.add_data(self.sentence_set.get_sentences()) self.mturk_output.add_data(self.sentence_set.get_masks()) self.mturk_output.add_data(self.sentence_set.get_annotations()) self.mturk_output.mturk_form.submit()
def swap(self, x1, y1): if self.base.control_panel.start_button.state == "up": return None blank_pos = self.getBlankPos() x2 = blank_pos[0] y2 = blank_pos[1] flag = False if x1 == x2: if (y1 - y2) in [1, -1]: flag = True elif y1 == y2: if (x1 - x2) in [1, -1]: flag = True if flag == True: w = self.getWidget(x1, y1) c = Cell(w.no, "images/button_%s.jpg" % w.no, "images/button_%s_down.jpg" % w.no) c.addMouseListener(CellListener()) c.x = x2 c.y = y2 c.screen = self self.setWidget(x2, y2, c) self.clearCell(x1, y1) self.incrCount() if self.complete(): Window.alert("Bingo!!!.. You won the game.. Congrats..")
def onRemoteError(self, code, errobj, request_info): message = errobj['message'] if code != 0: Window.alert("HTTP error %d: %s" % (code, message['name'])) else: code = errobj['code'] Window.alert("JSONRPC Error %s: %s" % (code, message))
def onRemoteResponse(self, response, request_info): # Window.alert(dir(request_info)) # Window.alert(request_info.method) # Window.alert(request_info.handler) # time.sleep( 3 ) Window.alert("inside MLAlgorithmService: compression is done") self.callback.loadImage(response)
def jumpsFromGregorian(self, gregorianDate): """ - Obtention of Number of seconds ahead or before reference point - Calculation*: - Calculation of _Number of Cycle Jumps_ from reference point in number of seconds """ Window.alert(gregorianDate) gregorianDate = datetime.datetime(gregorianDate) Window.alert(isinstance(gregorianDate, datetime.datetime)) Window.alert(gregorianDate) jumps = 0 diff = datetime.datetime(gregorianDate) - datetime.datetime(self.referencePoint.START_DATE) Window.alert(diff.days) f = diff>0 diff = math.abs(diff) while diff>0: jumps = jumps+1 Window.alert(float(self.referencePoint.CREATION_SPEED)) if f: """original formula: (1*13/(self.referencePoint.SPEED*13^jumps))""" diff = diff - (1/(self.referencePoint.CREATION_SPEED*13^(jumps-1))) else: """original formula: (1*13/(self.referencePoint.SPEED/13^jumps))""" diff = diff - (1/(self.referencePoint.CREATION_SPEED/13^(jumps+1))) return jumps
def themesPanel(self, themes=None): Window.alert('line:111') themes = None if not themes: themes=['0','1', 'cms', 'pypress'] vPanel = VerticalPanel() for i in range(len(themes)): """ a_n = location.getPathName().split('/')[1] lambda1 = lambda x: w_l.pathname.replace('/'+a_n+'/', '/'+x+'/')+'?theme='+x lambda2 = lambda x: w_l.pathname.replace('/'+a_n+'/', '/a/')+'?theme='+x href = { 'cms' : lambda1, 'pypress' : lambda1, 'o' : lambda2, '1' : lambda2 }.get(themes[i], lambda2)(themes[i]) """ a=Button('theme '+themes[i], lambda x: location.setSearchDict({'theme': x.getID()}), StyleName='link') a.setID(themes[i]) vPanel.add(a) return vPanel
def onSubmit(self, event): # This event is fired just before the form is submitted. We can take # this opportunity to perform validation. print "onSubmit", event if (len(self.tb.getText()) == 0): Window.alert("The text box must not be empty") event.setCancelled()
def StartButtonPressed(self): self.CountTurn = 1 if int(self.PlayerNum.getText()) >= 2 and int(self.PlayerNum.getText()) <= 6 and int(self.WinScore.getText()) >= 10 and int(self.WinScore.getText()) <= 100: self.DPanel.remove(self.TxtInstructions, DockPanel.CENTER) self.BankButton.setVisible(True) self.RollButton.setVisible(True) # self.image.setVisible(True) self.TempBoard.setVisible(True) self.NameScore.setVisible(True) self.image = Image( self.DummyUrl + "images/0.png") self.image.setSize("200px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) RootPanel().add(self.DPanel) self.StartButton.setEnabled(False) self.PlayerNum.setEnabled(False) self.WinScore.setEnabled(False) self.RollButton.setEnabled(True) self.TempBoard.setText(1,0,"Player"+str(1)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows") else: Window.alert("Please Enter Correct Parameters " ) #Command for alert window return 0 VarPlayer = ["Player" + str(i) for i in xrange(1,int(self.PlayerNum.getText())+1)] i = 0 while i < int(self.PlayerNum.getText()): self.NameScore.setText(i+1, 0, VarPlayer[i]) self.NameScore.setText(i+1, 1, "0") self.VarTotScore.append(0) #m*1 vector of zeros indicating the initial scores i += 1
def onError(self, text): obj = JSONParser().decode(text) # Hack for 201 being seen as error if not obj['ok']: Window.alert(text) else: self.editor.reloadDocument()
def BankButtonPressed(self): self.BankButton.setEnabled(False) self.NameScore.setText(self.CountTurn, 1, int(self.NameScore.getText(self.CountTurn, 1)) + int(self.TempBoard.getText(1,1))) if int(self.NameScore.getText(self.CountTurn, 1)) >= int(self.WinScore.getText()): AlrtTxt = "Congratulation!!! Player"+ str(self.CountTurn) + " wins !!!!" Window.alert(AlrtTxt) self.DPanel.remove(self.image, DockPanel.CENTER) self.DPanel.add(self.TxtInstructions, DockPanel.CENTER) self.BankButton.setVisible(False) self.RollButton.setVisible(False) # self.image.setVisible(False) self.TempBoard.setVisible(False) self.NameScore.setVisible(False) i = int(self.PlayerNum.getText()) while i > 0: self.NameScore. removeRow(i) i -= 1 self.TempBoard.setText(1,0,"X") self.TempBoard.setText(1, 1, "0") self.StartButton.setEnabled(True) # self.OK.setEnabled(True) self.PlayerNum.setEnabled(True) self.WinScore.setEnabled(True) self.RollButton.setEnabled(False) self.BankButton.setEnabled(False) self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows"); self.DPanel.remove(self.image, DockPanel.CENTER) self.image = Image( self.DummyUrl + "images/0.png") self.image.setSize("200px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) self.DPanel.setCellHeight(self.image, "200px") self.DPanel.setCellWidth(self.image, "400px") RootPanel().add(self.DPanel) else: self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows"); self.CountTurn += 1 if self.CountTurn % int(self.PlayerNum.getText()) == 1: self.CountTurn = 1 self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); else: self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows");
def check_win(self): for i in range(self.parent.getRowCount()): for j in range(self.parent.getColumnCount()): if self.parent.getWidget(i,j).light: return Window.alert('You win!!! But can you beat the next level?') global game game.next_level()
def onRemoteResponse(self, response, request_info): try: if request_info.method == 'array_from_expr': values = [float(x) for x in response] for w, v in zip(self._array.values, values): w.setText(str(v)) except: Window.alert(response)
def check_win(self): for i in range(self.parent.getRowCount()): for j in range(self.parent.getColumnCount()): if self.parent.getWidget(i, j).light: return Window.alert('You win!!! But can you beat the next level?') global game game.next_level()
def onSelection(self, event): clickedLink = event.getSelectedItem() if clickedLink.getChildCount() == 0: if not self.apiClient.isSessionValid(): Window.alert(u"Your session has expired") self.showcaseWrapper.clear() else: History.newItem(clickedLink.getText())
def onRemoteResponse(self, response, request_info): ''' Called when a response is received from a RPC. ''' if request_info.method == 'getaccounts': #TODO self.updateGrid(response) else: Window.alert('Unrecognized JSONRPC method.')
def createPanels(self): """ Create the various panels to be used by this application. This should be overridden by the subclass to create the various panels the application will use. Upon completion, the subclass should return a dictionary mapping the ID to use for each panel to the panel to be displayed. """ Window.alert("Must be overridden.")
def save(self, _): global gw pwd="" if self.password.getText() != "" or self.passwordRepeat.getText() != "": if self.password.getText() != self.passwordRepeat.getText(): Window.alert("Passwords differ"); return pwd = pwhash(self.password.getText()) gw.updateUser(self.app.cookie, self.uid, self.handle.getText(), self.name.getText(), pwd, self.admin.isChecked(), self.email.getText(), RPCCall(self.onUpdate))
def onRemoteResponse(self, response, request_info): method = request_info.method if method == 'getExampleObjects': self.exampleTable.clear() for obj in response: self.exampleTable.add(ExampleObject(obj, response[obj])) else: Window.alert('DefaultView: Unrecognized JSONRPC method. method= %s' % method)
def mouseOverMarker( self,ind ): Window.alert('test1') marker = self.markers[ind] iwo = InfoWindowOptions() iwo.position = marker['latlng'] iwo.content = marker['title'] Window.alert('test2') self.iw = InfoWindow( iwo ) self.iw.open( self.mapPanel.map )
def createPanels(self): """ Create the various panels to be used by this application. This should be overridden by the subclass to create the various panels the application will use. Upon completion, the subclass should return a dictionary mapping the ID to use for each panel to the panel to be displayed. """ Window.alert("Must be overridden.")
def start(sender): Window.alert("Hello, GAMERS!") hw = HTML("<img src='http://github.com/jrabbit/Defenditt/raw/master/public/media/instructions%20screen.png' alt='instructions'/>") hw.setID('instructions') RootPanel().add(hw) JS(""" parent.top.document.getElementById("splash").style.display = "none"; parent.top.document.getElementById("startbutton").style.display = "none"; parent.top.document.getElementById("startbutton").style.height = 0; """)
def run(self): self.tries += 1 if self.tries >= self.max_tries: Window.alert("It looks like there's a connection problem. We're sorry about the inconvenience. Please try again later.") self.cancel() return if populate_book_details(): self.cancel()
def __init__(self): def a(): Window.alert("in bar a") def b(): Window.alert("in bar b") Window.alert("you should now see 'in bar a', 'in bar b'") x = [a, b] for f in x: f()
def onRemoteResponse(self, response, request_info): ''' Called when a response is received from a RPC. ''' if request_info.method == 'login': if response['success']: self.listener.onLogin(self) else: self.error_message.setText(response['error_message']) else: Window.alert('Unrecognized JSONRPC method.')
def onRemoteResponse(self, response, request_info): ''' Called when a response is received from a RPC. ''' if request_info.method == 'isauthenticated': if response == True: self.showPanel('dashboardpanel') else: self.showPanel('loginpanel') else: Window.alert(JS('gettext("Unrecognized JSONRPC method.")'))
def onClose(self, evt): if self._opened: msg = 'Lost connection with the websocket server.' if self.has_fallback: msg += '\nFalling back to PHP.' Window.alert(msg) self.handler.close() else: if not self.has_fallback: Window.alert("No websocket server available at " + self.uri) self._opened = False
def populate_book_lists(self): """ check the JSON RPC containers and fill the UserLists if it finds them to be non-empty """ for b in self.wl_books: Window.alert(str(b)) self.wish_list.add_book(b) for b in self.sl_books: self.sell_list.add_book(b) return True
def __init__(self): def a(): Window.alert( "in bar a" ) def b(): Window.alert( "in bar b" ) Window.alert("you should now see 'in bar a', 'in bar b'") x = [a, b] for f in x: f()
def onClick(self): if not self.current_block.all_completed(): Window.alert("You must select something for each marked entity") else: self.current_block.send_results() self.remove(self.current_block) self.remove(self.commit) self.current_block = NERBlock() self.add(self.current_block) self.add(self.commit)
def onRemoteError(self, code, message, request_info): """ Called when a returned response is invalid or Server Error """ code = str(code) message = str(message) if len(code) > 200: code = code[0:200] + "..." if len(message) > 200: message = message[0:200] + "..." err_msg = Label("Server Error or invalid response: ERROR " + str(code) + " - " + str(message)) err_msg.addStyleName("status") Window.alert(err_msg.getText())
def onFailure(self, caught): if isinstance(caught, FacebookException): e = caught self.callback.onFailure(e) elif isinstance(caught, FacebookException): e = caught self.callback.onFailure(e) elif self.callback is not None: self.callback.onFailure(caught) else: Window.alert(u"Callback: Unknown error") GWT.log(u"" + java.str(caught), None)
def handleFailure(self, t): """ * Handle failure * @param t original exception """ if isinstance(t,FacebookException): e = t ui = ErrorResponseUI(e.getErrorMessage()) ui.center() ui.show() else: Window.alert(java.str(u"Showcase: Unknown exception :" + java.str(t)) + u"")
def onBtnClick(self, event): self.progress.setText('0%') if self.simple.isChecked(): self.form.submit() else: if AsyncUpload.is_old_browser(): Window.alert("Hmmm, your browser doesn't support this.") else: el = self.field.getElement() files = getattr(el, 'files') #TODO implement loop for multiple file uploads file = JS("@{{files}}[0]") #otherwise pyjs thinks it's a string? AsyncUpload.asyncUpload(self.url, file, self)
def onRemoteResponse(self, response, request_info): ''' Called when a response is received from a RPC. ''' if request_info.method in DataService.methods: # Compare self.stocks and the stocks in response stocks_set = set(self.stocks) response_set = set(response) # Add the differences for symbol in list(response_set.difference(stocks_set)): self.addStock(None, symbol) else: Window.alert('Unrecognized JSONRPC method.')
def close_app(self, app): app_zi = self.window_zindex[app.identifier] for t in self.window_zindex.keys(): w = self.window[t] zi = self.window_zindex[t] if zi > app_zi: self.set_app_zindex(t, zi-1) t = self.window[app.identifier] if not self.remove(t): Window.alert("%s not in app" % app.identifier) t.hide() del self.window[app.identifier]
def onClick(self,sender): """Call function for the text/button-based move controller""" if sender == self.b: cell1_txt = self.cell1.getText() cell2_txt = self.cell2.getText() #Window.alert(str(cell1_txt)) if cell1_txt and cell2_txt in self.game.board: piece = self.game.pieces[self.game.state[cell1_txt][len(self.game.state[cell1_txt])-1]] cell = self.game.board[cell2_txt] self.GUImove(piece, cell) else: Window.alert("cell names not recognized!") self.cell1.setText("") self.cell2.setText("")
def onBtnClick(self, event): self.progress.setText('0%') if self.simple.isChecked(): self.form.submit() else: if AsyncUpload.is_old_browser(): Window.alert("Hmmm, your browser doesn't support this.") else: el = self.field.getElement() files = getattr(el, 'files') #TODO implement loop for multiple file uploads file = JS( "@{{files}}[0]") #otherwise pyjs thinks it's a string? AsyncUpload.asyncUpload(self.url, file, self)
def apply_rule(self, rule, selected_indices, after): selected_formulas = [x for i, x in enumerate(proof.get_formula_list()) if i in selected_indices] selected_indices = [self.list_index_to_proof_index(n) for n in selected_indices] if not rule.is_applicable(selected_formulas): Window.alert(rule.name+selected_formulas[0].dump()) return def after1(formula, **kwargs): if not "predecessors" in kwargs: kwargs["predecessors"] = selected_indices self.add(formula, **kwargs) after() rule.apply(selected_formulas, after1)
def close_app(self, app): app_zi = self.window_zindex[app.identifier] for t in self.window_zindex.keys(): w = self.window[t] zi = self.window_zindex[t] if zi > app_zi: self.set_app_zindex(t, zi-1) t = self.window[app.identifier] if not self.remove(t): Window.alert("%s not in app" % app.identifier) t.hide() del self.window[app.identifier] del self.window_zindex[app.identifier]
def onClick(self, sender): found = False if sender == self.cmdNew: self.blanks = '' self.hangdude.clear() self.guesses = 0 self.score = 0 for i in range(len(self.key_widgets)): self.key_widgets[i].setEnabled(True) if self.level == 5: words = Wordlist_5.words elif self.level == 10: words = Wordlist_10.words elif self.level == 15: words = Wordlist_15.words elif self.level == 20: words = Wordlist_20.words #pick a random word g = random.Random() r = int(g.random() * len(words)) self.answer = words[r].upper() for i in range(len(self.answer)): if self.answer[i] == ' ': self.blanks += ' ' else: self.blanks += '_ ' self.puzzlestring.setHTML(self.blanks) else: guess_letter = sender.getText() sender.setEnabled(False) for i in range(len(self.answer)): if self.answer[i:i + 1] == guess_letter: j = i + 1 self.blanks = self.blanks[0:( j * 2) - 2] + guess_letter + ' ' + self.blanks[j * 2:] found = True self.score += 1 self.puzzlestring.setHTML(self.blanks) if not found: self.guesses += 1 self.hangdude.draw(self.guesses) if self.guesses >= 11: Window.alert("You lose! Answer: " + self.answer) else: if self.score >= len(self.answer): Window.alert("You win!")
def onClick(self, sender): if (sender == self.signOutLink): Window.alert( "If this were implemented, you would be signed out now.") elif (sender == self.aboutLink): # When the 'About' item is selected, show the AboutDialog. # Note that showing a dialog box does not block -- execution continues # normally, and the dialog fires an event when it is closed. dlg = AboutDialog() # Position it roughly in the middle of the screen. left = (Window.getClientWidth() - 512) / 2 top = (Window.getClientHeight() - 256) / 2 Logger("TopPanel", "left: %d" % left) Logger("TopPanel", "top: %d" % top) dlg.setPopupPosition(left, top) dlg.show()
def geocodeResult(self, results, status): print "geocodeResult" if status == GeocoderStatus.OK: for res in results: print res.formatted_address print res.geometry.location.lat() print res.geometry.location.lng() for compo in res.address_components: print "- " + compo.short_name print "" self.map.setCenter(results[0].geometry.location) marker = Marker( MarkerOptions(map=self.map, position=results[0].geometry.location)) else: Window.alert( "Geocode was not successful for the following reason: " + status)
def drawDemo(self): # The following is the same as doing self.canvas.resize(self.width, self.height) #self.canvas.setCoordSize(self.width, self.height) #self.canvas.setPixelHeight(self.height) #self.canvas.setPixelWidth(self.width) imageUrls = ["./pyjamas.128x128.png"] if self.img is None: # The first time this demo gets run we need to load our images. # Maintain a reference to the image we load so we can use it # the next time the demo is selected loadImages(imageUrls, self) else: # Go ahead and animate if self.isImageLoaded(self.img): self.run = True #log.writebr("already loaded") Timer(1, self) else: Window.alert("Refresh the page to reload the image.")
def reduceterm(sender, maxlines): """When the Reduce button is pressed: call cc.runfile with our input. There is a maximum number of lines that we will output, to prevent a stalling browser and an overfull document. The user can raise this limit with a link. """ input = inputArea.getText() output = "" nlines = 0 def catchoutput(s, end="\n"): output += s + end nlines += 1 if nlines > maxlines: raise OverlongOutput() cc._defs = dict() try: cc.runfile(inputfile=io.StringIO(input), verbose=False, printout=catchoutput, printerr=catchoutput) except OverlongOutput: extra = FlowPanel(StyleName="terminated") extra.add( InlineLabel("Reduction terminated after %s lines. " % (maxlines, ))) extra.add( Button( "Try longer", functools.partial(queuereduce, maxlines=nextmaxlines(maxlines)))) showOutput(output, extra=extra) except Exception, e: Window.alert(e)
def onRemoteError(self, code, errobj, request_info): Window.alert("inside MLAlgorithmService: onRemoteError") Window.alert(request_info) message = errobj['message'] Window.alert(message) if code != 0: self.callback.showStatus("HTTP error %d: %s" % (code, message)) else: json_code = errobj['code'] self.callback.showStatus("JSONRPC Error %s: %s" % (json_code, message))
def new_game(self, event): try: row = int(self.row.getText()) except: Window.alert('Invalid number in rows') return try: column = int(self.column.getText()) except: Window.alert('Invalid number in columns') return try: bomb = int(self.bomb.getText()) except: bomb = 0 if bomb >= (row * column): Window.alert("Number of bombs should not be greater than " \ "rows x columns.") else: self.menu.game.next_game((row, column), bomb) self.close_dialog()
def onList2ItemSelected(self, event): item = self.list2.getItemText(self.list2.getSelectedIndex()) Window.alert("You selected " + item + " from list 2")
def emit(self, record): msg = self.format(record) Window.alert(msg)
def execute(self): Window.alert("Thank you for selecting a menu item.")
def onSubmit(self, event): # This event is fired just before the form is submitted. We can take # this opportunity to perform validation. if (len(self.tb.getText()) == 0): Window.alert("The text box must not be empty") event.setCancelled(True)
def log(text): Window.alert(text)
def a(): Window.alert("in a")
def b(): Window.alert("in b")
def b(self): Window.alert("in bar b")
def a(self): Window.alert("in bar a")
def __init__(self): Window.alert("Next you should see 'in a', 'in b'") x = [a, b] for f in x: f()
def b(): Window.alert("in Bar b")
def a(): Window.alert("in bar a")