Ejemplo n.º 1
0
def parent():
    keepRunning = True  # flag to indicate whether to keep running
    #sys.stderr.write("\ngui Parent thread started: %s\n" % currentThread())
    Thread(target=child, args=(1,)).start()
    signals = StatechartSignals.StatechartSignals(guiOutput)
    while keepRunning:
        # Call all the objects' update()
        Application.update()
        mutex.acquire()
        if len(Events) > 0:  # check length of event queue before popping
            event = Events.pop(0)
            # LJR - Added special exit event.
            if event == "Quit":
                # quit parent
                keepRunning = False
                break;
            if len(event) > 1:   # Don't process the \n at the end of a command
                params = event.split()
                # Send the Entry or Exit event to the object
                # mapCharts return the object
                # EnterState and ExitState are member functions of the object
                #sys.stderr.write("## gui.%s processing %s ##\n" % (currentThread(), params))
                if Application.mapCharts.has_key(params[0]):
                    if params[2] == 'ENTRY':
                        Application.mapCharts[params[0]].EnterState(params[1])
                    elif params[2] == 'EXIT':
                        Application.mapCharts[params[0]].ExitState(params[1])
        else:  # release lock until event queue has something; prevents CPU hog
            mutex.wait(0.05) # timeout after 50ms, sufficient for GUI response
        #
        mutex.release()
Ejemplo n.º 2
0
def parent():
    keepRunning = True  # flag to indicate whether to keep running
    #sys.stderr.write("\ngui Parent thread started: %s\n" % currentThread())
    Thread(target=child, args=(1, )).start()
    signals = StatechartSignals.StatechartSignals(guiOutput)
    while keepRunning:
        # Call all the objects' update()
        Application.update()
        mutex.acquire()
        if len(Events) > 0:  # check length of event queue before popping
            event = Events.pop(0)
            # LJR - Added special exit event.
            if event == "Quit":
                # quit parent
                keepRunning = False
                break
            if len(event) > 1:  # Don't process the \n at the end of a command
                params = event.split()
                # Send the Entry or Exit event to the object
                # mapCharts return the object
                # EnterState and ExitState are member functions of the object
                #sys.stderr.write("## gui.%s processing %s ##\n" % (currentThread(), params))
                if Application.mapCharts.has_key(params[0]):
                    if params[2] == 'ENTRY':
                        Application.mapCharts[params[0]].EnterState(params[1])
                    elif params[2] == 'EXIT':
                        Application.mapCharts[params[0]].ExitState(params[1])
        else:  # release lock until event queue has something; prevents CPU hog
            mutex.wait(0.05)  # timeout after 50ms, sufficient for GUI response
        #
        mutex.release()
Ejemplo n.º 3
0
def l4_recvfrom(segment):

	frame = json.loads(segment)

	source_nid = frame['source_nid']
	source_port = frame['source_port']
	dest_nid = frame['destination_nid']
	dest_port = frame['destination_port']
	sequence_number = frame['sequence_number']
	ack_number = frame['ack_number']
	window_size = frame['window_size']
	checksum = frame['checksum']
	data = frame['data']

	# get md5 hash of data for checksum
	m = hashlib.md5()
	m.update(data)
	test = m.hexdigest()

	# compare checksums
	if (checksum == test):
		Application.l5_recvfrom(source_nid, dest_nid, data)
	else:
		data = "message was corrupted"
		Application.l5_recvfrom(source_nid, dest_nid, data)

 # April 28, 2016
Ejemplo n.º 4
0
 def checkSignals(self):
     """
     Check if signal flow between Application class and its sub and helper classes works
     """
     obj_ut = Application()
     obj_ut.sigCreateModelView.connect(self.mv_manager.slot_createModelView)
     obj_ut.createModelViewPair()
     assert self.mv_manager.signal_create == True,  'Signal sigCreateModelView not recieved'
Ejemplo n.º 5
0
def main():
    config = Config()

    application = Application(Meter(config), FrameProcessor(config),
                              FrameSource(config), config)

    application.start()
    return
Ejemplo n.º 6
0
 def __init__(self):
     #,self.handle.application
     self.data = []
     httpd = make_server('', 1234, self.handle)
     print('Server HTTP on port 1234...')
     #Application类的实例化
     self.app = Application()
     #Spider类的实例化
     self.spider = Spider()
     httpd.serve_forever()
Ejemplo n.º 7
0
 def checkSignals(self):
     """
     Check if signal flow between Application class and its sub and helper classes works
     """
     obj_ut = Application() # it's already tested, that this id possible
     # Connect the sigCreateModelView signal to a ModelViewManager (in this case a stub)
     obj_ut.sigCreateModelView.connect(self.mv_manager.slot_createModelView)
     # Trigger the signal from the application object by calling its createModelViewPair method
     obj_ut.createModelViewPair()
     assert self.mv_manager.signal_create == True,  'Signal sigCreateModelView not recieved'
Ejemplo n.º 8
0
 def conn(self):
     ser = serial.Serial(self.portName, self.br, timeout=self.to)
     print '### conn is on:\t conn to %s, at rate=%s and timeout=%s' % (self.portName, self.br, self.to)
     while self.flag:
         line = ser.readline()
         if len(line) != 0:
             print 'msg:', line
             Application.sent_all(line)
             # print server
     ser.close()
     print "self conn is down"
     return
Ejemplo n.º 9
0
def main():
    """Main Entry Point."""

    LOG = logging.getLogger("{{ cookiecutter.project_slug }}")
    LOG.setLevel(logging.DEBUG)

    Q_APP = QApplication([])
    APP = Application()

    LOG.info("Application Version: v{}".format(__version__))
    APP.show()

    sys.exit(Q_APP.exec_())
Ejemplo n.º 10
0
def updateThread(tid):
  while True:
    Application.update()
    mutex.acquire()
    if len(Events) > 0:
      event = Events.pop(0)
      if len(event) > 1:   # Don't process the \n at the end of a command
        params = event.split()
        if params[2] == 'ENTRY':
          Application.mapCharts[params[0]].EnterState(params[1])
        elif params[2] == 'EXIT':
          Application.mapCharts[params[0]].ExitState(params[1])
    mutex.release()
Ejemplo n.º 11
0
def updateThread(tid):
    while True:
        Application.update()
        mutex.acquire()
        if len(Events) > 0:
            event = Events.pop(0)
            if len(event) > 1:  # Don't process the \n at the end of a command
                params = event.split()
                if params[2] == 'ENTRY':
                    Application.mapCharts[params[0]].EnterState(params[1])
                elif params[2] == 'EXIT':
                    Application.mapCharts[params[0]].ExitState(params[1])
        mutex.release()
Ejemplo n.º 12
0
def GetModule():
    return Application.Module(
        'Core:Base',
        {'type':        Interpreter.BuiltIn(Type),
         'same-type?':  Interpreter.BuiltIn(SameType),
         'eq?':         Interpreter.BuiltIn(Eq),
         'neq?':        Interpreter.BuiltIn(Neq),
         'id':          Interpreter.BuiltIn(Id),
         'error':       Interpreter.BuiltIn(Error),
         'module':      Interpreter.BuiltIn(Module),
         'define':      Application.fastInterpret('[name value <Type Define Name (name) Value (value)>]'),
         'import':      Application.fastInterpret('[module names* as=none! <Type Import Module (module) Names (names) As (as)>]'),
         'export':      Application.fastInterpret('[names* <Type Export Names (names)>]')},
        {},['type','same-type?','eq?','neq?','id','error','module','define','import','export'])
Ejemplo n.º 13
0
def Module(name,directives_star):
    assert(isinstance(name,Interpreter.InAtom))
    assert(isinstance(directives_star,Interpreter.InAtom))

    Utils.testSymbol(name,'Module')

    directives = Utils.argStarAsList(directives_star)

    c_type = Interpreter.Symbol('Type')
    c_define = Interpreter.Symbol('Define')
    c_import = Interpreter.Symbol('Import')
    c_export = Interpreter.Symbol('Export')

    defines = {}
    imports = {}
    exports = []

    for directive in directives:
        t = directive.get(c_type)

        if t == c_define:
            defines[directive.get(Interpreter.Symbol('Name')).value] = directive.get(Interpreter.Symbol('Value'))
        elif t == c_import:
            imports[directive.get(Interpreter.Symbol('Module'))] = \
                (directive.get(Interpreter.Symbol('As')).value,
                 map(lambda x: x.value,Utils.argStarAsList(directive.get(Interpreter.Symbol('Names')))))
        elif t == c_export:
            exports.extend(map(lambda x: x.value,Utils.argStarAsList(directive.get(Interpreter.Symbol('Names')))))
        else:
            raise Exception('Invalid module directive type!')

    return Application.Module(name.value,defines,imports,exports)
Ejemplo n.º 14
0
def GetModule():
    return Application.Module(
        'Core:Control:Flow', {
            'if': Interpreter.BuiltIn(If),
            'case': Interpreter.BuiltIn(Case),
            'let': Interpreter.BuiltIn(Let)
        }, {}, ['if', 'case', 'let'])
Ejemplo n.º 15
0
 def add_app(self,name):
     self.apps.append(Application(self.way+'\\'+self.name,name))
     text=0
     with open(self.way+'\\'+self.name+'\\'+self.name+'\\urls.py','r') as f:
         text=f.read()
     with open(self.way+'\\'+self.name+'\\'+self.name+'\\urls.py','w') as f:
         f.write('import '+name+'.views \n'+text)
Ejemplo n.º 16
0
    def post(self):
        # day, hour1, minute1 = Application.getTime()
        # hour, minute = myMax(hour1, minute1, Domain.GUIDE_HOUR, Domain.GUIDE_MIN)

        # new
        day, hour, minute = Application.getTime()
        if minute >= 0:
            # hour, minute = myControl(hour, minute)
            db = Reserve()
            place = Domain.GUIDE_PLACE
            guide = db.getGuiding(day, hour, minute, place)
            total = 0
            for rows in guide:
                total += int(rows.get("number"))
            data = []
            for rows in guide:
                data.append({
                    "bi_value": {
                        "total": total,
                        "to_name": rows.get("to"),
                        "from_name": place,
                        "times": rows.get("number")
                    }
                })
            res = {"code": 200, "data": data, "hour": hour, "min": minute}
            self.write(json.dumps(res))
Ejemplo n.º 17
0
    def post(self):
        # day, hour1, minute1 = Application.getTime()
        # hour, minute = myMax(Domain.AVE_HOUR, Domain.AVE_MIN, Domain.NUM_HOUR, Domain.NUM_MIN)
        # hour, minute = myMax(hour1, minute1, hour, minute)

        # new
        day, hour, minute = Application.getTime()
        if minute >= 0:
            db = Reserve()
            num = db.getNumOfPeople(day, hour, minute)
            data = []
            for rows in num:
                data.append({
                    "dt_hour": rows.get("dt_hour"),
                    "dt_min": rows.get("dt_min"),
                    "count": rows.get("number")
                })
            ave = db.getAverage(day, hour, minute)
            res = {
                "code": 200,
                "number": ave.get("total"),
                "average": ave.get("average"),
                "data": data,
                "hour": hour,
                "min": minute
            }
            self.write(json.dumps(res))
Ejemplo n.º 18
0
    def __init__(self, N, nbPions):
        """
        params :
            N (int) : dimension de la grille
            nbPions (int) : nombre de pions
        """
        self.__dim = N
        self.__nbPions = nbPions

        # Initialisation de la grille
        self.__Grille = Grille(N, nbPions)

        # Initialisation de l'Historique (FIFO)
        self.__Historique = []

        # Console ou UI ?
        self.__isConsoleActive = self.activateConsole()
        print("INFO : Vous avez choisi de jouer %s" %
              ("dans l'UI", "dans la console")[self.__isConsoleActive])

        # Premier joueur
        self.__colorInit = random.randint(BLANC, NOIR)

        # Tableau des fonctions placer pion. On y accède avec self.__ModeJeu
        self.__TAB_PLACER_PION = [
            self.placer_pion_machine, self.placer_pion_humain,
            self.placer_pion, self.placer_pion, self.placer_pion,
            self.placer_pion, self.placer_pion_2machines
        ]
        # Tableau des constructeurs de tour. On y accède avec self.__ModeJeu
        self.__TAB_TOUR = [
            TourRandom, None, TourRandom, TourBestFirst, TourMinMax,
            TourAlphaBeta, (TourRandom, TourMinMax)
        ]
        self.__ModeJeu = 2  # par défaut ordirandom/humain

        self.__forceStop = False

        if not self.__isConsoleActive:
            # Initialisation de la fenêtre d'affichage
            self.__root = tk.Tk()
            # tk.CallWrapper = TkErrorCatcher
            self.__Application = Application.Application(self,
                                                         master=self.__root)

            # Selectionnons le mode de Jeu
            self.selectionnerModeJeu()

            # Lançons le tout
            self.jouer()
            self.__Application.mainloop()

        else:
            # Selectionnons le mode de Jeu
            self.selectionnerModeJeu()

            # Lançons le tout
            self.jouer()
Ejemplo n.º 19
0
class Main:
    def __init__(self):
        #,self.handle.application
        self.data = []
        httpd = make_server('', 1234, self.handle)
        print('Server HTTP on port 1234...')
        #Application类的实例化
        self.app = Application()
        #Spider类的实例化
        self.spider = Spider()
        httpd.serve_forever()

    def handle(self, environ, start_response):
        start_response('200 ok', [('Content-Type', 'text/html')])
        info = (environ['PATH_INFO'][1:])
        if info == 'a':
            responseInfo = 'aaaaa'
        elif info == 'b':
            responseInfo = 'bbbbb'
        elif info == 'c':
            self.data = self.connectDataBase()
            responseInfo = self.data
        elif info == 'e':
            value = self.app.printData()
            responseInfo = value
        elif info == 'spider':
            spiderData = self.spider.start()
            #打开文件,如果不存在,则创建
            file = open('baidu.html', 'w+')
            #在创建的文件中写入数据
            file.write(spiderData)
            #关闭文件
            file.close()
            responseInfo = '文件写入成功'
        else:
            responseInfo = '什么鬼'
        return responseInfo

    def connectDataBase(self):
        config = {
            'user': '',
            'password': '',
            'host': '127.0.0.1',
            'database': 'test',
            'raise_on_warnings': True,
        }
        cnx = mysql.connector.connect(**config)
        cursor = cnx.cursor()
        name = 'lily'
        cursor.execute("select * from node")
        values = cursor.fetchall()
        return str(values)
        '''
		for value in values:
			print 'id:' + str(value[0]) + ', username: '******',password: '******'''
        cnx.close()
Ejemplo n.º 20
0
 def __init__(self, Options):
     QtWidgets.QWidget.__init__(self)
     super().__init__()  #used for providing control to the inherited module
     self.setGeometry(700, 200, 500, 500)
     self.setWindowTitle("MP3 Downloader")
     self.setWindowIcon(QtGui.QIcon('Resources/Music.jpg'))
     self.song = Application.MP3D()
     self.home()
     self.option = Options
Ejemplo n.º 21
0
    def generateClient(self):
        TIMap = [[0.5, 1.25], [1.25, 2.25], [2.25, 3]]

        appType = random.randint(1, 3)
        appTI = random.uniform(TIMap[appType - 1][0], TIMap[appType - 1][1])
        appSize = random.randint(
            75 * 3, 75 * 50
        )  # 75 is the minimum traffic for application to consumpe in one slot
        appID = len(self.applications)
        return Application.Application(appID, appType, appSize, appTI)
Ejemplo n.º 22
0
def GetModule():
    return Application.Module(
        'Core:Data:Dict', {
            'is-dict?': Interpreter.BuiltIn(IsDict),
            'has-key?': Interpreter.BuiltIn(HasKey),
            'get': Interpreter.BuiltIn(Get),
            'set': Interpreter.BuiltIn(Set),
            'keys': Interpreter.BuiltIn(Keys),
            'values': Interpreter.BuiltIn(Values)
        }, {}, ['is-dict?', 'has-key?', 'get', 'set', 'keys', 'values'])
Ejemplo n.º 23
0
    def server(self):
        ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ser.bind(('localhost', 7777))
        ser.listen()
        while True:
            talk_cli, msg_cli = ser.accept()
            while True:
                urly = talk_cli.recv(1024).decode('utf-8').split(
                    '\r\n')[0].split('/')
                print('原:', urly)
                url = urly[1].split(' ')[0]
                if urly.__len__() > 3:
                    url = ''
                    for i in range(1, urly.__len__() - 1):
                        url += urly[i].split(' ')[0]
                        if not urly[i].__contains__('HTTP'):
                            url += '/'
                if url.__contains__('js/jquery-1.11.3.min.js'):
                    url = 'js/jquery-1.11.3.min.js'

                if url.endswith('/'):
                    # print('uuu:', url.__len__() - 1)

                    url = url[0:int(url.__len__() - 1)]
                print('url:', url)
                if url.endswith('.py'):
                    # 动态
                    env = dict()
                    env['PATH-INF'] = url
                    body = Application.application(env, self.myMethod)
                    response = self.status + '\r\n'
                    for i in self.heads:
                        response += i[0] + "=" + i[1] + "\r\n"
                        response += '\r\n'
                    talk_cli.send((response + body).encode('utf8'))
                else:

                    try:
                        with open(url, 'rb') as f:
                            con = f.read()
                            # heads
                            talk_cli.send(
                                'HTTP/1.1 200 OK\r\n\r\n'.encode('utf8'))
                            # talk_cli.send("静态资源...\r\n\r\n".encode('utf8'))
                            talk_cli.send(con)
                    except Exception as e:
                        # print("eee:", e)

                        talk_cli.send(
                            'HTTP/1.1 404 NOT FOUND\r\n\r\n'.encode('utf8'))
                        talk_cli.send("资源不存在...\r\n\r\n".encode('utf8'))

                talk_cli.close()
                break
Ejemplo n.º 24
0
def connect(port):
    """start server with assigned port. Note that 
    Application is inherited from Tornado!
        
    # Arguments:
        port: a int number passed from argparse
    # Returns:
        None:
    """
    application = Application.Application()
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()
Ejemplo n.º 25
0
def main():
	if singleton.running():
		sys.exit(1)

	window = Application(db.upload_src, db.upload_dirs, 
							get_library_file() != None)

	def app_started():
		def login_clicked():
			import upload
			fb.login(upload.login_callback)

		def options_changed(upload_src, upload_dirs):
			import upload
			db.upload_src = upload_src
			db.upload_dirs = upload_dirs
			upload.options_changed()

		def exit_clicked():
			singleton.atexit()
			window.quit()

		window.login_clicked = login_clicked
		window.options_changed = options_changed
		window.exit_clicked = exit_clicked
		window.listen_clicked = fb.listen_now

		singleton.set_callback(window.activate)

		def start_uploader():
			import upload
			guimgr = GuiManager(window, db.total_uploaded_tracks())
			set_gui_error(guimgr.fatal_error)
			upload.start_uploader(guimgr)

		thread.start_new_thread(start_uploader, ())

	window.app_started = app_started

	window.start()
Ejemplo n.º 26
0
def GetModule():
    return Application.Module(
        'Core:Data:Func', {
            'is-func?': Interpreter.BuiltIn(IsFunc),
            'apply': Interpreter.BuiltIn(Apply),
            'curry': Interpreter.BuiltIn(Curry),
            'inject': Interpreter.BuiltIn(Inject),
            'env-has-key?': Interpreter.BuiltIn(EnvHasKey),
            'env-get': Interpreter.BuiltIn(EnvGet),
            'env-set': Interpreter.BuiltIn(EnvSet)
        }, {}, [
            'is-func?', 'apply', 'curry', 'inject', 'env-has-key?', 'env-get',
            'env-set'
        ])
Ejemplo n.º 27
0
def parent():
    thread.start_new(child, (1, ))
    signals = StatechartSignals.StatechartSignals(guiOutput)
    while True:
        # Call all the objects update()
        Application.update()
        mutex.acquire()
        if len(Events) > 0:
            event = Events.pop(0)
            # LJR - Added special exit event.
            if event == "Quit":
                sys.exit(0)
            if len(event) > 1:  # Don't process the \n at the end of a command
                params = event.split()
                # Send the Entry or Exit event to the object
                # mapCharts return the object
                # EnterState and ExitState are member functions of the object
                if Application.mapCharts.has_key(params[0]):
                    if params[2] == 'ENTRY':
                        Application.mapCharts[params[0]].EnterState(params[1])
                    elif params[2] == 'EXIT':
                        Application.mapCharts[params[0]].ExitState(params[1])
        mutex.release()
Ejemplo n.º 28
0
def parent():
  thread.start_new(child, (1,))
  signals = StatechartSignals.StatechartSignals(guiOutput)
  while True:
    # Call all the objects update()
    Application.update()
    mutex.acquire()
    if len(Events) > 0:
      event = Events.pop(0)
      # LJR - Added special exit event.
      if event == "Quit":
          sys.exit(0)
      if len(event) > 1:   # Don't process the \n at the end of a command
        params = event.split()
        # Send the Entry or Exit event to the object
        # mapCharts return the object
        # EnterState and ExitState are member functions of the object
        if Application.mapCharts.has_key(params[0]):
          if params[2] == 'ENTRY':
            Application.mapCharts[params[0]].EnterState(params[1])
          elif params[2] == 'EXIT':
            Application.mapCharts[params[0]].ExitState(params[1])
    mutex.release()
Ejemplo n.º 29
0
    def http_server(self, new_client):
        web_c = new_client.recv(self.Buffer_size)
        # print(">>>>>>>>>>>>",web_c.decode())
        if not web_c:
            print("浏览器可能已经关闭!~")
            new_client.close()
            return

        res_data = re.match('GET\s(.*)\sHTTP/1.1', web_c.decode())
        if not res_data:
            print("浏览器请求的报文格式错误!")
            new_client.close()
            return

        res_path = res_data.group(1)
        print(">>>>>>>>>>>>", res_path)
        if res_path == "/":
            res_path = "static/index.html"
        ##动态页
        if res_path.endswith(".html"):
            path_app = {'PATH_APP': res_path}
            status, headers, response_body = Application.app(path_app)
            res_line = "HTTP/1.1 %s\r\n" % status

            res_heard = ""
            for heard in headers:
                res_heard += "%s:%s\r\n" % heard

            rr_data = (res_line + res_heard +
                       "\r\n").encode('utf8') + response_body
            new_client.send(rr_data)
            new_client.close()
        else:
            #静态页
            try:
                with open('static' + res_path, 'rb') as r_f:
                    res_content = r_f.read()
            except Exception as e:
                res_line = 'HTTP/1.1 404 ok\r\n'
                res_content = '%s...' % e
            else:
                res_line = 'HTTP/1.1 200 ok\r\n'
            finally:
                res_heard = 'Server:python/5.0\r\n'
                res_sc = '\r\n'
                rr_data = (res_line + res_heard +
                           res_sc).encode('utf8') + res_content
                new_client.send(rr_data)
                new_client.close()
Ejemplo n.º 30
0
def main():
    """ main function on the program """

    # defain main window
    root = Tk()

    root.title("Szyfrator haseł")
    root.geometry("480x480")
    root.resizable( width=False, height=False )

    logo = PhotoImage(file="img/maleLogo.png")
    root.iconphoto(True, logo)

    app = Application.Application(root)

    # main function of the window
    root.mainloop()
Ejemplo n.º 31
0
    def post(self):
        # day, hour1, minute1 = Application.getTime()
        # hour, minute = myMax(hour1, minute1, Domain.RANK_HOUR, Domain.RANK_MIN)

        # new
        day, hour, minute = Application.getTime()
        if minute >= 0:
            db = Reserve()
            rank = db.getRanking(day, hour, minute)
            data = []
            Domain.GUIDE_PLACE = rank[0].get("name")
            for rows in rank:
                data.append({
                    "name": rows.get("name"),
                    "value": rows.get("number")
                })
            res = {"code": 200, "data": data, "hour": hour, "min": minute}
            self.write(json.dumps(res))
Ejemplo n.º 32
0
    def post(self):
        # day, hour1, minute1 = Application.getTime()
        # hour, minute = myMax(hour1, minute1, Domain.BUY_HOUR, Domain.BUY_MIN)

        # new
        day, hour, minute = Application.getTime()
        if minute >= 0:
            # hour, minute = myControl(hour, minute)
            db = Reserve()
            buy = db.getBuy(day, hour, minute)
            data = []
            for rows in buy:
                data.append({
                    "name": rows.get("type"),
                    "data": [rows.get("a"), rows.get("b")]
                })
            res = {"code": 200, "data": data, "hour": hour, "min": minute}
            self.write(json.dumps(res))
Ejemplo n.º 33
0
    def post(self):
        # day, hour1, minute1 = Application.getTime()
        # hour, minute = myMax(hour1, minute1, Domain.PI_HOUR, Domain.PI_MIN)

        # new
        day, hour, minute = Application.getTime()
        if minute >= 0:
            # hour, minute = myControl(hour, minute)
            db = Reserve()
            buy = db.getPi(day, hour, minute)
            value = []
            categories = []
            for rows in buy:
                value.append(rows.get("value"))
                categories.append(rows.get("feature"))
            data = {"value": value, "categories": categories}
            res = {"code": 200, "data": data, "hour": hour, "min": minute}
            self.write(json.dumps(res))
def main(image):
    print('->app')
    app = Application.Application(sys.argv)

    if (app.isRunning()):
        exit()

    app.create_start_monitors()

    print('->w')
    w = QtWidgets.QWidget()
    print('->SystemTrayIcon')
    trayIcon = SystemTrayIcon(app, QtGui.QIcon(image), w)
    print('->Show')
    trayIcon.show()

    print('wait for main exit')
    sys.exit(app.exec_())
Ejemplo n.º 35
0
    def post(self):
        # day, hour1, minute1 = Application.getTime()
        # hour, minute = myMax(hour1, minute1, Domain.THE_HOUR, Domain.THE_MIN)

        # new
        day, hour, minute = Application.getTime()
        if minute >= 0:
            db = Reserve()
            thermodynamic = db.getThermodynamic(day, hour, minute)
            data = []
            for rows in thermodynamic:
                data.append({
                    "y": rows.get("posy"),
                    "x": rows.get("posx"),
                    "count": rows.get("number")
                })
            res = {"code": 200, "data": data, "hour": hour, "min": minute}
            self.write(json.dumps(res))
Ejemplo n.º 36
0
def GetModule():
    return Application.Module(
        'Core:Data:Number', {
            'pi': Interpreter.Number(3.1415926535897931),
            'e': Interpreter.Number(2.7182818284590451),
            'is-number?': Interpreter.BuiltIn(IsNumber),
            'add': Interpreter.BuiltIn(Add),
            'inc': Interpreter.BuiltIn(Inc),
            'sub': Interpreter.BuiltIn(Sub),
            'dec': Interpreter.BuiltIn(Dec),
            'mul': Interpreter.BuiltIn(Mul),
            'div': Interpreter.BuiltIn(Div),
            'mod': Interpreter.BuiltIn(Mod),
            'lt': Interpreter.BuiltIn(Lt),
            'lte': Interpreter.BuiltIn(Lte),
            'gt': Interpreter.BuiltIn(Gt),
            'gte': Interpreter.BuiltIn(Gte),
            'sin': Interpreter.BuiltIn(Sin),
            'cos': Interpreter.BuiltIn(Cos),
            'tan': Interpreter.BuiltIn(Tan),
            'ctg': Interpreter.BuiltIn(Ctg),
            'asin': Interpreter.BuiltIn(ASin),
            'acos': Interpreter.BuiltIn(ACos),
            'atan': Interpreter.BuiltIn(ATan),
            'actg': Interpreter.BuiltIn(ACtg),
            'rad2deg': Interpreter.BuiltIn(Rad2Deg),
            'deg2rad': Interpreter.BuiltIn(Deg2Rad),
            'exp': Interpreter.BuiltIn(Exp),
            'log': Interpreter.BuiltIn(Log),
            'ln': Interpreter.BuiltIn(Ln),
            'lg': Interpreter.BuiltIn(Lg),
            'sqrt': Interpreter.BuiltIn(Sqrt),
            'pow': Interpreter.BuiltIn(Pow),
            'abs': Interpreter.BuiltIn(Abs),
            'ceill': Interpreter.BuiltIn(Ceill),
            'floor': Interpreter.BuiltIn(Floor)
        }, {}, [
            'pi', 'e', 'is-number?', 'add', 'inc', 'sub', 'dec', 'mul', 'div',
            'mod', 'lt', 'lte', 'gt', 'gte', 'sin', 'cos', 'tan', 'ctg',
            'asin', 'acos', 'actg', 'rad2deg', 'deg2rad', 'exp', 'log', 'ln',
            'lg', 'sqrt', 'pow', 'abs', 'ceill', 'floor'
        ])
Ejemplo n.º 37
0
def main():
    csvFile_actualRating = r'C:\Users\shang\Documents\GitHub\MachineLearning---TeamChooser\Milestone3_DataAnalysis\rating_list.csv'
    csvFile_rawData = r'C:\Users\shang\Documents\GitHub\MachineLearning---TeamChooser\game_stances.csv'
    csvFile_processedData = r'C:\Users\shang\Documents\GitHub\MachineLearning---TeamChooser\ProcessedData.csv'
    csvFile_playerRating = r'C:\Users\shang\Documents\GitHub\MachineLearning---TeamChooser\PlayerRating.csv'
    csvFile_analysis = r'C:\Users\shang\Documents\GitHub\MachineLearning---TeamChooser\Milestone3_DataAnalysis\PerformanceAnalysis.csv'

    #    num_players = 150

    #    for i in range (1, 201):
    #        print(i)
    # step 1: preprocessing and feature extracting
    Preprocessor.RawDataProcessor(csvFile_rawData, csvFile_processedData, 1000)
    # step 2: Training (offline) - machine learning system (iterative process)
    #    MachineLearningAlgorithm.IterativeTrainingSystem()

    # step 3: Testing (online)
    Application.RatingCalculator(csvFile_processedData, csvFile_playerRating)

    # extra step: Performance analysis
    #        PerformanceAnalysis.Analysis(csvFile_actualRating, csvFile_playerRating, csvFile_analysis, i*5, num_players)

    #    PerformanceAnalysis.Plot(csvFile_analysis)
    return
Ejemplo n.º 38
0
#!/usr/bin/env python3

# Author: Dmitry Kukovinets ([email protected])

from Application import *


if __name__ == "__main__":
    app = Application()
    app.run()
Ejemplo n.º 39
0
 def __runGuiUpdater(self):
     """
     Main loop for the GUI thread.
     It is responsible for periodically updating the TkInter objects and
     sending Entry and Exit events to the statecharts from the update queue.
     """
     class PseudoSocket:
         """
         Pseudo-Socket class for the StateChartSignal GUI
         to send button events.
         """
         def __init__(self, server):
             self.__server = server
         def send(self, inString):
             # strip the newline
             cmds = inString.split('\n')
             self.__server.queueButtonEvent(cmds[0])
     #
     # Autocoder Python trace GUI imports
     try:
         import StatechartSignals
         StatechartSignals.StatechartSignals(PseudoSocket(self))
         #
         # invoke sim_state_start to generate Application.py if
         #  gui_server was invoked standalone (meaning, no sim_state_start!)
         if not self.__embeddedExec:  # import sim_state_start and set target
             import sim_state_start
             sim_state_start.setTargetDir(".")  # assume current dir
             sim_state_start.StartStateSim.getInstance().generateApplicationPy([])
         #
         # Now we can try importing Application.py
         import Application
         Application.update()  # bring up the GUI window(s)
         while not Application.windowsReady():
             time.sleep(0.5)
     except ImportError:
         raise
     #
     # Let's client know (via client's polling awaitGuiReady)
     # that GUI is ready 
     self.__markGuiReady()
     #
     while self.__keepRunning:
         # Call all the objects' update()
         Application.update()
         params = None
         try:
             # block, but only briefly to prevent locking GUI
             event = self.__updateQueue.get(block=True, timeout=0.0005)
             params = event.split()  # Don't process the \n at the end of a command
             if self.__debug:
                 print "==> Got params:", params
         except Queue.Empty:
             pass  # ignore, as exception is expected
         #
         # Send the Entry or Exit event to the object.
         # mapCharts return the object
         # EnterState and ExitState are member functions of the object
         if params is not None:
             # if "obj:Type", use "obj" as GUI window name, concat "Type" with state 
             instType = params[0].split(":")
             winName = instType[0]
             stateName = params[1]
             if len(instType) > 1:  # pattern "obj:Type", get "obj"
                 stateName = instType[1] + stateName
             if Application.mapCharts.has_key(winName):
                 if params[2] == 'ENTRY':
                     Application.mapCharts[winName].EnterState(stateName)
                 elif params[2] == 'EXIT':
                     Application.mapCharts[winName].ExitState(stateName)
     #
     if self.__debug:
         print "GUI update thread stopped!"
     #
     self.__destroy()
import sys
import telnetlib
import time
import Tkinter as tk
from tkMessageBox import *
from Application import *


#Requests input for Host and username

##HOST = raw_input("Enter your Host: ")
##user = raw_input("Enter username: "******"Enter your Server: ")
##folder = raw_input("Enter folder name: ")

app = Application(master=root)
app.mainloop()
print "in app"

HOST = app.HOST
user = app.user
server = app.server
folder = app.folder

print "from telnet " + HOST + user + server + folder
#+ server + folder
#print app.USB

reboot = "kill 1 1"
run = "/agk/bin/run"
mkdir = "mkdir /tmp/nvdmp"
Ejemplo n.º 41
0
from Application import *

#инициализация окна
root = Tk()
root.title = "Морской бой"
root.geometry("800x500+100+100")

#инициализация приложения
app = Application(master=root)
app.mainloop()
Ejemplo n.º 42
0
#
# Copyright (c) 2012 pinocchio964
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
#

from Application import *

if __name__ == "__main__":
    app = Application()
    app.execute()

Ejemplo n.º 43
0
def l4_recvfrom(segment):
  data = segment
  Application.l5_recvfrom(data)