def saveSessionManually(): sname = QInputDialog.getText(None, tr("Save Session"), tr("Enter a name here:")) if sname[1]: if not os.path.exists(settings.session_folder): os.makedirs(settings.session_folder) saveSession(os.path.join(settings.session_folder, sname[0]))
def test_output(msg, logging=False): global i if i == 0: assert(msg == tr("connected.to") + "('127.0.0.1', 1234)") if i == 1: assert(msg == tr("connexion.thread.start").format("('127.0.0.1', 1234)")) i += 1
def updateExtensions(self): if not self.thread.isRunning(): common.trayIcon.showMessage(tr("Updating extensions"), tr("This may take some time.")) self.thread.start() else: common.trayIcon.dontBeImpatient()
def setTrust(self, level): level = int(level) if not self.currentFingerprint: return if level < 0 or level > 2: raise ValueError if level == 0: entry = {} if self.savedFingerprints and self.currentFingerprint in self.savedFingerprints: entry = self.savedFingerprints[self.currentFingerprint] entry["level"] = "never" self.savedFingerprints[self.currentFingerprint] = entry self.saveFingerprints() self.trusted = False self.forceTrusted = False self.printMessage(tr("trust.saved.blacklist")) elif level == 1 or level == 2: self.trusted = True self.forceTrusted = True if level == 2: entry = {} if self.savedFingerprints and self.currentFingerprint in self.savedFingerprints: entry = self.savedFingerprints[self.currentFingerprint] entry["level"] = "always" self.savedFingerprints[self.currentFingerprint] = entry self.saveFingerprints() self.printMessage(tr("trust.saved.whitelist"))
def check_asserts(self): """ Are there asserts at the end of the source code ? """ defined_funs = set() funcalls = set() for node in self.AST.body: #print("node: {}".format(node)) if isinstance(node, ast.Assert): #print("assert found: {}".format(node)) call_visit = FunCallsVisitor() call_visit.visit(node) funcalls.update(call_visit.funcalls) elif isinstance(node, ast.FunctionDef): defined_funs.add(node.name) #print("defined funs = {}".format(defined_funs)) #print("funcalls = {}".format(funcalls)) missing = defined_funs.difference(funcalls) if missing: self.report.add_convention_error('warning', tr('Missing tests'), details="\n" + tr('Untested functions: ') + "{}".format(missing) + "\n") elif defined_funs: # all the functions are tested at least once self.report.add_convention_error( 'run', tr('All functions tested'), details="==> " + tr("All functions tested (good)") + "\n") return True
def __init__(self, parent=None): super(AdremoverSettingsPanel, self).__init__(parent) filterEntryRow = custom_widgets.LineEditRow(tr("Add filter:"), self) self.filterEntry = filterEntryRow.lineEdit self.filterEntry.returnPressed.connect(self.addFilter) self.layout().addWidget(filterEntryRow) self.addFilterButton = QPushButton(tr("Add")) self.addFilterButton.clicked.connect(self.addFilter) filterEntryRow.layout().addWidget(self.addFilterButton) # Ad Remover filter list. self.filterList = QListWidget(self) self.layout().addWidget(self.filterList) self.removeFilterButton = QPushButton(tr("Remove")) self.removeFilterButton.clicked.connect( lambda: self.removeFilter(True)) self.layout().addWidget(self.removeFilterButton) self.removeAction = QAction(self) self.removeAction.setShortcut("Del") self.removeAction.triggered.connect(self.removeFilter) self.addAction(self.removeAction)
def updateFilters(self): if not filtering.filter_updater.isRunning(): common.trayIcon.showMessage(tr("Updating content filters"), tr("This may take some time.")) filtering.update_filters() else: common.trayIcon.dontBeImpatient()
def check_asserts(self): """ Are there asserts at the end of the source code ? """ self.nb_asserts = 0 defined_funs = set() funcalls = set() for node in self.AST.body: #print("node: {}".format(node)) if isinstance(node, ast.Assert): #print("assert found: {}".format(node)) call_visit = FunCallsVisitor() call_visit.visit(node) self.nb_asserts += 1 funcalls.update(call_visit.funcalls) elif isinstance(node, ast.FunctionDef): defined_funs.add(node.name) #print("defined funs = {}".format(defined_funs)) #print("funcalls = {}".format(funcalls)) self.report.nb_defined_funs = len(defined_funs) missing = defined_funs.difference(funcalls) if missing: self.report.add_convention_error('warning', tr('Missing tests') , details="\n" + tr('Untested functions: ') + "{}".format(missing) + "\n") elif defined_funs: # all the functions are tested at least once self.report.add_convention_error('run', tr('All functions tested'), details="==> " + tr("All functions tested (good)")) return True
def RecordingOptionsMenuHandler(self, controller, data): log("in RecordingOptionsMenuHandler") try: rec=data[0] idx=data[1] except: return log("Got idx: %s rec %s" % (repr(idx), repr(rec).encode("ascii","replace"))) if idx==0 or idx==1: fn=lambda : ETV.PlayRecording(rec,idx==1) self.inEyeTV = 1 newCon=PyeTVWaitController.alloc().initWithStartup_exitCond_(fn,self.ReturnToFrontRow) ret=controller.stack().pushController_(newCon) return ret if idx==2: return self.ConfirmDeleteRecordingDialog(controller, rec) if idx==3: if self.AppRunning("ComSkipper"): os.system("/usr/bin/killall ComSkipper &") self.CurrentOptionsMenu.ds.menu.items[3].layer.setTitle_(tr("ComSkipper [Off]")) # deep magic else: os.system("/Library/Application\ Support/ETVComskip/ComSkipper.app/Contents/MacOS/ComSkipper &") self.CurrentOptionsMenu.ds.menu.items[3].layer.setTitle_(tr("ComSkipper [On]")) # deep magic #time.sleep(0.5) if idx==4: log("/Library/Application\ Support/ETVComskip/MarkCommercials.app/Contents/MacOS/MarkCommercials --log %s &" % rec.rec.unique_ID.get()) os.system("/Library/Application\ Support/ETVComskip/MarkCommercials.app/Contents/MacOS/MarkCommercials --log %s &" % rec.rec.unique_ID.get()) # if we return true, we'll pop the controller and back up past the option dialog return False
def DialogToParametersUpdate(self): # update all parameters from dialog widget for header_or_param in {"header", "param"}: listParam = self.query.param if header_or_param == "header": listParam = self.query.header for paramName in self.widgetParam[header_or_param].keys(): # widget linked to this parameter widget = self.widgetParam[header_or_param][paramName] param = listParam[paramName] [type_widget, type_options, name] = splitParamNameAndType(paramName) # update value param # print "DEBUG query_param TYPE = " + type_widget if type_widget == "text": param["value"] = widget.text() elif type_widget == "date": param["value"] = widget.lineEdit().text() elif type_widget == "select": param["value"] = widget.currentText() # selected item : try to read the attribute of a selected item on map elif type_widget == "selected_item": print "DEBUG query_param " currentLayer = self.iface.mapCanvas().currentLayer() if not type(currentLayer) is QgsVectorLayer: self.errorMessage = tr(u"Select a vector layer !") continue if currentLayer.selectedFeatureCount() != 1: self.errorMessage = tr(u"Select just one feature on map !") continue currentFeature = currentLayer.selectedFeatures()[0] # standard attribute : if type_options != "geom": if currentFeature.fields().indexFromName(type_options) == -1: self.errorMessage = tr(u"This feature does not have such an attribute : ") + type_options continue param["value"] = unicode(currentFeature.attribute(type_options)) # geom attribut : else: param["value"] = ( "ST_GeomFromEWKT('SRID=" + str(currentLayer.crs().postgisSrid()) + ";" + currentFeature.geometry().exportToWkt() + "')" )
def listen(self): try: import miniupnpc self.upnp = miniupnpc.UPnP() self.upnp.discoverdelay = 10 if (self.upnp.discover() > 0): self.upnp.selectigd() try: if (self.upnp.getspecificportmapping(self.port, "TCP")): self.upnp.deleteportmapping(self.port, 'TCP') self.upnp.addportmapping(self.port, 'TCP', self.upnp.lanaddr, self.port, tr("app.title"), '') self.printMessage( tr("upnp.external.ip") + self.upnp.externalipaddress()) self.upnpEnabled = True except Exception: self.printMessage(tr("upnp.error.add")) except ImportError: self.printMessage(tr("upnp.error.load")) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: self.sock.bind((self.host, self.port)) self.sock.listen(1) except OSError: self.printMessage(tr("error.server.listening")) self.stop()
def execute(self, locals): """ Run the file : customized parsing for checking rules, compile and execute """ # Compile the code and get the AST from it, which will be used for all # the conventions checkings that need to be done try: self.AST = ast.parse(self.source, self.filename) # Handle the different kinds of compilation errors except IndentationError as err: self.report.add_compilation_error('error', tr("Bad indentation"), err.lineno, err.offset) return False except SyntaxError as err: self.report.add_compilation_error('error', tr("Syntax error"), err.lineno, err.offset, details=err.text) return False except Exception as err: typ, exc, tb = sys.exc_info() self.report.add_compilation_error('error', str(typ), err.lineno, err.offset, details=str(err)) return False # No parsing error here # perform the local checks ret_val = True if not self.check_rules(self.report): ret_val = False self.run(locals) # we still run the code even if there is a convention error else: ret_val = self.run(locals) # Run the code if it passed all the convention tests if ret_val: self.report.nb_passed_tests = self.nb_asserts return ret_val
def execute(self, locals): """ Run the file : customized parsing for checking rules, compile and execute """ # Compile the code and get the AST from it, which will be used for all # the conventions checkings that need to be done try: self.AST = ast.parse(self.source, self.filename) # Handle the different kinds of compilation errors except IndentationError as err: self.report.add_compilation_error('error', tr("Bad indentation"), err.lineno, err.offset) return False except SyntaxError as err: self.report.add_compilation_error('error', tr("Syntax error"), err.lineno, err.offset, details=err.text) return False except Exception as err: typ, exc, tb = sys.exc_info() self.report.add_compilation_error('error', str(typ), err.lineno, err.offset, details=str(err)) return False # No compilation error here # perform the local checks if not self.check_rules(self.report): return False else: return self.run(locals) # Run the code if it passed all the convention tests
def __init__(self, parent=None): QListWidget.__init__(self, parent) self.setWindowTitle(tr("Saved Sessions")) self.setWindowFlags(Qt.Dialog) hideAction = QAction(self) hideAction.setShortcuts(["Esc", "Ctrl+W"]) hideAction.triggered.connect(self.hide) self.addAction(hideAction) self.sessionList = QListWidget(self) self.sessionList.itemActivated.connect(self.loadSession) self.setCentralWidget(self.sessionList) self.toolBar = QToolBar(self) self.toolBar.setMovable(False) self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu) self.addToolBar(Qt.BottomToolBarArea, self.toolBar) self.loadButton = QPushButton(tr("&Load"), self) self.loadButton.clicked.connect( lambda: self.loadSession(self.sessionList.currentItem())) self.toolBar.addWidget(self.loadButton) self.saveButton = QPushButton(tr("&Save"), self) self.saveButton.clicked.connect(saveSessionManually) self.saveButton.clicked.connect(self.refresh) self.toolBar.addWidget(self.saveButton) deleteAction = QAction(self) deleteAction.setShortcut("Del") deleteAction.triggered.connect(self.delete) self.addAction(deleteAction)
def __init__(self, parent=None): QListWidget.__init__(self, parent) self.setWindowTitle(tr("Saved Sessions")) self.setWindowFlags(Qt.Dialog) hideAction = QAction(self) hideAction.setShortcuts(["Esc", "Ctrl+W"]) hideAction.triggered.connect(self.hide) self.addAction(hideAction) self.sessionList = QListWidget(self) self.sessionList.itemActivated.connect(self.loadSession) self.setCentralWidget(self.sessionList) self.toolBar = QToolBar(self) self.toolBar.setMovable(False) self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu) self.addToolBar(Qt.BottomToolBarArea, self.toolBar) self.loadButton = QPushButton(tr("&Load"), self) self.loadButton.clicked.connect(lambda: self.loadSession(self.sessionList.currentItem())) self.toolBar.addWidget(self.loadButton) self.saveButton = QPushButton(tr("&Save"), self) self.saveButton.clicked.connect(saveSessionManually) self.saveButton.clicked.connect(self.refresh) self.toolBar.addWidget(self.saveButton) deleteAction = QAction(self) deleteAction.setShortcut("Del") deleteAction.triggered.connect(self.delete) self.addAction(deleteAction)
def toggleWindows(self): hidden = False for window in browser.windows: window.setVisible(not window.isVisible()) try: if not browser.windows[0].isVisible(): self.showMessage(tr("All windows hidden"), tr("Click again to restore.")) except: pass
def disc(): def startServer(): Thread(target=interface.startServer).start() global interface, msg_list for c in wd.winfo_children(): c.destroy() msg = StringVar() # pour le message qui sera envoyé label = Label(wd, text=tr("status.connected"), font=("courrier", 22), bg="#56646A", fg="white") label.pack(side=TOP) msg_list = Text(wd, bg="#545454", fg="white", state=DISABLED) msg_list.pack(expand=True, fill='both', padx=100) chp = Entry(wd, width=70, font=(22), bg="#56646A", fg="white", bd=2, relief=SUNKEN, textvariable=msg) chp.insert(0, tr("gui.message.placeholder")) chp.pack(side=BOTTOM, pady=10, padx=100, fill="x") chp.bind("<FocusIn>", lambda args: chp.delete('0', 'end')) btnSERV = Button(wd, text=tr("server.start"), font=("courrier", 22), bg="white", fg="#56646A", command=startServer) btnSERV.pack(fill=X) chpIPMsg = StringVar() chpIP = Entry(wd, width=20, font=(22), bg="#56646A", fg="white", bd=2, relief=SUNKEN, textvariable=chpIPMsg) chpIP.pack(side=BOTTOM, pady=30) def startClient(e): Thread(target=interface.startClient, args=[chpIPMsg.get()]).start() chpIPMsg.set("") def send(e): Thread(target=interface.parseCommand, args=[msg.get()]).start() msg.set("") chp.bind("<Return>", send) # definir "send" comme envoyer le message chpIP.bind("<Return>", startClient)
def report(self, report): if isinstance(self.node, ContainerAssign): report.add_convention_error('error', tr('Not-Python101'), -1, -1, tr("This function may return None")) else: report.add_convention_error('error', tr('Not-Python101'), self.node.ast.lineno, self.node.ast.col_offset, tr("This function may return None"))
def change_mode(self, event=None): """ Swap the python mode : full python or student """ if self.mode == "student": self.mode = "full" else: self.mode = "student" self.icon_widget.switch_icon_mode(self.mode) self.console.change_mode(tr(self.mode)) self.status_bar.change_mode(tr(self.mode))
def SelectProfile (parent, profiles): items = [] for prof in profiles: items.append( prof['name'].decode('ascii') ) idx = SelectItem(parent, tr('#Select profile'), tr('#Name'), items) if idx == None: return None else: return profiles[idx]
def find(self): find = QInputDialog.getText(self, tr("Find"), tr("Search for:"), QLineEdit.Normal, self.text) if find[1]: self.text = find[0] else: self.text = "" if self.findFlag: self.sourceView.find(self.text, self.findFlag) else: self.sourceView.find(self.text)
def __init__(self, parent=None): super(ClearHistoryDialog, self).__init__(parent) self.setWindowFlags(Qt.Dialog) self.setWindowTitle(tr("Clear Data")) closeWindowAction = QAction(self) closeWindowAction.setShortcuts(["Esc", "Ctrl+W", "Ctrl+Shift+Del"]) closeWindowAction.triggered.connect(self.close) self.addAction(closeWindowAction) self.layout = QVBoxLayout() self.setLayout(self.layout) label = QLabel(tr("What to clear:"), self) self.layout.addWidget(label) self.dataType = QComboBox(self) self.dataType.addItem(tr("History")) self.dataType.addItem(tr("Cookies")) self.dataType.addItem(tr("Memory Caches")) self.dataType.addItem(tr("Persistent Storage")) self.dataType.addItem(tr("Everything")) self.layout.addWidget(self.dataType) self.toolBar = QToolBar(self) self.toolBar.setStyleSheet(common.blank_toolbar) self.toolBar.setMovable(False) self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu) self.layout.addWidget(self.toolBar) self.clearHistoryButton = QPushButton(tr("Clear"), self) self.clearHistoryButton.clicked.connect(self.clearHistory) self.toolBar.addWidget(self.clearHistoryButton) self.closeButton = QPushButton(tr("Close"), self) self.closeButton.clicked.connect(self.close) self.toolBar.addWidget(self.closeButton)
def saveAs(self): fname = QFileDialog.getSaveFileName(None, tr("Save As..."), self.windowTitle() + ".txt", tr("Text files (*.txt)")) if type(fname) is tuple: fname = fname[0] if fname: g = str(self.sourceView.toPlainText()) f = open(fname, "w") f.write(g) f.close()
def about(self): try: parent = browser.activeWindow() except: parent = self.widget self.widget.show() QMessageBox.about(parent, tr("About %s") % (common.app_name,),\ "<h3>" + common.app_name + " " +\ common.app_version +\ "</h3>" +\ tr("A Qt-based web browser made in Python.<br><br>%s is provided to you free of charge, with no promises of security or stability. By using this software, you agree not to sue me for anything that goes wrong with it.") % (common.app_name,)) self.widget.hide()
def printMessage(text, message=False, username=None): global interface if message: username = interface.otherUsername if (not username): username = tr("user.other") print("\r" + ERASE_LINE + username + " : " + text + "\n" + tr("command.label") + " : ", end="") else: print("\r" + ERASE_LINE + text + "\n" + tr("command.label") + " : ", end="")
def populateChannelData(self, layer, asset): log("in populateChannelData") currentTitle="" nextDesc="" nextTime="" nextTitle="" currentDesc="" recording,data=asset.channel.GetProgramInfo() log("%s, %s" % (str(recording).encode("ascii","replace"),str(data).encode("ascii","replace"))) if not data: return if not recording and not data.has_key('currentShow'): return if recording: c=ETV.RecordingChannelName() log("Got recording, channel name %s" % c) if c is None: return currentTitle=tr("Now Recording!") currentDesc=(tr("Currently recording channel %s. Program info is not available.") % c) try: currentShow=data['currentShow'] currentTitle += currentShow['title'] if currentShow.has_key('shortDescription'): currentDesc += currentShow['shortDescription'] + " " currentDesc += currentShow['startTime'].strftime("%I:%M") + "-" + currentShow['endTime'].strftime("%I:%M%p") except: pass try: nextShow=data['nextShow'] nextTitle = nextShow['title'] nextTime = nextShow['startTime'].strftime("%I:%M%p") + "-" + nextShow['endTime'].strftime("%I:%M%p") nextDesc = nextShow['shortDescription'] except: pass layer.setTitle_(currentTitle) layer.setSummary_(currentDesc) labels=[ tr("Next"), tr("Episode"), tr("Time") ] data=[ nextTitle, nextDesc, nextTime ] layer.setMetadata_withLabels_(data,labels)
def __init__(self, parent=None): super(SearchEditor, self).__init__(parent) self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup) self.parent = parent self.setWindowTitle(tr('Search Editor')) self.styleSheet = "QMainWindow { background: palette(window); border: 1px solid palette(dark); }" self.setStyleSheet(self.styleSheet) try: self.setWindowIcon(common.app_icon) except: pass closeWindowAction = QAction(self) closeWindowAction.setShortcuts(["Ctrl+W", "Ctrl+Shift+K"]) closeWindowAction.triggered.connect(self.close) self.addAction(closeWindowAction) self.entryBar = QToolBar(self) self.entryBar.setIconSize(QSize(16, 16)) self.entryBar.setStyleSheet(common.blank_toolbar) self.entryBar.setContextMenuPolicy(Qt.CustomContextMenu) self.entryBar.setMovable(False) self.addToolBar(self.entryBar) eLabel = QLabel(" " + tr('New expression:'), self) self.entryBar.addWidget(eLabel) self.expEntry = custom_widgets.LineEdit(self) self.expEntry.returnPressed.connect(self.addSearch) self.entryBar.addWidget(self.expEntry) self.addSearchButton = QToolButton(self) self.addSearchButton.setText(tr("Add")) self.addSearchButton.setIcon(common.complete_icon("list-add")) self.addSearchButton.clicked.connect(self.addSearch) self.entryBar.addWidget(self.addSearchButton) self.engineList = QListWidget(self) self.engineList.setAlternatingRowColors(True) self.engineList.itemClicked.connect(self.applySearch) self.engineList.itemActivated.connect(self.applySearch) self.engineList.itemActivated.connect(self.close) self.setCentralWidget(self.engineList) self.takeSearchAction = QAction(self) self.takeSearchAction.triggered.connect(self.takeSearch) self.takeSearchAction.setShortcut("Del") self.addAction(self.takeSearchAction) self.hideAction = QAction(self) self.hideAction.triggered.connect(self.hide) self.hideAction.setShortcut("Esc") self.addAction(self.hideAction) self.reload_()
def _exec_or_eval(self, mode, code, globs, locs): assert mode=='exec' or mode=='eval' try: if mode=='exec': result = exec(code, globs, locs) elif mode=='eval': result = eval(code, globs, locs) except TypeError as err: a, b, tb = sys.exc_info() filename, lineno, file_type, line = traceback.extract_tb(tb)[-1] err_str = self._extract_error_details(err) self.report.add_execution_error('error', tr("Type error"), lineno, details=str(err)) return (False, None) except NameError as err: a, b, tb = sys.exc_info() # Get the traceback object # Extract the information for the traceback corresponding to the error # inside the source code : [0] refers to the result = exec(code) # traceback, [1] refers to the last error inside code filename, lineno, file_type, line = traceback.extract_tb(tb)[-1] err_str = self._extract_error_details(err) self.report.add_execution_error('error', tr("Name error (unitialized variable?)"), lineno, details=err_str) return (False, None) except ZeroDivisionError: a, b, tb = sys.exc_info() filename, lineno, file_type, line = traceback.extract_tb(tb)[-1] self.report.add_execution_error('error', tr("Division by zero"), lineno if mode=='exec' else None) return (False, None) except AssertionError: a, b, tb = sys.exc_info() lineno=None traceb = traceback.extract_tb(tb) if len(traceb) > 1: filename, lineno, file_type, line = traceb[-1] self.report.add_execution_error('error', tr("Assertion error (failed test?)"), lineno) return (False, None) except Exception as err: a, b, tb = sys.exc_info() # Get the traceback object # Extract the information for the traceback corresponding to the error # inside the source code : [0] refers to the result = exec(code) # traceback, [1] refers to the last error inside code lineno=None traceb = traceback.extract_tb(tb) if len(traceb) > 1: filename, lineno, file_type, line = traceb[-1] self.report.add_execution_error('error', a.__name__, lineno, details=str(err)) return (False, None) finally: self.running = False return (True, result)
def _exec_or_eval(self, mode, code, globs, locs): assert mode=='exec' or mode=='eval' try: if mode=='exec': result = exec(code, globs, locs) elif mode=='eval': result = eval(code, globs, locs) except TypeError as err: a, b, tb = sys.exc_info() filename, lineno, file_type, line = traceback.extract_tb(tb)[-1] err_str = self._extract_error_details(err) self.report.add_execution_error('error', tr("Type error"), lineno, details=str(err)) return (False, None) except NameError as err: a, b, tb = sys.exc_info() # Get the traceback object # Extract the information for the traceback corresponding to the error # inside the source code : [0] refers to the result = exec(code) # traceback, [1] refers to the last error inside code filename, lineno, file_type, line = traceback.extract_tb(tb)[-1] err_str = self._extract_error_details(err) self.report.add_execution_error('error', tr("Name error (unitialized variable?)"), lineno, details=err_str) return (False, None) except ZeroDivisionError: a, b, tb = sys.exc_info() filename, lineno, file_type, line = traceback.extract_tb(tb)[-1] self.report.add_execution_error('error', tr("Division by zero"), lineno if mode=='exec' else None) return (False, None) except AssertionError: a, b, tb = sys.exc_info() lineno=None traceb = traceback.extract_tb(tb) if len(traceb) > 1: filename, lineno, file_type, line = traceb[-1] self.report.add_execution_error('error', tr("Assertion error (failed test?)"), lineno) return (True, None) except Exception as err: a, b, tb = sys.exc_info() # Get the traceback object # Extract the information for the traceback corresponding to the error # inside the source code : [0] refers to the result = exec(code) # traceback, [1] refers to the last error inside code lineno=None traceb = traceback.extract_tb(tb) if len(traceb) > 1: filename, lineno, file_type, line = traceb[-1] self.report.add_execution_error('error', a.__name__, lineno, details=str(err)) return (False, None) finally: self.running = False return (True, result)
def fun_type_converter(fun_def): param_types = [] for (par, par_type) in zip(fun_def.parameters, fun_def.param_types): ok, ret_type = type_converter(par_type) if not ok: return (False, tr("Parameter '{}': {}").format(par, ret_type)) param_types.append(ret_type) ok, ret_type = type_converter(fun_def.returns) if not ok: return (False, tr("Return type: {}").format(ret_type)) return (True, FunctionType(param_types, ret_type, False, 1))
def __str__(self): s = "" if self.severity == 'warning': s = "{}{}".format(tr("Warning"), tr(": line {}\n").format(self.line) if self.line else "") s = s + self.error_details() elif self.severity == 'error': s = "{}{}".format(tr("Error"), tr(": line {}\n").format(self.line) if self.line else "") s = s + self.error_details() else: s = self.details return s
def checkTrust(self): if not self.currentFingerprint: return self.printMessage(tr("fingerprint.other") + " : " + self.currentFingerprint) if self.savedFingerprints and self.currentFingerprint in self.savedFingerprints: entry = self.savedFingerprints[self.currentFingerprint] if entry["level"] == "always": self.printMessage(tr("trust.whitelist")) self.trusted = True elif entry["level"] == "never": self.printMessage(tr("trust.blacklist")) self.trusted = False else: self.printMessage(tr("trust.unknown")) self.printMessage(tr("trust.usage"))
def run_module(self, event=None): """ Run the code : give the file name and code will be run from the source file """ # already running if self.running_interpreter_callback: if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive(): report = RunReport() report.set_header("\n====== STOP ======\n") report.add_execution_error('error', tr('User interruption')) report.set_footer("\n==================\n") self.running_interpreter_callback(False, report) self.running_interpreter_callback = None return # not (yet) running if self.editor_list.get_size() == 0: self.main_view.console.no_file_to_run_message() return reply = self.editor_list.get_current_editor().maybesave_run() if (reply != "cancel"): file_name = self.editor_list.get_current_editor().long_title() self.update_title() self.status_bar.update_save_label(file_name) self.console.run(file_name)
def __init__(self, *args, **kwargs): super(BatteryAction, self).__init__(*args, **kwargs) self.setToolTip(tr("Power")) if system.battery: self.updateLife() self.timer.timeout.connect(self.updateLife) if not self.timer.isActive(): self.timer.start(5000) elif system.is_on_ac(): self.setIcon(complete_icon("charging")) self.setText(tr("AC")) self.setToolTip(tr("System is running on AC power")) else: self.setIcon(complete_icon("dialog-warning")) self.setText(tr("N/A")) self.setToolTip(tr("Battery not detected"))
def injectCustomParameters(param, sql): # split sql to extract parameters exploded = sql.split(TAG) count = 0 finalSql="" for block in exploded: if (count % 2) == 1: # parameter sql block [paramName, value] = readParamter(block) # parameter for this block p = param[paramName] if "value" in p: finalSql += p["value"] else: # no value set : use default value finalSql += p["default"] else: # other sql block finalSql += block count += 1 if count != 0 and (count % 2) != 1: exc = SyntaxError() exc.text = tr(u"Wrong Number of " + TAG) raise exc return finalSql
def run(self, locals): """ Run the code, add the execution errors to the rapport, if any """ locals = install_locals(locals) code = None try: code = compile(self.source, self.filename, 'exec') except SyntaxError as err: self.report.add_compilation_error('error', tr("Syntax error"), err.lineno, err.offset, details=str(err)) return False except Exception as err: typ, exc, tb = sys.exc_info() self.report.add_compilation_error('error', str(typ), err.lineno, err.offset, details=str(err)) return False (ok, result) = self._exec_or_eval('exec', code, locals, locals) #if not ok: # return False # if no error get the output sys.stdout.seek(0) result = sys.stdout.read() self.report.set_output(result) return ok
def execute(self): """ Execute the runner corresponding to the chosen Python mode """ runner = None if self.mode == "student": runner = StudentRunner(self.filename, self.source) else: runner = FullRunner(self.filename, self.source) ok = runner.execute(self.locals) report = runner.get_report() import os begin_report = "=== " + tr("Interpretation of: ") + "'" + os.path.basename(self.filename) + "' ===\n" len_begin_report = len(begin_report) # enable? # if self.mode == 'student': # begin_report += "# Automatic importation of graphic library\n" # begin_report += "from studentlib.gfx.image import (draw_line, draw_triangle, fill_triangle\n" # begin_report += " , draw_ellipse, fill_ellipse\n" # begin_report += " , overlay, underlay)\n" # begin_report += "from studentlib.gfx.img_canvas import show_image\n\n" report.set_header(begin_report) end_report = "\n" + ('=' * len_begin_report) + "\n\n" report.set_footer(end_report) return (ok, report)
def addTab(self, title="New Tab", data=""): vsd = ViewSourceDialog(self, str(title)) vsd.setPlainText(data) self.tabs.addTab(vsd, tr("Source of %s") % (title,)) self.tabs.setCurrentIndex(self.tabs.count()-1) self.raise_() self.activateWindow()
def callback(ok, report): # XXX: the ok is not trustable if report.has_compilation_error() or report.has_execution_error(): ok = False nonlocal callback_called if callback_called: return else: callback_called = True #print("[console] CALLBACK: exec ok ? {} report={}".format(ok, report)) self.write_report(ok, report, 'exec') self.output_console.see('1.0') # Enable or disable the evaluation bar according to the execution status if report.has_compilation_error( ): # XXX: only for compilation ? , otherwise: or report.has_execution_error(): # kill the interpreter self.interpreter.kill() self.interpreter = None self.app.running_interpreter_proxy = None else: self.input_console.focus_set() #self.switch_input_status(True) self.app.icon_widget.disable_icon_running() self.app.running_interpreter_callback = None tracing.send_statement_execute(report, tr(self.mode), filename=filename)
def addTab(self, title="New Tab", data=""): vsd = ViewSourceDialog(self, str(title)) vsd.setPlainText(data) self.tabs.addTab(vsd, tr("Source of %s") % (title, )) self.tabs.setCurrentIndex(self.tabs.count() - 1) self.raise_() self.activateWindow()
def ParametersToDialogUpdate(self): query = self.query self.labelQueryName.setText(query.name) # index for param, header param separated from other param self.widgetParam = {"header": {}, "param": {}} for header_or_param in {"header", "param"}: listParam = self.query.param if header_or_param == "header": listParam = self.query.header def sort_param(key): return listParam[key]["order"] for paramName in sorted(listParam, key=sort_param): # in listParam: # ignore hidden header parameters if header_or_param == "header": if paramName in HIDDEN_HEADER_VALUE: continue value = listParam[paramName] # add param to dialog and index its widget self.widgetParam[header_or_param][paramName] = self.addParam(tr(paramName), value) # adjust dialog size self.setFixedHeight(40 + self.gridLayoutHeader.rowCount() * 25)
def do_open (self, fileName, prof): # assert not modified try: encodedText = util.readFile(fileName) except Exception, e: self.msg_set( tr('#File read error') + ': ' + exMsg(e) )
def __str__(self): s = "" if self.severity == 'warning': s = "{}{}".format( tr("Warning"), ": line {}\n".format(self.line) if self.line else "") s = s + self.error_details() elif self.severity == 'error': s = "{}{}".format( tr("Error"), ": line {}\n".format(self.line) if self.line else "") s = s + self.error_details() else: s = self.details return s
def __init__(self, iface, dbrequest, query, parent=None): """Constructor.""" super(QueryParamDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) self.iface = iface self.dbrequest = dbrequest self.query = query # translate widget self.setWindowTitle(tr(self.windowTitle())) # index of widget by param name self.widgetParam = None # in case of failure self.errorMessage = "" self.buttonBox.accepted.connect(self.DialogToParametersUpdate)
def run_module(self, event=None): """ Run the code : give the file name and code will be run from the source file """ # already running if self.running_interpreter_callback: if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive( ): report = RunReport() report.set_header("\n====== STOP ======\n") report.add_execution_error('error', tr('User interruption')) report.set_footer("\n==================\n") self.running_interpreter_callback(False, report) self.running_interpreter_callback = None return # not (yet) running if self.editor_list.get_size() == 0: self.main_view.console.no_file_to_run_message() return reply = self.editor_list.get_current_editor().maybesave_run() if (reply != "cancel"): file_name = self.editor_list.get_current_editor().long_title() self.update_title() self.status_bar.update_save_label(file_name) self.console.run(file_name)
def change_mode(self, event=None): """ Swap the python mode : full python or student """ if self.mode == "student": self.mode = "full" else: self.mode = "student" self.icon_widget.switch_icon_mode(self.mode) self.console.change_mode(tr(self.mode)) self.status_bar.change_mode(tr(self.mode)) if event: tracing.user_is_interacting() tracing.send_statement( "switched", "mode", { "https://www.lip6.fr/mocah/invalidURI/extensions/mode": tr(self.mode) })
def doCompile (base): text = getText(base.srcTextView) text = normalizeLineSep(text, base.mod['lineSep']) try: encodedText, encoding = exportText(base.mod, text) except Exception, e: base.msg_set( tr('#Text convert error') + ': ' + exMsg(e) ) return
def reset_output(self): """ Clear all the output console """ #self.output_console.config(state=NORMAL) self.output_console.delete(1.0, END) self.begin() self.write("MrPython v.{} -- mode {}\n".format(version.version_string(), tr(self.mode)))
def initWithStartup_exitCond_(self, startup=None,exitCond=None): log("initWithStartup_") #self.tickCount=0 self.wasHidden=False self.startup=startup self.exitCond=exitCond self.frcontroller = BRAppManager.sharedApplication().delegate() return PyFR.WaitController.WaitController.initWithText_(self, tr("Launching EyeTV"))
def modified_changed (self): if Trace: print 'modified:', self.mod['modified'] if self.mod['fileName'] == None: t = tr('#untitled') else: t = self.mod['fileName'].decode(locale.getpreferredencoding()) if self.mod['modified']: t = t + '*' self.mainWindow.set_title("(%s) %s".encode('utf-8') % (self.mod['profile']['name'], t))
def changeAboutText(self, name): aboutpath = os.path.join(settings.extensions_folder, name, "about.txt") try: f = open(aboutpath, "r") except: self.aboutText.setText(tr("This extension has no description.")) return aboutText = f.read().replace("\n", "") f.close() self.aboutText.setText(aboutText)
def fpcCompile (text, encodedText, encoding, fileName): assert type(text) is unicode assert type(encodedText) is str assert encoding != None r = _pPas.match(text) if r != None: modName = r.group(1).encode('ascii') baseName = modName + '.$$$' if fileName == None: fName = baseName # inCurDir = True else: d = os.path.dirname(fileName) if (d == '') or sameFile(os.getcwd(), d): fName = baseName # inCurDir = True else: fName = os.path.join(d, baseName) # inCurDir = False if not os.path.exists(fName): try: try: util.writeFile( fName, encodedText.replace('\t', ' '), sync=False ) except Exception, e: msg = tr('#File write error') + ': ' + exMsg(e) return (msg, None, None) try: e, o = cmd(["fpc", fName]) except Exception, e: msg = 'fpc: ' + exMsg(e) return (msg, None, None) msg = e + o.decode( encoding ) eLines = e.count('\n') errs = [] warns = [] i = eLines for l in o.split('\n'): r = _pfpcLine.match(l + '\n') if r and (r.group(1) == baseName): line = int(r.group(2)) - 1 col = int(r.group(3)) - 1 pos = (line, col) link = (i, pos) m = r.group(4) if m.startswith('Error:') or m.startswith('Fatal:'): errs.append(link) else: warns.append(link) i = i + 1 return (msg, errs, warns) finally: