Beispiel #1
0
 def __init__(self, bot, config):
     self.bot = bot
     self.config = config
     self.statuses = statusstore()
     self.about = "'sleekmotion_aways' Learn status messages from people, and use them.\nWritten by Kevin Smith"
     self.bot.add_handler("<presence />", self.handle_presence)
     thread.start_new(self.loop,())
Beispiel #2
0
 def UpdatePlot(self, data, times):
     if USE_THREADS:
         if not self.plot.mutex.locked():
             self.plot.mutex.acquire()
             thread.start_new(self.plot.Update, (data, times))#self.plot.Update(data)
     else:
         self.plot.Update(data, times)
    def start(self):
        """Start the uber basic interface.

        All request are handled by BasicWeb method handle_request.

        """

        def make_handler(parent):
            class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
                # A super-simple HTTP request handler:
                def do_GET(self):
                    parent.handle_request("GET", self)

                def do_POST(self):
                    parent.handle_request("POST", self)

                def do_PUT(self):
                    parent.handle_request("PUT", self)

                def do_DELETE(self):
                    parent.handle_request("DELETE", self)

                def do_HEAD(self):
                    parent.handle_request("HEAD", self)

            return RequestHandler

        self.log.info("Creating FakeWebServer.")
        self.server = StoppableTCPServer((self.interface, self.port), make_handler(self))

        def _start(data=0):
            self.log.info("start: URI<%s>" % self.uri)
            self.server.serve_forever()

        thread.start_new(_start, (0,))
Beispiel #4
0
def main():
    # Set up arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("-ps", "--port_server", help="Server for http client port", type=int, default=35001)
    parser.add_argument("-pm", "--port_master", help="Master port toward the game instances", type=int, default=65523)
    parser.add_argument("-sc", "--screen_config",
                        help="Pick a screen config of the available files inside the screenconfig folder",
                        type=str, default="default")
    parser.add_argument("-t", "--time", help="How long should the game run before it shutdown, in second", type=int)
    parser.add_argument("-m", "--measure", help="Should game resources be measured", type=bool, default=False)
    args = parser.parse_args()

    #Set up the Master connection
    connection_point = mcp.MasterConnectionPoint('0.0.0.0',
                                                 args.port_master,
                                                 args.screen_config,
                                                 args.time,
                                                 args.measure)

    app.connection_point = connection_point
    thread.start_new(connection_point.listen_for_slaves, ())

    signal.signal(signal.SIGINT, signal_handler)
    #Start running flask
    app.run(host='0.0.0.0', port=args.port_server)
Beispiel #5
0
	def __init__(self, bot, config):
		self.bot = bot
		self.config = config
		self.about = "Eggdropbot allows sleekbots to run Eggdrop IRC (TCL) scripts, providing the (currently partial) Eggdrop API re-implemented for XMPP MUC.\nWritten By: Kevin Smith"
		self.bot.addIMCommand('eggdrop', self.handle_eggdrop)
		self.bot.addMUCCommand('eggdrop', self.handle_eggdrop)
		self.bot.addHelp('eggdrop', 'Eggdrop control command', "Configure eggdrop compatability support.", 'eggdrop [args]')
		self.bot.add_event_handler("message", self.handle_message_event, threaded=True)
		self.bot.add_event_handler("groupchat_message", self.handle_muc_event, threaded=True)
		# queue of outgoing TCL
		self.queue = Queue.Queue()
		# list of incoming messages from tcl
		self.messageQueue = []
		#self.queueExec('puts "bert"')
		#TCL support scripts - these are the TCL side of the eggdrop emulation
		self.queueExec('source "plugins/eggdrop/support.tcl"')
		self.queueExec('source "plugins/eggdrop/eggdropcompat.tcl"')
		#load the user-specified eggdrop scripts
		scripts = self.config.findall('script')
		if scripts:
			for script in scripts:
				logging.info("eggdropbot.py loading script %s." % script.attrib['file'])
				self.queueExec('source "scripts/' + script.attrib['file'] + '"')
		
		thread.start_new(self.loop,())
Beispiel #6
0
def run():
    try:
        insert_iptables_rules()
        thread.start_new(handle_nfqueue, ())
    except:
        LOGGER.exception('failed to start dns service')
        dns_service_status.error = traceback.format_exc()
Beispiel #7
0
def parent():
    i = 0
    while 1:
        i = i + 1
        thread.start_new(child, (i,))
        if raw_input() == "q":
            break
Beispiel #8
0
def applyFunctionToNFrames(func, filesPerThread, nframes, conversionargs):
    if (nframes < filesPerThread):
        func(0, 0, nframes, conversionargs)
    else:
        try:
            import thread
            keepSpawning = 1
            start = filesPerThread
            end = filesPerThread
            threadID = 1
            # Create a mutex array
            numThreads = nframes / filesPerThread
            if (numThreads * filesPerThread < nframes):
                numThreads = numThreads + 1
            exitmutex = [0] * numThreads
            while keepSpawning == 1:
                end = end + filesPerThread
                if (end >= nframes):
                    end = nframes
                    keepSpawning = 0
                thread.start_new(
                    applyFunctionToNFramesWMutex,
                    (threadID, exitmutex, func, start, end, conversionargs))
                start = start + filesPerThread
                threadID = threadID + 1
            # Do the first part of the work on the main thread.
            applyFunctionToNFramesWMutex(0, exitmutex, func, 0, filesPerThread,
                                         conversionargs)

            # Wait for all of the threads to complete
            while 0 in exitmutex:
                pass
        except ImportError:
            print "Could not import threads module."
            func(0, 0, nframes, conversionargs)
 def __init__(self):
     self.log = logging.getLogger()
     logging.basicConfig()
     self.log.setLevel(logging.DEBUG)
     self.GPIO = GPIO.setmode(GPIO.BOARD)
     self.log.debug('GPIO.BOARD')
     thread.start_new(self.init,(7,))
Beispiel #10
0
def init_pipe():
    try:
        thread.start_new(socket_output_thread, ())
        thread.start_new(socket_input_thread,())
    except:
        print "Could nor start pipe thread ...."
        exit()  
Beispiel #11
0
 def aceptarConexionPlayerTCP(self):
     print "Esperando aceptar conexion TCP por parte del player VLC"
     thread.start_new(self.abrirVLC, ())
     (self.socketClientePlayer,
      self.direccionPlayer) = self.socketPlayerTCP.accept()
     print "Conexion con el player aceptada"
     print "Direccion player: ", self.direccionPlayer
Beispiel #12
0
    def perspective_requestPassword(self, publicname, email):
        # TODO: should have some logging here that can be linked to fail2ban
        from newplayeremail import LostPasswordEmail

        try:
            a = Account.byPublicName(publicname)
        except:
            return (
                -1,
                "Unknown Public Name, please check spelling and case.\n\n  If you continue to have problems, please contact support."
            )

        if a.email.lower() != email.lower():
            return (
                -1,
                "Email doesn't match, please make sure to specify the email used when registering.\n\n  If you continue to have problems, please contact support."
            )

        if not USE_WX:
            import thread
            thread.start_new(LostPasswordEmail,
                             (a.email, a.publicName, a.password))

        return (0,
                "Your password has been sent to the email address specified.")
Beispiel #13
0
def main():
    global hpclient
    try:
        hpclient = hpfeeds.new(args.g[0], 10000, args.g[1], args.g[2])

        if args.f:
            f = open(args.f, 'a')
            f.write('Starting Server at %s\n' % (str(now)))
            f.close()
        print("Starting NBNS Request Thread...")
        thread.start_new(sender, ())
        try:
            print("Starting UDP Response Server...")
            sniff(iface=iface,
                  filter="udp and port 137",
                  store=0,
                  prn=get_packet)
        except KeyboardInterrupt:
            print("\nStopping Server and Exiting...\n")
            now3 = datetime.datetime.now()
            if args.f:
                f = open(args.f, 'a')
                f.write('Stopping Server at %s\n' % (str(now3)))
                f.close()
        except Exception as err:
            print("""Server could not be started, confirm you're running this
                    as root.\n %s""" % err)
    except KeyboardInterrupt:
        exit()
    except Exception as err:
        print("""Server could not be started, confirm you're running this
                as root.\n %s""" % err)
    finally:
        hpclient.close()
Beispiel #14
0
def initEventLoop():
    global sckt, debugging, hasPassedNameScreen, hasPassedMainScreen
    playSound("bgm")
    thread.start_new(connectServer, (1, connectAttempts))
    while True:
        for event in pygame.event.get():
            if (event.type == KEYDOWN):
                # print "key is", event.key, pygame.key.name(event.key)
                if (event.key == K_RETURN):
                    if hasPassedMainScreen == True:
                        # has passed main screen
                        hasPassedNameScreen = True		
                if event.key<256:
                    if hasPassedNameScreen == False:
					    # is on name screen
                        sckt.send(chr(event.key))
                    else:
                        # is on game screen
                        sckt.send(chr(AltControls(event.key)))
                    hasPassedMainScreen = True
                if (event.key == K_ESCAPE):
                    screen = pygame.display.set_mode((640, 480))
                    sys.exit(0)
               		
            elif event.type == USEREVENT:
                line = event.serverLine
                if debugging == 1:
                    print "about to process", line
                processLine(line)
                if line != 'sync':
                    historyList.append([line, pygame.time.get_ticks()])
                if line == 'quit':
                    return
                if line == 'abort':
                    sys.exit(0)
Beispiel #15
0
  def __init__(self, serverIP, port=8000, autoEvents=True): 
    utils.logger.debug("RClient.__init__")
    synchronized.Synchronized.__init__(self)

    dMVC.setRClient(self)

    self.__serverIP   = serverIP
    self.__serverPort = port

    self.__rootModel = None
    self.__sessionID = None
    self.__version = None
    self.__initialDataSemaphore = threading.Semaphore(0)

    self.__answersCommandsList = []

    self.__remoteSuscriptions = {}  

    self.__socket = None
    self.__connect()

    self.__commandQueue = Queue.Queue()
    self.__asyncCommandQueue = Queue.Queue()
    self.__asyncCallback = {}
    self.__fragmentAnswer = {}

    self.__autoEvents = autoEvents
    if self.__autoEvents:
      threadProcessCommand = threading.Thread(target=self.processCommandQueue)
      threadProcessCommand.setDaemon(True)
      threadProcessCommand.start()
    thread.start_new(self.__start, ())
Beispiel #16
0
    def startCell(self):

        self._procs = []
        modules = self._config.modules()
        for module in modules:
            print "Importing module %s" % module
            exec("import %s" % module)

        cmdlines = self._config.commandLines()
        for cmd in cmdlines:
            print "Running: %s" % (cmd)
            pid = os.fork()
            if pid==0:  # child process
                args = [sys.executable]+cmd
                os.execvp(sys.executable, args)
                # exec shouldn't return in child process
                assert 0, "Error launching child process"   # exec shou
            else:
                print "CellManager started child process with command: %s" % \
                        cmd
                # Warning: Magic 
                args = cmd # [entity|entityservice, name, key]
                port = 50000+pid
                client = {'name':args[1], 'key':args[2], 'port':port,
                          'pid':pid, 'queue':Queue()}
                thread.start_new(self.handleClient, (client,))
                self._clients.append(client)
   def resolveFakeDimensions (self, task):      
      netCdfObject = GmiNetCdfFileTools ()

      print "about to start threads for resolving dimensions..."

      exitMutexes = []
      count = 0
      for prefix in self.PREFIXES:
         for resolution in ["2x2.5", "1x1.25", "0.625x0.5"]:
            fileName = self.basePath + prefix  + self.endPath + "." + resolution + ".nc"
            if not os.path.exists (fileName): raise fileName + " does not exist! ERROR"

            # for each file type fix the fake dimensions
            exitMutexes.append (thread.allocate_lock())
            thread.start_new (netCdfObject.resolveFieldDimensions, \
                (fileName, count, self.GEOS5FIELDS, ['time', 'lat', 'lon'], exitMutexes[count]))
            
            count = count + 1
         
      #----------------------------------------------------------------
      # Wait for all three threads before proceeding 
      #----------------------------------------------------------------
      for mutex in exitMutexes:
         while not mutex.locked (): 
            pass
    

      print "All threads returned from resolveFieldDimensions"
def find_url(r, nused):
	while True:
		try:
			for i in r["response"]["posts"]:
			
				id = i["id"]
				id = str(id)
				#print id
				test_url = 'http://api.tumblr.com/v2/blog/'+tumblr+'/posts?id='
				test_url += str(i["id"]) + "&api_key=LavgbZzW1LV2skL5EMhhrEucUPikpP4Ag6KKNBJB77dojfzfaw"
				#print test_url
				testinfo = requests.get(test_url, auth=oauth).json()
				for aa in testinfo["response"]["posts"]:
					if 'photos' not in aa:
						continue
					else:
						for bb in aa["photos"]:
							#print bb["original_size"]["url"]
							filename = str(bb["original_size"]["url"])
							filename = filename.split('_', 1)[-1]
							filename = os.path.join(dest_dir, filename)
							while threading.activeCount() >= 100:
								sleep(2)
							else:
								thread.start_new(download_url, (bb["original_size"]["url"], filename))

		except requests.exceptions.RequestException:
			global problem
			problem = problem + 1
			sleep(5)
			continue
		else:
			break
Beispiel #19
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self, parent=getMayaWindow())

        _DEFAULT_PORT = "18812"

        # This is where the tmp geo will be saved (as .obj)
        # and load in Houdini from.

        self.PATH = os.path.join(os.environ['temp'],
                                 "tmp.obj").replace('\\', '/')

        self.setWindowTitle("Maya - Houdini bridge")
        cw = QtGui.QWidget()

        # Default connection variables
        self.houdini_connexion = None
        self.hou = None

        # Switch variables
        self.check_connection = True
        self.dynamicCameraON = False
        self.cancel = False

        cw_layout = QtGui.QVBoxLayout()
        cw_layout.setSpacing(10)

        # Houdini connection UI
        houConnectionLayout = QtGui.QHBoxLayout(spacing=20)
        self.houConnectionLabel = QtGui.QLabel("Not connected to Houdini")

        self.houConnectionBtn = QtGui.QPushButton("")
        self.houConnectionBtn.setFlat(True)
        self.houConnectionBtn.setIcon(
            QtGui.QIcon(os.path.dirname(__file__) + "/icons/red_light.png"))
        self.houConnectionBtn.setFixedSize(32, 32)
        self.houConnectionBtn.setIconSize(QtCore.QSize(32, 32))
        self.houConnectionBtn.clicked.connect(self._connectTOHou)

        houConnectionLayout.addWidget(self.houConnectionBtn)
        houConnectionLayout.addWidget(self.houConnectionLabel)

        # Send geo button UI
        self.sendGeoToHouBtn = QtGui.QPushButton(
            "Send selected mesh to houdini", self)
        self.sendGeoToHouBtn.clicked.connect(self.sendSelectionToHoudini)
        self.sendGeoToHouBtn.setDisabled(True)

        # Dynamic camera create / disable button
        self.dynCamBtn = QtGui.QPushButton("Create/Enable Dynamic Camera")
        self.dynCamBtn.clicked.connect(self.createDynamicCamera)
        self.dynCamBtn.setDisabled(True)

        cw_layout.addItem(houConnectionLayout)
        cw_layout.addWidget(self.sendGeoToHouBtn)
        cw_layout.addWidget(self.dynCamBtn)
        cw.setLayout(cw_layout)
        self.setCentralWidget(cw)

        # Check here if we can connect to houdini or not
        thread.start_new(self._connectionCheck, ())
Beispiel #20
0
def WaitFunc(Parent_, Msg_, Func_, FuncArgs_=(), FuncKW_={}, Frames_=None):
    """
    Окно ожидания.
    @param Parent_: Ссылка на окно.
    @param Msg_: Текст диалога.
    @param Func_: Функция, которую необходимо подождать.
    @param FuncArgs_: Аргументы функции.
    @param FuncKW_: Именованные аргументы функции.
    @param Frames_: Файлы-кадры.
    """
    global ic_wait_proccess_dlg

    wait_result = [None]
    if not Frames_:
        # Определить кадры по умолчанию
        wait_dir = os.path.dirname(__file__) + '/Wait/'
        Frames_ = [
            wait_dir + 'Wait1.png', wait_dir + 'Wait2.png',
            wait_dir + 'Wait3.png', wait_dir + 'Wait4.png',
            wait_dir + 'Wait5.png', wait_dir + 'Wait6.png',
            wait_dir + 'Wait7.png', wait_dir + 'Wait8.png',
            wait_dir + 'Wait9.png', wait_dir + 'Wait10.png',
            wait_dir + 'Wait11.png', wait_dir + 'Wait12.png',
            wait_dir + 'Wait13.png', wait_dir + 'Wait14.png',
            wait_dir + 'Wait15.png'
        ]
    ic_wait_proccess_dlg = wait_box = icWaitBox(Parent_, Msg_, Frames_)
    wait_box.SetResultList(wait_result)
    # Запустить функцию ожидания
    thread.start_new(wait_box.Run, (Func_, FuncArgs_, FuncKW_))
    wait_box.ShowModal()
    wait_box.Destroy()
    ic_wait_proccess_dlg = None
    return wait_result[0]
Beispiel #21
0
    def bConvert(self, widget, data=None):

        self.response = gtk.RESPONSE_OK
        self.ProgressBar = ProgressBar(self.__progress, self, self.DlgConvert)
        self.ProgressBar.start()

        thread.start_new(self.worker_thread, (self.convertToXML(), ))
Beispiel #22
0
    def test_wait(self):
        for i in range(NUM_THREADS):
            thread.start_new(self.f, (i,))

        time.sleep(LONGSLEEP)

        a = self.alive.keys()
        a.sort()
        self.assertEquals(a, range(NUM_THREADS))

        prefork_lives = self.alive.copy()

        if sys.platform in ['unixware7']:
            cpid = os.fork1()
        else:
            cpid = os.fork()

        if cpid == 0:
            # Child
            time.sleep(LONGSLEEP)
            n = 0
            for key in self.alive:
                if self.alive[key] != prefork_lives[key]:
                    n += 1
            os._exit(n)
        else:
            # Parent
            self.wait_impl(cpid)
            # Tell threads to die
            self.stop = 1
            time.sleep(2*SHORTSLEEP) # Wait for threads to die
Beispiel #23
0
def main():

    prog = Program()
    print "Starting..."

    #prog.Login_Online_DB()    #moved to __init__

    socketIO.on('sendLocation' + PhoneNumber, prog.Update_GPS_Socket)
    socketIO.on('TakePic' + PhoneNumber, prog.Update_Picture_Socket)
    socketIO.on('Light' + PhoneNumber, prog.Update_Light_Socket)
    socketIO.on('sendHeartBit' + PhoneNumber, prog.Update_Pulse_Socket)

    try:
        thread1 = thread.start_new(prog.Get_Gps, ())
        thread2 = thread.start_new(prog.Update_GPS_DB, ())
        thread3 = thread.start_new(prog.leds_controler, ())
        thread4 = thread.start_new(prog.Get_Pulse, ())
        #thread5 = thread.start_new(prog.Get_temperature, ())
    except:
        print "Thread Exeption"




    socketIO.wait(seconds=10000)
def main():
    for i in range(NUM_THREADS):
        thread.start_new(f, (i, ))

    time.sleep(LONGSLEEP)

    a = alive.keys()
    a.sort()
    verify(a == range(NUM_THREADS))

    prefork_lives = alive.copy()

    if sys.platform in ['unixware7']:
        cpid = os.fork1()
    else:
        cpid = os.fork()

    if cpid == 0:
        # Child
        time.sleep(LONGSLEEP)
        n = 0
        for key in alive.keys():
            if alive[key] != prefork_lives[key]:
                n = n + 1
        os._exit(n)
    else:
        # Parent
        spid, status = os.waitpid(cpid, 0)
        verify(spid == cpid)
        verify(status == 0,
               "cause = %d, exit = %d" % (status & 0xff, status >> 8))
        global stop
        # Tell threads to die
        stop = 1
        time.sleep(2 * SHORTSLEEP)  # Wait for threads to die
Beispiel #25
0
 def __init__(self, bot, config):
     self.bot = bot
     self.config = config
     self.about = "Attempts to keep Sleek in muc channels."
     self.shuttingDown = False
     thread.start_new(self.loop, ())
     self.bot.add_handler("<message xmlns='jabber:client' type='error'><error type='modify' code='406' ><not-acceptable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></message>", self.handle_message_error)
Beispiel #26
0
    def test_wait(self):
        for i in range(NUM_THREADS):
            thread.start_new(self.f, (i, ))

        time.sleep(LONGSLEEP)

        a = self.alive.keys()
        a.sort()
        self.assertEquals(a, range(NUM_THREADS))

        prefork_lives = self.alive.copy()

        if sys.platform in ['unixware7']:
            cpid = os.fork1()
        else:
            cpid = os.fork()

        if cpid == 0:
            # Child
            time.sleep(LONGSLEEP)
            n = 0
            for key in self.alive:
                if self.alive[key] != prefork_lives[key]:
                    n += 1
            os._exit(n)
        else:
            # Parent
            self.wait_impl(cpid)
            # Tell threads to die
            self.stop = 1
            time.sleep(2 * SHORTSLEEP)  # Wait for threads to die
Beispiel #27
0
    def test_fork(self):
        # XXX This test depends on a multicore machine, as busy_thread must
        # aquire the GIL the instant that the main thread releases it.
        # It will incorrectly pass if the GIL is not grabbed in time.
        import thread
        import os
        import time

        if not hasattr(os, 'fork'):
            skip("No fork on this platform")

        run = True
        done = []
        def busy_thread():
            while run:
                time.sleep(0)
            done.append(None)

        try:
            thread.start_new(busy_thread, ())

            pid = os.fork()

            if pid == 0:
                os._exit(0)

            else:
                time.sleep(1)
                spid, status = os.waitpid(pid, os.WNOHANG)
                assert spid == pid
        finally:
            run = False
            self.waitfor(lambda: done)
Beispiel #28
0
 def __init__(self, acceptAllTokens=True):
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.socket.bind(("", 7534))
     self.socket.listen(2)
     self.connections = []
     thread.start_new(self.main_loop, tuple())
Beispiel #29
0
    def test_fork(self):
        # XXX This test depends on a multicore machine, as busy_thread must
        # aquire the GIL the instant that the main thread releases it.
        # It will incorrectly pass if the GIL is not grabbed in time.
        import thread
        import os
        import time

        if not hasattr(os, 'fork'):
            skip("No fork on this platform")

        run = True
        done = []

        def busy_thread():
            while run:
                time.sleep(0)
            done.append(None)

        try:
            thread.start_new(busy_thread, ())

            pid = os.fork()

            if pid == 0:
                os._exit(0)

            else:
                time.sleep(1)
                spid, status = os.waitpid(pid, os.WNOHANG)
                assert spid == pid
        finally:
            run = False
            self.waitfor(lambda: done)
Beispiel #30
0
def get_txt(lang):
    try:
        txt = open(langs[lang]).read()
        return txt
    except:
        return "no input file"
        thread.start_new()
Beispiel #31
0
def newAnalyse():
    global processors

    args = request.get_json()
    analysisMode = args.get("mode", "psnr")
    referenceVideo = args.get("reference", None)
    videos = args.get("videos", None)

    if referenceVideo == None or videos == None:
        abort(400)

    if not type(videos) == list and len(video) > 0:
        abort(400)

    if not type(referenceVideo) == unicode:
        abort(400)

    outputFile = os.path.join("results", str(uuid.uuid4()) + ".xml")

    processor = QpsnrProcessor()
    processor.analysisMode = analysisMode
    processor.outputFile = outputFile
    processor.referenceVideo = referenceVideo
    processor.videos = videos

    processors.append(processor)

    thread.start_new(processors[len(processors) - 1].run, ())
    return jsonify(processor.__dict__)
Beispiel #32
0
 def run_websocket(self, url):
     websocket.enableTrace(True)
     if not self.client.ws:
         self.client.ws = websocket.WebSocketApp(url=url,
                                                 on_message=self.on_message,
                                                 header=self.client.headers)
         thread.start_new(self.client.ws.run_forever, ())
Beispiel #33
0
def main():
    monitoring_channel = acquire_xos_monitoring_channel()
    if not monitoring_channel:
        print 'SRIKANTH: XOS monitoring_channel is not created... Create it before using this app'
        return
    loadAllXosTenantInfo()
    loadAllXosInstanceInfo()
    ceilometer_url = monitoring_channel['ceilometer_url']
    if use_kafka:
        thread.start_new(read_notification_from_ceilometer_over_kafka, (
            KAFKA_SERVER_IP,
            KAFKA_SERVER_PORT,
            KAFKA_TOPIC,
        ))
        subscribe_data = {
            "sub_info": "cpu_util",
            "app_id": "xos_auto_scale",
            "target": LOCAL_KAFKA_TARGET_URL
        }
    else:
        thread.start_new(read_notification_from_ceilometer, (
            UDP_IP,
            UDP_PORT,
        ))
        subscribe_data = {
            "sub_info": "cpu_util",
            "app_id": "xos_auto_scale",
            "target": "udp://10.11.10.1:12346"
        }
    subscribe_url = ceilometer_url + 'v2/subscribe'
    response = requests.post(subscribe_url, data=json.dumps(subscribe_data))
    print 'SRIKANTH: Ceilometer meter "cpu_util" Subscription status:%s' % response.text
    #TODO: Fix the typo in 'sucess'
    if (not 'sucess' in response.text) and (not 'already exists'
                                            in response.text):
        print 'SRIKANTH: Ceilometer meter "cpu_util" Subscription unsuccessful...Exiting'
        return
    if use_kafka:
        subscribe_data = {
            "sub_info": "instance",
            "app_id": "xos_auto_scale2",
            "target": LOCAL_KAFKA_TARGET_URL
        }
    else:
        subscribe_data = {
            "sub_info": "instance",
            "app_id": "xos_auto_scale2",
            "target": "udp://10.11.10.1:12346"
        }
    subscribe_url = ceilometer_url + 'v2/subscribe'
    response = requests.post(subscribe_url, data=json.dumps(subscribe_data))
    print 'SRIKANTH: Ceilometer meter "instance" Subscription status:%s' % response.text
    #TODO: Fix the typo in 'sucess'
    if (not 'sucess' in response.text) and (not 'already exists'
                                            in response.text):
        print 'SRIKANTH: Ceilometer meter "instance"Subscription unsuccessful...Exiting'
        return
    periodic_cpu_threshold_evaluator()
    periodic_print()
    setup_webserver()
Beispiel #34
0
def wait_func(parent, message,
              function, func_args=(), func_kwargs={},
              art_frames=None):
    """
    Окно ожидания.
    @param parent: Ссылка на окно.
    @param message: Текст диалога.
    @param function: Функция, которую необходимо подождать.
    @param func_args: Аргументы функции.
    @param func_kwargs: Именованные аргументы функции.
    @param art_frames: Файлы-кадры.
    """
    global ic_wait_process_dlg
    
    wait_result = [None]
    if not art_frames:
        # Определить кадры по умолчанию
        cur_dir = os.path.dirname(__file__)
        if not cur_dir:
            cur_dir = os.getcwd()
        wait_dir = cur_dir+'/img/wait/'
        art_gif = wait_dir+'spinner.gif'

    if parent is None:
        parent = wx.GetApp().GetTopWindow()
    ic_wait_process_dlg = wait_box = icWaitBox(parent, message, art_gif)
    wait_box.set_result_list(wait_result)

    # Запустить функцию ожидания
    thread.start_new(wait_box.run, (function, func_args, func_kwargs))
    wait_box.ShowModal()
    wait_box.Destroy()
    ic_wait_process_dlg = None
    return wait_result[0]
Beispiel #35
0
    def start(self):
        """Start the uber basic interface.

        All request are handled by BasicWeb method handle_request.

        """
        def make_handler(parent):
            class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
                # A super-simple HTTP request handler:
                def do_GET(self):
                    parent.handle_request('GET', self)

                def do_POST(self):
                    parent.handle_request('POST', self)

                def do_PUT(self):
                    parent.handle_request('PUT', self)

                def do_DELETE(self):
                    parent.handle_request('DELETE', self)

                def do_HEAD(self):
                    parent.handle_request('HEAD', self)

            return RequestHandler

        self.log.info("Creating FakeWebServer.")
        self.server = StoppableTCPServer((self.interface, self.port),
                                         make_handler(self))

        def _start(data=0):
            self.log.info("start: URI<%s>" % self.uri)
            self.server.serve_forever()

        thread.start_new(_start, (0, ))
Beispiel #36
0
    def test_fork_with_thread(self):
        # XXX This test depends on a multicore machine, as busy_thread must
        # aquire the GIL the instant that the main thread releases it.
        # It will incorrectly pass if the GIL is not grabbed in time.
        import thread
        import os
        import time

        if not hasattr(os, 'fork'):
            skip("No fork on this platform")

        def busy_thread():
            print 'sleep'
            while run:
                time.sleep(0)
            done.append(None)

        for i in range(5):
            run = True
            done = []
            try:
                print 'sleep'
                thread.start_new(busy_thread, ())

                pid = os.fork()
                if pid == 0:
                    os._exit(0)
                else:
                    self.timeout_killer(pid, 10)
                    exitcode = os.waitpid(pid, 0)[1]
                    assert exitcode == 0  # if 9, process was killed by timer!
            finally:
                run = False
                self.waitfor(lambda: done)
                assert done
Beispiel #37
0
def applyFunctionToNFrames(func, filesPerThread, nframes, conversionargs):
    if(nframes < filesPerThread):
        func(0, 0, nframes, conversionargs)
    else:
        try:
            import thread
            keepSpawning = 1
            start = filesPerThread
            end = filesPerThread
            threadID = 1
            # Create a mutex array
            numThreads = nframes / filesPerThread
            if(numThreads * filesPerThread < nframes):
                numThreads = numThreads + 1
            exitmutex = [0] * numThreads
            while keepSpawning == 1:
                end = end + filesPerThread
                if(end >= nframes):
                    end = nframes
                    keepSpawning = 0
                thread.start_new(applyFunctionToNFramesWMutex, (threadID, exitmutex, func, start, end, conversionargs))
                start = start + filesPerThread
                threadID = threadID + 1
            # Do the first part of the work on the main thread.
            applyFunctionToNFramesWMutex(0, exitmutex, func, 0, filesPerThread, conversionargs)

            # Wait for all of the threads to complete
            while 0 in exitmutex: pass
        except ImportError:
            print "Could not import threads module."
            func(0, 0, nframes, conversionargs)
  def __init__(self, input, log):

      for row in input:
          thread.start_new(self.testPort, (row[0], row[1], log))
          self.thread_count = self.thread_count + 1
      while self.thread_count > 0:
          pass
Beispiel #39
0
 def POST(self):
     web.header("Access-Control-Allow-Origin", "*")
     params = web.input()
     information = model.Information_model()
     information_data = information.query('SELECT * FROM information WHERE \
                 class_cl_id=%s and exam_ex_id=%s' % (params.class_cl_id, params.ex_id))
     information_data = [model.Information_model(**item) for item in information_data]
     exam = model.Exam_model.getByPK(params.ex_id)
     if exam.ex_type=="0":
         for information in information_data:
             information.in_endtime = datetime.datetime.now()
             information.in_state = '2'
             information.in_temp_ip = None
             db.update('exam_question', where="information_in_id = %s" % (information.in_id), eq_get_score='-2', )
             information.update()
         response = util.Response(status=util.Status.__success__, )
         return util.objtojson(response)
     else:
         if exam.ex_auto =="1":
             for information in information_data:
                 information.in_endtime = datetime.datetime.now()
                 if information.in_state=='1':
                     information.in_state = '2'
                     information.in_temp_ip = None
                     db.update('exam_question', where="information_in_id = %s" % (information.in_id),
                           eq_get_score='-2', )
                     information.update()
                     thread.start_new(util.GetScore, (1,information.in_id))
         response = util.Response(status=util.Status.__success__, )
         return util.objtojson(response)
Beispiel #40
0
def main():
    for i in range(NUM_THREADS):
        thread.start_new(f, (i,))

    time.sleep(LONGSLEEP)

    a = alive.keys()
    a.sort()
    verify(a == range(NUM_THREADS))

    prefork_lives = alive.copy()

    if sys.platform in ['unixware7']:
        cpid = os.fork1()
    else:
        cpid = os.fork()

    if cpid == 0:
        # Child
        time.sleep(LONGSLEEP)
        n = 0
        for key in alive.keys():
            if alive[key] != prefork_lives[key]:
                n = n+1
        os._exit(n)
    else:
        # Parent
        spid, status = os.waitpid(cpid, 0)
        verify(spid == cpid)
        verify(status == 0,
                "cause = %d, exit = %d" % (status&0xff, status>>8) )
        global stop
        # Tell threads to die
        stop = 1
        time.sleep(2*SHORTSLEEP) # Wait for threads to die
 def pressStart(self):
     '''
     Function triggered by clicking 'START' button.
     It will start a new thread to simulate the streaming fashion.
     '''
     thread.start_new(self.runForever, ());
     self.start_btn['state'] = Tkinter.DISABLED;
Beispiel #42
0
def main():
    bot = TulingWXBot()
    bot.DEBUG = True
    bot.conf['qr'] = 'tty'
    thread.start_new(sendJOYJInfo, (bot, 60))
    thread.start_new(sendWeatherReport, (bot, 60 * 60 * 12))
    bot.run()
Beispiel #43
0
    def release(self, path, fh):

        if Debug:
            print "*********************release"
        full_path = self._full_path(path)
        info = self.get_info(path)
        if info == None or info["isdir"]:
            full_path = self._full_path(path)
            raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), full_path)
        if os.stat(info["content_temp_path"]).st_size != 0:
            info["st_atime"] = time.time()
            info["st_size"] = os.stat(info["content_temp_path"]).st_size
            self.filesCollection.update_one({"_id": info["_id"]}, {"$set": {
                "st_size": info["st_size"],
                "st_atime": info["st_atime"]
            }})
            self.set_info(info)
            thread.start_new(self.save, (info,))
            os.close(fh)
        else:
            os.close(fh)
            os.remove(info["content_temp_path"])
            self.fileCacheLock.acquire()
            self.fileCache.pop(info["content_hash"], None)
            self.fileCacheLock.release()
Beispiel #44
0
	def httpd(self):
		# set up webserver
		self.sock = socket( AF_INET, SOCK_STREAM )
		self.listening = 0

		while self.listening != 1:
			try:
				print "Creating server... "

				if self.public:
					self.sock.bind( ("", self.port) )
				else:
					self.sock.bind( ("localhost", self.port) )

				self.sock.listen(5)
				self.listening = 1
			except:
				print "Error binding socket (retrying in 5 secs...)"
				time.sleep(5)

		print "Created server OK"

		self.openbrowser()

		while self.listening == 1:
			self.newsock, self.address = self.sock.accept()
			# print "Incoming from:  %s" % self.address[0]
			thread.start_new(self.handleClient, (self.newsock,))
 def __init__(self, bot, config):
     self.bot = bot
     self.config = config
     self.statuses = statusstore()
     self.about = "'sleekmotion_aways' Learn status messages from people, and use them.\nWritten by Kevin Smith"
     self.bot.add_handler("<presence />", self.handle_presence)
     thread.start_new(self.loop, ())
    def _connect_to_client(self, connection_ip, connection_port, direction_list):
        client = Client()
        try:
            send_list = []  # A list to store which direction this connection represent to the other client
            client.connect(connection_ip, connection_port)

            for direction in direction_list:
                self.direction_connection_dict[direction] = client  # storing the client to the direction
                send_list.append(OPPOSITE_DIRECTION_DICT[direction])  # opposite direction to the ones this game uses

            # storing the direction to the client
            self.connection_direction_dict[client.connection].extend(direction_list)
            self.connected_clients.append(client.connection)

            client.send(json.dumps({'cmd': 'setup_migration_direction', "direction": send_list}))
            thread.start_new(self._receive_for_ever, (client.connection, 1024))

        except socket.error:
            # could not connect to direction so should block it
            for direction in direction_list:
                self.the_game.block_paths_in_direction(direction)
                if direction in self.direction_connection_dict:
                    del self.direction_connection_dict[direction]
            if client.connection in self.connection_direction_dict:
                del self.connection_direction_dict[client.connection]
            if client.connection in self.connected_clients:
                self.connected_clients.remove(client.connection)
Beispiel #47
0
	def startSkulltag(self, deadArg):
		self.skulltag = subprocess.Popen(['/usr/games/skulltag/skulltag-server', '+sv_markchatlines 1']+self.args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
		self.stdinPoll = select.poll()
		self.stdinPoll.register(self.skulltag.stdout, select.POLLIN)
		self.stdoutPoll = select.poll()
		self.stdoutPoll.register(self.skulltag.stdout, select.POLLOUT)
		thread.start_new(self.rwLoop, (None,))
Beispiel #48
0
    def state_change_handler(self, ev):                                 ## to do add flow in switch enter hander and switch leave handler
         """Update topology graph when a switch enters or leaves.
         ev -- datapath event and all of it's fields

         important fields:
         ev.dp.id: dpid that is joining or leaving
         ev.enter is true if the datapath is entering and false if it is leaving
         """

         
         dp=ev.datapath
#         ports = ev.datapath.ports
         ofproto = dp.ofproto
         parser = dp.ofproto_parser   


                          
         assert dp is not None
         if dp.id is None:
            return
 

         if ev.state == MAIN_DISPATCHER:

            match = parser.OFPMatch()
            switch_list = []
            for i in self.dpid_to_switch:
               switch_list.append(i)

            self.deploy_flow_entry(dp,switch_list,match)

            if not self.graph.has_node(dp.id):
#             dpid = format_dpid_str(dpid_to_str(dp.id))
              self.graph.add_node(dp.id)
              thread.start_new(getPeriodicStats, (dp,))
              self.logger.info('Switch %s added to the topology', str(dp.id))
#             for port in ev.datapath.ports: 
#                  ports = []
#                  ports=dp.ports
#                  out_port = ports[port][0] 
#                  print out_port
#                  print 'f**k'
#                  actions =[]
#              actions = [parser.OFPActionOutput(out_port)]
#              self.add_flow( dp ,0 ,match , actions)
                   

         elif ev.state == DEAD_DISPATCHER:
            if dp.id is None:
                return
            if self.graph.has_node(dp.id):
              self.graph.remove_node(dp.id)
              self.logger.info('Switch %s removed from the topology',
                              str(dp.id))

         nx.draw(self.graph)
         plt.show()


         LOG.debug(dp)         
def messageCB(conn, msg):
    # print msg
    if msg.getType() == "groupchat":
        temp = str(msg.getFrom()).split("/", 1)
        sender = temp[0]  # Naricht kommt vom Gruppenchat
    elif msg.getType() == "chat":
        sender = msg.getFrom()  # Naricht kommt aus dem privat Chat
    if not re.search('.*/' + BOTNAME + '.*', str(
            msg.getFrom())):  # Wenn Naricht nicht vom Bot stammt
        if msg.getSubject():  # wenn das Topic dabei ist - speicher es
            global topic
            topic = msg.getSubject().encode('utf-8')
        if msg.getBody():  # Wenn Text vorhanden ist
            if not msg.getTimestamp(
            ):  # wenn Message keinen Timestamp enthaelt -- Annahme: sonst veraltet
                text = msg.getBody().encode('utf-8')
                print str(msg.getFrom()) + ": " + text  # Ausgabe auf Terminal
                splittext = text.split(" ", 1)
                global COMMAND_HANDLERS
                if text == "!help":
                    global bothelp
                    sendit(msg.getFrom(), msg.getType(), bothelp)
                if COMMAND_HANDLERS.has_key(splittext[0]):
                    if " " in text:
                        thread.start_new(COMMAND_HANDLERS[splittext[0]],
                                         (sender, msg.getType(), splittext[1]))
                    else:
                        thread.start_new(COMMAND_HANDLERS[splittext[0]],
                                         (sender, msg.getType(), ""))
                else:
                    pass
Beispiel #50
0
 def dispecher(self):
     """receiving clients and their distribution in the processing flow"""
     while True:
         connection, address = self._sockobj.accept()
         print('server connected by', address)
         print('at', self.now())
         thread.start_new(self.handleClient, (connection, address,))
 def makewidget(self):
     root = Tk()
     root.title('Chat Server...')
     bkInfo = Form(root)
     self.bkInfo = bkInfo
     thread.start_new(self.start,())
     root.mainloop()
Beispiel #52
0
 def run(self, nworkers):
     if not self.work:
         return  # Nothing to do
     for i in range(nworkers - 1):
         thread.start_new(self._worker, ())
     self._worker()
     self.todo.acquire()
Beispiel #53
0
    def onAction(self, action):
        xbmc.log(str(action.getId()))
        if action == 11:  # Info
            from resources.lib import movie

            movie.movie_id = self.current_movie["id"]
            movie.startup()
        if action == 117 or action == 101:  # Context
            cm = dialogContext("context_menu.xml", addon_path, "Default")
            cm.movie = self.current_movie
            cm.mode = self.source
            cm.xbmc_movies = self.xbmc_movies
            cm.session_id = addon.getSetting("session_id")
            cm.doModal()
            xbmc.sleep(1000)
            thread.start_new(self.updateIcons, (self.current_movie, self.current_item, 3))
        if action == 10 and action != 101:
            d = xbmcgui.Dialog()
            ans = d.yesno("tmdb Browser", "Exit themoviedb.org Browser?")
            if ans:
                xbmc.executebuiltin("Dialog.Close(all,true)")
        elif action == 92:
            self.close()
        elif action == 159:
            xbmc.executebuiltin("Dialog.Close(all,true)")
            from resources.lib import opening

            opening.startup()
Beispiel #54
0
	def run(self, nworkers):
		if not self.work:
			return # Nothing to do
		for i in range(nworkers-1):
			thread.start_new(self._worker, ())
		self._worker()
		self.todo.acquire()
Beispiel #55
0
 def onFocus(self, control):
     movieid = self.get_movieid_from_control(control)
     if movieid != "":
         self.current_item = control - 400
         movie = tmdb.get_movie(movieid)
         if show_icons == "1":
             thread.start_new(self.updateIcons, (movie, 0, 3))
         backdrop = self.getControl(32107)
         cast = self.getControl(32109)
         plot = self.getControl(32108)
         self.current_movie = movie
         actors = movie["credits"]["cast"]
         actors = sorted(actors, key=lambda k: k["order"])
         a = ""
         i = 0
         for actor in actors:
             i = i + 1
             a = a + actor["name"] + ", "
             if i == 3:
                 break
         a = a[:-2]
         cast.setLabel("[B]" + a + "[/B]")
         try:
             self.getControl(3001).setLabel("[B]" + movie["title"] + " (" + movie["release_date"][:4] + ")[/B]")
         except:
             pass
         plot.setText(movie["overview"])
         backdrop.setImage("")
         if movie["backdrop_path"] != None:
             self.getControl(32121).setLabel("Loading")
             backdrop.setImage("http://image.tmdb.org/t/p/w300" + movie["backdrop_path"])
         else:
             self.getControl(32121).setLabel("No Background Available")
Beispiel #56
0
def main():
    try:
        if args.f:
            f = open(args.f, 'a')
            f.write('Starting Server at %s\n' % (str(now)))
            f.close()
        print "Starting NBNS Request Thread..."
        thread.start_new(sender, ())
        try:
            print "Starting UDP Response Server..."
            sniff(iface='enp0s3',
                  filter="udp and port 137",
                  store=0,
                  prn=get_packet)
        except KeyboardInterrupt:
            print "\nStopping Server and Exiting...\n"
            now3 = datetime.datetime.now()
            if args.f:
                f = open(args.f, 'a')
                f.write('Stopping Server at %s\n' % (str(now3)))
                f.close()
        except Exception as err:
            print "Server could not be started, confirm you're running this as root.\n %s" % err
    except KeyboardInterrupt:
        exit()
    except Exception as err:
        print "Server could not be started, confirm you're running this as root.\n %s" % err
 def startPycheckerRun(self):
     self.result = None
     old = win32api.SetCursor(
         win32api.LoadCursor(0, win32con.IDC_APPSTARTING))
     win32ui.GetApp().AddIdleHandler(self.idleHandler)
     import thread
     thread.start_new(self.threadPycheckerRun, ())