Esempio n. 1
0
    def __init__(self, *args, **kwargs):
        QtGui.QMainWindow.__init__(self, *args, **kwargs)

        self._app = Application.instance()

        title = "ChromaClub"
        if self._app.isTestNet:
            title += " [testnet]"
        title += " - " + clubAsset['monikers'][0]
        self.setWindowTitle(title)
        self.setWindowIcon(QtGui.QIcon(':icons/chromaclub.png'))
        self.resize(900, 550)
        self.move(Application.instance().desktop().screen().rect().center() - self.rect().center())
        self.setCentralWidget(QtGui.QStackedWidget())

        self.overviewpage = OverviewPage(self)
        self.sendpage = SendPage(self)
        self.chatpage = ChatPage(self)
        self.centralWidget().addWidget(self.overviewpage)
        self.centralWidget().addWidget(self.sendpage)
        self.centralWidget().addWidget(self.chatpage)

        self._create_actions()
        self._create_menu_bar()
        self._create_tool_bar()
        self._create_status_bar()
        self._create_tray_icon()
        self._create_tray_icon_menu()

        self._app.statusChanged.connect(self._status_changed)
Esempio n. 2
0
    def test_not_in_team(self):
        # Mock Application.fetch_name_from_file
        Application.fetch_name_from_file = mock.Mock()
        Application.fetch_name_from_file.return_value = 'Krishna'

        app = Application()
        self.assertFalse(app.is_in_team())
Esempio n. 3
0
    def test_in_team(self):
        # Mock Application.fetch_name_from_file
        Application.fetch_name_from_file = mock.Mock()
        Application.fetch_name_from_file.return_value = 'Apurva'

        app = Application()
        self.assertTrue(app.is_in_team())
	def recibeVideo(self):
		connection = Application.getInstance().getConnection()
		while not self.closedInterface.is_set() and connection != None:
			start = time.time()
			frameTime = 1/self.fpsOutput

			if connection.isRunning():
				try: 
					msg = connection.rcv()
					frame = msg['image']
					self.fpsInput = msg['fps']
					self.inputResolution = msg['resolution']
					img_tk = ImageTk.PhotoImage(frame)
					# Lo mostramos en el GUI
					self.app.setImageData('receivedVideoImage', img_tk, fmt = 'PhotoImage')
					self.app.setImageWidth('receivedVideoImage', self.inputResolution[0])
					self.app.setImageHeight('receivedVideoImage', self.inputResolution[1])

					self.app.setStatusbar('Recibiendo a {}x{}/{} fps.'.format(self.inputResolution[0], self.inputResolution[1], msg['fps']), field=0)
					self.app.setStatusbar('Retraso de {:+.3f} segundos.'.format(time.time() - msg['timestamp']), field=1)
					self.app.setStatusbar('Duracion de la llamada: {} segundos'.format(utils.timedeltaToStr(time.time() - self.timeCallStarted)), field=2)

				except BlockingIOError as e:
					# No recibimos datos
					self.app.setImage('receivedVideoImage', 'imgs/user_icon.gif')
				except TypeError as e:
					# timeCallStarted es None por haber sido cambiado en otro hilo al cerrarse la llamada
					pass

			# Pausamos el tiempo necesario para cuadrar los fps
			pauseTime = frameTime + start - time.time() # frameTime - (time.time() - start)
			if pauseTime < 0:
				continue
			time.sleep(pauseTime)
			connection = Application.getInstance().getConnection()
	def login(self, button):
		# Nos registramos / logeamos en el servidor de descubrimiento
		password = self.app.getEntry('loginPasswordEntry')
		if not password:
			self.notifyLogin('Es necesario que introduzcas una contraseña.')
		
		self.notifyLogin('Consultando información con el servidor.')
		# Deshabilitamos los botones mientras consultamos en el servidor para evitar 
		# posibles errores al pulsar varias veces
		self.app.queueFunction(self.app.disableButton, 'Register user')
		self.app.queueFunction(self.app.disableButton, 'Login')

		user = getUserInfo()
		if user == None:
			self.notifyLogin('Ha habido un error, el usuario no esta almacenado. Es necesario que se registre')
			self.app.queueFunction(self.app.hideLabelFrame, 'Login')
			return
			
		tmp = identityGestion.registerUser(user.nick, user.ip, user.port, password, '#'.join(user.protocols))
		if tmp != None:
			# La contraseña es correcta, acabamos
			Application.getInstance().setUser(tmp)
			Application.getInstance().startControlConnection(tmp.ip, tmp.port)
			# La conexión de control se encarga de mostrar o no la pantalla principal
		else:
			# Volvemos a habilitar los botones
			self.app.queueFunction(self.app.enableButton, 'Register user')
			self.app.queueFunction(self.app.enableButton, 'Login')
			self.notifyLogin('La contraseña es incorrecta o el usuario ya no existe.')
	def stop(self, signal=None, _=None):
		# Al hacer sys.exit(0), es posible que el manejador de Ctrl+C llame a la funcion
		# En ese caso, ya se habrá cerrado todo. Así evitamos fallos.
		if self.closedInterface.is_set():
			return True

		print('Cerramos la aplicacion')
		self.closedInterface.set()
		try:
			# Dejamos tiempo para que los hilos de mostrar video acaben
			self.notify('Cerrando la aplicación.')
			time.sleep(1)

			# Liberamos el archivo de video usado
			if not self.usingCamera.is_set():
				self.cap.release()

			connection = Application.getInstance().getConnection()
			if connection != None:
				user = connection.dstUser
				# Colgamos la llamada con el usuario
				self.notify('Finalizando la llamada.')
				Application.getInstance().getControlConnection().endCall()
				self.closeCallWindow()

			self.notify('Cerrando la conexión de control.')
			Application.getInstance().getControlConnection().quit()
			self.app.queueFunction(sys.exit, 0)
			return True
		except Exception as e:
			self.logger.exception('VideoClient - Error al cerrar: '+str(e))
			self.app.queueFunction(sys.exit, 0)
Esempio n. 7
0
def main():
    LogHelper.start_logging("logdownloader.log")
    parser = argparse.ArgumentParser(
        description="AWS bootstrapper log downloader" +
        "Downloads instances logs from AWS S3")
    parser.add_argument(
        "--manifestPath",
        help=
        "path to a manifest file describing the jobs and data requirements for the application",
        required=True)
    parser.add_argument("--outputPath",
                        help="directory to where instance logs will be copied",
                        required=True)

    try:
        args = vars(parser.parse_args())
        manifestPath = os.path.abspath(args["manifestPath"])
        outputdir = os.path.abspath(args["outputPath"])
        s3 = boto3.resource('s3')
        app = Application(s3, manifestPath, outputdir)
        app.downloadLogs(outputdir)

    except Exception as ex:
        logging.exception("error in log downloader")
        sys.exit(1)
Esempio n. 8
0
def main():

    parser = ArgumentParser(description=
        'MegaMinerAI PyVis - Python Implementation of the Visualizer')
    parser.add_argument('glog', type=str, nargs='*', 
            help='Optional glogs to open in the visualizer.')
    parser.add_argument('-f', dest='fullscreen', action='store_true', 
            help='Start in fullscreen mode')
    parser.add_argument('-a', dest='arena', metavar='server', type=str, nargs=1, 
            help='Enables arena mode querying from the given url')
    parser.add_argument('-s', dest='spectate', 
            metavar=('server', 'gamenumber'), nargs=2, type=str, 
            help='Spectates on gamenumber at server.')

    args = parser.parse_args()

    app = Application(fullscreen=args.fullscreen)
    '''
    renderer = Renderer()
    renderer.register_with_app(app)
    app.request_update_on_draw(Test(renderer).update)

    r = Renderer.Rectangle(1, 2, 20, 30, renderer=renderer)
    try:
        r = Renderer.Rectangle(40, 40, 20, 30)
    except:
        pass
    '''

    app.run(args.glog)
Esempio n. 9
0
def main(args=None):
    """
    The main routine
    """

    app = Application()
    app.run()
Esempio n. 10
0
 def test_detail_url(self):
     self.print_header()
     oracle = Application({
         'host_name': 'test',
         'name': 'test',
         'type': 'generic',
     })
     url = MonitoringDetail({
         'host_name': 'test',
         'application_name': 'test',
         'application_type': 'generic',
         'monitoring_type': 'URL',
         'monitoring_0': 'oracle://*****:*****@dbsrv:1522/svc',
     })
     oracle.monitoring_details.append(url)
     oracle.resolve_monitoring_details()
     self.assert_(len(oracle.urls) == 1)
     # consol app_db_oracle class will call wemustrepeat() to create
     # a fake LOGIN-detail, so there is a oracle.username
     self.assert_(oracle.urls[0].username == 'dbadm')
     self.assert_(oracle.urls[0].password == 'pass')
     self.assert_(oracle.urls[0].hostname == 'dbsrv')
     self.assert_(oracle.urls[0].port == 1522)
     # will be without the / in the consol app_db_oracle class
     self.assert_(oracle.urls[0].path == '/svc')
Esempio n. 11
0
    def test_not_a_dir(self):
        conf = copy.copy(self.DUMMY_CONF)
        conf['temp_dir'] = 'nonexistentdir'
        with self.assertRaises(ConfigurationException):
            app = Application(
                BASE_DIR,
                args_parser.parse_args([
                    '-c',
                    os.path.join('conf_files', 'dummy_file'), 'version'
                ]), conf)

        conf = copy.copy(self.DUMMY_CONF)
        conf['out_dir'] = 'nonexistentdir'
        with self.assertRaises(ConfigurationException):
            app = Application(
                BASE_DIR,
                args_parser.parse_args([
                    '-c',
                    os.path.join('conf_files', 'dummy_file'), 'version'
                ]), conf)

        conf = copy.copy(self.DUMMY_CONF)
        conf['log_dir'] = 'nonexistentdir'
        with self.assertRaises(ConfigurationException):
            app = Application(
                BASE_DIR,
                args_parser.parse_args([
                    '-c',
                    os.path.join('conf_files', 'dummy_file'), 'version'
                ]), conf)
Esempio n. 12
0
    def reload(self, reset=True):
        '''
        The reload function reloads the application and its reconstruction
        This allows for updating the code while the GUI is active
        This function does not reload the
        :return:
        '''
        try:
            self.disconnect()
            import application
            self.logger.warning("Reloading Application")
            importlib.reload(application)
            from application import Application
            if reset:
                # create a new empty application
                self.app = Application(gui=self, logger=self.logger)
            else:
                # or create a copy of the existing application, but with functionality that is reloaded
                self.app = Application.create_copy(application=self.app)
            # add the new application for all widgets that use it
            self.macro_photo_widget.set_app(self.app)
            self.slice_photo_widget.set_app(self.app)
            self.slice_table_widget.set_app(self.app)
            self.coupe_table_widget.set_app(self.app)
            # reconnect buttons:
            self.connect()
            # and update the gui
            self.update()

        except:
            print(sys.exc_info()[0])
            print(traceback.format_exc())
            pass
Esempio n. 13
0
 def __init__(self, environ, app_cores, client_cores, nice=0, instance=1, size='train'):
     Application.__init__(self, environ, 'Spec', client_cores, app_cores, nice, instance)
     self._size = size
     self._load_params = [self._bmark_name, self._size]
     self._cleanup_params = [self._bmark_name]
     self._run_params = [self._bmark_name, self._size, '0']
     self._interfere_params = [self._bmark_name, self._size, '1']
Esempio n. 14
0
 def show_application(self, application, fullscreen, context):
     """
     Render <application> widget with the given name and the given context.
     """
     if isinstance(application, (str, unicode)):
         tmp = self.theme.application.get(application)
         if not tmp:
             return log.error('no application named %s', application)
         application = tmp(size=self.size, context=context)
         self.add_layer(application, sibling=self.applications_idx)
     elif application is None:
         application = Application(self.size, [], context=context)
         self.add_layer(application, sibling=self.applications_idx)
     else:
         application.visible = True
         self.applications.remove(application)
     # TODO: add show/hide/remove/unparent/whatever here
     for l in self.layer:
         l.visible = not fullscreen
         if l == self.applications_idx:
             break
     if self.applications:
         self.applications[-1].visible = False
     self.applications.append(application)
     return application
Esempio n. 15
0
class MainApplication(tk.Tk):
    """Container for all frames within the application"""

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # initialize menu
        self.config(menu=MenuBar(self))
        self.title("FIFA 16 Auto Buyer")
        self.geometry("950x650-5+40")
        self.minsize(width=650, height=450)

        # bind ctrl+a
        if platform == "darwin":
            self.bind_class("Entry", "<Command-a>", self.selectall)
        else:
            self.bind_class("Entry", "<Control-a>", self.selectall)

        self.status = StatusBar(self)
        self.status.pack(side="bottom", fill="x")
        self.status.set_credits("0")

        self.appFrame = Application(self)
        self.appFrame.pack(side="top", fill="both", expand="True")

    def selectall(self, e):
        e.widget.select_range(0, tk.END)
        return "break"
Esempio n. 16
0
class MainApplication(tk.Tk):
    """Container for all frames within the application"""

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        #initialize menu
        self.config(menu=MenuBar(self))
        self.title('FIFA 17 Auto Buyer')
        self.geometry('950x650-5+40')
        self.minsize(width=650, height=450)

        # bind ctrl+a
        if(platform == 'darwin'):
            self.bind_class("Entry", "<Command-a>", self.selectall)
        else:
            self.bind_class("Entry", "<Control-a>", self.selectall)

        self.status = StatusBar(self)
        self.status.pack(side='bottom', fill='x')
        self.status.set_credits('0')

        self.appFrame = Application(self)
        self.appFrame.pack(side='top', fill='both', expand='True')

    def selectall(self, e):
        e.widget.select_range(0, tk.END)
        return 'break'
Esempio n. 17
0
class MainApplication(tk.Tk):
    """Container for all frames within the application"""

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        #initialize menu
        self.config(menu=MenuBar(self))
        self.title('FIFA 16 Auto Buyer')
        self.geometry('850x650-5+40')
        self.minsize(width=650, height=450)

        # bind ctrl+a
        if(platform == 'darwin'):
            self.bind_class("Entry", "<Command-a>", self.selectall)
        else:
            self.bind_class("Entry", "<Control-a>", self.selectall)

        self.status = StatusBar(self)
        self.status.pack(side='bottom', fill='x')
        self.status.set_credits('0')

        self.appFrame = Application(self)
        self.appFrame.pack(side='top', fill='both', expand='True')

    def selectall(self, e):
        e.widget.select_range(0, tk.END)
        return 'break'
Esempio n. 18
0
    def test_get_json_should_return_expected_json(self):
        id = 66
        name = "name"
        available_version = "available_version"
        download_location = "download_location"
        relitive_install_path = "relitive_install_path"
        executable_path = "executable_path"
        installed_path = "installed_path"
        icon = "icon"
        current_version = "current_version"
        shortcut_path = "shortcut_path"
        app = Application(id, name, available_version, download_location,
                          relitive_install_path, executable_path,
                          installed_path, icon, current_version, shortcut_path)
        expected_json = {
            "id": 66,
            "name": {
                "en-us": "name",
            },
            "available_version": "available_version",
            "download_location": "download_location",
            "relitive_install_path": "relitive_install_path",
            "executable_path": "executable_path",
            "installed_path": "installed_path",
            "icon": "icon",
            "current_version": "current_version",
            "shortcut_path": "shortcut_path",
        }

        actual = json.loads(app.get_json())
        self.assertEquals(expected_json, actual)
Esempio n. 19
0
def do_test_2():
    "2nd Watsup Test"
    filename = 'atestfile.txt'

    if os.path.exists(filename):
        os.remove(filename)

    app = Application()
    try:
        app.connect_(title ='Simple Form')
    except WindowNotFoundError:
        app.start_(r'examples\simple.exe')

    form = app.SimpleForm

    form.Edit.SetText(filename)
    sleep(.6)

    print 'clicking button to create file'
    form.CreateFile.Click()

    # now check that the file is there
    if os.path.exists(filename):
        print 'file %s is present' % filename
    else:
        print "file %s isn't there" % filename

    form.MenuSelect("File->Exit")
Esempio n. 20
0
def main():
    parse_command_line()
    app = Application()
    port = int(os.environ.get('PORT', 8888))
    app.listen(port)
    print('Run server on port: {}'.format(port))
    tornado.ioloop.IOLoop.current().start()
Esempio n. 21
0
class Main_Menu:

    def __init__(self):
        self.app = Application()
        self.app.load()
        self.options = {
            "1.": self.app.sign_up,
            "2.": self.app.sign_in,
        }
    
    def display_options(self):
        print(""" 
            ************* MAIN MENU *************
             Welcome to CheapFlights! 
             Please choose one of the options below:
 
             1. Create an account
             2. Sign in to your account
             Q. Quit
             """)
    def run(self):
        while True:
            self.display_options()
            option = input("Enter an option: ")
            if option.lower() == "q":
                print("JSON file has been saved to account.json file")
                self.app.save()
                break

            action = self.options.get(option)
            if action:
                action()
            else:
                print("{0} is not a valid option, please try again!".format(option))         
Esempio n. 22
0
 def __init__(self):
     self.app = Application()
     self.app.load()
     self.options = {
         "1.": self.app.sign_up,
         "2.": self.app.sign_in,
     }
Esempio n. 23
0
    def __init__(self, *args, **kwargs):
        QtGui.QMainWindow.__init__(self, *args, **kwargs)

        self._app = Application.instance()

        title = "ChromaClub"
        if self._app.isTestNet:
            title += " [testnet]"
        title += " - " + clubAsset['monikers'][0]
        self.setWindowTitle(title)
        self.setWindowIcon(QtGui.QIcon(':icons/chromaclub.png'))
        self.resize(900, 550)
        self.move(Application.instance().desktop().screen().rect().center() -
                  self.rect().center())
        self.setCentralWidget(QtGui.QStackedWidget())

        self.overviewpage = OverviewPage(self)
        self.sendpage = SendPage(self)
        self.chatpage = ChatPage(self)
        self.centralWidget().addWidget(self.overviewpage)
        self.centralWidget().addWidget(self.sendpage)
        self.centralWidget().addWidget(self.chatpage)

        self._create_actions()
        self._create_menu_bar()
        self._create_tool_bar()
        self._create_status_bar()
        self._create_tray_icon()
        self._create_tray_icon_menu()

        self._app.statusChanged.connect(self._status_changed)
    def place_containers_with_group(self, app: Application, existing_group):
        print("App {} requires {} containers".format(app, app.n_containers))

        if existing_group == -1:
            print("No preferred group to schedule with, check if can schedule on slot 1")
            chosen_slot = JobGroupData.SLOT_1
            if self.cluster.has_application_running():
                print("There are already job running, scheduling on slot 2")
                chosen_slot = JobGroupData.SLOT_2
            app.cluster_slot = chosen_slot
            for address,node in self.cluster.nodes.items():
                if JobGroupData.cluster_slots_index[address] == chosen_slot:
                    self._place(app, node, 4)
        else:
            print("The chosen existing group to co-locate is: {}".format(existing_group))
            co_located_app = None
            running_apps, running_apps_weight = self.cluster.applications(with_full_nodes=False, by_name=True)
            #print(running_apps.__str__())
            for running_app in running_apps:
                if JobGroupData.groupIndexes[running_app.name] == existing_group:
                    print("Choose app {} of group {} to co-locate".format(running_app.name, existing_group))
                    co_located_app = running_app
                    break
            if co_located_app is not None:
                print("The chosen slot to place new job is {}".format(co_located_app.cluster_slot))
                app.cluster_slot = co_located_app.cluster_slot
                for address, node in self.cluster.nodes.items():
                    #print(co_located_app.nodes)
                    #print(address)
                    if address in co_located_app.nodes:
                        self._place(app, node, 4)
Esempio n. 25
0
    def __init__(self, pkg, cfg):
        Application.__init__(self, pkg, cfg)
        self.type_id = u'codec'
        self.requires_appdata = True
        self.categories = []
        self.cached_icon = False
        self.icon = 'application-x-executable'
        self.categories.append(u'Addons')
        self.categories.append(u'Codecs')

        # use the pkgname as the id
        app_id = pkg.name
        app_id = app_id.replace('gstreamer1-', '')
        app_id = app_id.replace('gstreamer-', '')
        app_id = app_id.replace('plugins-', '')
        self.set_id('gstreamer-' + app_id)

        # map the ID to a nice codec name
        self.codec_name = {}
        csvfile = open('../data/gstreamer-data.csv', 'r')
        data = csv.reader(csvfile)
        for row in data:
            if row[1] == '-':
                continue
            codec_id = row[0][31:-3]
            self.codec_name[codec_id] = row[1].split('|')
        csvfile.close()
Esempio n. 26
0
def test3(mocked_method):
    app = Application()
    # vytiskneme informaci o tom, zda se mockovaná metoda zavolala
    print("mocked method called: {c}".format(c=mocked_method.called))
    print("method1 returns: {v}".format(v=app.method1()))
    # opět vytiskneme informaci o tom, zda se mockovaná metoda zavolala
    print("mocked method called: {c}".format(c=mocked_method.called))
Esempio n. 27
0
def main():
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s - %(filename)s[line:%(lineno)d] '
                        '- %(levelname)s: %(message)s',
                        filename='server.log')
    game = Application([UserService, ChatService, GameService])
    game.run()
Esempio n. 28
0
    def setUp(self):
        self.generator = Generator()
        self.generator.setup_logging()
        self.hosts = {}
        self.applications = {}
        Application.init_classes([
            os.path.join(os.path.dirname(__file__), '../recipes/default/classes'),
            os.path.join(os.path.dirname(__file__), 'recipes/test10/classes')])
        MonitoringDetail.init_classes([
            os.path.join(os.path.dirname(__file__), '../recipes/default/classes'),
            os.path.join(os.path.dirname(__file__), 'recipes/test10/classes')])
        pass
        row = ['drivelsrv', '11.120.9.10', 'Server', 'Red Hat 6.0', '', 'vs', '7x24', '2nd floor', 'ps']
        final_row = { }
        for (index, value) in enumerate(['host_name', 'address', 'type', 'os', 'hardware', 'virtual', 'notification_period', 'location', 'department']):
            final_row[value] = [None if row[index] == "" else row[index]][0]
        h = Host(final_row)
        self.hosts[h.host_name] = h

        row = ['drivel', 'mysql', '', '', '', 'drivelsrv', '7x24']
        final_row = { }
        for (index, value) in enumerate(['name', 'type', 'component', 'version', 'patchlevel', 'host_name', 'check_period']):
            final_row[value] = [None if row[index] == "" else row[index]][0]
        a = Application(final_row)
        #a.__init__(final_row)
        self.applications[a.fingerprint()] = a
        setattr(a, "host", self.hosts[a.host_name])
Esempio n. 29
0
 def stop(self):
   """Stop the instance by pid. By the default
   the signal is 15."""
   Application.stop(self)
   if socketStatus(self.hostname, self.port):
     self._releaseOpenOfficePort()
   self._cleanRequest()
Esempio n. 30
0
 def start(self):
   """Start Instance."""
   self.path_user_installation = join(self.path_run_dir, \
       "cloudooo_instance_%s" % self.port)
   if exists(self.path_user_installation):
     removeDirectory(self.path_user_installation)
   # Create command with all parameters to start the instance
   self.command = [join(self.office_binary_path, self._bin_soffice),
        '-headless',
        '-invisible',
        '-nocrashreport',
        '-nologo',
        '-nodefault',
        '-norestore',
        '-nofirststartwizard',
        '-accept=socket,host=%s,port=%d;urp;' % (self.hostname, self.port),
        '-env:UserInstallation=file://%s' % self.path_user_installation,
        '-language=%s' % self.default_language,
        ]
   # To run soffice.bin, several environment variables should be set.
   env = self.environment_dict.copy()
   env.setdefault("LANG", "en_US.UTF-8")
   env["HOME"] = self.path_user_installation
   env["TMP"] = self.path_user_installation
   env["TMPDIR"] = self.path_user_installation
   self._startProcess(self.command, env)
   self._cleanRequest()
   Application.start(self)
Esempio n. 31
0
    def __init__(self, doc):
        self.doc = doc
        self.type = ""  # this variable will be changed when we press any button regarding what type to

        self.handler = ManageAccounts(doc)
        self.handler.getData()
        self.application = Application(self.handler.getAccounts())
Esempio n. 32
0
 def __init__(self, pkg, cfg):
     Application.__init__(self, pkg, cfg)
     self.type_id = 'inputmethod'
     self.categories = [ 'Addons', 'InputSources' ]
     self.icon = 'system-run-symbolic'
     self.cached_icon = False
     self.requires_appdata = True
Esempio n. 33
0
 def stop(self):
   """Stop the instance by pid. By the default
   the signal is 15."""
   Application.stop(self)
   if socketStatus(self.hostname, self.port):
     self._releaseOpenOfficePort()
   self._cleanRequest()
Esempio n. 34
0
def post_init():
    app = Application()
    init_result = app.init()
    if not init_result:
        reactor.stop()
        return
    app.app_logger.info("main loop ...")
Esempio n. 35
0
def _process_files(mediafile, subtitlesfile):
	print "Processing the files now .." 
	print "Media File --> " + mediafile
	print "Subtitles File -->"  + subtitlesfile
	
	application = Application(mediafile, subtitlesfile)
	application.speech_recognition()
Esempio n. 36
0
 def show_application(self, application, fullscreen, context):
     """
     Render <application> widget with the given name and the given context.
     """
     if isinstance(application, (str, unicode)):
         tmp = self.theme.application.get(application)
         if not tmp:
             return log.error('no application named %s', application)
         application = tmp(size=self.size, context=context)
         self.add_layer(application, sibling=self.applications_idx)
     elif application is None:
         application = Application(self.size, [], context=context)
         self.add_layer(application, sibling=self.applications_idx)
     else:
         application.visible = True
         self.applications.remove(application)
     # TODO: add show/hide/remove/unparent/whatever here
     for l in self.layer:
         l.visible = not fullscreen
         if l == self.applications_idx:
             break
     if self.applications:
         self.applications[-1].visible = False
     self.applications.append(application)
     return application
    def test_get_json_should_return_expected_json(self):
        id = 66
        name = "name"
        available_version = "available_version"
        download_location = "download_location"
        relitive_install_path = "relitive_install_path"
        executable_path = "executable_path"
        installed_path = "installed_path"
        icon = "icon"
        current_version = "current_version"
        shortcut_path = "shortcut_path"
        app = Application(id, name, available_version, download_location, relitive_install_path, executable_path, installed_path, icon, current_version, shortcut_path)
        expected_json = {
                        "id": 66,
                        "name": {
                            "en-us": "name",
                        },
                        "available_version": "available_version",
                        "download_location": "download_location",
                        "relitive_install_path": "relitive_install_path",
                        "executable_path": "executable_path",
                        "installed_path": "installed_path",
                        "icon": "icon",
                        "current_version": "current_version",
                        "shortcut_path": "shortcut_path",
                        }

        actual = json.loads(app.get_json())
        self.assertEquals(expected_json, actual)
Esempio n. 38
0
def APPLY(next, n):
    app = stack.pop()
    args = [stack.pop() for x in range(n)]

    #print app
    #print args
    #print app.arity, n
    if isinstance(
            app,
            Application) and app.args is not None and len(app.args +
                                                          args) >= app.arity:
        #print "apply type 1"
        missing = app.arity - len(app.args)
        app.args.extend(args[:missing])
        apply = lookup(FakeFullyQualifId("", "_apply"))
        #print args, missing, args[:missing], args[missing:]
        for arg in args[missing:]:
            app = Application(apply, [app, arg])
    elif isinstance(app, Application):
        #print "apply type 2"
        app.args.extend(args)
    elif not isinstance(app, Application) and app.arity < n:
        #print "apply type 3"
        app = Application(app, args[:app.arity])
        apply = lookup(FakeFullyQualifId("", "_apply"))
        for arg in args[app.arity:]:
            app = Application(apply, [app, arg])
    else:
        #print "apply type 4"
        app = Application(app, args)
    stack.push(app)
    return next
Esempio n. 39
0
def main():
    options.logging = None
    parse_command_line()
    options.subpath = options.subpath.strip('/')
    if options.subpath:
        options.subpath = '/' + options.subpath

    # Connect to mongodb
    io_loop = ioloop.IOLoop.instance()
    # conn = torndb.Connection(config.DB_HOST + ":" + str(config.DB_PORT),
    # config.DB_NAME, user = config.DB_USER, password = config.DB_PWD)

    # self.conn = conn
    # Star application
    from application import Application
    # app.conn=conn

    if options.unix_socket:
        server = tornado.httpserver.HTTPServer(Application())
        socket = tornado.netutil.bind_unix_socket(options.unix_socket, 0o666)
        server.add_socket(socket)
        print('Server is running at %s' % options.unix_socket)
        print('Quit the server with Control-C')

    else:
        http_server = tornado.httpserver.HTTPServer(Application())
        http_server.listen(options.port)
        print('Server is running at http://127.0.0.1:%s%s' %
              (options.port, options.subpath))
        print('Quit the server with Control-C')

    io_loop.start()
Esempio n. 40
0
 def start(self, init=True):
   """Start Instance."""
   self.path_user_installation = join(self.path_run_dir, \
       "cloudooo_instance_%s" % self.port)
   if init and exists(self.path_user_installation):
     removeDirectory(self.path_user_installation)
   # Create command with all parameters to start the instance
   self.command = [join(self.office_binary_path, self._bin_soffice),
        '-headless',
        '-invisible',
        '-nocrashreport',
        '-nologo',
        '-nodefault',
        '-norestore',
        '-nofirststartwizard',
        '-accept=socket,host=%s,port=%d;urp;' % (self.hostname, self.port),
        '-env:UserInstallation=file://%s' % self.path_user_installation,
        '-language=%s' % self.default_language,
        ]
   # To run soffice.bin, several environment variables should be set.
   env = self.environment_dict.copy()
   env.setdefault("LANG", "en_US.UTF-8")
   env["HOME"] = self.path_user_installation
   env["TMP"] = self.path_user_installation
   env["TMPDIR"] = self.path_user_installation
   self._startProcess(self.command, env)
   self._cleanRequest()
   Application.start(self)
Esempio n. 41
0
def main2():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--date",
        type=str,
        help="The date used to load meetings from RMBS. Format: YYYY-MM-DD",
        required=True)
    parser.add_argument("--noMinWaste",
                        help="If set, then we will skip minWaste optimization",
                        action="store_true")
    parser.add_argument("--debug", action="store_true")
    parser.add_argument("--maxTime",
                        help="Max. resolving time in sec",
                        type=int,
                        default=600)
    args = parser.parse_args()

    _debug = args.debug

    # We have 3 rooms (A, B and C)
    # Use edge to mark which room is next to which
    # g_rooms = networkx.Graph()
    # for rm in list(room_names):
    #    g_rooms.add_node(rm)

    # g_rooms.add_edge("A", "B")
    # g_rooms.add_edge("B", "C")

    rmbs = Rmbs()

    applications = Application.get_applications(rmbs)
    if not applications:
        logger.info("No applications found")
        return

    df_apps = Application.applications_to_df(applications)

    df_apps_too_late = df_apps.query(
        f'status == "{Application.STATUS_TOO_LATE}"')

    # Please note that each app form can apply for multiple days.  Some may succeeed, and some may fail!
    if len(df_apps_too_late) > 0:
        logger.info(f"{len(df_apps_too_late)} found to be too_late")
        Site.send_too_late_bookings_email(df_apps_too_late)

    df_apps = df_apps.query(f'status != "{Application.STATUS_TOO_LATE}"')
    if len(df_apps) == 0:
        logger.info("No more non-too-late found")
        return

    grouped_apps = df_apps.groupby(['event_site', 'event_date'])
    for group_name, df_entries in grouped_apps:
        ret = process_site_applications(area=group_name[0],
                                        rmbs=rmbs,
                                        event_date=group_name[1],
                                        requests=df_entries,
                                        max_resolve_time=args.maxTime,
                                        no_min_waste=args.noMinWaste)
        Application.update_entries_status(df_entries, ret, rmbs)
Esempio n. 42
0
def test3(mocked_method):
    """Použití handleru volaného namísto mockované funkce."""
    app = Application()
    # vytiskneme informaci o tom, zda se mockovaná metoda zavolala
    print("mocked method called: {c}".format(c=mocked_method.called))
    print("method1 returns: {v}".format(v=app.method1()))
    # opět vytiskneme informaci o tom, zda se mockovaná metoda zavolala
    print("mocked method called: {c}".format(c=mocked_method.called))
Esempio n. 43
0
def main():
    app = Application()
    app.initialize()
    for y in range(20):
        for x in range(20):
            app.cellManager.set_alive(x, y, True)
    app.cellManager.next_generation()
    app.window.quit()
Esempio n. 44
0
def test2(mocked_method):
    """Druhý test zjištuje, zda se volala mockovaná metoda či nikoli."""
    app = Application()
    # vytiskneme informaci o tom, zda se mockovaná metoda zavolala
    print("mocked method called: {c}".format(c=mocked_method.called))
    print("method1 returns: {v}".format(v=app.method1()))
    # opět vytiskneme informaci o tom, zda se mockovaná metoda zavolala
    print("mocked method called: {c}".format(c=mocked_method.called))
Esempio n. 45
0
def main(stdscr):
    configs = Configs(host="localhost", port=1488, nport=1489)

    # We must delay all our packages initialization to give native
    # curses chance inialize inteslf properly.
    from application import Application

    app = Application(stdscr, configs)
    app.run()
Esempio n. 46
0
 def init_class_cache(self):
     Datasource.init_classes(self.classes_path)
     logger.debug("init Datasource classes (%d)" % len(Datasource.class_factory))
     Datarecipient.init_classes(self.classes_path)
     logger.debug("init Datarecipient classes (%d)" % len(Datarecipient.class_factory))
     Application.init_classes(self.classes_path)
     logger.debug("init Application classes (%d)" % len(Application.class_factory))
     MonitoringDetail.init_classes(self.classes_path)
     logger.debug("init MonitoringDetail classes (%d)" % len(MonitoringDetail.class_factory))
Esempio n. 47
0
 def _get_app_node(self, network_node, app):
     assert self._lock.locked()
     name = "a%s" % app
     if network_node.has_child(name):
         return network_node.get_child(name)
     # Obviously an app factory based on app id, someday...
     application_node = Application()
     application_node.configure({"parent": network_node, "name": name, "app": app})
     application_node.start()
     return application_node
Esempio n. 48
0
def main():
    app = Application()
    renderer = Renderer()
    renderer.register_with_app(app)
    #app.request_update_on_draw(Test(renderer).update)

    mainWindow = ui.Window(renderer, 50, 50, 300, 400)
    mainWindow.addWidget(ui.Button, x=20, y=20, width=50, height=60, color=(1, 0, 1, 1), text="Example Text")

    app.run()
Esempio n. 49
0
def main(args):
    projectDir = args[2]
    outputDir = args[3]

    print("Moving Assets")

    app = Application(projectDir)
    app.process(outputDir)

    return 0
Esempio n. 50
0
def main():
    "main function"

    root = Tk()

    # set title
    root.title("Visual Dictionary Tree")

    app = Application(root)

    app.mainloop()
Esempio n. 51
0
  def testAppSetup( self ):
    self.assert_( Setting.is_app_setup() == False )
    self.assert_( Application.has_been_setup() == False )

    Setting(
      app_name = 'Foobar',
      app_version = 0.01,
      allow_registration = True
    ).put()

    self.assert_( Setting.is_app_setup() == True )
    self.assert_( Application.has_been_setup() == True )
 def initialize(self):
     try:
         web_config = self._get_web_config()
         for web_app in web_config['applications']:
             file_app = self._get_file_config(web_app['id'])
             if file_app:
                 self._applications.append(Application.from_configs(web_app, file_app))
             else:
                 self._applications.append(Application.from_configs(web_app))
     except ConfigException as cfgex:
         return (False, cfgex.error_code, cfgex.message)
     return (True, "0", "Success")
Esempio n. 53
0
def main():
    app = Application()
    renderer = Renderer()
    renderer.register_with_app(app)
    app.request_update_on_draw(Test(renderer).update)

    r = Renderer.Rectangle(1, 2, 20, 30, renderer=renderer)
    try:
        r = Renderer.Rectangle(40, 40, 20, 30)
    except:
        pass

    app.run()
Esempio n. 54
0
    def __init__(self, conf, options, output_prefix, init_equations=True, **kwargs):
        """`kwargs` are passed to  ProblemDefinition.from_conf()

        Command-line options have precedence over conf.options."""
        Application.__init__(self, conf, options, output_prefix)
        self.setup_options()

        is_eqs = init_equations
        if hasattr(options, "solve_not") and options.solve_not:
            is_eqs = False
        self.problem = ProblemDefinition.from_conf(conf, init_equations=is_eqs, **kwargs)

        self.setup_output_info(self.problem, self.options)
Esempio n. 55
0
def skencil_run():

	"""Skencil application launch routine."""

	global config

	_pkgdir = __path__[0]
	config = get_app_config(_pkgdir)
	__path__.insert(0, os.path.join(_pkgdir, 'modules'))

	from application import Application

	app = Application(_pkgdir)
	app.run()
Esempio n. 56
0
def sword_run():

	"""SWord application launch routine."""

	global config

	_pkgdir = __path__[0]
	config = get_app_config(_pkgdir)

	os.environ["UBUNTU_MENUPROXY"] = "0"
	os.environ["LIBOVERLAY_SCROLLBAR"] = "0"

	from application import Application

	app = Application(_pkgdir)
	app.run()
Esempio n. 57
0
def do_test_3():
    "3rd Watsup Test"
    app = Application()
    try:
        app.connect_(title ='Performance Form 2')
    except WindowNotFoundError:
        app.start_(r'examples\perform2.exe')

    app.PerformanceForm1.Clickme.Click()
    waited = 0
    while not app.PerformacneForm1.Edit1._.Texts and not waited >= 1:
        print 'waiting'
        sleep(.1)
        waited += .1

    print `app.PerformacneForm1.Edit1._.Texts`
class Client:
  def __init__(self, user):
    self.user = user
    self.ip = str(54) + '.' + str(random.randrange(0, 255)) + '.' + str(random.randrange(0, 255)) + '.' + str(random.randrange(0, 255))
    self.connections = []
    self.routerBuffer = []
    self.inbox = {}
    self.transportLayer = Transport(self)
    self.applicationLayer = Application(self)

  # Adds a link between this client and another
  def addConnection(self, client):
    if client == self:
      return
    if client.ip in self.connections:
      return
    self.connections.append(client.ip)

  # Sends a message (tells the application layer to make a packet)
  def sendMessage(self, source, destination, message , time):
    applicationPacket = self.applicationLayer.generatePacket(time, source, destination, message)
    tcpPackets = self.transportLayer.process(applicationPacket, time)

  def __repr__(self):
    return self.ip

  def __str__(self):
    return self.ip + ' - ' + str(self.connections) + " => Router Buffer: " + str(self.routerBuffer) + "  Inbox: " + str(self.inbox)
Esempio n. 59
0
 def loadSettings(self, hostname, port, path_run_dir,
                  office_binary_path, uno_path, default_language,
                  environment_dict=None, **kw):
   """Method to load the configuratio to control one OpenOffice Instance
   Keyword arguments:
   office_path -- Full Path of the OOo executable.
     e.g office_binary_path='/opt/openoffice.org3/program'
   uno_path -- Full path of the Uno Library
   """
   if environment_dict is None:
     environment_dict = {}
   Application.loadSettings(self, hostname, port, path_run_dir)
   self.office_binary_path = office_binary_path
   self.uno_path = uno_path
   self.default_language = default_language
   self.environment_dict = environment_dict
Esempio n. 60
0
    def __init__(self):
        Application.__init__(self)
        self.xorg_conf_path = "/etc/X11/xorg.conf"
        self.xorg_conf_d_path = "/etc/X11/xorg.conf.d"
        self.xorg_conf_backup_path = "%s-backup" %(self.xorg_conf_path)
        self.xorg_conf_d_backup_path = "%s-backup" %(self.xorg_conf_d_path)

        self.pages['welcome'] = self.create_welcome_page()
        self.pages['actions'] = self.create_actions_page()
        self.pages['reconfigure'] = self.create_reconfigure_page()
        self.pages['troubleshoot'] = self.create_troubleshoot_page()

        # Refresh
        self.update_frame()
        self.window.show_all()
        self.on_page(None, 'welcome')