Exemplo n.º 1
0
logger.setLevel(logging.INFO)

# enable ipython QtGui support if needed
try:
    from IPython import get_ipython
    IPYTHON = get_ipython()
    IPYTHON.magic("gui qt")
except BaseException as e:
    logger.debug('Could not enable IPython gui support: %s.' % e)

# get QApplication instance
from qtpy import QtCore, QtWidgets
APP = QtWidgets.QApplication.instance()
if APP is None:
    logger.debug('Creating new QApplication instance "pyrpl"')
    APP = QtWidgets.QApplication(['pyrpl'])

# get user directories
import os
try:  # first try from environment variable
    user_dir = os.environ["PYRPL_USER_DIR"]
except KeyError:  # otherwise, try ~/pyrpl_user_dir (where ~ is the user's home dir)
    user_dir = os.path.join(os.path.expanduser('~'), 'pyrpl_user_dir')

# make variable directories
user_config_dir = os.path.join(user_dir, 'config')
user_curve_dir = os.path.join(user_dir, 'curve')
user_lockbox_dir = os.path.join(user_dir, 'lockbox')
default_config_dir = os.path.join(os.path.dirname(__file__), 'config')
# create dirs if necessary
for path in [user_dir, user_config_dir, user_curve_dir, user_lockbox_dir]:
Exemplo n.º 2
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--version',
                        '-V',
                        action='store_true',
                        help='show version')
    parser.add_argument('--reset-config',
                        action='store_true',
                        help='reset qt config')
    parser.add_argument(
        '--logger-level',
        default='info',
        choices=['debug', 'info', 'warning', 'fatal', 'error'],
        help='logger level',
    )
    parser.add_argument('filename', nargs='?', help='image or label filename')
    parser.add_argument(
        '--output',
        '-O',
        '-o',
        help='output file or directory (if it ends with .json it is '
        'recognized as file, else as directory)')
    default_config_file = os.path.join(os.path.expanduser('~'), '.labelmerc')
    parser.add_argument(
        '--config',
        dest='config_file',
        help='config file (default: %s)' % default_config_file,
        default=default_config_file,
    )
    # config for the gui
    parser.add_argument(
        '--nodata',
        dest='store_data',
        action='store_false',
        help='stop storing image data to JSON file',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--autosave',
        dest='auto_save',
        action='store_true',
        help='auto save',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--nosortlabels',
        dest='sort_labels',
        action='store_false',
        help='stop sorting labels',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--flags',
        help='comma separated list of flags OR file containing flags',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--labelflags',
        dest='label_flags',
        help='yaml string of label specific flags OR file containing json '
        'string of label specific flags (ex. {person-\d+: [male, tall], '
        'dog-\d+: [black, brown, white], .*: [occluded]})',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--labels',
        help='comma separated list of labels OR file containing labels',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--validatelabel',
        dest='validate_label',
        choices=['exact', 'instance'],
        help='label validation types',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--keep-prev',
        action='store_true',
        help='keep annotation of previous frame',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--epsilon',
        type=float,
        help='epsilon to find nearest vertex on canvas',
        default=argparse.SUPPRESS,
    )
    args = parser.parse_args()

    if args.version:
        print('{0} {1}'.format(__appname__, __version__))
        sys.exit(0)

    logger.setLevel(getattr(logging, args.logger_level.upper()))

    if hasattr(args, 'flags'):
        if os.path.isfile(args.flags):
            with codecs.open(args.flags, 'r', encoding='utf-8') as f:
                args.flags = [l.strip() for l in f if l.strip()]
        else:
            args.flags = [l for l in args.flags.split(',') if l]

    if hasattr(args, 'labels'):
        if os.path.isfile(args.labels):
            with codecs.open(args.labels, 'r', encoding='utf-8') as f:
                args.labels = [l.strip() for l in f if l.strip()]
        else:
            args.labels = [l for l in args.labels.split(',') if l]

    if hasattr(args, 'label_flags'):
        if os.path.isfile(args.label_flags):
            with codecs.open(args.label_flags, 'r', encoding='utf-8') as f:
                args.label_flags = yaml.safe_load(f)
        else:
            args.label_flags = yaml.safe_load(args.label_flags)

    config_from_args = args.__dict__
    config_from_args.pop('version')
    reset_config = config_from_args.pop('reset_config')
    filename = config_from_args.pop('filename')
    output = config_from_args.pop('output')
    config_file = config_from_args.pop('config_file')
    config = get_config(config_from_args, config_file)

    if not config['labels'] and config['validate_label']:
        logger.error('--labels must be specified with --validatelabel or '
                     'validate_label: true in the config file '
                     '(ex. ~/.labelmerc).')
        sys.exit(1)

    output_file = None
    output_dir = None
    if output is not None:
        if output.endswith('.json'):
            output_file = output
        else:
            output_dir = output

    translator = QtCore.QTranslator()
    translator.load(QtCore.QLocale.system().name(),
                    osp.dirname(osp.abspath(__file__)) + '/translate')
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon('icon'))
    app.installTranslator(translator)
    win = MainWindow(
        config=config,
        filename=filename,
        output_file=output_file,
        output_dir=output_dir,
    )

    if reset_config:
        logger.info('Resetting Qt config: %s' % win.settings.fileName())
        win.settings.clear()
        sys.exit(0)

    win.show()
    win.raise_()
    sys.exit(app.exec_())
Exemplo n.º 3
0
        self.horizontalLayout_2.addWidget(self.frame)

        self.tree2 = BasicTreeView(self)
        self.tree2.setObjectName('tree2')

        self.horizontalLayout_2.addWidget(self.tree2)
        self.gridLayout_2.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)

        self.setWindowTitle('Double Tree')
        self.add_all_btn.setText('--->>')
        self.add_btn.setText('---->')
        self.remove_btn.setText('<----')
        self.remove_all_btn.setText('<<---')

        DoubleTreeHandler.__init__(self, self.tree1, self.tree2, self.add_btn,
                                   self.remove_btn, self.add_all_btn,
                                   self.remove_all_btn)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication([])

    double_tree = DoubleTree()
    double_tree.handler.set_data([5, 4, 3, 2, 1], [6, 7, 8, 9])

    double_tree.show()

    sys.exit(app.exec_())
Exemplo n.º 4
0
def get_qapp(icon_path=None):
    qapp = QtWidgets.QApplication.instance()
    if qapp is None:
        qapp = QtWidgets.QApplication([''])
    return qapp
Exemplo n.º 5
0
def pdsspect(inlist=None):
    """Run pdsspect from python shell or command line with arguments

    Parameters
    ----------
    inlist : :obj:`list`
        A list of file names/paths to display in the pdsspect

    Examples
    --------

    From the command line:

    To view all images from current directory

    pdsspect

    To view all images in a different directory

    pdsspect path/to/different/directory/

    This is the same as:

    pdsspect path/to/different/directory/*

    To view a specific image or types of images

    pdsspect 1p*img

    To view images from multiple directories:

    pdsspect * path/to/other/directory/

    From the (i)python command line:

    >>> from pdsspect.pdsspect import pdsspect
    >>> pdsspect()
    Displays all of the images from current directory
    >>> pdsspect('path/to/different/directory')
    Displays all of the images in the different directory
    >>> pdsspect ('1p*img')
    Displays all of the images that follow the glob pattern
    >>> pdsspect('a1.img, b*.img, example/path/x*img')
    You can display multiple images, globs, and paths in one window by
    separating each item by a command
    >>> pdsspect(['a1.img, b3.img, c1.img, d*img'])
    You can also pass in a list of files/globs
    pdsspect returns a dictionary of the ROIs:
    >>> rois = pdsspect(['a1.img, b3.img, c1.img, d*img'])
    >>> rois['red'][:2, :2]
    array(
        [
            [False, False],
            [False, False]
        ],
        dtype=bool
    )
    """

    app = QtWidgets.QApplication.instance()
    if not app:
        app = QtWidgets.QApplication(sys.argv)
    window = open_pdsspect(app, inlist)
    try:
        sys.exit(app.exec_())
    except SystemExit:
        pass
    return window.image_set.get_rois_masks_to_export()
Exemplo n.º 6
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    ex = ConfigEditor()
    ex.show()
    app.exec_()
Exemplo n.º 7
0
def main():
    """"""
    app = QtWidgets.QApplication(sys.argv)
    window = ClusterStatusWindow()
    window.show()
    app.exec_()
Exemplo n.º 8
0
def opensesamerun():

    # First, load a minimum number of modules and show an empty app window. This
    # gives the user the feeling of a snappy response.
    import os, sys
    # Add the folder that contains the OpenSesame modules to the path. This is
    # generally only necessary if OpenSesame is directly run from source,
    # instead from an installation.
    if os.path.exists(os.path.join(os.getcwd(), 'libopensesame')):
        sys.path.insert(0, os.getcwd())
    import libopensesame.misc
    libopensesame.misc.parse_environment_file()
    import libopensesame.experiment
    # Parse the command line options
    options = libopensesame.misc.opensesamerun_options()
    app = None
    # If the command line options haven't provided sufficient information to
    # run right away, present a GUI
    while not libopensesame.misc.opensesamerun_ready(options):
        # If PyQt4 is not available (e.g., this might be the case on Mac OS)
        # give an error instead of showing a GUI. This makes sure that even
        # without PyQt4, people can still run experiments.
        try:
            # Change Qt API
            import sip
            sip.setapi('QString', 2)
            sip.setapi('QVariant', 2)
            from qtpy import QtGui, QtCore, QtWidgets
        except:
            libopensesame.misc.messagebox(
                u"OpenSesame Run",
                u"Incorrect or missing options.\n\nRun 'opensesame --help' from a terminal (or command prompt) to see a list of available options, or install Python Qt4 to enable the graphical user interface."
            )
            sys.exit()
        # Create the GUI and show it
        import libqtopensesame.qtopensesamerun
        if app is None:
            app = QtWidgets.QApplication(sys.argv)
            myapp = libqtopensesame.qtopensesamerun.qtopensesamerun(options)
        myapp.show()
        app.exec_()
        # Update the options from the GUI
        options = myapp.options
        # Exit if the GUI was canceled
        if not myapp.run:
            sys.exit()
    # Decode the experiment path and logfile
    experiment = os.path.abspath(options.experiment)
    if isinstance(experiment, str):
        experiment = safe_decode(experiment,
                                 enc=libopensesame.misc.filesystem_encoding(),
                                 errors=u'ignore')
    # experiment_path = os.path.dirname(experiment)
    logfile = options.logfile
    if isinstance(logfile, str):
        logfile = safe_decode(logfile,
                              enc=libopensesame.misc.filesystem_encoding(),
                              errors=u'ignore')

    if options.debug:
        # In debug mode, don't try to catch any exceptions
        exp = libopensesame.experiment.experiment(
            u"Experiment", experiment, experiment_path=experiment_path)
        exp.set_subject(options.subject)
        exp.var.fullscreen = options.fullscreen
        exp.logfile = logfile
        exp.run()
        exp.end()
    else:
        # Try to parse the experiment from a file
        experiment_path = safe_decode(
            os.path.abspath(options.experiment),
            enc=libopensesame.misc.filesystem_encoding())
        try:
            exp = libopensesame.experiment.experiment(
                u"Experiment", experiment, experiment_path=experiment_path)
        except Exception as e:
            libopensesame.misc.messagebox(u"OpenSesame Run",
                                          libopensesame.misc.strip_tags(e))
            sys.exit()
        # Set some options
        exp.set_subject(options.subject)
        exp.var.fullscreen = options.fullscreen
        exp.logfile = logfile
        # Initialize random number generator
        import random
        random.seed()
        # Try to run the experiment
        try:
            exp.run()
        except Exception as e:
            # Try to nicely end the experiment, even though an exception
            # occurred.
            try:
                exp.end()
            except Exception as f:
                libopensesame.misc.messagebox(u"OpenSesame Run",
                                              libopensesame.misc.strip_tags(f))
            libopensesame.misc.messagebox(u"OpenSesame Run",
                                          libopensesame.misc.strip_tags(e))
    libopensesame.experiment.clean_up(exp.debug)
Exemplo n.º 9
0
def main():
    app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
    win = MainWindow()
    win.show()
    app.exec_()
    return win
Exemplo n.º 10
0
def test_preferencesdialog():
    app = QtWidgets.QApplication(sys.argv)
    d = PreferencesDialog()
    d.show()
    app.exec_()
Exemplo n.º 11
0
#warnings.simplefilter('default',DeprecationWarning)
#End compatibility block for Python 3

import sys
import os
from Topolib.MSC.connect.method import myObj
from qtpy import QtWidgets as qtw

#myPath = os.path.dirname(os.path.realpath(__file__))
#sys.path.insert(0,myPath)


## Main Function for Test

if __name__ == '__main__':
  app = qtw.QApplication(sys.argv)

  X = None
  Y = None
  # if len(sys.argv) > 1:
  #   print('\tYou probably want me to load a file...')
  #   print('\tThe Maker has not included this in my programming.')


  main = myObj(X,Y,debug=True)
  #main.loadData()
  main.loadData('Pu_TOT.csv')

  #main.show()
  #main.addNewView('TopologyMapView')
  #main.addNewView('ScatterView2D')
Exemplo n.º 12
0
def test_aboutdialog():
    app = QtWidgets.QApplication(sys.argv)
    d = AboutDialog()
    d.show()
    app.exec_()
def start_light_sheet_controller():
    app = QtWidgets.QApplication(sys.argv)
    check_if_NI_devs_are_present()
    ipython_qt_event_loop_setup()
    maingui = MainGui()
    return maingui, app
Exemplo n.º 14
0
 def setUpClass(cls):
     cls.app = QtWidgets.QApplication.instance()
     if cls.app is None:
         cls.app = QtWidgets.QApplication([])
Exemplo n.º 15
0
        only_run = args[0]

    else:

        only_run = None

    try:

        threading.Thread(target=reactor.run,
                         kwargs={
                             'installSignalHandlers': 0
                         }).start()

        QP.MonkeyPatchMissingMethods()
        app = QW.QApplication(sys.argv)

        app.call_after_catcher = QP.CallAfterEventCatcher(app)

        try:

            # we run the tests on the Qt thread atm
            # keep a window alive the whole time so the app doesn't finish its mainloop

            win = QW.QWidget(None)
            win.setWindowTitle('Running tests...')

            controller = TestController.Controller(win, only_run)

            def do_it():
Exemplo n.º 16
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--version",
                        "-V",
                        action="store_true",
                        help="show version")
    parser.add_argument("--reset-config",
                        action="store_true",
                        help="reset qt config")
    parser.add_argument(
        "--logger-level",
        default="info",
        choices=["debug", "info", "warning", "fatal", "error"],
        help="logger level",
    )
    parser.add_argument("filename", nargs="?", help="image or label filename")
    parser.add_argument(
        "--output",
        "-O",
        "-o",
        help="output file or directory (if it ends with .json it is "
        "recognized as file, else as directory)",
    )
    default_config_file = os.path.join(os.path.expanduser("~"), ".labelmerc")
    parser.add_argument(
        "--config",
        dest="config",
        help="config file or yaml-format string (default: {})".format(
            default_config_file),
        default=default_config_file,
    )
    # config for the gui
    parser.add_argument(
        "--nodata",
        dest="store_data",
        action="store_false",
        help="stop storing image data to JSON file",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--autosave",
        dest="auto_save",
        action="store_true",
        help="auto save",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--nosortlabels",
        dest="sort_labels",
        action="store_false",
        help="stop sorting labels",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--flags",
        help="comma separated list of flags OR file containing flags",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--labelflags",
        dest="label_flags",
        help=r"yaml string of label specific flags OR file containing json "
        r"string of label specific flags (ex. {person-\d+: [male, tall], "
        r"dog-\d+: [black, brown, white], .*: [occluded]})",  # NOQA
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--labels",
        help="comma separated list of labels OR file containing labels",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--validatelabel",
        dest="validate_label",
        choices=["exact"],
        help="label validation types",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--keep-prev",
        action="store_true",
        help="keep annotation of previous frame",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--epsilon",
        type=float,
        help="epsilon to find nearest vertex on canvas",
        default=argparse.SUPPRESS,
    )
    args = parser.parse_args()

    if os.name == 'posix':
        st = os.stat('./script.sh')
        os.chmod('./script.sh', st.st_mode | stat.S_IEXEC)

    if args.version:
        print("{0} {1}".format(__appname__, __version__))
        sys.exit(0)

    logger.setLevel(getattr(logging, args.logger_level.upper()))

    if hasattr(args, "flags"):
        if os.path.isfile(args.flags):
            with codecs.open(args.flags, "r", encoding="utf-8") as f:
                args.flags = [line.strip() for line in f if line.strip()]
        else:
            args.flags = [line for line in args.flags.split(",") if line]

    if hasattr(args, "labels"):
        if os.path.isfile(args.labels):
            with codecs.open(args.labels, "r", encoding="utf-8") as f:
                args.labels = [line.strip() for line in f if line.strip()]
        else:
            args.labels = [line for line in args.labels.split(",") if line]

    if hasattr(args, "label_flags"):
        if os.path.isfile(args.label_flags):
            with codecs.open(args.label_flags, "r", encoding="utf-8") as f:
                args.label_flags = yaml.safe_load(f)
        else:
            args.label_flags = yaml.safe_load(args.label_flags)

    config_from_args = args.__dict__
    config_from_args.pop("version")
    reset_config = config_from_args.pop("reset_config")
    filename = config_from_args.pop("filename")
    output = config_from_args.pop("output")
    config_file_or_yaml = config_from_args.pop("config")
    config = get_config(config_file_or_yaml, config_from_args)

    if not config["labels"] and config["validate_label"]:
        logger.error("--labels must be specified with --validatelabel or "
                     "validate_label: true in the config file "
                     "(ex. ~/.labelmerc).")
        sys.exit(1)

    output_file = None
    output_dir = None
    if output is not None:
        if output.endswith(".json"):
            output_file = output
        else:
            output_dir = output

    translator = QtCore.QTranslator()
    translator.load(
        QtCore.QLocale.system().name(),
        osp.dirname(osp.abspath(__file__)) + "/translate",
    )
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon("icon"))
    app.installTranslator(translator)
    win = MainWindow(
        config=config,
        filename=filename,
        output_file=output_file,
        output_dir=output_dir,
    )

    if reset_config:
        logger.info("Resetting Qt config: %s" % win.settings.fileName())
        win.settings.clear()
        sys.exit(0)

    win.show()
    win.raise_()
    app.exec_()
    win.terminate_subprocess()
    sys.exit(1)
Exemplo n.º 17
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--version',
                        '-V',
                        action='store_true',
                        help='show version')
    parser.add_argument('filename', nargs='?', help='image or label filename')
    parser.add_argument('--output', '-O', '-o', help='output label name')
    parser.add_argument('--config', dest='config_file', help='config file')
    # config
    parser.add_argument('--nodata',
                        dest='store_data',
                        action='store_false',
                        help='stop storing image data to JSON file')
    parser.add_argument('--autosave',
                        dest='auto_save',
                        action='store_true',
                        help='auto save')
    parser.add_argument('--labels',
                        help='comma separated list of labels OR file '
                        'containing one label per line')
    parser.add_argument('--nosortlabels',
                        dest='sort_labels',
                        action='store_false',
                        help='stop sorting labels')
    parser.add_argument('--validatelabel',
                        dest='validate_label',
                        choices=['exact', 'instance'],
                        help='label validation types')
    args = parser.parse_args()

    if args.version:
        print('{0} {1}'.format(__appname__, __version__))
        sys.exit(0)

    if args.labels is None:
        if args.validate_label is not None:
            logger.error('--labels must be specified with --validatelabel or '
                         'validate_label: true in the config file '
                         '(ex. ~/.labelmerc).')
            sys.exit(1)
    else:
        if os.path.isfile(args.labels):
            with codecs.open(args.labels, 'r', encoding='utf-8') as f:
                args.labels = [l.strip() for l in f if l.strip()]
        else:
            args.labels = [l for l in args.labels.split(',') if l]

    config_from_args = args.__dict__
    config_from_args.pop('version')
    filename = config_from_args.pop('filename')
    output = config_from_args.pop('output')
    config_file = config_from_args.pop('config_file')
    # drop the default config
    if not config_from_args['auto_save']:
        config_from_args.pop('auto_save')
    if config_from_args['store_data']:
        config_from_args.pop('store_data')
    if not config_from_args['labels']:
        config_from_args.pop('labels')
    if not config_from_args['sort_labels']:
        config_from_args.pop('sort_labels')
    if not config_from_args['validate_label']:
        config_from_args.pop('validate_label')
    config = get_config(config_from_args, config_file)

    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon('icon'))
    win = MainWindow(config=config, filename=filename, output=output)
    win.show()
    win.raise_()
    sys.exit(app.exec_())
Exemplo n.º 18
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    ui=gui()
    ui.show()
    sys.exit(app.exec_())
Exemplo n.º 19
0
def runDemo():
    # Add parser settings like normal
    parser = argparse.ArgumentParser(
        description="Settings are grouped, but ungrouped items appear here.")
    parser.add_argument("--orphanedSetting",
                        help="This setting does not belong to a group :(")

    textSettings = parser.add_argument_group("Strings",
                                             description="Text input")
    textSettings.add_argument(
        "--freetext",
        type=str,
        default="Enter freetext here",
        help="Type anything you want here",
    )
    textSettings.add_argument(
        "--pickText",
        default="I choo-choo-choose you",
        choices=["Bee mine", "I choo-choo-choose you"],
        help="Choose one of these",
    )

    numericSettings = parser.add_argument_group("Numbers",
                                                description="Numeric input")
    numericSettings.add_argument("--int",
                                 type=int,
                                 default=100,
                                 help="Decimals are not allowed")
    numericSettings.add_argument("--float",
                                 type=float,
                                 help="Decimals are allowed")
    numericSettings.add_argument("--pickInt",
                                 type=int,
                                 choices=[1, 2, 3],
                                 help="Choose one of these")
    numericSettings.add_argument(
        "--pickFloat",
        type=float,
        choices=[1.1, 22.22, 333.333],
        default=333.333,
        help="You can only pick one",
    )

    booleanSettings = parser.add_argument_group(
        "Booleans", description="Booleans and consts")
    booleanSettings.add_argument("--storeTrue", action="store_true")
    booleanSettings.add_argument("--storeFalse", action="store_false")
    booleanSettings.add_argument("--storeConst",
                                 action="store_const",
                                 const=999)

    exoticSettings = parser.add_argument_group("Exotic types",
                                               description="Fancy data types")
    exoticSettings.add_argument("--rgb", type=argparseqt.typeHelpers.rgb)
    exoticSettings.add_argument("--rgba", type=argparseqt.typeHelpers.rgba)
    exoticSettings.add_argument("--path",
                                type=pathlib.Path,
                                default=pathlib.Path.home() / "file.txt")

    try:
        import serial

        exoticSettings.add_argument("--serialPort",
                                    type=argparseqt.typeHelpers.Serial)
    except ImportError:
        pass

    listTypes = parser.add_argument_group("List types",
                                          description="Lists of types")
    listTypes.add_argument("--textList",
                           type=typing.List,
                           default=["Hello", "world!"])
    listTypes.add_argument("--intList", type=typing.List[int])
    listTypes.add_argument("--floatList", type=typing.List[float])
    listTypes.add_argument("--boolList", type=typing.List[bool])
    listTypes.add_argument("--colorList",
                           type=typing.List[argparseqt.typeHelpers.rgba])
    listTypes.add_argument("--pathList", type=typing.List[pathlib.Path])
    listTypes.add_argument(
        "--ListList",
        type=typing.List[typing.List],
        default=[["1a", "1b", "1c"], ["2a", "2b", "2c"]],
    )

    # Now make it a GUI
    app = QtWidgets.QApplication()

    # Create a dialog box for our settings
    dialog = argparseqt.gui.ArgDialog(parser)

    # Parse command line arguments and organize into groups
    cliSettings = argparseqt.groupingTools.parseIntoGroups(parser)

    # Set dialog values based on command line arguments
    dialog.setValues(cliSettings)

    # Show the dialog
    dialog.exec_()

    if dialog.result() == QtWidgets.QDialog.Accepted:
        values = dialog.getValues()
        print("Values:", values)
    else:
        print("User cancelled")
Exemplo n.º 20
0
        qDebug('onWidgetMoved')
        # Update GUI
        U = rot[1]
        sgn = np.sign(np.dot(U, normal))
        udotn = float("{:.5f}".format(np.abs(np.dot(U, normal))))
        self.leUdotN.setText(str(udotn))
        trans = float("{:.5f}".format(np.sqrt(np.sum(p**2))))
        self.leTransDist.setText(str(trans))
        arg = rot[0]
        arg = np.fmod(arg + 180.0, 360.0) - 180.0
        arg = float("{:.5f}".format(arg * sgn))
        self.leAngle.setText(str(arg))

    def initialize(self):
        self.vtk_widget.start()


if __name__ == '__main__':
    app = QtWidgets.QApplication(["Liver Registration"])
    main_window = ViewersApp()
    main_window.show()
    main_window.initialize()
    app.exec_()

# Local variables: #
# tab-width: 2 #
# python-indent: 2 #
# python-indent-offset: 2 #
# indent-tabs-mode: nil #
# End: #
Exemplo n.º 21
0
 def setup_class(self):
     self.app = QtWidgets.QApplication(sys.argv)
Exemplo n.º 22
0
def run_demo(close_after=None, auto_test=False):
    '''
    Args:
    close_after: either None or integer. Number of seconds
    after which the demo will close
    auto_test: boolean. If true then randomly select a style at intervals.

    This function provides a demonstration in changing the application style sheet.
    1) The first option is to set the style sheet once with
       app.setStyleSheet(StylePicker("default").get_sheet())
    2) The second option is to include a style picker widget (QComboBox) that'll
       change the application style sheet when a new style is selected
       grid.addWidget(StylePickerWidget(), 2, 0)
    '''

    app = QtWidgets.QApplication.instance()
    if not app:
        app = QtWidgets.QApplication([])

    win = QtWidgets.QMainWindow()
    win.setWindowTitle("Style Sheets")

    frame = QtWidgets.QFrame()
    win.setCentralWidget(frame)

    grid = QtWidgets.QGridLayout(frame)
    grid.setHorizontalSpacing(5)
    grid.setVerticalSpacing(5)
    grid.addWidget(QtWidgets.QLabel("Username"), 0, 0)
    grid.addWidget(QtWidgets.QLabel("Password"), 1, 0)
    user_input = QtWidgets.QLineEdit()
    pass_input = QtWidgets.QLineEdit()
    grid.addWidget(user_input, 0, 1)
    grid.addWidget(pass_input, 1, 1)

    picker_widget = StylePickerWidget()
    grid.addWidget(picker_widget, 2, 0)
    grid.addWidget(QtWidgets.QPushButton("Submit"), 2, 1)
    win.show()

    def choose_random_style():
        ''' select a random style from the picker_widget '''
        style_list = StylePicker().available_styles
        chosen_style = random.choice(style_list)
        picker_widget.setCurrentIndex(picker_widget.findText(chosen_style))

    def close_demo():
        ''' close the demo once 'close_after' seconds have elapsed '''
        win.close()

    if auto_test:
        timer = QtCore.QTimer()
        timer.timeout.connect(choose_random_style)
        timer.start(1000)

    if isinstance(close_after, int):
        close_timer = QtCore.QTimer()
        close_timer.singleShot(close_after * 1000, close_demo) # seconds * 1000 = milliseconds

    app.setStyleSheet(StylePicker("default").get_sheet())
    app.exec_()
Exemplo n.º 23
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--version', '-V', action='store_true', help='show version'
    )
    parser.add_argument(
        '--reset-config', action='store_true', help='reset qt config'
    )
    parser.add_argument(
        '--logger-level',
        default='info',
        choices=['debug', 'info', 'warning', 'fatal', 'error'],
        help='logger level',
    )
    parser.add_argument('filename', nargs='?', help='image or label filename')
    parser.add_argument(
        '--output',
        '-O',
        '-o',
        help='output file or directory (if it ends with .json it is '
             'recognized as file, else as directory)'
    )
    default_config_file = os.path.join(os.path.expanduser('~'), '.labelmerc')
    parser.add_argument(
        '--config',
        dest='config_file',
        help='config file (default: %s)' % default_config_file,
        default=default_config_file,
    )
    # config for the gui
    parser.add_argument(
        '--nodata',
        dest='store_data',
        action='store_false',
        help='stop storing image data to JSON file',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--autosave',
        dest='auto_save',
        action='store_true',
        help='auto save',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--nosortlabels',
        dest='sort_labels',
        action='store_false',
        help='stop sorting labels',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--flags',
        help='comma separated list of flags OR file containing flags',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--labelflags',
        dest='label_flags',
        help='yaml string of label specific flags OR file containing json '
             'string of label specific flags (ex. {person-\d+: [male, tall], '
             'dog-\d+: [black, brown, white], .*: [occluded]})',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--labels',
        help='comma separated list of labels OR file containing labels',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--validatelabel',
        dest='validate_label',
        choices=['exact', 'instance'],
        help='label validation types',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--keep-prev',
        action='store_true',
        help='keep annotation of previous frame',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--epsilon',
        type=float,
        help='epsilon to find nearest vertex on canvas',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--debug-mode',
        dest='debug_mode',
        action='store_true',
        help='start in debug mode',
        default=argparse.SUPPRESS,
    )
    args = parser.parse_args()

    if args.version:
        print('{0} {1}'.format(__appname__, __version__))
        sys.exit(0)

    if hasattr(args, 'debug_mode'):
        logger.addStreamHandler(logging.DEBUG)
    else:
        level = args.logger_level.upper()
        logger.addStreamHandler(getattr(logging, level))

    if hasattr(args, 'flags'):
        if os.path.isfile(args.flags):
            with codecs.open(args.flags, 'r', encoding='utf-8') as f:
                args.flags = [l.strip() for l in f if l.strip()]
        else:
            args.flags = [l for l in args.flags.split(',') if l]

    if hasattr(args, 'labels'):
        if os.path.isfile(args.labels):
            with codecs.open(args.labels, 'r', encoding='utf-8') as f:
                args.labels = [l.strip() for l in f if l.strip()]
        else:
            args.labels = [l for l in args.labels.split(',') if l]

    if hasattr(args, 'label_flags'):
        if os.path.isfile(args.label_flags):
            with codecs.open(args.label_flags, 'r', encoding='utf-8') as f:
                args.label_flags = yaml.load(f)
        else:
            args.label_flags = yaml.load(args.label_flags)

    config_from_args = args.__dict__
    config_from_args.pop('version')
    reset_config = config_from_args.pop('reset_config')
    filename = config_from_args.pop('filename')
    output = config_from_args.pop('output')
    config_file = config_from_args.pop('config_file')
    config = get_config(config_from_args, config_file)

    # localization
    current_path = os.path.dirname(os.path.abspath(__file__))
    locale_dir = os.path.join(current_path, 'locale')
    if os.path.isfile(os.path.join(locale_dir, config['language'], 'LC_MESSAGES', 'labelme.po')):
        lang = gettext.translation('labelme', localedir=locale_dir, languages=[config['language']])
        lang.install()
    else:
        gettext.install('labelme')
    locale.setlocale(locale.LC_ALL, config['language'])

    if not config['labels'] and config['validate_label']:
        logger.error('--labels must be specified with --validatelabel or '
                     'validate_label: true in the config file '
                     '(ex. ~/.labelmerc).')
        sys.exit(1)

    output_file = None
    output_dir = None
    if output is not None:
        if output.endswith('.json'):
            output_file = output
        else:
            output_dir = output

    # MXNet environment variables
    if 'MXNET_GPU_MEM_POOL_TYPE' in os.environ:
        logger.debug('Environment variable MXNET_GPU_MEM_POOL_TYPE = {}'.format(os.environ['MXNET_GPU_MEM_POOL_TYPE']))
    if 'MXNET_CUDNN_AUTOTUNE_DEFAULT' in os.environ:
        logger.debug('Environment variable MXNET_CUDNN_AUTOTUNE_DEFAULT = {}'.format(os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT']))
    if 'MXNET_HOME' in os.environ:
        logger.debug('Environment variable MXNET_HOME = {}'.format(os.environ['MXNET_HOME']))

    # # Qt environment variable
    # if 'QT_AUTO_SCREEN_SCALE_FACTOR' in os.environ:
    #     logger.debug('Environment variable QT_AUTO_SCREEN_SCALE_FACTOR = {}'.format(os.environ['QT_AUTO_SCREEN_SCALE_FACTOR']))

    # Enable high dpi for 4k monitors
    QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    if hasattr(QtWidgets.QStyleFactory, 'AA_UseHighDpiPixmaps'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
    
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon('digivod'))
    win = MainWindow(
        config=config,
        filename=filename,
        output_file=output_file,
        output_dir=output_dir,
    )

    if reset_config:
        logger.info('Resetting Qt config: %s' % win.settings.fileName())
        win.settings.clear()
        sys.exit(0)

    win.showMaximized()
    win.raise_()
    sys.excepthook = excepthook
    win.check_startup()
    sys.exit(app.exec_())
Exemplo n.º 24
0
def main(tmc_file, *, dbd=None):
    app = QtWidgets.QApplication([])
    interface = create_types_gui(tmc_file)
    interface.show()
    sys.exit(app.exec_())
Exemplo n.º 25
0
 def init_qt_app(self):
     # separate from qt_elements, because it must run first
     self.app = QtWidgets.QApplication(['jupyter-qtconsole'])
     self.app.setApplicationName('jupyter-qtconsole')
Exemplo n.º 26
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    QtCore.QTimer.singleShot(5000, app.exit)
    _ = AwesomeExample()
    sys.exit(app.exec_())
Exemplo n.º 27
0
'''
import sys
import qtpy as qt
from qtpy.QtCore import Qt, QAbstractItemModel, QModelIndex
import qtpy.QtGui as qg
import qtpy.QtWidgets as qw

from .toolkit import ToolkitBase, ListBinding
from .list_model import ObsList

__all__ = [
    'ToolkitQt',
]

_qtapp = qw.QApplication(sys.argv)
_qt_running=False

def _make_focusout(func):
    def _pte_focusOutEvent(event):
        if event.reason() != Qt.PopupFocusReason:
            func()
    return _pte_focusOutEvent

class ToolkitQt(ToolkitBase):
    default_shortcuts = {
        'new': qg.QKeySequence.New,
        'open': qg.QKeySequence.Open,
        'save': qg.QKeySequence.Save,
        'undo': qg.QKeySequence.Undo,
        'redo': qg.QKeySequence.Redo,
Exemplo n.º 28
0
def boot():

    args = sys.argv[1:]

    if len(args) > 0:

        only_run = args[0]

    else:

        only_run = None

    try:

        threading.Thread(target=reactor.run,
                         kwargs={
                             'installSignalHandlers': 0
                         }).start()

        QP.MonkeyPatchMissingMethods()
        app = QW.QApplication(sys.argv)

        app.call_after_catcher = QP.CallAfterEventCatcher(app)

        try:

            # we run the tests on the Qt thread atm
            # keep a window alive the whole time so the app doesn't finish its mainloop

            win = QW.QWidget(None)
            win.setWindowTitle('Running tests...')

            controller = TestController.Controller(win, only_run)

            def do_it():

                controller.Run(win)

            QP.CallAfter(do_it)

            app.exec_()

        except:

            HydrusData.DebugPrint(traceback.format_exc())

        finally:

            HG.started_shutdown = True

            HG.view_shutdown = True

            controller.pubimmediate('wake_daemons')

            HG.model_shutdown = True

            controller.pubimmediate('wake_daemons')

            controller.TidyUp()

    except:

        HydrusData.DebugPrint(traceback.format_exc())

    finally:

        reactor.callFromThread(reactor.stop)

        print('This was version ' + str(HC.SOFTWARE_VERSION))

        if sys.stdin.isatty():

            input('Press any key to exit.')

        if controller.was_successful:

            sys.exit(0)

        else:

            sys.exit(1)
Exemplo n.º 29
0
        # avoid circular references with CodeEdit
        from pyqode.core._forms import dlg_encodings_ui
        self.ui = dlg_encodings_ui.Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.comboBoxEncodings.current_encoding = encoding
        self.ui.lblDescription.setText(
            self.ui.lblDescription.text() %
            (_('There was a problem opening the file %r with encoding: %s') %
             (path, encoding)))

    @classmethod
    def choose_encoding(cls, parent, path, encoding):
        """
        Show the encodings dialog and returns the user choice.

        :param parent: parent widget.
        :param path: file path
        :param encoding: current file encoding
        :return: selected encoding
        """
        dlg = cls(parent, path, encoding)
        dlg.exec_()
        return dlg.ui.comboBoxEncodings.current_encoding


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    new_encoding = DlgEncodingsChoice.choose_encoding(None, __file__, 'utf-8')
    print(new_encoding)
Exemplo n.º 30
0
def initialize():
    global app
    if app is None:
        app = QtWidgets.QApplication(sys.argv)
    plt.show = show
    plt.figure = figure