示例#1
0
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))

        # full screen mode
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien Invasion")

        # Create an instance to store game statistics, and create a scoreboard.
        # need to create it before defining other game elements, such as the ship.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        # Ship constructor needs an instance of AlienInvasion class
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # Make the Play button.
        self.play_button = Button(self, "Play")
示例#2
0
    def __init__(self):
        """Initialize the game, and create game resources."""

        pygame.init()

        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        # Full screen
        # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Alien Invasion")

        # Create an instance to store game statistics, and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        self._start_event_handler()

        # MAke the play button
        self.play_button = Button(self, "Play")
示例#3
0
    def onBatch1(self):
        dfilename = askdirectory()
        if dfilename:

            pickles = []
            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    basename = os.path.basename(filename)
                    root, ext = os.path.splitext(basename)
                    logging.debug(root)
                    BRANCH = Settings(root)
                    pickles.append(BRANCH.get_filename())

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            message = "Processed pickles:\n" + plain(pickles) + "\n\n" +\
                      "Note: Empty pickles was not created!"
            showinfo("Info", message)
            self.setText()
            self.setStatus()
示例#4
0
    def onBatch1(self):
        dfilename = askdirectory()
        if dfilename:

            pickles = []
            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    basename = os.path.basename(filename)
                    root, ext = os.path.splitext(basename)
                    logging.debug(root)
                    BRANCH = Settings(root)
                    pickles.append(BRANCH.get_filename())

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            message = "Processed pickles:\n" + plain(pickles) + "\n\n" +\
                      "Note: Empty pickles was not created!"
            showinfo("Info", message)
            self.setText()
            self.setStatus()
示例#5
0
文件: rptool.py 项目: signove/rptool
 def __init__(self):
     self.playback = None
     self.recorder = None
     self.log = Logger('RPTool')
     self.fileManager = FileManager()
     self.file = ''
     self.alert = Alert('RPTool')
     self.api = TestlinkAPI()
     self.setting = Settings('testlink.cfg')
     self.testFolder = 'artifacts'
示例#6
0
 def onLoadFile(self):
     initialdir = os.path.expanduser("~")
     filename = askopenfilename(initialdir=initialdir,
                                filetypes=[
                                    ('Config files', '*.pickle'),
                                    ('All files', '*.*'),
                                ])
     if filename:
         self.s = Settings(filename=filename)
         self.showInfo()
示例#7
0
 def __init__(self, file_manager):
     self.fileManager = file_manager
     self.log = Logger('PlayBack')
     self.traces = []
     self.hostKeys = []
     self.keyboardListener = KeyboardListener(on_press=self.onPress,
                                              on_release=self.onRelease)
     self.stopped = False
     self.interval = 0
     self.file = ''
     self.alert = Alert('RPTool - Playback')
     self.setting = Settings('rptool.cfg')
     self.verifier = Verifier()
示例#8
0
def main():
    """
    Main entry point of cmd line interface
    """

    # parse cmd line arguments

    parser = argument_parser.create_parser()
    args = parser.parse_args()

    settings = Settings.load_from_file(args.settings)
    # insert default feed for Zoo
    # if not args, just print help
    if len(sys.argv) <= 1:
        parser.print_help()
        return

    # load settings from settings.yaml
    # print("encoding %s" % sys.getdefaultencoding())
    # sys.setdefaultencoding("utf-8")
    # if additional feed urls are in cmd line args, then add it to settings
    if args.urls:
        local_list = args.urls
        settings.urls.extend(local_list)

    # route commands
    process_commands(args, settings)
示例#9
0
    def get(self):
        pushid = core.util.get_int_arg(self.request, 'id')
        override = core.util.get_int_arg(self.request, 'override')
        response = yield tornado.gen.Task(
                        self.async_api_call,
                        "pushdata",
                        {"id": pushid}
                    )

        push_info, push_requests, available_requests = self.get_api_results(response)

        if not push_info['stageenv']:
            push_info['stageenv'] = '(to be determined)'

        push_survey_url = Settings.get('push_survey_url', None)

        self.render(
            "push.html",
            page_title=push_info['title'],
            pushid=pushid,
            push_info=push_info,
            push_contents=push_requests,
            push_survey_url=push_survey_url,
            available_requests=available_requests,
            fullrepo=_repo,
            override=override
        )
示例#10
0
文件: zoocmd.py 项目: helicontech/zoo
def main():
    """
    Main entry point of cmd line interface
    """

    # parse cmd line arguments



    parser = argument_parser.create_parser()
    args = parser.parse_args()



    settings = Settings.load_from_file(args.settings)
    # insert default feed for Zoo
    # if not args, just print help
    if len(sys.argv) <= 1:
        parser.print_help()
        return

    # load settings from settings.yaml
    # print("encoding %s" % sys.getdefaultencoding())
    # sys.setdefaultencoding("utf-8")
    # if additional feed urls are in cmd line args, then add it to settings
    if args.urls:
        local_list = args.urls
        settings.urls.extend(local_list)

    # route commands
    process_commands(args, settings)
示例#11
0
 def __init__(self):
     self.logger = logging.getLogger('raveberry')
     self.settings = Settings(self)
     self.user_manager = UserManager(self)
     self.lights = Lights(self)
     self.pad = Pad(self)
     self.musiq = Musiq(self)
示例#12
0
def run_game():

    # ---initializing---
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((
        ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # ---Make the Play button---
    play_button = Button(ai_settings, screen, "Play")

    # ---instances loading---
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    powerups = Group()

    gf.create_fleet(ai_settings, screen, ship, aliens)

    # ---start---
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)
        
        if stats.game_active:
            ship.update()
            powerups.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets, powerups)
            gf.check_powerup_collisions(ai_settings, screen, ship, powerups, bullets, sb, stats)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens, bullets)
        
        gf.screen_update(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button, powerups)
示例#13
0
文件: zoocmd.py 项目: perldev/zoo
def main():
    """
    Main entry point of cmd line interface
    """

    # parse cmd line arguments
    parser = argument_parser.create_parser()
    args = parser.parse_args()

    # if not args, just print help
    if len(sys.argv) <= 1:
        parser.print_help()
        return

    # get debug level
    log_level_str = args.log_level or os.environ.get('LOG_LEVEL') or 'INFO'
    log_level_str = log_level_str.upper()
    log_level = getattr(logging, log_level_str, logging.INFO)
    # init logger
    init_logger(log_level, args.quiet)

    # load settings from settings.yaml
    settings = Settings.load_from_file()
    # if additional feed urls are in cmd line args, then add it to settings
    if args.urls:
        settings.urls.extend(args.urls)

    # route commands
    process_commands(args, settings)
示例#14
0
 def onLoadFile(self):
     initialdir = os.path.expanduser("~")
     filename = askopenfilename(initialdir=initialdir, filetypes=[
                    ('Config files', '*.pickle'),
                    ('All files', '*.*'),
                ])
     if filename:
         self.s = Settings(filename=filename)
         self.showInfo()
示例#15
0
文件: amdh.py 项目: SecTheTech/AMDH
def process_settings(adb_instance, device_id=""):
    if main_settings.harden:
        settings_check = Settings(SETTINGS_FILE,
                                  adb_instance,
                                  True,
                                  out=main_settings.out[device_id])
    else:
        settings_check = Settings(SETTINGS_FILE,
                                  adb_instance,
                                  out=main_settings.out[device_id])

    if main_settings.scan_settings:
        with open(
                f"{main_settings.output_dir}/{device_id}_report_settings.json",
                'w') as fp:
            json.dump(settings_check.check(), fp, indent=4)

        main_settings.out["std"].print_info(
            "Report generated: %s_report_settings.json" % device_id)
示例#16
0
def retrieve_app_settings(app_data_dir):
    ''' Read in the app_main settings from the file system.
    '''

    app_settings_path = fileutils.join(app_data_dir, APP_CONFIG_FILE_NAME)

    if not fileutils.is_file_exists(app_settings_path):
        raise ItemNotFound("Settings file not found '" + app_settings_path +
                           "'")

    app_settings = AppSettings(DEFAULT_DEBUG_VALUE, app_data_dir)

    settings = Settings(app_settings_path)
    app_settings.debug = settings.get_bool(APP_CONFIG_SECTION,
                                           DEBUG_CONFIG_PROPERTY,
                                           DEFAULT_DEBUG_VALUE)
    app_settings.serial_port = settings.get_string(
        APP_CONFIG_SECTION, SERIAL_PORT_CONFIG_PROPERTY,
        DEFAULT_SERIAL_PORT_VALUE)
    app_settings.log_console_level = settings.get_log_level(
        APP_CONFIG_SECTION, CONSOLE_LOG_LEVEL_PROPERTY, DEFAULT_LOG_LEVEL)
    app_settings.log_file_level = settings.get_log_level(
        APP_CONFIG_SECTION, FILE_LOG_LEVEL_PROPERTY, DEFAULT_LOG_LEVEL)

    return app_settings
示例#17
0
文件: amdh.py 项目: idkwim/AMDH
def amdh():
    arguments = args_parse()

    if arguments.adb_path:
        adb_path = arguments.adb_path

    dump_apks = False
    apks_dump_folder = ""
    if arguments.apks_dump_folder:
        dump_apks = True
        apks_dump_folder = arguments.apks_dump_folder

    adb_instance = ADB(adb_path)
    device_id = device_choice(adb_instance)
    adb_instance = ADB(adb_path, device_id)
    settings_check = None

    packages = []
    if arguments.app_type:
        packages = adb_instance.list_installed_packages(arguments.app_type)

    report_apps = {}
    for package in packages:
        dumpsys_out = adb_instance.dumpsys(["package", package])
        perm_list = adb_instance.get_req_perms_dumpsys_package(dumpsys_out)
        app = App(adb_instance, package, dump_apks, apks_dump_folder,
                  perm_list)
        perms, dangerous_perms = app.check_apps()
        print("")
        if dangerous_perms.items():
            print_warning_header("Package " + package +
                                 " have some dangerous permissions: ")
            for perm, desc in dangerous_perms.items():
                print_warning("\t " + perm + " : ")
                print_warning("\t\t" + desc)
            report_apps[package] = {
                "permissions": perms,
                "dangerous_perms": dangerous_perms
            }
            print("")
            print(
                "************************************************************************"
            )
        else:
            print_info("Package " + package + " have no dangerous permissions")
            print("")
            print(
                "************************************************************************"
            )

    if arguments.H:
        settings_check = Settings(settings_file, adb_instance, True)
    else:
        settings_check = Settings(settings_file, adb_instance)

    settings_check.check()
示例#18
0
    def run(self):
        daemon_context = daemon.DaemonContext(stdout=self.log, stderr=self.log, working_directory=os.getcwd())
        with daemon_context:
            pid.write(self.pid_file)
            try:
                self.start_services()
                pid.write(self.pid_file, append=True)

                # Drop privileges
                uid = pwd.getpwnam(Settings.get("username", "www-data"))[2]
                os.setuid(uid)

                tornado.ioloop.IOLoop.instance().start()
            finally:
                pid.remove(self.pid_file)
示例#19
0
 def __init__(self):
     self.config = {
         'username': '******',
         'api_key': 'bae5852b0e4a8ac7faa16befb5216c2d',
         'url': 'http://127.0.0.1/testlink/lib/api/xmlrpc/v1/xmlrpc.php',
         'project_id': '0',
         'plan_id': '0',
         'platform_id': '0',
         'build_id': '0',
         'build_name': ''
     }
     os.environ["TESTLINK_API_PYTHON_SERVER_URL"] = self.config['url']
     os.environ["TESTLINK_API_PYTHON_DEVKEY"] = self.config['api_key']
     self.setting = Settings('testlink.cfg')
     try:
         self.tlh = testlink.TestLinkHelper()
         self.tls = self.tlh.connect(testlink.TestlinkAPIClient)
     except TLResponseError as err:
         print(err)
示例#20
0
class Verifier:

    def __init__(self):
        self.checkPointIndex = 0
        self.alert = Alert('Verifier')
        self.setting = Settings('testlink.cfg')
        self.config = self.setting.readConfig()
        self.api = TestlinkAPI()

    def printScreen(self, filename):
        """ Key F2 pressed should capture the selected area on screen """
        print('check {0}'.format(filename))
        filename = '{0}_{1}.png'.format(filename, self.checkPointIndex)
        print('Saved as {}'.format(filename))
        subprocess.run(['scrot', '-s -d 2', filename])
        self.checkPointIndex += 1
        return filename

    def check(self, checkpoint):
        """ Check if the checkpoint image is visible on screen """
        checked = pyautogui.locateOnScreen(checkpoint)
        if checked:
            self.alert.notify('checked Ok')
            self.report(checkpoint, 'p')
        else:
            self.alert.notify('checked Fail')
            self.report(checkpoint, 'f')

    def report(self, checkpoint, status):
        """ Sends the test result to Testlink """
        identifier = checkpoint.split('/')[-1]
        test = identifier.split('_')[0]
        plan = self.config['plan_id']
        build = self.config['build_name']
        notes = '...'
        user = self.config['username']
        platform = self.config['platform_id']
        try:
            self.api.reportTCResult(None, plan, build, status, notes, user, platform, test)
            print('reporting ... ', test)
        except TLResponseError as err:
            print('error: ', err)
    def setUp(self):
        self.settings = Settings.load_config('../conf.json')

        # Centrifuge uses it's own internal process.
        # During running the tests this process prevents correct server shutdown and socket does not returns port.
        # To prevent it - centrifuge should be simply disabled.
        # (it is not used in this tests)
        self.settings.use_centrifuge = False

        self.core = Core(self.settings)

        def run():
            # It is necessary to seed random in forked process,
            # otherwise - Crypto would throw an error.
            Random.atfork()

            self.core.run()

        self.process = Process(target=run)
        self.process.start()

        # Wait until server would be stopped.
        sleep(0.5)
示例#22
0
def scan():
    if request.method == 'POST':
        if 'scan' in request.form.keys() and request.form['scan'] == 'apps_scan':
            device = request.form['device']
            app_type = request.form['app']
            dict_packages = refresh_scan(device, app_type)
            return render_template('scan.html', scan="apps_scan", app_type=app_type, show=request.form['show'],
                                   packages=dict_packages,
                                   device=device)

        if 'scan' in request.form.keys() and request.form['scan'] == 'settings_scan':
            device = request.form['device']
            adb = ADB(ADB_PATH, device_id=device)
            settings = Settings(json_settings, adb)
            settings.check()
            return render_template('scan.html', scan="settings_scan", secure_result=settings.get_scan_report("secure"),
                                   global_result=settings.get_scan_report("global"), device=device)

    return redirect(url_for('index'))
示例#23
0
def target(param_names, param_values, model_nr):
    # model_nr = pickle.load(open(nr_steps_path, "rb")) + 1
    # pickle.dump(model_nr, open(nr_steps_path, "wb"))

    s = Settings()

    param_values = list(param_values)

    for i in range(len(param_names)):
        eval('s.{}'.format(param_names[i]))
        if isinstance(param_values[i], str):
            param_values[i] = '\'' + param_values[i] + '\''
        expr = 's.{} = {}'.format(param_names[i], param_values[i])
        exec(expr)

    # print('s.DROPOUT == {}'.format(s.DROPOUT))
    # print('s.LEARNING_RATE == {}'.format(s.LEARNING_RATE))
    # print('s.LOSS_FUNCTION == {}'.format(s.LOSS_FUNCTION))

    s.MODEL_NAME = MAIN_FOLDER + str(model_nr)
    s.VALTEST_MODEL_NAMES = [s.MODEL_NAME]
    h = Helper(s)

    # with suppress_stdout():
    # print('here1')
    not_model_nrs = []
    if model_nr not in not_model_nrs:
        # print('here2')
        t = Train(s, h)
        t.train()
        del t
        metric_means, metric_sds = Test(s, h).test()
    else:
        # print('here3')
        s.CALC_PROBS = False
        metric_means, metric_sds = Test(s, h).test()
        s.CALC_PROBS = True

    return metric_means[s.MODEL_NAME]['Dice'], metric_sds[s.MODEL_NAME]['Dice']
示例#24
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(676, 456)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(10, 10, 661, 401))
        self.tabWidget.setObjectName("tabWidget")
        self.tabRPTool = QtWidgets.QWidget()
        self.tabRPTool.setObjectName("tabRPTool")

        # List Widget Test Cases
        self.lvTestCases = QtWidgets.QListWidget(self.tabRPTool)
        self.lvTestCases.setGeometry(QtCore.QRect(10, 60, 641, 271))
        self.lvTestCases.setObjectName("lvTestCases")
        self.lvTestCases.itemClicked.connect(self.itemSelected)

        # Button 'rec'
        self.pbRec = QtWidgets.QPushButton(self.tabRPTool)
        self.pbRec.setGeometry(QtCore.QRect(10, 340, 41, 25))
        self.pbRec.setObjectName("pbRec")
        self.pbRec.clicked.connect(self.addTestCase)

        self.leTestCaseName = QtWidgets.QLineEdit(self.tabRPTool)
        self.leTestCaseName.setGeometry(QtCore.QRect(10, 30, 301, 25))
        self.leTestCaseName.setObjectName("leTestCaseName")
        self.leTestFolder = QtWidgets.QLineEdit(self.tabRPTool)
        self.leTestFolder.setGeometry(QtCore.QRect(320, 30, 331, 25))
        self.leTestFolder.setObjectName("leTestFolder")
        self.lblTestCaseName = QtWidgets.QLabel(self.tabRPTool)
        self.lblTestCaseName.setGeometry(QtCore.QRect(10, 10, 121, 17))
        self.lblTestCaseName.setObjectName("lblTestCaseName")
        self.lblTestFolder = QtWidgets.QLabel(self.tabRPTool)
        self.lblTestFolder.setGeometry(QtCore.QRect(320, 10, 71, 17))
        self.lblTestFolder.setObjectName("lblTestFolder")

        self.pbPlay = QtWidgets.QPushButton(self.tabRPTool)
        self.pbPlay.setGeometry(QtCore.QRect(60, 340, 51, 25))
        self.pbPlay.setObjectName("pbPlay")
        self.pbPlay.setEnabled(False)
        self.pbPlay.clicked.connect(self.playTestCase)

        self.pbDelete = QtWidgets.QPushButton(self.tabRPTool)
        self.pbDelete.setGeometry(QtCore.QRect(180, 340, 51, 25))
        self.pbDelete.setObjectName("pbDelete")
        self.pbDelete.setEnabled(False)
        self.pbDelete.clicked.connect(self.deleteTestCase)

        self.pbPlayAll = QtWidgets.QPushButton(self.tabRPTool)
        self.pbPlayAll.setGeometry(QtCore.QRect(120, 340, 51, 25))
        self.pbPlayAll.setObjectName("pbPlayAll")
        self.pbPlayAll.setEnabled(False)

        self.lblToolStatus = QtWidgets.QLabel(self.tabRPTool)
        self.lblToolStatus.setGeometry(QtCore.QRect(250, 330, 371, 41))
        self.lblToolStatus.setObjectName("lblToolStatus")

        # Loop Tests
        self.chboxLoop = QtWidgets.QCheckBox(self.tabRPTool)
        self.chboxLoop.setGeometry(QtCore.QRect(510, 340, 61, 21))
        self.chboxLoop.stateChanged.connect(self.changeLoopState)
        self.chboxLoop.setObjectName("chboxLoop")
        self.leInterval = QtWidgets.QLineEdit(self.tabRPTool)
        self.leInterval.setGeometry(QtCore.QRect(580, 340, 71, 25))
        self.leInterval.setObjectName("leInterval")
        self.leInterval.setText('0')

        self.tabWidget.addTab(self.tabRPTool, "")
        self.tabSettings = QtWidgets.QWidget()
        self.tabSettings.setObjectName("tabSettings")

        # Save settings
        self.pbSaveSettings = QtWidgets.QPushButton(self.tabSettings)
        self.pbSaveSettings.setGeometry(QtCore.QRect(10, 330, 61, 25))
        self.pbSaveSettings.setObjectName("pbSaveSettings")
        self.pbSaveSettings.clicked.connect(self.saveSettings)

        self.lblUsername = QtWidgets.QLabel(self.tabSettings)
        self.lblUsername.setGeometry(QtCore.QRect(10, 0, 81, 31))
        self.lblUsername.setObjectName("lblUsername")
        self.lblTestlinkApiKey = QtWidgets.QLabel(self.tabSettings)
        self.lblTestlinkApiKey.setGeometry(QtCore.QRect(310, 10, 111, 17))
        self.lblTestlinkApiKey.setObjectName("lblTestlinkApiKey")
        self.leUsername = QtWidgets.QLineEdit(self.tabSettings)
        self.leUsername.setGeometry(QtCore.QRect(10, 30, 291, 25))
        self.leUsername.setObjectName("leUsername")
        self.leTestlinkApiKey = QtWidgets.QLineEdit(self.tabSettings)
        self.leTestlinkApiKey.setGeometry(QtCore.QRect(310, 30, 341, 25))
        self.leTestlinkApiKey.setObjectName("leTestlinkApiKey")
        # combo box projects
        self.cbProjects = QtWidgets.QComboBox(self.tabSettings)
        self.cbProjects.setGeometry(QtCore.QRect(10, 150, 291, 25))
        self.cbProjects.setObjectName("cbProjects")
        self.cbProjects.currentTextChanged.connect(self.getTestlinkPlans)

        self.leTestlinkAddress = QtWidgets.QLineEdit(self.tabSettings)
        self.leTestlinkAddress.setGeometry(QtCore.QRect(10, 90, 641, 25))
        self.leTestlinkAddress.setObjectName("leTestlinkAddress")
        self.lblTestlinkAddress = QtWidgets.QLabel(self.tabSettings)
        self.lblTestlinkAddress.setGeometry(QtCore.QRect(10, 70, 101, 17))
        self.lblTestlinkAddress.setObjectName("lblTestlinkAddress")

        # connect push button
        self.pbConnect = QtWidgets.QPushButton(self.tabSettings)
        self.pbConnect.setGeometry(QtCore.QRect(80, 330, 80, 25))
        self.pbConnect.setObjectName("pbConnect")
        self.pbConnect.clicked.connect(self.getTestlinkProjects)

        self.lblSettingsStatus = QtWidgets.QLabel(self.tabSettings)
        self.lblSettingsStatus.setGeometry(QtCore.QRect(180, 330, 171, 21))
        self.lblSettingsStatus.setObjectName("lblSettingsStatus")
        self.lblTestProject = QtWidgets.QLabel(self.tabSettings)
        self.lblTestProject.setGeometry(QtCore.QRect(10, 120, 91, 31))
        self.lblTestProject.setObjectName("lblTestProject")

        # Combobox plans
        self.cbPlans = QtWidgets.QComboBox(self.tabSettings)
        self.cbPlans.setGeometry(QtCore.QRect(310, 150, 341, 25))
        self.cbPlans.setObjectName("cbPlans")
        self.cbPlans.currentTextChanged.connect(self.getTeslinkPlatforms)

        self.lblTestPlan = QtWidgets.QLabel(self.tabSettings)
        self.lblTestPlan.setGeometry(QtCore.QRect(310, 126, 91, 21))
        self.lblTestPlan.setObjectName("lblTestPlan")

        #Combobox platforms
        self.cbPlatforms = QtWidgets.QComboBox(self.tabSettings)
        self.cbPlatforms.setGeometry(QtCore.QRect(10, 210, 291, 25))
        self.cbPlatforms.setObjectName("cbPlatforms")
        self.cbPlatforms.currentTextChanged.connect(self.getTestlinkBuilds)

        self.cbBuilds = QtWidgets.QComboBox(self.tabSettings)
        self.cbBuilds.setGeometry(QtCore.QRect(310, 210, 341, 25))
        self.cbBuilds.setObjectName("cbBuilds")
        self.lblPlatform = QtWidgets.QLabel(self.tabSettings)
        self.lblPlatform.setGeometry(QtCore.QRect(10, 186, 91, 21))
        self.lblPlatform.setObjectName("lblPlatform")
        self.lblBuild = QtWidgets.QLabel(self.tabSettings)
        self.lblBuild.setGeometry(QtCore.QRect(310, 186, 54, 21))
        self.lblBuild.setObjectName("lblBuild")
        self.tabWidget.addTab(self.tabSettings, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 676, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        # RPTool init
        self.rpt = RPTool()
        self.setting = Settings('rptool.cfg')
        self.config = self.rpt.getConfig()
        self.interval = 0
        self.setFolderDir()
        self.listTests()
        self.testlinkSettings()
示例#25
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(676, 456)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(10, 10, 661, 401))
        self.tabWidget.setObjectName("tabWidget")
        self.tabRPTool = QtWidgets.QWidget()
        self.tabRPTool.setObjectName("tabRPTool")

        # List Widget Test Cases
        self.lvTestCases = QtWidgets.QListWidget(self.tabRPTool)
        self.lvTestCases.setGeometry(QtCore.QRect(10, 60, 641, 271))
        self.lvTestCases.setObjectName("lvTestCases")
        self.lvTestCases.itemClicked.connect(self.itemSelected)

        # Button 'rec'
        self.pbRec = QtWidgets.QPushButton(self.tabRPTool)
        self.pbRec.setGeometry(QtCore.QRect(10, 340, 41, 25))
        self.pbRec.setObjectName("pbRec")
        self.pbRec.clicked.connect(self.addTestCase)

        self.leTestCaseName = QtWidgets.QLineEdit(self.tabRPTool)
        self.leTestCaseName.setGeometry(QtCore.QRect(10, 30, 301, 25))
        self.leTestCaseName.setObjectName("leTestCaseName")
        self.leTestFolder = QtWidgets.QLineEdit(self.tabRPTool)
        self.leTestFolder.setGeometry(QtCore.QRect(320, 30, 331, 25))
        self.leTestFolder.setObjectName("leTestFolder")
        self.lblTestCaseName = QtWidgets.QLabel(self.tabRPTool)
        self.lblTestCaseName.setGeometry(QtCore.QRect(10, 10, 121, 17))
        self.lblTestCaseName.setObjectName("lblTestCaseName")
        self.lblTestFolder = QtWidgets.QLabel(self.tabRPTool)
        self.lblTestFolder.setGeometry(QtCore.QRect(320, 10, 71, 17))
        self.lblTestFolder.setObjectName("lblTestFolder")

        self.pbPlay = QtWidgets.QPushButton(self.tabRPTool)
        self.pbPlay.setGeometry(QtCore.QRect(60, 340, 51, 25))
        self.pbPlay.setObjectName("pbPlay")
        self.pbPlay.setEnabled(False)
        self.pbPlay.clicked.connect(self.playTestCase)

        self.pbDelete = QtWidgets.QPushButton(self.tabRPTool)
        self.pbDelete.setGeometry(QtCore.QRect(180, 340, 51, 25))
        self.pbDelete.setObjectName("pbDelete")
        self.pbDelete.setEnabled(False)
        self.pbDelete.clicked.connect(self.deleteTestCase)

        self.pbPlayAll = QtWidgets.QPushButton(self.tabRPTool)
        self.pbPlayAll.setGeometry(QtCore.QRect(120, 340, 51, 25))
        self.pbPlayAll.setObjectName("pbPlayAll")
        self.pbPlayAll.setEnabled(False)

        self.lblToolStatus = QtWidgets.QLabel(self.tabRPTool)
        self.lblToolStatus.setGeometry(QtCore.QRect(250, 330, 371, 41))
        self.lblToolStatus.setObjectName("lblToolStatus")

        # Loop Tests
        self.chboxLoop = QtWidgets.QCheckBox(self.tabRPTool)
        self.chboxLoop.setGeometry(QtCore.QRect(510, 340, 61, 21))
        self.chboxLoop.stateChanged.connect(self.changeLoopState)
        self.chboxLoop.setObjectName("chboxLoop")
        self.leInterval = QtWidgets.QLineEdit(self.tabRPTool)
        self.leInterval.setGeometry(QtCore.QRect(580, 340, 71, 25))
        self.leInterval.setObjectName("leInterval")
        self.leInterval.setText('0')

        self.tabWidget.addTab(self.tabRPTool, "")
        self.tabSettings = QtWidgets.QWidget()
        self.tabSettings.setObjectName("tabSettings")

        # Save settings
        self.pbSaveSettings = QtWidgets.QPushButton(self.tabSettings)
        self.pbSaveSettings.setGeometry(QtCore.QRect(10, 330, 61, 25))
        self.pbSaveSettings.setObjectName("pbSaveSettings")
        self.pbSaveSettings.clicked.connect(self.saveSettings)

        self.lblUsername = QtWidgets.QLabel(self.tabSettings)
        self.lblUsername.setGeometry(QtCore.QRect(10, 0, 81, 31))
        self.lblUsername.setObjectName("lblUsername")
        self.lblTestlinkApiKey = QtWidgets.QLabel(self.tabSettings)
        self.lblTestlinkApiKey.setGeometry(QtCore.QRect(310, 10, 111, 17))
        self.lblTestlinkApiKey.setObjectName("lblTestlinkApiKey")
        self.leUsername = QtWidgets.QLineEdit(self.tabSettings)
        self.leUsername.setGeometry(QtCore.QRect(10, 30, 291, 25))
        self.leUsername.setObjectName("leUsername")
        self.leTestlinkApiKey = QtWidgets.QLineEdit(self.tabSettings)
        self.leTestlinkApiKey.setGeometry(QtCore.QRect(310, 30, 341, 25))
        self.leTestlinkApiKey.setObjectName("leTestlinkApiKey")
        # combo box projects
        self.cbProjects = QtWidgets.QComboBox(self.tabSettings)
        self.cbProjects.setGeometry(QtCore.QRect(10, 150, 291, 25))
        self.cbProjects.setObjectName("cbProjects")
        self.cbProjects.currentTextChanged.connect(self.getTestlinkPlans)

        self.leTestlinkAddress = QtWidgets.QLineEdit(self.tabSettings)
        self.leTestlinkAddress.setGeometry(QtCore.QRect(10, 90, 641, 25))
        self.leTestlinkAddress.setObjectName("leTestlinkAddress")
        self.lblTestlinkAddress = QtWidgets.QLabel(self.tabSettings)
        self.lblTestlinkAddress.setGeometry(QtCore.QRect(10, 70, 101, 17))
        self.lblTestlinkAddress.setObjectName("lblTestlinkAddress")

        # connect push button
        self.pbConnect = QtWidgets.QPushButton(self.tabSettings)
        self.pbConnect.setGeometry(QtCore.QRect(80, 330, 80, 25))
        self.pbConnect.setObjectName("pbConnect")
        self.pbConnect.clicked.connect(self.getTestlinkProjects)

        self.lblSettingsStatus = QtWidgets.QLabel(self.tabSettings)
        self.lblSettingsStatus.setGeometry(QtCore.QRect(180, 330, 171, 21))
        self.lblSettingsStatus.setObjectName("lblSettingsStatus")
        self.lblTestProject = QtWidgets.QLabel(self.tabSettings)
        self.lblTestProject.setGeometry(QtCore.QRect(10, 120, 91, 31))
        self.lblTestProject.setObjectName("lblTestProject")

        # Combobox plans
        self.cbPlans = QtWidgets.QComboBox(self.tabSettings)
        self.cbPlans.setGeometry(QtCore.QRect(310, 150, 341, 25))
        self.cbPlans.setObjectName("cbPlans")
        self.cbPlans.currentTextChanged.connect(self.getTeslinkPlatforms)

        self.lblTestPlan = QtWidgets.QLabel(self.tabSettings)
        self.lblTestPlan.setGeometry(QtCore.QRect(310, 126, 91, 21))
        self.lblTestPlan.setObjectName("lblTestPlan")

        #Combobox platforms
        self.cbPlatforms = QtWidgets.QComboBox(self.tabSettings)
        self.cbPlatforms.setGeometry(QtCore.QRect(10, 210, 291, 25))
        self.cbPlatforms.setObjectName("cbPlatforms")
        self.cbPlatforms.currentTextChanged.connect(self.getTestlinkBuilds)

        self.cbBuilds = QtWidgets.QComboBox(self.tabSettings)
        self.cbBuilds.setGeometry(QtCore.QRect(310, 210, 341, 25))
        self.cbBuilds.setObjectName("cbBuilds")
        self.lblPlatform = QtWidgets.QLabel(self.tabSettings)
        self.lblPlatform.setGeometry(QtCore.QRect(10, 186, 91, 21))
        self.lblPlatform.setObjectName("lblPlatform")
        self.lblBuild = QtWidgets.QLabel(self.tabSettings)
        self.lblBuild.setGeometry(QtCore.QRect(310, 186, 54, 21))
        self.lblBuild.setObjectName("lblBuild")
        self.tabWidget.addTab(self.tabSettings, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 676, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        # RPTool init
        self.rpt = RPTool()
        self.setting = Settings('rptool.cfg')
        self.config = self.rpt.getConfig()
        self.interval = 0
        self.setFolderDir()
        self.listTests()
        self.testlinkSettings()

    def saveSettings(self):
        value = self.cbBuilds.currentText()
        self.config['build_id'] = value.split('-')[0]
        self.config['build_name'] = value.split('-')[1]
        self.config['username'] = self.leUsername.text()
        print('config ', self.config)
        self.rpt.saveConfig(self.config)

    def testlinkSettings(self):
        self.leUsername.setText(self.rpt.getUsername())
        self.leTestlinkAddress.setText(self.rpt.getUrl())
        self.leTestlinkApiKey.setText(self.rpt.getApiKey())

    def getTestlinkBuilds(self, value):
        print('loading build for', value)
        self.config['platform_id'] = value.split('-')[0]
        builds = self.rpt.getBuilds(self.config['plan_id'])
        self.cbBuilds.clear()
        for build in builds:
            id = build['id']
            name = build['name']
            self.cbBuilds.addItem('{0}-{1}'.format(id, name))

    def getTeslinkPlatforms(self, value):
        print('loading platforms for', value)
        self.config['plan_id'] = value.split('-')[0]
        platforms = self.rpt.getPlatforms(self.config['project_id'])
        self.cbPlatforms.clear()
        for platform in platforms:
            id = platform['id']
            name = platform['name']
            self.cbPlatforms.addItem('{0}-{1}'.format(id, name))

    def getTestlinkPlans(self, value):
        print('loading plans for ', value)
        self.config['project_id'] = int(value.split('-')[0])
        plans = self.rpt.getPlans(self.config['project_id'])
        self.cbPlans.clear()
        for plan in plans:
            id = plan['id']
            name = plan['name']
            self.cbPlans.addItem('{0}-{1}'.format(id, name))

    def getTestlinkProjects(self):
        print('load projects')
        projects = self.rpt.getProjects()
        self.cbProjects.clear()
        for project in projects:
            id = project['id']
            prefix = project['prefix']
            name = project['name']
            self.cbProjects.addItem('{0}-{1}-{2}'.format(id, prefix, name))

    def changeLoopState(self):
        if self.chboxLoop.isChecked():
            self.interval = int(self.leInterval.text())
            self.rpt.notifyLoop(self.interval)
        else:
            self.interval = 0
        self.setting.saveConfig({'loop': self.interval})
        cfg = self.setting.readConfig()

    def setFolderDir(self):
        self.leTestFolder.setText(self.rpt.getTestFolder())

    def listTests(self):
        for test in self.rpt.getTestFiles():
            self.lvTestCases.addItem(test)

    def addTestCase(self):
        tc_name = self.leTestCaseName.text()
        self.leTestCaseName.setText('')
        self.lvTestCases.addItem(tc_name)
        self.rpt.rec(tc_name)

    def itemSelected(self, item):
        print('selected ', item.text())
        self.tcItem = item
        self.pbRec.setEnabled(False)
        self.pbPlay.setEnabled(True)
        self.pbDelete.setEnabled(True)

    def deleteTestCase(self):
        print('deleting ', self.tcItem.text())
        self.lvTestCases.takeItem(self.lvTestCases.currentRow())
        self.rpt.delete(self.tcItem.text())
        self.pbRec.setEnabled(True)
        self.pbPlay.setEnabled(False)

    def playTestCase(self):
        print('playing ', self.tcItem.text())
        self.pbRec.setEnabled(True)
        self.pbPlay.setEnabled(False)
        self.rpt.play(self.tcItem.text())
        self.checkLoopEnabled()

    def checkLoopEnabled(self):
        cfg = self.setting.readConfig()
        if cfg['loop'] == '0':
            self.chboxLoop.setChecked(False)
            self.leInterval.setText('0')
        else:
            self.rpt.notifyLoop(cfg['loop'])
            time.sleep(int(cfg['loop']))
            self.playTestCase()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "RPTool Viewer"))
        self.pbRec.setText(_translate("MainWindow", "Rec"))
        self.lblTestCaseName.setText(_translate("MainWindow",
                                                "Test Case Name"))
        self.lblTestFolder.setText(_translate("MainWindow", "Test Folder"))
        self.pbPlay.setText(_translate("MainWindow", "Play"))
        self.pbDelete.setText(_translate("MainWindow", "Del"))
        self.pbPlayAll.setText(_translate("MainWindow", "Play All"))
        self.lblToolStatus.setText(_translate("MainWindow",
                                              "Not started yet!"))
        self.chboxLoop.setText(_translate("MainWindow", "Loop"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabRPTool),
                                  _translate("MainWindow", "RPTool"))
        self.pbSaveSettings.setText(_translate("MainWindow", "Save"))
        self.lblUsername.setText(_translate("MainWindow", "Username"))
        self.lblTestlinkApiKey.setText(
            _translate("MainWindow", "Testlink API KEY"))
        self.lblTestlinkAddress.setText(
            _translate("MainWindow", "Testlink Address"))
        self.pbConnect.setText(_translate("MainWindow", "Connect"))
        self.lblSettingsStatus.setText(
            _translate("MainWindow", "Not connected"))
        self.lblTestProject.setText(_translate("MainWindow", "Test Projects"))
        self.lblTestPlan.setText(_translate("MainWindow", "Test Plans"))
        self.lblPlatform.setText(_translate("MainWindow", "Platforms"))
        self.lblBuild.setText(_translate("MainWindow", "Builds"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabSettings),
                                  _translate("MainWindow", "Settings"))
示例#26
0
            if el.get_image().shape is not self.__elements[0].get_image().shape:
                raise Exception('Image shapes of all elements should be equal. Found {}, while expected {}.'
                                .format(self.__elements[0].get_image().shape, el.get_image().shape))

        self.__elements.append(el)

    def get_result(self):
        return self.__result

    def show_result(self):
        print(self.get_result().shape)
        imshow3D(self.get_result())


if __name__ == '__main__':
    s = Settings()
    h = Helper(s)

    # Get a mask which represents a left atrium
    _, _, la_path = h.getImagePaths([24], True)
    la_image = h.loadImages(["../data/4chamber/GlassHeartNonIsotropicCT_seg.gipl"])
    imshow3D(la_image[0])

    # Make left atrium object with mask image
    la = LeftAtrium()
    la.set_mask_image((la_image[0] == 2).astype(int))
    la.init_generation()

    # Add scar and fibrosis to the image
    la.add_adjustment(Wall(2))
    la.add_adjustment(ScarFibrosis(2))
示例#27
0
class AppUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("tkSettings")

        # === Menu ===

        self.menubar = tk.Menu(self)

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=menu)
        menu.add_command(command=self.onLoadDefault, label="Load default")
        menu.add_command(command=self.onLoadFile, label="Load file")
        menu.add_separator()
        menu.add_command(command=self.quit, label="Exit")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Edit", menu=menu)
        menu.add_command(command=self.onCleanData, label="Clean data")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Batch import", menu=menu)
        menu.add_command(command=self.onBatch1, label="File to file")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Help", menu=menu)
        menu.add_command(command=self.onAbout, label="About")

        self.config(menu=self.menubar)

        # === Widgets ===

        # Frame with Buttons
        self.frame1 = tk.Frame(self)

        button = tk.Button(self.frame1, text="Settings")
        button.pack()
        button.bind("<Button-1>", self.onShowSettings)

        button = tk.Button(self.frame1, text="Save test data")
        button.pack()
        button.bind("<Button-1>", self.onSaveTestData)

        button = tk.Button(self.frame1, text="Import from module")
        button.pack()
        button.bind("<Button-1>", self.onImportFromModule)

        button = tk.Button(self.frame1, text="Import from module to branch")
        button.pack()
        button.bind("<Button-1>", self.onImportFromModuleToBranch)

        button = tk.Button(self.frame1, text="Import from dir")
        button.pack()
        button.bind("<Button-1>", self.onImportFromDir)

        button = tk.Button(self.frame1, text="Import from dir to branch")
        button.pack()
        button.bind("<Button-1>", self.onImportFromDirToBranch)

        # Text Widget
        dFont1 = Font(family="Courier", size=9)
        self.text1 = tk.Text(self, font=dFont1)
        self.text1_y = tk.Scrollbar(self,
                                    orient=tk.VERTICAL,
                                    command=self.text1.yview)
        self.text1['yscrollcommand'] = self.text1_y.set

        # Status Widget
        self.status = tk.StringVar()
        label1 = tk.Label(self, textvariable=self.status, anchor=tk.W)
        self.setStatus()

        # === Grid widgets ===

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1, minsize=120)
        self.grid_columnconfigure(1, weight=5, minsize=400)
        self.grid_columnconfigure(2)

        self.frame1.grid(row=0, column=0, sticky='nwes')
        self.text1.grid(row=0, column=1, sticky='nwes')
        self.text1_y.grid(row=0, column=2, sticky='nwes')

        self.grid_rowconfigure(1)
        label1.grid(row=1, column=0, columnspan=4, sticky='nwes')

        # === Initial ===

        self.onLoadDefault()

        self.update_idletasks()
        self.minsize(self.winfo_reqwidth(), self.winfo_reqheight())

    def appendText(self, text=""):
        self.text1.insert(tk.INSERT, "{0}\n".format(plain(text)))

    def setText(self, text=""):
        self.text1.delete(1.0, tk.END)
        self.appendText(text)

    def setStatus(self, text=""):
        self.status.set(text)

    def showInfo(self):
        self.setText("System:")
        self.appendText(self.s.get_systems())
        self.appendText("Settings:")
        self.appendText(self.s.get_dict())
        self.setStatus(self.s.get_filename())

    # === From menu ===

    def onAbout(self, event=None):
        text = """{0}\n{1}\nVersion {2}\n
Python: {3}
Binary: {4}
""".format(__pkgname__, __description__, __version__, sys.version,
           sys.executable)
        showinfo("About", text)

    def onLoadDefault(self):
        self.s = Settings()
        self.showInfo()

    def onLoadFile(self):
        initialdir = os.path.expanduser("~")
        filename = askopenfilename(initialdir=initialdir,
                                   filetypes=[
                                       ('Config files', '*.pickle'),
                                       ('All files', '*.*'),
                                   ])
        if filename:
            self.s = Settings(filename=filename)
            self.showInfo()

    def onCleanData(self):
        response = askquestion(
            "Clean data", "Are you sure you want to "
            "permanently delete all information from the config?")
        if response == 'yes':
            self.s.clean()
            self.showInfo()

    def onBatch1(self):
        dfilename = askdirectory()
        if dfilename:

            pickles = []
            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    basename = os.path.basename(filename)
                    root, ext = os.path.splitext(basename)
                    logging.debug(root)
                    BRANCH = Settings(root)
                    pickles.append(BRANCH.get_filename())

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            message = "Processed pickles:\n" + plain(pickles) + "\n\n" +\
                      "Note: Empty pickles was not created!"
            showinfo("Info", message)
            self.setText()
            self.setStatus()

    # === From buttons ===

    def onShowSettings(self, event):
        propertyDialog(self.s.get_dict())

    def onSaveTestData(self, event):
        #       answer = YesNoDialog(self.s.get_dict(), "Would you like append new data?")

        self.s.saveEnv()
        self.s.set_path('test_instance', '$')
        self.s.set_path('test_home', '~')
        self.s.set_path('test_location', '~~', True)
        self.s.set_path('test_app', '~~~', True)
        self.showInfo()

    def onImportFromModuleToBranch(self, event):
        self.onImportFromModule(event, tobranch=True)

    def onImportFromModule(self, event, tobranch=False):
        filename = askopenfilename(filetypes=[
            ('Python files', '*.py'),
            ('All files', '*.*'),
        ])
        if filename:
            module = import_file(filename)
            if module:
                if tobranch:
                    branch = module.__name__
                    BRANCH = self.s.get_group(branch)
                else:
                    BRANCH = self.s

                for i in dir(module):
                    if i[0] != '_':
                        value = getattr(module, i)

                        # Словари объединяем
                        if isinstance(value, dict) and isinstance(
                                BRANCH.get(i), dict):
                            #                           value1 = BRANCH.get(i)
                            #                           value1.update(value)
                            #                           BRANCH.set(i, value1)
                            BRANCH.update(value)

                        elif isinstance(value, all_types):
                            BRANCH.set(i, value)

                self.showInfo()

    def onImportFromDirToBranch(self, event):
        self.onImportFromDir(event, tobranch=True)

    def onImportFromDir(self, event, tobranch=False):
        dfilename = askdirectory()
        if dfilename:
            basename = os.path.basename(dfilename)
            logging.debug(basename)
            ROOT = self.s  # Settings(basename)

            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    if tobranch:
                        branch = module.__name__
                        BRANCH = self.s.get_group(branch)
                    else:
                        BRANCH = self.s

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            self.showInfo()
示例#28
0
def loadDataSettings():
    current_dir = os.path.dirname(__file__)
    config_file = os.path.join(current_dir, 'app.properties')
    data_settings = Settings(config_file)
    return data_settings
示例#29
0
 def __init__(self, settingsFile):
   threading.Thread.__init__(self, name="Worker: " + settingsFile)
   settignsFromFile = Settings(settingsFile)
   self.settings = settignsFromFile.getSettings()
示例#30
0
文件: settings.py 项目: perldev/zoo
)

ROOT_URLCONF = 'web.urls'

WSGI_APPLICATION = 'web.wsgi.application'

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = False
USE_L10N = False
USE_TZ = False
STATIC_URL = '/static/'
JSTEMPLATE_EXTS = ('hbs',)


from core.settings import Settings
zoo_settings = Settings.get_instance()

if not zoo_settings:
    raise RuntimeError('No zoo settings')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(zoo_settings.storage_path, 'db.sqlite3'),
    }
}



示例#31
0
from core.core import Core
from core.settings import Settings

if __name__ == '__main__':
    settings = Settings.load_config()
    core = Core(settings).run()
示例#32
0
def harden_settings(device):
    adb = ADB(ADB_PATH, device_id=device)
    settings = Settings(json_settings, adb, True)
    settings.check()
    return redirect(url_for('index'))
示例#33
0
 def __init__(self) -> None:
     self.settings = Settings(self)
     self.user_manager = UserManager(self)
     self.lights = Lights(self)
     self.pad = Pad(self)
     self.musiq = Musiq(self)
示例#34
0
 def onLoadDefault(self):
     self.s = Settings()
     self.showInfo()
示例#35
0

@contextmanager
def suppress_stdout():
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:
            yield
        finally:
            sys.stdout = old_stdout


# MAIN_FOLDER = 'la_2018_challenge_1/'
MAIN_FOLDER = 'sf_grid_search_05July2018/'
h = Helper(Settings())
bo_path = h.getBOPath(MAIN_FOLDER)
# nr_steps_path = h.getNrStepsPath(MAIN_FOLDER)


def target(param_names, param_values, model_nr):
    # model_nr = pickle.load(open(nr_steps_path, "rb")) + 1
    # pickle.dump(model_nr, open(nr_steps_path, "wb"))

    s = Settings()

    param_values = list(param_values)

    for i in range(len(param_names)):
        eval('s.{}'.format(param_names[i]))
        if isinstance(param_values[i], str):
示例#36
0
 def onLoadDefault(self):
     self.s = Settings()
     self.showInfo()
示例#37
0
class AppUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("tkSettings")

        # === Menu ===

        self.menubar = tk.Menu(self)

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=menu)
        menu.add_command(command=self.onLoadDefault, label="Load default")
        menu.add_command(command=self.onLoadFile, label="Load file")
        menu.add_separator()
        menu.add_command(command=self.quit, label="Exit")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Edit", menu=menu)
        menu.add_command(command=self.onCleanData, label="Clean data")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Batch import", menu=menu)
        menu.add_command(command=self.onBatch1, label="File to file")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Help", menu=menu)
        menu.add_command(command=self.onAbout, label="About")

        self.config(menu=self.menubar)

        # === Widgets ===

        # Frame with Buttons
        self.frame1 = tk.Frame(self)

        button = tk.Button(self.frame1, text="Settings")
        button.pack()
        button.bind("<Button-1>", self.onShowSettings)

        button = tk.Button(self.frame1, text="Save test data")
        button.pack()
        button.bind("<Button-1>", self.onSaveTestData)

        button = tk.Button(self.frame1, text="Import from module")
        button.pack()
        button.bind("<Button-1>", self.onImportFromModule)

        button = tk.Button(self.frame1, text="Import from module to branch")
        button.pack()
        button.bind("<Button-1>", self.onImportFromModuleToBranch)

        button = tk.Button(self.frame1, text="Import from dir")
        button.pack()
        button.bind("<Button-1>", self.onImportFromDir)

        button = tk.Button(self.frame1, text="Import from dir to branch")
        button.pack()
        button.bind("<Button-1>", self.onImportFromDirToBranch)

        # Text Widget
        dFont1 = Font(family="Courier", size=9)
        self.text1 = tk.Text(self, font=dFont1)
        self.text1_y = tk.Scrollbar(self, orient=tk.VERTICAL,
                                    command=self.text1.yview)
        self.text1['yscrollcommand'] = self.text1_y.set

        # Status Widget
        self.status = tk.StringVar()
        label1 = tk.Label(self, textvariable=self.status, anchor=tk.W)
        self.setStatus()

        # === Grid widgets ===

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1, minsize=120)
        self.grid_columnconfigure(1, weight=5, minsize=400)
        self.grid_columnconfigure(2)

        self.frame1.grid(row=0, column=0, sticky='nwes')
        self.text1.grid(row=0, column=1, sticky='nwes')
        self.text1_y.grid(row=0, column=2, sticky='nwes')

        self.grid_rowconfigure(1)
        label1.grid(row=1, column=0, columnspan=4, sticky='nwes')

        # === Initial ===

        self.onLoadDefault()

    def appendText(self, text=""):
        self.text1.insert(tk.INSERT, "{0}\n".format(plain(text)))

    def setText(self, text=""):
        self.text1.delete(1.0, tk.END)
        self.appendText(text)

    def setStatus(self, text=""):
        status = sys.executable
        if text:
            status += " :: " + text
        self.status.set(status)

    def showInfo(self):
        self.setText("System:")
        self.appendText(self.s.get_systems())
        self.appendText("Settings:")
        self.appendText(self.s.get_dict())
        self.setStatus(self.s.get_filename())

    # === From menu ===

    def onAbout(self):
        text = """{0}\n{1}\nVersion {2}\n
Python: {3}
Package: {4}
""".format(__pkgname__, __description__, __version__,
           sys.version, __package__)
        showinfo("About", text)

    def onLoadDefault(self):
        self.s = Settings()
        self.showInfo()

    def onLoadFile(self):
        initialdir = os.path.expanduser("~")
        filename = askopenfilename(initialdir=initialdir, filetypes=[
                       ('Config files', '*.pickle'),
                       ('All files', '*.*'),
                   ])
        if filename:
            self.s = Settings(filename=filename)
            self.showInfo()

    def onCleanData(self):
        response = askquestion("Clean data", "Are you sure you want to "
                   "permanently delete all information from the config?")
        if response == 'yes':
            self.s.clean()
            self.showInfo()

    def onBatch1(self):
        dfilename = askdirectory()
        if dfilename:

            pickles = []
            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    basename = os.path.basename(filename)
                    root, ext = os.path.splitext(basename)
                    logging.debug(root)
                    BRANCH = Settings(root)
                    pickles.append(BRANCH.get_filename())

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            message = "Processed pickles:\n" + plain(pickles) + "\n\n" +\
                      "Note: Empty pickles was not created!"
            showinfo("Info", message)
            self.setText()
            self.setStatus()

    # === From buttons ===

    def onShowSettings(self, event):
        propertyDialog(self.s.get_dict())

    def onSaveTestData(self, event):
#       answer = YesNoDialog(self.s.get_dict(), "Would you like append new data?")

        self.s.saveEnv()
        self.s.set_path('test_instance', '$')
        self.s.set_path('test_home',     '~')
        self.s.set_path('test_location', '~~',  True)
        self.s.set_path('test_app',      '~~~', True)
        self.showInfo()

    def onImportFromModuleToBranch(self, event):
        self.onImportFromModule(event, tobranch=True)

    def onImportFromModule(self, event, tobranch=False):
        filename = askopenfilename(filetypes=[
                       ('Python files', '*.py'),
                       ('All files', '*.*'),
                   ])
        if filename:
            module = import_file(filename)
            if module:
                if tobranch:
                    branch = module.__name__
                    BRANCH = self.s.get_group(branch)
                else:
                    BRANCH = self.s

                for i in dir(module):
                    if i[0] != '_':
                        value = getattr(module, i)

                        # Словари объединяем
                        if isinstance(value, dict) and isinstance(BRANCH.get(i), dict):
#                           value1 = BRANCH.get(i)
#                           value1.update(value)
#                           BRANCH.set(i, value1)
                            BRANCH.update(value)

                        elif isinstance(value, all_types):
                            BRANCH.set(i, value)

                self.showInfo()

    def onImportFromDirToBranch(self, event):
        self.onImportFromDir(event, tobranch=True)

    def onImportFromDir(self, event, tobranch=False):
        dfilename = askdirectory()
        if dfilename:
            basename = os.path.basename(dfilename)
            logging.debug(basename)
            ROOT = self.s   # Settings(basename)

            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    if tobranch:
                        branch = module.__name__
                        BRANCH = self.s.get_group(branch)
                    else:
                        BRANCH = self.s

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            self.showInfo()
示例#38
0
class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""

        pygame.init()

        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        # Full screen
        # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Alien Invasion")

        # Create an instance to store game statistics, and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        self._start_event_handler()

        # MAke the play button
        self.play_button = Button(self, "Play")

    def _start_event_handler(self):
        """Start event handler"""
        self.event_handler = EventHandler()
        self._add_accepted_event_types()
        self._add_accepted_key_down_type()
        self._add_accepted_key_up_type()

    def _add_accepted_event_types(self):
        """Add available event types"""
        self.event_handler.register_types({
            pygame.QUIT:
            EventType(sys.exit, False),
            pygame.KEYDOWN:
            EventType(self._check_keydown_events, True),
            pygame.KEYUP:
            EventType(self._check_keyup_events, True),
            pygame.MOUSEBUTTONDOWN:
            EventType(self._check_play_button, False),
        })

    def _add_accepted_key_down_type(self):
        self.event_handler.register_key_down_actions({
            pygame.K_RIGHT:
            self.ship.move_right,
            pygame.K_LEFT:
            self.ship.move_left,
            pygame.K_UP:
            self.ship.move_up,
            pygame.K_DOWN:
            self.ship.move_down,
            pygame.K_SPACE:
            self._fire_bullet,
            pygame.K_q:
            sys.exit,
        })

    def _add_accepted_key_up_type(self):
        self.event_handler.register_key_up_actions({
            pygame.K_RIGHT:
            self.ship.stop_move_right,
            pygame.K_LEFT:
            self.ship.stop_move_left,
            pygame.K_UP:
            self.ship.stop_move_up,
            pygame.K_DOWN:
            self.ship.stop_move_down,
        })

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets"""
        # Update bullets position
        self.bullets.update()

        self._clear_bullets()

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """Respond to bullet-alien collisions."""
        # Remove any bullets and aliens that have collided.
        collisions = pygame.sprite.groupcollide(self.bullets,
                                                self.aliens,
                                                dokilla=True,
                                                dokillb=True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()

        if not self.aliens:
            # Destroy existing bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level.
            self.stats.level += 1
            self.sb.prep_level()

    def _clear_bullets(self):
        """Get rid of bullets that have disappeared."""
        for b in self.bullets.copy():
            if b.rect.bottom <= 0:
                self.bullets.remove(b)

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        # Redraw the screen during each pass though the loop
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for b in self.bullets.sprites():
            b.draw_bullet()
        self.aliens.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        # Draw the play button if the game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()

        # Make the most recently drawn screen visible.
        pygame.display.flip()

    def _check_events(self):
        """Respond to key presses and mouse events"""
        for event in pygame.event.get():
            self.event_handler.execute_event(event)

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        self.event_handler.execute_key_up(event.key)

    def _check_keydown_events(self, event):
        """Respond to key presses."""
        self.event_handler.execute_key_down(event.key)

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _create_fleet(self):
        """Create the fleet of aliens"""
        alien_height, number_aliens_x = self._get_alien_height_and_number_of_aliens_per_line(
        )

        number_rows = self._get_number_of_rows_of_aliens_based_on_alien_height(
            alien_height)

        # Create the full fleet of aliens
        for row in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._creat_alien(alien_number, row)

    def _get_number_of_rows_of_aliens_based_on_alien_height(
            self, alien_height):
        """Base on screen height and alien height, calculate how many line of aliens we can have."""
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)
        return number_rows

    def _get_alien_height_and_number_of_aliens_per_line(self):
        """
        Get alien size, calculate the number of aliens that fit in one row
        and return the height of alien and the number.
        """
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)
        return alien_height, number_aliens_x

    def _creat_alien(self, alien_number, row_number):
        """Create an alien and place it in the row."""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien_height + 2 * alien_height * row_number
        self.aliens.add(alien)

    def _update_aliens(self):
        """
        Check if the fleet is at an edge, then update the positions of all aliens in the fleet
        """
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Look for aliens hitting the bottom of the screen
        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens have reached and edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        """Respond to the ship being hit by an alien."""

        if self.stats.ships_left > 0:

            # Decrement ships_left.
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                self._ship_hit()
                break

    def _check_play_button(self):
        """Start a new game when the player clicks Play."""
        mouse_pos = pygame.mouse.get_pos()
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset the game settings
            self.settings.initialize_dynamic_settings()

            # Reset the game statistics
            self.stats.reset_stats()

            self.stats.game_active = True

            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)
示例#39
0
def get_grid():
    s = Settings()
    h = Helper(s)

    ip = []
    gt = []
    an = []

    nrs = np.array([
        70, 21, 95, 73, 78, 26, 38, 82, 47, 40, 66, 59, 13, 89, 71, 88, 37, 22,
        84, 10, 97, 68, 65, 48, 45
    ])

    d = np.array([
        0.9009270902037788, 0.9104197765530493, 0.9128334854875481,
        0.8607061285160114, 0.726180976928685, 0.7618735476244846,
        0.8426088283800738, 0.9227242238885163, 0.9267448462842333,
        0.8202146853529186, 0.9124323842524247, 0.8758631939535643,
        0.8686964143471794, 0.9156216299184503, 0.9226021312080136,
        0.8982460315886207, 0.9316061013262126, 0.8248859357030646,
        0.8955985800466059, 0.7870071142712975, 0.6458948916498899,
        0.9089561365052262, 0.9061868164772646, 0.8842184960264304,
        0.8842468629005924
    ])
    nrs = np.flip(nrs[np.argsort(d)], 0)

    for nr in nrs:
        path = '{}input_image_{}_-1.nii'.format(
            h.getModelPredictPath(s.MODEL_NAME), nr)
        im = sitk.GetArrayFromImage(sitk.ReadImage(path))
        ip.append(im)

        path = '{}anno_image_{}_-1.nii'.format(
            h.getModelPredictPath(s.MODEL_NAME), nr)
        im = sitk.GetArrayFromImage(sitk.ReadImage(path))
        gt.append(im)

        path = '{}prob_thresh_image_{}_-1.nii'.format(
            h.getModelPredictPath(s.MODEL_NAME), nr)
        im = sitk.GetArrayFromImage(sitk.ReadImage(path))
        an.append(im)

    grid_all = []

    yx_size = (200, 200)

    for i in range(len(nrs)):
        # nz = np.argwhere(np.sum(gt[i], axis=(1, 2)) > 0)
        # nz = list(np.reshape(nz, nz.shape[:1]))
        # print(nz)
        # s = nz[int(round(len(nz) * perc))]
        # print(s)
        s = 44
        filter = sitk.LabelShapeStatisticsImageFilter()
        filter.Execute(sitk.GetImageFromArray(gt[i][s]))
        center = list(reversed(filter.GetCentroid(1)))

        # print(np.min(n))
        # print(np.max(n))
        ip_rgb = grey2rgb(ip[i][s])
        cropped = crop_around(ip_rgb, yx_size, center)
        cropped = normalize(cropped)
        gt_cropped = crop_around(gt[i][s], yx_size, center)
        an_cropped = crop_around(an[i][s], yx_size, center)
        gt_masked = get_mask_overlay(cropped, gt_cropped, [1, 0, 0], 0.5)
        gt_an_masked = get_mask_overlay(gt_masked, an_cropped, [0, 1, 0], 0.5)

        gt_an_masked = np.pad(gt_an_masked, ((10, 10), (10, 10), (0, 0)),
                              mode='constant',
                              constant_values=255)
        grid_all.append(gt_an_masked)
        # grid_all.append(crop_around(ip_rgb, yx_size, center))
        # grid_all.append(crop_around(get_mask_overlay(ip_rgb, gt[i][s]), yx_size, center))
        # grid_all.append(crop_around(get_mask_overlay(ip_rgb, an[i][s]), yx_size, center))

        print(grid_all[-1].shape)

    grid_size = [5, 5]

    print(len(grid_all))

    rows = []
    for y in range(grid_size[1]):
        print(y)
        rows.append(
            np.concatenate(grid_all[y * grid_size[0]:y * grid_size[0] +
                                    grid_size[0]],
                           axis=1))
    img_out = np.concatenate(rows, axis=0)

    return img_out