Пример #1
0
def main():

    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    app.exec_()
Пример #2
0
def main(argv):
    app = QApplication(
        argv)  # Early so that QT is initialized before other imports
    app.setWindowIcon(resourceIcon("application/window_icon_cutout"))

    # There seems to be a setlocale() call deep down in the initialization of
    # QApplication, if the user has set the LC_NUMERIC environment variables to
    # a locale with decimalpoint different from "." the application will fail
    # hard quite quickly.
    current_locale = QLocale()
    decimal_point = str(current_locale.decimalPoint())
    if decimal_point != ".":
        msg = """
** WARNING: You are using a locale with decimalpoint: '{}' - the ert application is
            written with the assumption that '.' is used as decimalpoint, and chances
            are that something will break if you continue with this locale. It is highly
            reccomended that you set the decimalpoint to '.' using one of the environment
            variables 'LANG', LC_ALL', or 'LC_NUMERIC' to either the 'C' locale or
            alternatively a locale which uses '.' as decimalpoint.\n""".format(
            decimal_point)

        sys.stderr.write(msg)

    if len(argv) == 1:
        config_file = QFileDialog.getOpenFileName(None,
                                                  "Open Configuration File")

        config_file = str(config_file)

        if len(config_file) == 0:
            print(
                "-----------------------------------------------------------------"
            )
            print(
                "-- You must supply the name of configuration file as the first --"
            )
            print(
                "-- commandline argument:                                       --"
            )
            print(
                "--                                                             --"
            )
            print(
                "-- bash%  gert <config_file>                                   --"
            )
            print(
                "--                                                             --"
            )
            print(
                "-- If the configuration file does not exist, gert will create  --"
            )
            print(
                "-- create a new configuration file.                            --"
            )
            print(
                "-----------------------------------------------------------------"
            )

            sys.exit(1)
    else:
        config_file = argv[1]

    help_center = HelpCenter("ERT")
    help_center.setHelpLinkPrefix(
        os.path.join(pkg_dir, "resources", "gui", "help"))
    help_center.setHelpMessageLink("welcome_to_ert")

    strict = True

    verbose = False
    verbose_var = os.getenv("ERT_VERBOSE", "False")
    lower_verbose_var = verbose_var.lower()
    if lower_verbose_var == "true":
        verbose = True

    if not os.path.exists(config_file):
        print("Trying to start new config")
        new_configuration_dialog = NewConfigurationDialog(config_file)
        success = new_configuration_dialog.exec_()
        if not success:
            print("Can not run without a configuration file.")
            sys.exit(1)
        else:
            config_file = new_configuration_dialog.getConfigurationPath()
            dbase_type = new_configuration_dialog.getDBaseType()
            num_realizations = new_configuration_dialog.getNumberOfRealizations(
            )
            storage_path = new_configuration_dialog.getStoragePath()

            EnKFMain.createNewConfig(config_file, storage_path, dbase_type,
                                     num_realizations)
            strict = False

    if os.path.isdir(config_file):
        print("The specified configuration file is a directory!")
        sys.exit(1)

    splash = ErtSplash()
    splash.version = "Version %s" % ert_gui.__version__

    splash.show()
    splash.repaint()

    now = time.time()

    res_config = ResConfig(config_file)
    os.chdir(res_config.config_path)
    ert = EnKFMain(res_config, strict=strict, verbose=verbose)
    ert_gui.configureErtNotifier(ert, config_file)

    window = GertMainWindow()
    window.setWidget(SimulationPanel())

    plugin_handler = PluginHandler(ert,
                                   ert.getWorkflowList().getPluginJobs(),
                                   window)

    help_tool = HelpTool("ERT", window)

    window.addDock("Configuration Summary",
                   SummaryPanel(),
                   area=Qt.BottomDockWidgetArea)
    window.addTool(IdeTool(os.path.basename(config_file), help_tool))
    window.addTool(PlotTool())
    window.addTool(ExportTool())
    window.addTool(WorkflowsTool())
    window.addTool(ManageCasesTool())
    window.addTool(PluginsTool(plugin_handler))
    window.addTool(RunAnalysisTool())
    window.addTool(LoadResultsTool())
    window.addTool(help_tool)
    window.adjustSize()
    sleep_time = 2 - (time.time() - now)

    if sleep_time > 0:
        time.sleep(sleep_time)

    window.show()
    splash.finish(window)
    window.activateWindow()
    window.raise_()
    ResLog.log(
        3, "Versions: ecl:%s    res:%s    ert:%s" %
        (ecl.__version__, res.__version__, ert_gui.__version__))

    if not ert._real_enkf_main().have_observations():
        em = QMessageBox.warning(
            window, "Warning!",
            "No observations loaded. Model update algorithms disabled!")

    finished_code = app.exec_()
    sys.exit(finished_code)
Пример #3
0
        super(MainWindow, self).__init__(parent)

        # Create the parameter window widget
        #params = FindspotsParameterWidget()
        #params = RefineParameterWidget()
        params = IntegrateParameterWidget()

        # Create the window layout
        layout = QVBoxLayout()
        layout.addWidget(params)

        # Setup the window contents
        window = QWidget()
        window.setLayout(layout)
        self.setCentralWidget(window)


if __name__ == '__main__':
    import sys

    # Create the application
    app = QApplication(sys.argv)

    # Create the main window
    window = MainWindow()
    window.resize(800, 600)
    window.show()

    # Execute the application
    sys.exit(app.exec_())
Пример #4
0
def viewerApp():
    app = QApplication(sys.argv)
    v = Viewer()
    return (v, app)
Пример #5
0
 def keyPressEvent(self, e):
 global flag
 global i

 if e.key() == QtCore.Qt.Key_S:
 flag = 1
 i = 0
 print ("Start Capture")
 elif e.key() == QtCore.Qt.Key_Q: 
 flag = 0 
 print ("End Capture")

 s.sendall('Event')
 data = s.recv(1024)
 ans = int(data.encode('hex'), 16)
 print(ans)

 tts = ALProxy("ALTextToSpeech", self.nao_ip, self.nao_port)
 
 if ans == 0:
 # no gesture
 tts.say("No Gesture Detected")
 elif ans == 1:
 # left
 pi_2 = -3.1415/2

 postureProxy = ALProxy("ALRobotPosture", self.nao_ip, self.nao_port)
 posture = postureProxy.getPosture()
 
 if(posture == 'Sit'):
 tts.say("I need to stand first")
 postureProxy.goToPosture("Stand", 1.0)

 tts.say("Moving to your Left")

 motion = ALProxy("ALMotion", self.nao_ip, self.nao_port)
 motion.moveInit()
 motion.moveTo(0, 0, pi_2)
 motion.moveTo(0.2, 0, 0)
 elif ans == 2:
 # right
 pi_2 = 3.1415/2
 postureProxy = ALProxy("ALRobotPosture", self.nao_ip, self.nao_port)
 posture = postureProxy.getPosture()
 
 if(posture == 'Sit'):
 tts.say("I need to stand first")
 postureProxy.goToPosture("Stand", 1.0)

 tts.say("Moving to your Right")

 motion = ALProxy("ALMotion", self.nao_ip, self.nao_port)
 motion.moveInit()
 motion.moveTo(0, 0, pi_2)
 motion.moveTo(0.2, 0, 0)
 elif ans == 3:
 # down
 tts.say("Sit Down")

 postureProxy = ALProxy("ALRobotPosture", self.nao_ip, self.nao_port)
 postureProxy.goToPosture("Sit", 1.0)

 elif ans == 4:
 # up
 tts.say("Stand Up")

 postureProxy = ALProxy("ALRobotPosture", self.nao_ip, self.nao_port)
 postureProxy.goToPosture("Stand", 1.0)
 elif ans == 5:
 # shaking hand
 tts.say("Hi")
 elif ans == 6:
 # stop
 postureProxy = ALProxy("ALRobotPosture", self.nao_ip, self.nao_port)
 posture = postureProxy.getPosture()
 
 if(posture == 'Sit'):
 tts.say("I need to stand first")
 postureProxy.goToPosture("Stand", 1.0)

 tts.say("Moving Back")

 motion = ALProxy("ALMotion", self.nao_ip, self.nao_port)
 motion.moveInit()
 motion.moveTo(-0.2, 0, 0)
 elif ans == 7:
 # forward
 postureProxy = ALProxy("ALRobotPosture", self.nao_ip, self.nao_port)
 posture = postureProxy.getPosture()
 
 if(posture == 'Sit'):
 tts.say("I need to stand first")
 postureProxy.goToPosture("Stand", 1.0)

 tts.say("Moving Forward")
 
 motion = ALProxy("ALMotion", self.nao_ip, self.nao_port)
 motion.moveInit()
 motion.moveTo(0.2, 0, 0)

 files = glob.glob('./temp/test_img/*')
 for f in files:
 os.remove(f)
 
 self.close()
 s.close()

if __name__ == '__main__':
 IP = "172.16.21.202" # Replace here with your NaoQi's IP address.
 PORT = 9559
 CameraID = 0

 # Read IP address from first argument if any.
 if len(sys.argv) > 1:
 IP = sys.argv[1]

 # Read CameraID from second argument if any.
 if len(sys.argv) > 2:
 CameraID = int(sys.argv[2])

 aware = ALProxy("ALBasicAwareness",IP,PORT)
 aware.setEngagementMode("FullyEngaged")
 aware.setStimulusDetectionEnabled("Sound",False)
 aware.startAwareness()

 app = QApplication(sys.argv)
 myWidget = ImageWidget(IP, PORT, CameraID)
 myWidget.show()
 sys.exit(app.exec_())
Пример #6
0
def main(font, root_directory, settings_directory, mount_directory,
         adjust_width, adjust_height, edit_settings):
    """
    Run the GUI.

    Arguments:
    font - Default value for the font size
    adjust_width - Value to adjust the width of buttons
    adjust_height - Value to adjust the height of buttons
    edit_settings - If True, open the default settings dialog

    Return:
    None
    """
    # Start the GUI from the users home directory.
    os.chdir(root_directory)

    app = QApplication([])
    app.setStyle('cleanlooks')

    # Create default folders
    tu.mkdir_p(settings_directory)
    tu.mkdir_p(mount_directory)

    # Load default font settings for the default settings dialog
    if font is None:
        try:
            with open('{0}/content_Font.txt'.format(settings_directory),
                      'r') as file_r:
                settings = json.load(file_r)
            app.setStyleSheet(
                tu.look_and_feel_small(app=app,
                                       font=settings[0][0]['Font'][0]))
        except FileNotFoundError:
            pass
    else:
        app.setStyleSheet(tu.look_and_feel_small(app=app, font=font))

    # Get default settings 0: content
    IDX_CONTENT = 0
    content = DefaultSettings.get_content_default(
        edit_settings=edit_settings,
        apply=False,
        settings_folder=settings_directory)[IDX_CONTENT]

    # Apply font settings to application
    app.setStyleSheet(
        tu.look_and_feel(app=app,
                         font=font,
                         adjust_width=adjust_width,
                         adjust_height=adjust_height,
                         default=content['Font']))

    # Load content for the GUI
    content_gui = tu.get_content_gui(content=content)

    # Initilise and show GUI
    gui = MainWindow(content_gui=content_gui,
                     content_pipeline=content['Pipeline'],
                     settings_folder=settings_directory,
                     mount_directory=mount_directory,
                     version=transphire.__version__)
    gui.show()

    sys.exit(app.exec_())
Пример #7
0
def qt_application():
    """ Shorthand to create a QApplication instance with the command line arguments.

    :return: The new QApplication instance.
    """
    return QApplication(os_util.command_line_arguments())
Пример #8
0
            polylines.append(polyline)

    return polylines

if __name__ == '__main__':

    grid_path = None
    grid_data_path = None
    polyline_root_path = None

    if len(sys.argv) == 4:
        grid_path = sys.argv[1]
        grid_data_path = sys.argv[2]
        polyline_root_path = sys.argv[3]
        
    app = QApplication(["Slice Viewer"])
    window = QMainWindow()
    window.resize(1024, 768)

    textures, bounds, nx, ny, nz, data_range , faults = createDataStructures(grid_path, grid_data_path , polyline_root_path)


    polylines = readPolylines(root_path=polyline_root_path)

    color_scales = createColorScales()
    textures["color_scale"] = color_scales[color_scales.keys()[0]]

    viewer = SliceViewer(textures=textures, volume_bounds=bounds, color_scales=color_scales, data_range=data_range, polylines=polylines , faults = faults)
    viewer.setSliceSize(width=nx, height=ny)

    slice_settings = SliceSettingsWidget(max_slice_count=nz, color_scales=color_scales.keys())
Пример #9
0
 def setUpClass(cls):
     cls.app = None
     if QApplication.instance():
         cls.app = QApplication.instance()
     else:
         cls.app = QApplication([], False)
Пример #10
0
def main():
    app = QApplication(sys.argv)
    form = RoiBuddy()
    form.show()
    app.exec_()
Пример #11
0
def main():

        app = QApplication(sys.argv)
        usr = User()
        sys.exit(app.exec_())
Пример #12
0
def main():
    app = QApplication(sys.argv)
    window = MainWindow(sys.argv)
    window.show()
    sys.exit(app.exec_())
Пример #13
0
from PyQt4.QtGui import QApplication, QMessageBox

import shared, qtsixa_main, qtsixa_manage

#--------------- main ------------------
if __name__ == '__main__':

    #For easy debugging, print version information to terminal
    print "Qt version:", QT_VERSION_STR
    print "PyQt version:", PYQT_VERSION_STR
    print "QtSixA version: 1.5.1"

    #Check for root tool
    shared.ROOT = getoutput("qtsixa " + "--get-root")
    print "Will use '" + shared.ROOT.split()[0] + "' for root actions"

    shared.init_config(None)
    shared.editProfile = ""

    shared.app = QApplication(sys.argv)
    if (shared.Globals.close_to_tray):
        shared.app.setQuitOnLastWindowClosed(False)
    gui = qtsixa_main.MainW()
    #gui = qtsixa_manage.ManageW()
    if (shared.Globals.start_minimized and shared.Globals.systray_enabled):
        gui.hide()
    else:
        gui.show()
    gui.show()
    shared.app.exec_()
Пример #14
0
            if Codigo == '':
                self.__inserir(Codigo, CPF, Nome, Logradouro, Numero, Bairro, Cidade, UF)
                msg = MessageBox()
                msg.information(self, 'Cadastro de clientes', 'CListe salvo com sucesso !!!', MessageBox.Ok)
            else:
                pass
        except Exception, e:
            msg = MessageBox()
            msg.critical(self, 'Cadastro de clientes', 'Ocorreu o seguinte erro ao tentar inserir o cliente: \n ' + str(e), MessageBox.Ok)
    
    def __inserir(self, id, cpf, nome, logradouro, numero, bairro, cidade, uf):
        '''Método cria um objeto cliente do modulo de acesso a dados, e inclui um novo cliente no banco'''
        
        self.clientedb.Salvar(id, cpf, nome, logradouro, numero, bairro, cidade, uf)

    def __Excluir(self, pId):
        try:
            codigo = int(self.txtCodigo.text())
            self.clientedb.Excluir(codigo)
            
        except Exception, e:
            msg = MessageBox()
            msg.critical(self, 'Cadastro de clientes', 'Ocorreu o seguinte erro ao tentar excluir: \n ' + str(e).decode('utf8'), MessageBox.Ok)


if __name__ == '__main__':
    import sys
    root = QApplication(sys.argv)
    app = FrmCadCliente(None)
    app.show()
    root.exec_()
Пример #15
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from Login_new import CWidgetLogin
from PyQt4.QtGui import QApplication, QDialog

DialoginApp = QApplication(sys.argv)
window = QDialog()
ui = CWidgetLogin()
#ui.setup()
window.show()
sys.exit(DialoginApp.exec_())
Пример #16
0
class PrivilegeControllerTest(unittest.TestCase):
    """ Tests of privilege controller. """

    _application = QApplication(sys.argv)
    _testPrincipalItems = [
        PrincipalItem(principal) for principal in SPECIAL_PRINCIPALS
    ]

    def setUp(self):
        """ Creates the test fixture. """

        selectedItem = PrivilegeItemMock("/test/test.pdf", None)
        self._repositoryMock = PrivilegeRepositoryMock([selectedItem])
        self._privilegeDialog = PrivilegeDialog(self._repositoryMock)
        self._privilegeDialog.item = selectedItem
        self._principalController = self._privilegeDialog._principalSearchController
        self._model = self._privilegeDialog._privilegeModel
        self._controller = self._privilegeDialog._privilegeController

    def testAddPrincipals(self):
        """ Tests the addition of a list of principals """

        # Tests adding of three principals whereby one already exists
        self.assertEquals(self._model.rowCount(), 1)
        self.assertEquals(self._controller._applyButton.isEnabled(), False)
        self._addTestPrincipals()
        for count in range(3):
            item = self._model.itemFromIndex(self._model.index(2, count))
            if count == 0:
                self.assertEquals(item.principal, SPECIAL_PRINCIPALS[2])
            elif count == 1 or count == 2:
                self.assertEquals(unicode(item.text()),
                                  READ_ONLY_ACCESS_LEVEL.displayName)
            else:
                self.assertEquals(unicode(item.text()),
                                  NONE_ACCESS_LEVEL.displayName)
        self.assertEquals(self._controller._applyButton.isEnabled(), True)

        # Ensuring that there are no duplicate principal entries
        self._addTestPrincipals()

    def _addTestPrincipals(self):
        """ Adds three test principals. """

        self._principalController.emit(
            SIGNAL(self._principalController.ADD_PRINCIPAL_SIGNAL),
            self._testPrincipalItems)
        self.assertEquals(self._controller._applyButton.isEnabled(), True)
        self.assertEquals(self._model.rowCount(), 3)

    def testRemovePrincipal(self):
        """ Tests the removal of principals. """

        # Testing removal with no selection
        self.assertEquals(self._model.rowCount(), 1)
        self.assertEquals(self._controller._applyButton.isEnabled(), False)
        self.assertEquals(self._controller._removeButton.isEnabled(), False)

        # Testing removal of one principal
        self._removeRow(0)
        self.assertEquals(self._model.rowCount(), 0)
        self.assertEquals(self._controller._applyButton.isEnabled(), True)
        self.assertEquals(len(self._model._acl.principals), 0)

        # Adding three principals
        self._addTestPrincipals()

        # Removing the last two so the start state is reached
        self._removeRow(2)
        self._removeRow(1)
        self.assertEquals(self._model.rowCount(), 1)
        self.assertEquals(self._controller._applyButton.isEnabled(), False)

    def _removeRow(self, row):
        """ Removes a row. """

        self._selectRow(row)
        self._controller._removeButton.click()

    def _selectRow(self, row):
        """ Selects the given row. """

        self._controller._privilegeWidget.selectRow(row)

    def testButtonEnabledStates(self):
        """ Tests the enabled state of the controlled buttons. """

        # Checks the initial button enabling state
        self.assertEquals(self._model.rowCount(), 1)
        self.assertEquals(self._controller._applyButton.isEnabled(), False)
        self.assertEquals(self._controller._removeButton.isEnabled(), False)
        self.assertEquals(self._controller._upButton.isEnabled(), False)
        self.assertEquals(self._controller._downButton.isEnabled(), False)

        # Adds and selects different entries and checks the enabling state again
        self._addTestPrincipals()
        self.assertEquals(self._controller._removeButton.isEnabled(), False)
        self.assertEquals(self._controller._upButton.isEnabled(), False)
        self.assertEquals(self._controller._downButton.isEnabled(), False)
        self._selectRow(0)
        self.assertEquals(self._controller._upButton.isEnabled(), False)
        self.assertEquals(self._controller._downButton.isEnabled(), True)
        self._selectRow(2)
        self.assertEquals(self._controller._upButton.isEnabled(), True)
        self.assertEquals(self._controller._downButton.isEnabled(), False)
        self._selectRow(1)
        self.assertEquals(self._controller._upButton.isEnabled(), True)
        self.assertEquals(self._controller._downButton.isEnabled(), True)

        # Creates the initial state and checks again the enabling state of buttons
        self._removeRow(2)
        self._removeRow(1)
        self.assertEquals(self._controller._applyButton.isEnabled(), False)
        self.assertEquals(self._controller._removeButton.isEnabled(), False)

    def testChangePosition(self):
        """ Tests the changing of principal positions. """

        # Adding three principals and selecting the second entry
        self._addTestPrincipals()
        self._controller._applyButton.click()
        self._waitUntilFinished()
        self.assertFalse(self._model.isDirty)
        principal = SPECIAL_PRINCIPALS[1]
        self._selectRow(1)

        # Move the second entry up and down
        self._controller._upButton.click()
        self.assertEquals(self._model.item(0).principal, principal)
        self.assertTrue(self._model.isDirty)

        self._controller._downButton.click()
        self.assertEquals(self._model.item(1).principal, principal)
        self.assertFalse(self._model.isDirty)

        self._controller._downButton.click()
        self.assertEquals(self._model.item(2).principal, principal)
        self.assertTrue(self._model.isDirty)

    def _waitUntilFinished(self):
        """ Helper function which waits until the worker thread has finished. """

        while self._controller._workerThread.isRunning():
            pass
        self._controller._applyCallback()

    def testApplySuccess(self):
        """ Tests the successful apply behavior. """

        self._addTestPrincipals()
        self._privilegeDialog.item.error = None
        self._controller._applyButton.click()
        self._waitUntilFinished()
        self.assertFalse(self._model.isDirty)

    def testApplyError(self):
        """ Tests apply error handling. """

        self._privilegeDialog.item = PrivilegeItemMock("/test/test.pdf",
                                                       CoreError(""))
        self._addTestPrincipals()
        self._controller._applyButton.click()
        self._waitUntilFinished()
        self.assertTrue(self._model.isDirty)

    def testEditAccessLevel(self):
        """ Tests the privilege editing functionality. """

        itemDelegate = self._controller._privilegeWidget.itemDelegate()

        # Nothing should happen when trying to edit the principal
        index = self._model.index(0, 0)
        editor = itemDelegate.createEditor(None, None, index)
        self.assertEquals(editor, None)

        # Checking an invalid index
        index = self._model.index(10, 200)
        editor = itemDelegate.createEditor(None, None, index)
        self.assertEquals(editor, None)

        # Checking the three access levels
        for column in range(1, 4):
            index = self._model.index(0, column)
            editor = itemDelegate.createEditor(None, None, index)
            editor.setCurrentIndex(0)
            itemDelegate.setModelData(editor, None, index)
            self.assertEquals(
                self._model.item(0, column).text(), editor.currentText())
 def __init__(self, url):
     self.app = QApplication(sys.argv)
     QWebPage.__init__(self)
     self.loadFinished.connect(self.on_page_load)
     self.mainFrame().load(QUrl(url))
     self.app.exec_()
Пример #18
0
def main():
    if platform.system() == "Windows":
        print "Running on Windows"
        # On Windows, redirect stderr to a file
        import imp, ctypes
        if (hasattr(sys, "frozen") or  # new py2exe
                hasattr(sys, "importers") or  # old py2exe
                imp.is_frozen("__main__")):  # tools/freeze
            sys.stderr = open(os.path.expanduser("~/friture.exe.log"), "w")
        # set the App ID for Windows 7 to properly display the icon in the
        # taskbar.
        myappid = 'Friture.Friture.Friture.current'  # arbitrary string
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                myappid)
        except:
            print "Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal."

    app = QApplication(sys.argv)

    # Splash screen
    pixmap = QPixmap(":/images/splash.png")
    splash = QSplashScreen(pixmap)
    splash.show()
    splash.showMessage("Initializing the audio subsystem")
    app.processEvents()

    # Set the separator stylesheet here
    # As of Qt 4.6, separator width is not handled correctly
    # when the stylesheet is applied directly to the QMainWindow instance.
    # QtCreator workarounds it with a "minisplitter" special class
    app.setStyleSheet(STYLESHEET)

    # Logger class
    logger = Logger()

    window = Friture(logger)
    window.show()
    splash.finish(window)

    profile = "no"  # "python" or "kcachegrind" or anything else to disable

    if len(sys.argv) > 1:
        if sys.argv[1] == "--python":
            profile = "python"
        #elif sys.argv[1] == "--kcachegrind":
        #profile = "kcachegrind"
        elif sys.argv[1] == "--no":
            profile = "no"
        else:
            print "command-line arguments (%s) not recognized" % sys.argv[1:]

    if profile == "python":
        import cProfile
        import pstats

        cProfile.runctx('app.exec_()',
                        globals(),
                        locals(),
                        filename="friture.cprof")

        stats = pstats.Stats("friture.cprof")
        stats.strip_dirs().sort_stats('time').print_stats(20)
        stats.strip_dirs().sort_stats('cumulative').print_stats(20)

        sys.exit(0)
    #elif profile == "kcachegrind":
    #import cProfile
    #import lsprofcalltree

    #p = cProfile.Profile()
    #p.run('app.exec_()')

    #k = lsprofcalltree.KCacheGrind(p)
    #data = open('cachegrind.out.00000', 'wb')
    #k.output(data)
    #data.close()

    ## alternative code with pyprof2calltree instead of lsprofcalltree
    ##import pyprof2calltree
    ##pyprof2calltree.convert(p.getstats(), "cachegrind.out.00000") # save

    #sys.exit(0)
    else:
        sys.exit(app.exec_())
Пример #19
0
        km.start_channels(hb=self._heartbeat)
        self.kernel_manager = km
        atexit.register(self.kernel_manager.cleanup_connection_file)

    def connect_kernel(self, connection_file, heartbeat=False):
        self._heartbeat = heartbeat
        if os.path.exists(connection_file):
            self._connection_file = connection_file
        else:
            self._connection_file = find_connection_file(connection_file)

        self._init_kernel_manager()


def main(**kwargs):
    kernelapp = IPythonLocalKernelApp.instance()
    kernelapp.start()

    widget = IPythonConsoleQtWidget()
    widget.connect_kernel(connection_file=kernelapp.connection_file)
    widget.show()

    return widget


if __name__ == "__main__":
    from PyQt4.QtGui import QApplication
    app = QApplication([''])
    main()
    app.exec_()
                dict(
                    # TODO: set units to something more readable than #periods (e.g. days)
                    data=pac,
                    type='column',
                    name=attr_name,
                    zIndex=2,
                ))

        # TODO: give periods meaning (datetime names)
        plotlines.append(dict(value=0, color='black', width=2, zIndex=3))
        if series:
            self.plot.chart(options,
                            yAxis_plotLines=plotlines,
                            xAxis_type='linear')
        else:
            self.plot.clear()


if __name__ == "__main__":
    from PyQt4.QtGui import QApplication

    a = QApplication([])
    ow = OWCorrelogram()

    # data = Timeseries('yahoo_MSFT')
    data = Timeseries('UCI-SML2010-1')
    ow.set_data(data)

    ow.show()
    a.exec()
Пример #21
0
# OSMesaGetCurrentContext does not return the same object for the context.
# setGLContextGetter(mesa.OSMesaGetCurrentContext)


# main ########################################################################

if __name__ == "__main__":
    import sys
    try:
        from PyQt4.QtGui import QApplication
    except ImportError:
        from PyQt5.QtWidgets import QApplication

    from PyMca5.PyMcaGraph.Plot import Plot

    app = QApplication([])
    w = Plot(None, backend=OSMesaGLBackend)

    size = 1024
    data = np.arange(float(size)*size, dtype=np.uint16)
    data.shape = size, size

    colormap = {'name': 'gray', 'normalization': 'linear',
                'autoscale': True, 'vmin': 0.0, 'vmax': 1.0,
                'colors': 256}
    w.addImage(data, legend="image 1",
               xScale=(25, 1.0), yScale=(-1000, 1.0),
               replot=False, colormap=colormap)
    w.insertXMarker(512, 'testX', 'markerX', color='pink',
                    selectable=False, draggable=True)
Пример #22
0
    from sys import argv, exit

    class Test(QWidget):
        def __init__(self, parent=None):
            QWidget.__init__(self, parent)

            self.setWindowTitle("QLed Test")

            _l = QGridLayout()
            self.setLayout(_l)

            self.leds = []
            for row, shape in enumerate(QLed.shapes.keys()):
                for col, colour in enumerate(QLed.colours.keys()):
                    if colour == QLed.Grey: continue
                    led = QLed(self, onColour=colour, shape=shape)
                    _l.addWidget(led, row, col, Qt.AlignCenter)
                    self.leds.append(led)

            self.toggleLeds()

        def toggleLeds(self):
            for led in self.leds:
                led.toggleValue()
            QTimer.singleShot(10, self.toggleLeds)

    a = QApplication(argv)
    t = Test()
    t.show()
    t.raise_()
    exit(a.exec_())
Пример #23
0
    def _updateCurrentStepLabel(self, singlet):
        self.times.append(singlet)
        t = sum(self.times) / len(self.times)
        if len(self.times) > 5:
            self.times.pop(0)
        if t < 120:
            self.currentStepLabel.setText("Estimated time left: %.02f sec" %
                                          (t))
        else:
            self.currentStepLabel.setText("Estimated time left: %.02f min" %
                                          (t / 60))

    def _initUic(self):
        p = os.path.split(__file__)[0] + '/'
        if p == "/": p = "." + p
        uic.loadUi(p + "ui/multiStepProgressDialog.ui", self)
        self.buttonBox.button(QDialogButtonBox.Ok).hide()
        self.failedLabel.hide()


if __name__ == "__main__":
    from PyQt4.QtGui import QApplication
    import vigra, numpy
    app = QApplication(list())

    d = MultiStepProgressDialog()
    d.setNumberOfSteps(5)
    d.show()
    app.exec_()
Пример #24
0
def main():
    app = QApplication(sys.argv)
    ex = Compression()
    sys.exit(app.exec_())
Пример #25
0
def get_app():
    app = QApplication([])
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt())
    yield app
Пример #26
0
 def setUpClass(cls):
     cls.app = QApplication([])
     cls.errors = False
Пример #27
0
def start(filenames=None,
          projects_path=None,
          extra_plugins=None,
          linenos=None):
    app = QApplication(sys.argv)
    QCoreApplication.setOrganizationName('NINJA-IDE')
    QCoreApplication.setOrganizationDomain('NINJA-IDE')
    QCoreApplication.setApplicationName('NINJA-IDE')
    app.setWindowIcon(QIcon(resources.IMAGES['icon']))

    # Check if there is another session of ninja-ide opened
    # and in that case send the filenames and projects to that session
    running = ipc.is_running()
    start_server = not running[0]
    if running[0] and (filenames or projects_path):
        sended = ipc.send_data(running[1], filenames, projects_path, linenos)
        running[1].close()
        if sended:
            sys.exit()
    else:
        running[1].close()

    # Create and display the splash screen
    splash_pix = QPixmap(resources.IMAGES['splash'])
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())
    splash.show()
    app.processEvents()

    # Set the cursor to unblinking
    global cursor_flash_time
    cursor_flash_time = app.cursorFlashTime()
    app.setCursorFlashTime(0)

    #Set the codec for strings (QString)
    QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8'))

    #Translator
    qsettings = QSettings()
    language = QLocale.system().name()
    lang = qsettings.value('preferences/interface/language', language) + '.qm'
    lang_path = file_manager.create_path(resources.LANGS, lang)
    if file_manager.file_exists(lang_path):
        settings.LANGUAGE = lang_path
    elif file_manager.file_exists(
            file_manager.create_path(resources.LANGS_DOWNLOAD, lang)):
        settings.LANGUAGE = file_manager.create_path(resources.LANGS_DOWNLOAD,
                                                     lang)
    translator = QTranslator()
    if settings.LANGUAGE:
        translator.load(settings.LANGUAGE)
        app.installTranslator(translator)

    #Loading Syntax
    splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black)
    json_manager.load_syntax()

    #Read Settings
    splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop,
                       Qt.black)
    settings.load_settings()

    #Set Stylesheet
    style_applied = False
    if settings.NINJA_SKIN not in ('Default', 'Classic Theme'):
        file_name = ("%s.qss" % settings.NINJA_SKIN)
        qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD,
                                            file_name)
        if file_manager.file_exists(qss_file):
            with open(qss_file) as f:
                qss = f.read()
                app.setStyleSheet(qss)
                style_applied = True
    if not style_applied:
        if settings.NINJA_SKIN == 'Default':
            with open(resources.NINJA_THEME) as f:
                qss = f.read()
        else:
            with open(resources.NINJA__THEME_CLASSIC) as f:
                qss = f.read()
        app.setStyleSheet(qss)

    #Loading Schemes
    splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop,
                       Qt.black)
    scheme = qsettings.value('preferences/editor/scheme', "default")
    if scheme != 'default':
        scheme = file_manager.create_path(resources.EDITOR_SKINS,
                                          scheme + '.color')
        if file_manager.file_exists(scheme):
            resources.CUSTOM_SCHEME = json_manager.parse(open(scheme))

    #Loading Shortcuts
    resources.load_shortcuts()
    #Loading GUI
    splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black)
    ide = IDE(start_server)

    #Showing GUI
    ide.show()

    #Loading Session Files
    splash.showMessage("Loading Files and Projects",
                       Qt.AlignRight | Qt.AlignTop, Qt.black)
    #Files in Main Tab
    main_files = qsettings.value('openFiles/mainTab', [])
    if main_files is not None:
        mainFiles = list(main_files)
    else:
        mainFiles = list()
    tempFiles = []
    for file_ in mainFiles:
        fileData = list(file_)
        tempFiles.append((fileData[0], int(fileData[1])))
    mainFiles = tempFiles
    #Files in Secondary Tab
    sec_files = qsettings.value('openFiles/secondaryTab', [])
    if sec_files is not None:
        secondaryFiles = list(sec_files)
    else:
        secondaryFiles = list()
    tempFiles = []
    for file_ in secondaryFiles:
        fileData = list(file_)
        tempFiles.append((fileData[0], int(fileData[1])))
    secondaryFiles = tempFiles
    # Recent Files
    recent = qsettings.value('openFiles/recentFiles', [])
    if recent is not None:
        recent_files = list(recent)
    else:
        recent_files = list()
    recent_files = [file_ for file_ in recent_files]
    #Current File
    current_file = qsettings.value('openFiles/currentFile', '')
    #Projects
    projects_list = qsettings.value('openFiles/projects', [])
    if projects_list is not None:
        projects = list(projects_list)
    else:
        projects = list()
    projects = [project for project in projects]
    #Include files received from console args
    file_with_nro = list(
        map(lambda f: (f[0], f[1] - 1), zip(filenames, linenos)))
    file_without_nro = list(map(lambda f: (f, 0), filenames[len(linenos):]))
    mainFiles += file_with_nro + file_without_nro
    #Include projects received from console args
    if projects_path:
        projects += projects_path
    ide.load_session_files_projects(mainFiles, secondaryFiles, projects,
                                    current_file, recent_files)
    #Load external plugins
    if extra_plugins:
        ide.load_external_plugins(extra_plugins)

    splash.finish(ide)
    ide.notify_plugin_errors()
    sys.exit(app.exec_())
Пример #28
0
def main():
    """
    Check starting conditions and start GUI.

    First, check command line arguments and start loggers. Set log levels. Try
    all imports and exit verbosely if a library is not found. Disable outputs
    to stdout and start the GUI.
    """

    # Set ERROR level for PyQt4 logger
    qtlogger = logging.getLogger('PyQt4')
    qtlogger.setLevel(logging.ERROR)

    parser = argparse.ArgumentParser(description="cfclient - "
                                     "Crazyflie graphical control client")
    parser.add_argument('--debug',
                        '-d',
                        nargs=1,
                        default='info',
                        type=str,
                        help="set debug level "
                        "[minimal, info, debug, debugfile]")
    args = parser.parse_args()
    globals().update(vars(args))

    cflogger = logging.getLogger('')

    # Set correct logging fuctionality according to commandline
    if ("debugfile" in debug):
        logging.basicConfig(level=logging.DEBUG)
        # Add extra format options for file logger (thread and time)
        formatter = logging.Formatter('%(asctime)s:%(threadName)s:%(name)'
                                      's:%(levelname)s:%(message)s')
        filename = "debug-%s.log" % datetime.datetime.now()
        filehandler = logging.FileHandler(filename)
        filehandler.setLevel(logging.DEBUG)
        filehandler.setFormatter(formatter)
        cflogger.addHandler(filehandler)
    elif ("debug" in debug):
        logging.basicConfig(level=logging.DEBUG)
    elif ("minimal" in debug):
        logging.basicConfig(level=logging.WARNING)
    elif ("info" in debug):
        logging.basicConfig(level=logging.INFO)

    logger = logging.getLogger(__name__)

    logger.debug("Using config path {}".format(sys.path[1]))
    logger.debug("sys.path={}".format(sys.path))

    # Try all the imports used in the project here to control what happens....
    try:
        import usb
    except ImportError:
        logger.critical("No pyusb installation found, exiting!")
        sys.exit(1)

    try:
        import pygame
    except ImportError:
        logger.critical("No pygame installation found, exiting!")
        sys.exit(1)

    try:
        import PyQt4
    except ImportError:
        logger.critical("No PyQT4 installation found, exiting!")
        sys.exit(1)

    # Disable printouts from STL
    if os.name == 'posix':
        stdout = os.dup(1)
        os.dup2(os.open('/dev/null', os.O_WRONLY), 1)
        sys.stdout = os.fdopen(stdout, 'w')
        logger.info("Disabling STL printouts")

    # Start up the main user-interface
    from ui.main import MainUI
    from PyQt4.QtGui import QApplication
    app = QApplication(sys.argv)
    main_window = MainUI()
    main_window.show()
    sys.exit(app.exec_())
 def main():
     import sys
     app = QApplication(sys.argv)
     my_gauge = AnalogGaugeWidget()
     my_gauge.show()
     sys.exit(app.exec_())
Пример #30
0
 def setUp(self):
     self.app = QApplication([])
     QTimer.singleShot(20000, self.app.exit)