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)
def main(): config = Config() application = Application(Meter(config), FrameProcessor(config), FrameSource(config), config) application.start() return
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()
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)
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 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()
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_())
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()
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_())
def renaming(): path = 'source/Favorites/' for file_name in os.listdir(path): new_name = file_name.split('-')[1] new_name = 'source/Favorites/' + new_name + '.png' print(new_name) os.rename(path + file_name, new_name) #open('source/Favorites/icons8-3-100.png') if __name__ == '__main__': # renaming() # print(cos(pi / 180 * 180)) if (Constants.GRAPHTYPE == 0): file = 'graph.txt' graph = GetGraph(file) elif (Constants.GRAPHTYPE == 1): file = BuildRandomGraph() graph = GetMatrixGraph(file) elif (Constants.GRAPHTYPE == 2): file = BuildRandomKGraph(Constants.CC_NUMBER) graph = GetMatrixGraph(file) #file = 'RandomGraph.txt' #graph = GetGraph(file) GraphBuilder = Application(Constants.SIZE_X, Constants.SIZE_Y, graph) pyglet.clock.schedule_interval(update, 1 / 20, GraphBuilder) pyglet.app.run()
from Application import * chess_app = Application() chess_app.mainloop()
# create Client clientPort = 300 client2Port = 500 #Choose a random port as destination and add it to the message (default start is 1) dest = random.randint(2, len(network)) randomPath = RandomWalk.randomWalk(network, 1, dest) print "Sending message through", randomPath print "Number of Nodes traversed by random walk: ", len(randomPath) message = "Is this a potato?" data = {"Path": randomPath, "Message": message} send = json.dumps(data) client = Application.Application(clientPort, proxyServerAddress, send) client.connectToServer() shortestPath = shortest_path(network, 1, dest) print "Sending message with shortest path : ", shortestPath print "Number of nodes traversed by shortest path: ", len(shortestPath) dataOfShortestPath = {"Path": shortestPath, "Message": message} sendToShortestPath = json.dumps(dataOfShortestPath) client2 = Application.Application(client2Port, proxyServerAddress, sendToShortestPath) client2.connectToServer()
import threading import Client import Application if __name__ == '__main__': client2 = Client.Client('2', 10002, 40002) client2.bind_address() threads = [] thread = threading.Thread(target=client2.register) threads.append(thread) thread = threading.Thread(target=client2.get_client_info) threads.append(thread) app = Application.Application(client2.toClient, 'client2') thread = threading.Thread(target=client2.add_peer_to_app, args=(app, )) threads.append(thread) thread = threading.Thread(target=app.receive_message) threads.append(thread) for t in threads: t.setDaemon(True) t.start() app.create_app() app.run() for t in threads: t.join()
def __init__( self, name='ClinkDev', description='Container for CameraLink Dev', dev='/dev/datadev_0', # path to PCIe device version3=False, # true = PGPv3, false = PGP2b pollEn=True, # Enable automatic polling registers initRead=True, # Read all registers at start of the system numLane=4, # Number of PGP lanes camType=['Opal000', None], defaultFile=None, **kwargs): super().__init__(name=name, description=description, dev=dev, version3=version3, numLane=numLane, **kwargs) self.defaultFile = defaultFile # Set the min. firmware Versions self.minPcieVersion = 0x01000200 self.minFebVersion = 0x01000200 # PGP Application on PCIe self.add( app.Application( memBase=self._memMap, numLane=numLane, expand=True, )) # Check if not doing simulation if (dev != 'sim'): # Create arrays to be filled self._srp = [None for lane in range(numLane)] # Create the stream interface for lane in range(numLane): # SRP self._srp[lane] = rogue.protocols.srp.SrpV3() pr.streamConnectBiDir(self._dma[lane][0], self._srp[lane]) # CameraLink Feb Board self.add( feb.ClinkFeb( name=(f'ClinkFeb[{lane}]'), memBase=self._srp[lane], serial=[self._dma[lane][2], self._dma[lane][3]], camType=camType, version3=version3, enableDeps=[ self.Hardware.PgpMon[lane].RxRemLinkReady ], # Only allow access if the PGP link is established expand=False, )) # Else doing Rogue VCS simulation else: # Create arrays to be filled self._frameGen = [None for lane in range(numLane)] # Create the stream interface for lane in range(numLane): # Create the frame generator self._frameGen[lane] = MyCustomMaster() # Connect the frame generator pr.streamConnect(self._frameGen[lane], self._pgp[lane][1]) # Create a command to execute the frame generator self.add( pr.BaseCommand( name=f'GenFrame[{lane}]', function=lambda cmd, lane=lane: self._frameGen[lane]. myFrameGen(), )) self.add( pr.LocalVariable( name='RunState', description= 'Run state status, which is controlled by the StopRun() and StartRun() commands', mode='RO', value=False, )) @self.command( description='Stops the triggers and blows off data in the pipeline' ) def StopRun(): print('ClinkDev.StopRun() executed') # Get devices trigChDev = self.find(typ=timingCore.EvrV2ChannelReg) # Turn off the triggering for devPtr in trigChDev: devPtr.EnableReg.set(False) # Update the run state status variable self.RunState.set(False) @self.command( description= 'starts the triggers and allow steams to flow to DMA engine') def StartRun(): print('ClinkDev.StartRun() executed') # Get devices trigChDev = self.find(typ=timingCore.EvrV2ChannelReg) # Reset all counters self.CountReset() # Turn on the triggering for devPtr in trigChDev: devPtr.EnableReg.set(True) # Update the run state status variable self.RunState.set(True) # Start the system self.start( pollEn=self._pollEn, initRead=self._initRead, timeout=self._timeout, ) # Hide all the "enable" variables for enableList in self.find(typ=pr.EnableVariable): # Hide by default enableList.hidden = True # Check if simulation if (dev == 'sim'): # Disable the PGP PHY device (speed up the simulation) self.Hardware.enable.set(False) self.Hardware.hidden = True # Bypass the time AXIS channel eventDev = self.find(typ=batcher.AxiStreamBatcherEventBuilder) for dev in eventDev: dev.Bypass.set(0x1) else: # Read all the variables self.ReadAll() # Check for min. PCIe FW version fwVersion = self.Hardware.AxiPcieCore.AxiVersion.FpgaVersion.get() if (fwVersion < self.minPcieVersion): errMsg = f""" PCIe.AxiVersion.FpgaVersion = {fwVersion:#04x} < {self.minPcieVersion:#04x} Please update PCIe firmware using software/scripts/updatePcieFpga.py """ click.secho(errMsg, bg='red') raise ValueError(errMsg) # Check for min. FEB FW version for lane in range(numLane): # Unhide the because dependent on PGP link status self.ClinkFeb[lane].enable.hidden = False # Check for PGP link up if (self.Hardware.PgpMon[lane].RxRemLinkReady.get() != 0): # Expand for the GUI self.ClinkFeb[lane]._expand = True self.ClinkFeb[lane].ClinkTop._expand = True self.ClinkFeb[lane].TrigCtrl[0]._expand = True self.ClinkFeb[lane].TrigCtrl[1]._expand = True if camType[1] is None: self.ClinkFeb[lane].ClinkTop.Ch[1]._expand = False self.ClinkFeb[lane].TrigCtrl[1]._expand = False # Check for min. FW version fwVersion = self.ClinkFeb[lane].AxiVersion.FpgaVersion.get( ) if (fwVersion < self.minFebVersion): errMsg = f""" Fpga[lane={lane}].AxiVersion.FpgaVersion = {fwVersion:#04x} < {self.minFebVersion:#04x} Please update Fpga[{lane}] at Lane={lane} firmware using software/scripts/updateFeb.py """ click.secho(errMsg, bg='red') raise ValueError(errMsg) else: self.Application.AppLane[lane]._expand = False # Startup procedures for OPA1000 uartDev = self.find(typ=cl.UartOpal1000) for dev in uartDev: pass # Startup procedures for Piranha4 uartDev = self.find(typ=cl.UartPiranha4) for dev in uartDev: dev.SendEscape() dev.SPF.setDisp('0') dev.GCP() # Startup procedures for Up900cl12b uartDev = self.find(typ=cl.UartUp900cl12b) for dev in uartDev: clCh = self.find(typ=cl.ClinkChannel) for clChDev in clCh: clChDev.SerThrottle.set(30000) dev.AM() dev.SM.set('f') dev.RP() # Load the configurations if self.defaultFile is not None: print(f'Loading {self.defaultFile} Configuration File...') self.LoadConfig(self.defaultFile)
import Application, Application_pf import numpy as np np.set_printoptions(edgeitems=3200, linewidth=1000, precision=6) app = Application.Application("world/map/map.csv") # app = Application_pf.Application("world/map/map.csv") # app = Application2.Application("world/map/map.csv") # app = Application3.Application("world/map/map.csv")
# Panda3D imports import direct.directbase.DirectStart from direct.showbase import DirectObject from direct.showbase.DirectObject import DirectObject # Project imports from Application import * # Run the game a = Application() run()
def main(): app = Application() app.command() app.display_data() app.write_data()
# a mad lib generator in Python import tkinter as tk import Application root = tk.Tk() root.title("Python Mad Lib Generator") root.geometry("1000x800") app = Application.Application(root) root.mainloop()
def window(qtbot): """Pass the application to the test functions via a pytest fixture.""" new_window = Application() qtbot.add_widget(new_window) new_window.show() return new_window
try: application = None from Application import * from CLIInput import * from CLIOutput import * from CLIMedia import * from MemoryBillRepository import * from MemoryDataRepository import * from MemoryUserRepository import * application = Application(CLIMedia(CLIInput(), CLIOutput()), MemoryUserRepository(), MemoryDataRepository(), MemoryBillRepository()) application.run() except Exception: """ If your exception reaches this point, it's either you are _bad_ programmer or a fatal circumstance """ print "You should never see this message. If you do see it, something pretty ridiculous happened" if isinstance(application, Application): application.exit()
import sys import os import time import thread import quickfix as fix import quickfix44 as fix44 from datetime import datetime import Application if __name__ == '__main__': config = 'settings.cfg' accesskey = 'add your accesskey here' # add your API keys created in BTCC exchange secretkey = 'add your secretkey here' settings = fix.SessionSettings (config) storeFactory = fix.FileStoreFactory (settings) logFactory = fix.FileLogFactory (settings) application = Application.Application() initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory) initiator.start () application.run (accesskey, secretkey) initiator.stop ()
self.slider.blockSignals(True) self.slider.setValue(value) self.slider.blockSignals(False) print('FeatureWidget {} 2 set value {}'.format(self.name, value)) RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" THEME_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize" ACCENT_PATH = r'HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Accent' if __name__ == '__main__': # print(os.environ['QT_API']) getAccentColor() app = Application(sys.argv) # settings = QSettings(RUN_PATH, QSettings.NativeFormat) # clock = Window() # setup stylesheet # the default system in qdarkstyle uses qtpy environment variable # app.setStyleSheet(qdarkstyle.load_stylesheet()) # clock.show() app.window.position_show() sys.exit(app.exec_())
import pygame from Application import * pygame.init() main_screen = pygame.display.set_mode((1280, 720)) pygame.display.set_caption("Pac-Man - G.Koganovskiy") pygame.display.set_icon(pygame.image.load("Static/Sprites/Pacman/Pacman-Open-R.png")) frame_rate = pygame.time.Clock() game_application = Application() running = True while running: running = stop_check() main_screen.fill((18, 18, 18)) frame_rate.tick(60) game_application.update(pygame.key.get_pressed()) main_screen.blit(game_application.screen, (0, 0)) pygame.display.update() pygame.QUIT
# -*- coding: utf-8 -*- {%- if cookiecutter.pyapp_type == "asyncio" -%} {%- set async = "async" -%} {%- set appmod = "nicfit.aio" -%} {%- else -%} {%- set async = "" -%} {%- set appmod = "nicfit" -%} {%- endif %} from {{ appmod }} import Application from nicfit.console import pout from . import version {{ async }} def main(args): pout("\m/") app = Application(main, version=version, {%- if cookiecutter.gettext_domain != "None" %} gettext_domain="{{ cookiecutter.gettext_domain }}") {% else %} gettext_domain=None) {% endif %} if __name__ == "__main__": app.run()
from ConfigurationHandler import ConfigurationHandler logger = logging.getLogger(__name__) #tmp_video_folder = os.path.abspath("F:/GoPro/Kabelpark/20180603") #tmp_video_folder = os.path.abspath("E:/DCIM/100GOPRO") # - very slow to read from SD card using converter and build-in reader #tmp_user_folder = os.path.abspath("F:/GoPro/BearVision/users") tmp_video_folder = os.path.abspath("input_video") tmp_user_folder = os.path.abspath("users") tmp_config_file = os.path.abspath("test_config.ini") # list of actions to do in the test tmp_action_list = [ ActionOptions.GENERATE_MOTION_FILES.value, ActionOptions.INIT_USERS.value, ActionOptions.MATCH_LOCATION_IN_MOTION_FILES.value, ActionOptions.GENERATE_FULL_CLIP_OUTPUTS.value, ActionOptions.GENERATE_TRACKER_CLIP_OUTPUTS.value ] print("Starting test!\n") logger.debug( "------------------------Start------------------------------------") tmp_options = ConfigurationHandler.read_config_file(tmp_config_file) app_instance = Application.Application() app_instance.run(tmp_video_folder, tmp_user_folder, tmp_action_list) print("\nFinished test!") logger.debug( "-------------------------End-------------------------------------")
def main(stdout=False): print(powstr) print(60*"-") print("Collecting the routes") print(60*"-") app=Application() if stdout: print() #tornado.options.parse_command_line() #from tornado.log import enable_pretty_logging #enable_pretty_logging() #print(dir(tornado.options.options)) tornado.options.options.log_file_prefix = myapp["logfile"] tornado.options.options.log_file_num_backups=5 # size of a single logfile tornado.options.options.log_file_max_size = 10 * 1000 * 1000 tornado.options.parse_command_line() gen_logger = logging.getLogger("tornado.general") gen_logger.addHandler(log_handler) access_logger = logging.getLogger("tornado.access") access_logger.addHandler(log_handler) #print(access_logger.handlers) #for elem in access_logger.handlers: # print(dir(elem)) app_logger = logging.getLogger("tornado.application") app_logger.addHandler(log_handler) #app = tornado.web.Application(handlers=routes, **app_settings) #if stdout: # print(60*"-") # print("Databases: " ) # print(60*"-") # #for idx, elem in enumerate(db_settings["sql"]): # print(" SQL-DB : enabled: {} type: {}".format( # str(db_settings["sql"]["enabled"]), db_settings["sql"]["type"] )) # print(" TinyDB : enabled: {}".format( str(db_settings["tinydb"]["enabled"]))) # print(" MongoDB : enabled: {}".format( str(db_settings["mongodb"]["enabled"]))) # for idx, elem in enumerate(db_settings["mongodb"]["indexes"]): # print(" Index #{:2}: collection: {:12} def: {} ".format( # str(idx), elem, db_settings["mongodb"]["indexes"][elem] )) # print(" Elastic : enabled: {}".format( str(db_settings["elastic"]["enabled"]))) #app=Application() #print(app) if stdout: #print(app.handlers) print() print(60*"-") print("Final routes (order matters from here on ;) " ) print(60*"-") for idx,elem in enumerate(app.handlers): print("ROUTE {:2}: pattern: {:50} handler: {:20} ".format( str(idx), str(elem[0])[0:48], str(elem[1].__name__) )) if app_settings["ssl"]: ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain(app_settings["ssl_options"]["certfile"], app_settings["ssl_options"]["keyfile"]) app_settings["protocol"] = "https" http_server = tornado.httpserver.HTTPServer(app,ssl_options = ssl_ctx) else: app_settings["protocol"] = "http" http_server = tornado.httpserver.HTTPServer(app) print() print(60*"-") print("starting the PythonOnWheels server Server ") print(60*"-") print(f"visit: {app_settings['protocol']}://{app_settings['host']}:{app_settings['port']}") print("starting...") http_server.listen(app_settings["port"]) ioloop = tornado.ioloop.IOLoop.instance() if app_settings["IOLoop.set_blocking_log_threshold"]: ioloop.set_blocking_log_threshold( app_settings["IOLoop.set_blocking_log_threshold"]) ioloop.start()
# khz / 2016 # import tornado.httpserver import os import os.path import sys from {{appname}}.config import server_settings as app_settings from {{appname}}.config import myapp from {{appname}}.config import database as db_settings from {{appname}}.powlib import merge_two_dicts from {{appname}}.application import Application, log_handler import logging app=Application() def main(stdout=False): if stdout: print() #tornado.options.parse_command_line() #from tornado.log import enable_pretty_logging #enable_pretty_logging() #print(dir(tornado.options.options)) tornado.options.options.log_file_prefix = myapp["logfile"] tornado.options.options.log_file_num_backups=5 # size of a single logfile tornado.options.options.log_file_max_size = 10 * 1000 * 1000 tornado.options.parse_command_line()
from config import change_address_to, change_address_from from searchTranslation import search_translation, config_language from extractDataWeb import extract_translation import searchTranslation #name of the mail subject - in the function it adds the file name SUBJECT = 'english_notebook' file_name = input('Introduce the name of the file:\n>>> ') #Check if the file_name has the termination .csv if file_name[-4:] != '.csv': file_name += '.csv' app = a.Application(file_name) #try to load the data if the file already exist try: app.load() except FileNotFoundError: print('You dont have data. Lets start to fill it! :D') def main_screen(): """ main screen - Show all the options """ screen = "(1) Add\n" \ "(2) Delete\n" \ "(3) Search\n" \
this class is the link between ros callback listener and the gui App. Author: Quentin Marmouget Last modified: """ import rospy from std_msgs.msg import String from std_msgs.msg import Int32 from Tkinter import * import Application def listener(): rospy.init_node('DMX_listener', anonymous=True) # spin() simply keeps python from exiting until this node is stopped root.mainloop() root.destroy() while not rospy.is_shutdown(): rospy.spin() if __name__ == '__main__': root = Tk() App = Application.Application(master=root) listener()
import sys from DataBaseManager import * from utils import * import numpy as np from sklearn.cluster import KMeans from sklearn.metrics.pairwise import cosine_similarity import operator import random from ProfileManager import * from Profile import * # Creat DB #DBM = DataBaseManager("Recipes.db", "Profile.db") #recipes = DBM.load_recipes_from_database2("Recipes.db") #DBM.create_profile_table('Vincent') #r1 = Recipe("ww.test.org", "soupe aux poireaux", "plat principal", "Facile", "pas cher", "2", "40", "40", "poireaux|pommesdeterre|oignon", "faire cuire la soupe", "like", "2") #r2 = Recipe("ww.test.org", "soupe aux champignons", "plat principal", "Moyennement difficile", "difficile", "2", "40", "40", "champignon|salade|carottes", "faire cuire la soupe", "dislike", "0") #liked_recipes = [r1] #DBM.add_liked_recipes_to_profile('Vincent', liked_recipes) #vince_profile = DBM.load_profile_from_database('Vincent') #print(vince_profile.get_name()) #============================================== app = Application("Recipes.db", "Profile.db") app.start()