def _run_commands_capture_output(self, commands):
     """Runs the specified commands, kill them if the timeout is exceeded, 
     and returns anything the program(s) output on stdout or stderr.
     commands must be a list of commands to run where each command to run
     is a list with the command to run in the 0th element followed by the 
     args in the following positions. Eg:
     [
         ["ls"],
         ["mv", "foo", "bar"]
     ]
     Can raise ExecutionTimedOutError.
     Implementation: This function spawns a second thread to do the execution
     of the commands and read their output into a class variable. Since that 
     thread doesn't block on anything and reads both stdout and stderr in one
     stream, there shouldn't be any possible deadlocks.
     The first thread does the timing and kills the child process if the 
     timeout specified in the settings is exceeded. Then it returns the data 
     captured by the second thread.
     """
     assert type(commands) == list
     assert len(commands) > 0
     assert type(commands[0]) == list
     assert len(commands[0]) > 0
     self.commands_output = ""
     # commands needs to be in [] because the call dereferences one set of brackets
     run_commands_thread = Thread(target=self.__actual_run_commands_capture_output, args=[commands])
     # TODO start timer
     run_commands_thread.run()
     # TODO kill process when timer expires
     return self.commands_output
Exemple #2
0
def _run(func, message):
    try:
        thread = Thread(target=func, args=(message, ))
        thread.daemon = True
        thread.run()
    except:
        print(traceback.print_exc())
    def test_fake_lock_multithreaded(self):
        lock = FakeLock()

        def f(s):
            print("In", s)
            with lock:
                print("Locked", s)
                assert lock._locked
                time.sleep(0.05)
            print("Unlocked", s)
            assert lock._locked == False

        if sys.version_info.major == 2:
            t1 = Thread(target=lambda: f("thread"))
            t2 = Thread(target=lambda: f("thread"))
            t1.daemon = True
            t2.daemon = True
        else:
            t1 = Thread(target=lambda: f("thread"), daemon=True)
            t2 = Thread(target=lambda: f("thread"), daemon=True)
        print("In Main Thread")
        f("main1")
        print("Starting Thread")
        t1.run()
        t2.run()
        f("main2")
Exemple #4
0
def run_command(command, sync=False):
    if sync:
        thread = Thread(target=run_sync, args=(command, ))
    else:
        thread = CommandThread(command)
    thread.run()
    return thread
Exemple #5
0
    def run(self):
        try:
            plugin = self.__plugin

            arguments = plugin.getArguments()
            dialog = ProcessJobDialog(plugin.getName(), plugin.getParentWindow())

            dialog.cancelConfirmed.connect(self.cancel)

            run_function = partial(self.__runWorkflowJob, plugin, arguments)

            workflow_job_thread = Thread(name="ert_gui_workflow_job_thread")
            workflow_job_thread.setDaemon(True)
            workflow_job_thread.run = run_function
            workflow_job_thread.start()


            poll_function = partial(self.__pollRunner, plugin, dialog)

            poll_thread = Thread(name="ert_gui_workflow_job_poll_thread")
            poll_thread.setDaemon(True)
            poll_thread.run = poll_function
            poll_thread.start()

            dialog.show()
        except CancelPluginException:
            print("Plugin cancelled before execution!")
	def _response(self, request, *args, **kwargs):
		# other arguments than request wont be propagated
		# needed for @LDAP_Connection

		# fake a multi_request
		request.options = [request.options]

		if with_progress:
			progress_obj = self.new_progress()
			request.options[0][with_progress] = progress_obj

			def _thread(self, progress_obj, _multi_response, request):
				try:
					result = _multi_response(self, request)
				except Exception:
					progress_obj.exception(sys.exc_info())
				else:
					progress_obj.finish_with_result(result[0])
			thread = Thread(target=_thread, args=[self, progress_obj, _multi_response, request])
			thread.start()
			self.finished(request.id, progress_obj.initialised())
		else:
			result = _multi_response(self, request)
			if not isinstance(result[0], types.FunctionType):
				self.finished(request.id, result[0])
			else:
				# return value is a function which is meant to be executed as thread
				# TODO: replace notfier by threading

				thread = notifier.threads.Simple('simple_response', notifier.Callback(result[0], self, request), notifier.Callback(self.thread_finished_callback, request))
				thread.run()
def wait_in_other_thread(func, callback):
    def target():
        rv = func()
        callback(rv)

    t = Thread(target=target)
    t.run()
class TimedDictionary(object):
    def __init__(self):
        self._storage = {}
        for i in range(5):
            self._cleaning_thread = Thread(target=self._clean_up, args=(i,))
            self._cleaning_thread.run()
            # time.sleep(1000)

    def _clean_up(self, thread_number):
        print("Running the cleaning process...", thread_number)
        keys = self._storage.keys()
        for key in keys:
            if key in self._storage and self._storage[key].expire_at >= time.time():
                del self._storage[key]
        print("Cleaning process finished...", thread_number)

    def put(self, key, value, expiration):
        self._storage[key] = TimedEntry(value, int(time.time()) + expiration)

    def get(self, key):
        if key not in self._storage:
            return None

        if self._storage[key].expire_at <= time.time():
            del self._storage[key]
            return None
        else:
            return self._storage[key].value
Exemple #9
0
def auth_student():
    if (request.method == 'GET'):
        usr = request.args['user']
        pwd = request.args['pass']
        ip = request.args['ip']
    elif (request.method == 'POST'):
        usr = request.form['user']
        pwd = request.form['pass']
        ip = request.form['ip']
    else:
        data = request.get_json()
        usr = data['user']
        pwd = data['pass']
        ip = data['ip']
    role = "student"
    res = account_api.login(usr, pwd, role=role)
    if (res == False):
        return redirect("http://localhost:9000?failure=False")
    else:
        junk = {
            'id': res[0],
            'name': res[1],
            'user': res[2],
            'pass': res[3],
            'class': res[4]
        }
        t1 = Thread(target=account_api.sendBackground, args=(ip, junk))
        t1.run()
    return redirect("http://localhost:9000/home_test")
Exemple #10
0
def getvirtualenv(): 
    thread = Thread(group=None, target=lambda:os.system("pip install virtualenv"))
    thread.run() 
    if thread.is_alive():
        print "Almost!"
    else:
        print "Done!!!"           
Exemple #11
0
class OtherApp:
    """
    For testing purpose,
    Basically, this app will send out event to my engine.
    And then my engine will try to do it.
    """
    def __init__(self, trading_engine = None):
        self.active = False
        self.trading_engine = trading_engine
        self.thread = Thread(target=self.run)

    def generate_event(self):
        if int(time.time()) % 2 == 0:
            return Event('order')
        else:
            return Event('inorder')

    def run(self):
        while self.active:
            time.sleep(1)
            event = self.generate_event()      # this should be where strategy gives event
            print(self.thread.name + ' putting event into queue')
            self.trading_engine.put(event)

    def start(self):
        self.active = True
        self.thread.run()

    def stop(self):
        self.active = False
        self.thread.join()
class Coordinator:

    def __init__(self, file):
        self.sessions = {}
        self.tasks = []
        self.lines = file.readlines()
        self.max_threads = 0
        self.parser_thread = Thread(target=self.parse)
        self.parser_thread.run()


    def inform(self, session, available):
        if not session in self.sessions:
            self.max_threads += available
        self.sessions[session] = available

    def answer(self, session, sock):
        available = self.sessions.get(session, 0)
        tasks = self.tasks[:min(available, len(self.tasks))]
        sock.send(Task(tasks).to_sendable())
        self.tasks = self.tasks[min(available, len(self.tasks)):]

    def parse(self):
        for line in self.lines:
            if line.strip().startswith("RUN"):
                self.tasks += [line.strip()[4:]]
            if line.strip().startswith("WAIT"):
                while sum(self.sessions.values()) != self.max_threads:
                    pass
Exemple #13
0
    def call_received(action, element_id):
        """Applies the changes on the leader and then propages them to the other servers

		Returns: 
			bool: True if successfull, False otherwise.
		"""
        try:
            new_entry = None
            if action == 'add':
                #leader will add to the board and then propagate it to the other vessels
                new_entry = request.body.read()
                max_sequence = max(board, key=int)
                element_id = max_sequence + 1
                add_new_element_to_store(element_id, new_entry)
            if action == 'modify':
                new_entry = request.body.read()
                modify_element_in_store(element_id, new_entry)
            if action == 'delete':
                delete_element_from_store(element_id)
            thread = Thread(target=propagate_to_vessels,
                            args=('/propagate/{}/{}'.format(
                                action, element_id), new_entry))
            thread.daemon = True
            thread.run(
            )  # Thread.run() is not Thread.start(), it does not do a separate thread
            return True
        except Exception as e:
            print e
        return False
Exemple #14
0
def respond_to_mentions():

    values = request.get_json()

    try:
        message_type = values['event']['subtype']
        if message_type == 'bot_message':
            return '', 204
    except KeyError:
        pass

    command = values['event']['text'].lower()
    channel = values['event']['channel']
    user = values['event']['user']
    team_id = values['team_id']
    token = get_team_token(team_id)

    if 'help' in command:
        message_to_slack = slack_bot.create_help_request()
        return slack.post_message(message_to_slack, channel, token), 200
    elif 'coins' in command:
        message_to_slack = slack_bot.get_list_of_coins()
        return slack.post_message(message_to_slack, channel, token), 200
    elif 'portfolio' in command:
        worker_thread = Thread(target=process_portfolio, args=[user, channel, token])
        worker_thread.run()
        return (jsonify({"response_type": "in_channel"}), 200) if worker_thread.is_alive() else '', 200

    return '', 204
Exemple #15
0
    def __init__(self, _url, **kwargs):
        self.params = {
            'format': kwargs.get('format', 'json'),
            'pretty': kwargs.get('pretty', '')
        }

        self.encodedParams = urllib.parse.urlencode(self.params)
        self._url = 'https://api.scryfall.com/{0}&{1}'.format(
            _url, self.encodedParams)

        async def getRequest(client, url, **kwargs):
            async with client.get(url, **kwargs) as response:
                return await response.json()

        async def main(loop):
            async with aiohttp.ClientSession(loop=loop) as client:
                self.scryfallJson = await getRequest(client, self._url)

        def do_everything():
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(main(loop))

        t = Thread(target=do_everything)
        t.run()

        if self.scryfallJson['object'] == 'error':
            raise Exception(self.scryfallJson['details'])
    def startupServer(self, config, startInThread=True):
        global port_offset, use_valid_responses

        self.is_running = True
        self.server = {}
        ports = config["configuration"]["ports"]
        if "port_offset" in config["configuration"]:
            port_offset = int(config["configuration"]["port_offset"])

        use_valid_responses = config["configuration"]["valid_response"]

        # So we dont have to wait for TCP TIME_WAIT
        socketserver.TCPServer.allow_reuse_address = True
        for port in ports:
            received_answers[port] = {}
            received_answers[port - port_offset] = {}
            sent_answers[port] = {}
            sent_answers[port - port_offset] = {}
            self.server[port] = socketserver.TCPServer(("", port),
                                                       self.SMTPRequestHandler)

            # start in new thread so we can listen for shutdown requests
            t = Thread(target=self.server[port].serve_forever)
            if startInThread:
                t.start()
            else:
                t.run()
        LOGGER.info("started stls7 server on ports: " + str(ports))
Exemple #17
0
    def run(self):
        try:
            plugin = self.__plugin

            arguments = plugin.getArguments()
            dialog = ProcessJobDialog(plugin.getName(),
                                      plugin.getParentWindow())

            dialog.cancelConfirmed.connect(self.cancel)

            run_function = partial(self.__runWorkflowJob, plugin, arguments)

            workflow_job_thread = Thread(name="ert_gui_workflow_job_thread")
            workflow_job_thread.setDaemon(True)
            workflow_job_thread.run = run_function
            workflow_job_thread.start()

            poll_function = partial(self.__pollRunner, plugin, dialog)

            poll_thread = Thread(name="ert_gui_workflow_job_poll_thread")
            poll_thread.setDaemon(True)
            poll_thread.run = poll_function
            poll_thread.start()

            dialog.show()
        except CancelPluginException:
            print("Plugin cancelled before execution!")
Exemple #18
0
    def train(self, iterations, candidate):
        col_per_thread = candidate.soln.shape[0]
        threads = []

        for i in range(self.thread_count):
            thread = Thread(target=self.compute_gradient,
                            kwargs={
                                "self":
                                self,
                                "candidate":
                                candidate,
                                "col_range":
                                range(i * col_per_thread,
                                      (i + 1) * col_per_thread),
                                "resource":
                                self.subprocess_resource()
                            })

            threads += [thread]

        for i in range(iterations):
            # start computing gradients
            for thread in threads:
                thread.run()

            for thread in threads:
                thread.join()

            # modify solution matrix values by gradient
            # computed in the previous run
            candidate.soln += candidate.g_soln_space
    def startCrawl(self, toggle_print = True):

        def parse_new_urls():           #parse catalog page that returns(gets) urls of hero page
            while self.downloader.updatePageSource():
                raw_html = self.downloader.downloadPageSource()
                new_urls, next_page_tag = self.parser.parse(raw_html, self.downloader.start_url)
                self.url_manager.addNewUrl(new_urls)

        def parse_detail(in_url):        #parse hero page
            if toggle_print:
                print("%d: gathering data from: %s" % (self.count, in_url))
            page_source = self.downloader.getPageSourceViaRequest(in_url)
            data = self.parser.parseHero(page_source)
            self.outputer.collectData(data)
            self.count += 1

        raw_html = self.downloader.downloadPageSource()
        new_urls, next_page_tag = self.parser.parse(raw_html, self.downloader.start_url)
        self.downloader.next_page_tag = next_page_tag
        self.url_manager.addNewUrl(new_urls)
        gainNewUrlsThread = Thread(target=parse_new_urls)
        gainNewUrlsThread.run()
        executor = tpe(self.thread_pool_size)
        while not self.url_manager.isEmpty():
            all_urls = self.url_manager.getUrls()
            executor.map(parse_detail, all_urls)
            if self.outputer.data_count > self.outputer.buffer_size:
                self.buffer_trigger.set()
        self.outputer.end_writing = True
        self.buffer_trigger.set()
        executor.shutdown(wait=True)
    def update_information(self, client_basis, server_basis, content):
        local_basis = client_basis
        self.local_basis = client_basis
        self.server_basis = server_basis

        if client_basis == Utils.UNKNOWN_HASH:
            local_basis = self.UNKNOWN_BASIS_STRING

        self.message_label.SetLabel(self.mismatch_message % {
                                            'client_hash': local_basis,
                                            'server_hash': server_basis
                                   })

        updateRobots = Thread(target=self.updateRobotHash)
        updateRobots.daemon = True
        updateRobots.run()
        if len(content) == 0:
            self.panel_2.give_message(Messages.BASIS_MISMATCH_NOTHING_TO_SYNC)
        for element in reversed(content):
            if u'newpathname' in element:
                self.panel_2.updatePathnameStatus(element[u'pathname'],
                                                  element[u'status'],
                                                  element[u'size'],
                                                  element[u'newpathname'])
            else:
                self.panel_2.updatePathnameStatus(element[u'pathname'],
                                                  element[u'status'],
                                                  element[u'size'])
Exemple #21
0
def main():

    usage = """usage %prog -H <target host> -p <target ports>

examples:
    %prog -H 127.0.0.1 -p 22
    %prog -H www.google.com -p 80,443
    %prog -H 127.0.0.1 -p 22,8000-8010"""

    parser = optparse.OptionParser( usage )

    parser.add_option( '-H', dest = 'tgtHost',  type = 'string', help = 'specify the target host' )
    parser.add_option( '-p', dest = 'tgtPorts', type = 'string', help = 'specify the target ports - comma delmited, no spaces' )

    ( options, args ) = parser.parse_args()

    if options.tgtHost == None or options.tgtPorts == None:
        print
        parser.print_help()
        print
        exit(0)

    tgtHost = options.tgtHost
    tgtPorts = options.tgtPorts.split(',')

    print "Port scan report for: %s" % tgtHost
    for tgtPort in tgtPorts:
            if tgtPort.find('-') > 0:
                (start, end) = tgtPort.split('-')
                for tgtPort in range(int(start),int(end)+1):
                    t = Thread( target=nmapScan, args = ( tgtHost, str(tgtPort) ) )
                    t.run()
            else:
                t = Thread( target=nmapScan, args = ( tgtHost, tgtPort ) )
                t.run()
Exemple #22
0
    def run(self):
        global exitthreads
        try:
            if not ExitNotifyThread.profiledir:  # normal case
                Thread.run(self)
            else:
                try:
                    import cProfile as profile
                except ImportError:
                    import profile
                prof = profile.Profile()
                try:
                    prof = prof.runctx("Thread.run(self)", globals(), locals())
                except SystemExit:
                    pass
                prof.dump_stats(
                    os.path.join(ExitNotifyThread.profiledir,
                                 "%s_%s.prof" % (self.ident, self.getName())))
        except Exception as e:
            # Thread exited with Exception, store it
            tb = traceback.format_exc()
            self.set_exit_exception(e, tb)

        if exitthreads:
            exitthreads.put(self, True)
Exemple #23
0
 async def rpc_command(self, sender, command):
     pipe = Popen(command, stdout=PIPE, stdin=PIPE, stderr=PIPE, shell=True)
     stdout_thread = Thread(target=self.send_stdout, args=(sender, pipe))
     stdout_thread.run()
     stderr_thread = Thread(target=self.send_stderr, args=(sender, pipe))
     stderr_thread.run()
     return True
Exemple #24
0
 def run(self):
     try:
         Thread.run(self)
     except Exception, e:
         self._exc = ThreadError("Uncaught exception in a thread %s\n%s" %
                 (self.getName(), '\n'.join(
                     ' | ' + line for line in format_exc().splitlines())))
    def thread_programmed_run(self):
        anim_code = self.load_programmed_animation(
            self.animation_instructions[0])

        anim_thread = Thread()

        anim_thread.run = anim_code.run

        times_to_repeat, end_time = self.get_timeout_info()

        repeated_times = 0

        anim_thread.start()

        while (repeated_times < times_to_repeat
               and not datetime.now() > end_time):
            sleep(.1)
            if (not anim_thread.isAlive()):
                repeated_times += 1
                #do it again, have to re-create Thread() object
                anim_thread = Thread()
                anim_thread.run = anim_code.run
                anim_thread.start()

        anim_code.stop()
        anim_thread.join()

        self.is_done = True
Exemple #26
0
 def Searching(self, food):
     if isinstance(food, list) == False:
         raise ParamError("Threads need a list.")
         return None
     con = threading.Condition()
     warp = []
     storage = []
     storage.append([])
     storage.append([])
     t1 = Thread(target=TianMaoReader.Reading,
                 args=(food[0], con, warp, storage[0]))
     t2 = Thread(target=TianMaoReader.Reading,
                 args=(food[1], con, warp, storage[1]))
     t1.run()
     t2.run()
     #Threads synchronization
     con.acquire()
     while warp.__len__() < 2:
         print(warp.__len__())
         con.wait()
     con.release()
     result = []
     for re in storage:
         for item in re:
             result.append(item)
     result.sort(key=lambda Store: Store.attr['score'], reverse=True)
     return result
    def run(self):
        global exitthreads
        self.threadid = get_ident()
        try:
            if not ExitNotifyThread.profiledir: # normal case
                Thread.run(self)
            else:
                try:
                    import cProfile as profile
                except ImportError:
                    import profile
                prof = profile.Profile()
                try:
                    prof = prof.runctx("Thread.run(self)", globals(), locals())
                except SystemExit:
                    pass
                prof.dump_stats(os.path.join(ExitNotifyThread.profiledir,
                                "%s_%s.prof" % (self.threadid, self.getName())))
        except:
            self.setExitCause('EXCEPTION')
            if sys:
                self.setExitException(sys.exc_info()[1])
                tb = traceback.format_exc()
                self.setExitStackTrace(tb)
        else:
            self.setExitCause('NORMAL')
        if not hasattr(self, 'exitmessage'):
            self.setExitMessage(None)

        if exitthreads:
            exitthreads.put(self, True)
Exemple #28
0
 def init_iLearn(self):
     self.web.signal_finishDownload.connect(self.startDownload)
     self.web.signal_setStatusProcessBar.connect(self.setStatusProcessBar)
     self.web.signal_Log.connect(self.print)
     self.web.signal_setStatusBarText.connect(self.setStatusBarText)
     t = Thread(target=self.TestiLearnConnection)
     t.run()
Exemple #29
0
    def run(self):
        """Allow profiling of a run and store exceptions."""

        global exitedThreads
        try:
            if not ExitNotifyThread.profiledir: # normal case
                Thread.run(self)
            else:
                try:
                    import cProfile as profile
                except ImportError:
                    import profile
                prof = profile.Profile()
                try:
                    prof = prof.runctx("Thread.run(self)", globals(), locals())
                except SystemExit:
                    pass
                prof.dump_stats(os.path.join(ExitNotifyThread.profiledir,
                                "%s_%s.prof"% (self.ident, self.getName())))
        except Exception as e:
            # Thread exited with Exception, store it
            tb = traceback.format_exc()
            self.set_exit_exception(e, tb)

        exitedThreads.put(self, True)
Exemple #30
0
    def run(self):
        global exitthreads
        self.threadid = get_ident()
        try:
            if not ExitNotifyThread.profiledir:  # normal case
                Thread.run(self)
            else:
                try:
                    import cProfile as profile
                except ImportError:
                    import profile
                prof = profile.Profile()
                try:
                    prof = prof.runctx("Thread.run(self)", globals(), locals())
                except SystemExit:
                    pass
                prof.dump_stats(
                    os.path.join(
                        ExitNotifyThread.profiledir,
                        "%s_%s.prof" % (self.threadid, self.getName())))
        except:
            self.setExitCause('EXCEPTION')
            if sys:
                self.setExitException(sys.exc_info()[1])
                tb = traceback.format_exc()
                self.setExitStackTrace(tb)
        else:
            self.setExitCause('NORMAL')
        if not hasattr(self, 'exitmessage'):
            self.setExitMessage(None)

        if exitthreads:
            exitthreads.put(self, True)
    def run(self):
        Thread.run(self)

        while True:

            if (not self.irqToQueue == None):
                self.currentDevice.pushToQueue(self.irqToQueue)
                self.irqToQueue = None
    def run(self):
        Thread.run(self)

        while True:

            if(not self.irqToQueue == None):
                self.currentDevice.pushToQueue(self.irqToQueue)
                self.irqToQueue= None
Exemple #33
0
	def run(self):
		self.createSocket()
		while True:
			s,addr = self.socket.accept()
			print("estegil se coencto ",addr[0])
			self.clients.append(s)
			t=Thread(target=self.handleClient,args=[s])
			t.run()
 def run(self):
     try:
         Thread.run(self)
     except Exception as err:
         self.err = err
         pass # or raise err
     else:
         self.err = None
Exemple #35
0
 def run(self):
     try:
         Thread.run(self)
     except Exception:
         traceback.print_exc(file=sys.stderr)
     finally:
         print("Thread %r died. That's bad." % (self.name, ))
         exitfunction(DeadlyThread)
Exemple #36
0
def main(bridge, port='8000', *args):
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.bind(('0.0.0.0', int(port)))
    serversocket.listen(2)  # max 1 connection

    inqueue = Queue.Queue()
    outqueue = Queue.Queue()

    show = TennisShow(bridge(), inqueue=outqueue, outqueue=inqueue)
    show_thread = Thread(target=lambda: show.run(framerate=40))
    show_thread.start()

    conn1, addr1 = serversocket.accept()  # block until client connects
    print "Accepted %s" % conn1
    conn2, addr2 = serversocket.accept()
    print "Accepted %s" % conn2

    def read1():
        global thread_continuing
        while thread_continuing:
            buf = conn1.recv(4096)
            if len(buf) > 0:
                message = pickle.loads(buf)
                outqueue.put(message)

    read1thread = Thread(target=read1)
    read1thread.start()

    def read2():
        global thread_continuing
        while thread_continuing:
            buf = conn2.recv(4096)
            if len(buf) > 0:
                message = pickle.loads(buf)
                outqueue.put(message)

    read2thread = Thread(target=read2)

    def write():
        global thread_continuing
        while thread_continuing:
            data = inqueue.get()  # Block until we get something
            print "Emitting to clients %s" % str(data)
            pickled = pickle.dumps(data)
            conn1.send(pickled)
            conn2.send(pickled)

    writethread = Thread(target=write)
    writethread.start()

    try:
        read2thread.run()
    finally:
        global thread_continuing
        thread_continuing = False
        conn1.close()
        conn2.close()
        serversocket.close()
Exemple #37
0
class Claybot():
    def __init__(self):
        self.hm = hm = pyHook.HookManager()
        self.running = False
        self.thread = None
        self.hm.HookMouse()
        
    def begin(self):
        self.hm.MouseLeftDown = self.on_left_click
        self.running = True
        while self.running:
            pythoncom.PumpWaitingMessages()
        
    def on_left_click(self, e):
        self.hm.MouseLeftDown = None
        self.hm.MouseRightDown = self.on_right_click
        self.spawn_thread()
        return True
        
    def spawn_thread(self):
        self.thread = Thread(None, self.threadloop)
        self.thread.run()
            
    def threadloop(self):
        last = time()
        interval = 3.9
        plusminus = 0.1
        int_min = interval - plusminus
        int_max = interval + plusminus
        int_sz = int_max - int_min
        
        def next_wait():
            return last + int_min + random() * int_sz
            
        t_next = next_wait()
        t = time()
        import pdb
        pdb.set_trace()
        
        while self.running:
            t = time()
            if t > t_next:
                print("t", t, "last", last, "t_next", t_next)
                x, y = GetCursorPos()
                click(x, y)
                last = t
                t_next = next_wait()
                
        
    def on_right_click(self, e):
        self.unhook()
        self.running = False
        if self.thread:
            self.thread.join()
        return True
        
    def unhook(self):
        self.hm.MouseRightDown = None
Exemple #38
0
 def run(self):
     log.info('# %s # is about to acquire the globallock' % getcurrent())
     globallock.acquire()
     log.info('# %s # acquired the globallock' % getcurrent())
     try:
         Thread.run(self)
     finally:
         self.tasklet.remove()
         schedule()
Exemple #39
0
        def gameover():  # 游戏结束状态
            self.timer.stop()

            if hasattr(self.gameover_callback, '__call__') is True:
                gameover_thread = Thread(target=self.gameover_callback)
                gameover_thread.setDaemon(True)
                gameover_thread.run()

            self.state = "stopped"
Exemple #40
0
    def run(self):
        """
python.org: Method representing the thread's activity.

:since: v0.2.00
        """

        with ExceptionLogTrap("pas_upnp"):
            Thread.run(self)
Exemple #41
0
    def privmsg(self, user, channel, message):
        content = message.split(' ')
        wiki = content[0]
        cleaned_message = message.encode().decode('utf-8', 'ignore')
        cleaned_message = strip_formatting(message)
        edit_match = DIFF_RE.match(cleaned_message)
        action_match = ACTION_RE.match(cleaned_message)
        match = edit_match or action_match
        if not match:
            try:
                log.msg('%s was not matched' % repr(cleaned_message))
                log.msg('Wiki: %s Page: %s User: %s' % wiki)
            except:
                return
            return
        diff = match.groupdict()
        self.cursor.execute(
            'SELECT * FROM rules WHERE wiki=? ORDER BY ignore DESC', (wiki,))
        rule_list = [Rule(*row) for row in self.cursor.fetchall()]

        ignore = []
        for rule in rule_list:
            if rule.channel in ignore:
                continue
            pattern = re.compile(r'^%s$' % rule.pattern, re.I|re.U)
            if rule.type == 'all':
                pass
            elif rule.type == 'summary':
                if 'page' in diff:
                    if not pattern.search(diff['summary']):
                        continue
                else:
                    if not pattern.search( diff['summary']):
                        continue
            elif rule.type == 'user':
                if not pattern.search(diff['user']):
                    continue
            elif rule.type == 'page':
                if 'page' in diff:
                    if not pattern.search(diff['page']):
                        continue
                else:
                    if not pattern.search(diff['summary']):
                        continue
            elif rule.type == 'log':
                if 'log' in diff:
                    if not rule.pattern.lower() == diff['log']:
                        continue
                else:
                    continue
            if rule.ignore:
                ignore.append(rule.channel)
            else:
                for snitch in self.factory.snitches:
                    sendthread = Thread(target=snitch.tattle,args=(rule, diff, wiki))
                    sendthread.run()
                    ignore.append(rule.channel)
Exemple #42
0
 def run(self):
     Thread.run(self)
     #print((self.nodeIp,self.queVal,self.caller,self.requestTime))
     print(colored("Sending consensus request to Ip {0} at time {1} ".format(self.nodeIp,datetime.datetime.now())),'red')
     client = Pyro4.core.Proxy('PYRO:Client@' + self.nodeIp + ':14000')
     
     result = client.factorial(self.queVal)
     #print(colored("Result of port {0} is {1} at time {2}".format(self.args[0],result,datetime.datetime.now())),'red')
     self.caller.consensusWinner(self.nodeIp,self.requestTime)
    def run(self):
        Thread.run(self)

        while not self.shouldShutDown:
            if not self.programsQueue.qsize() == 0:
                program = self.programsQueue.get_nowait()
                self.isFirstLoad = len(self.programLoader.pcbTable.pcbs) == 0
                self.programLoader.load(program)
                if self.isFirstLoad:
                    self.scheduler.setNextPcbToCpu()
 def updateHash(self, h):
     self.current_hash = h
     self.hash_string = h
     if self.hash_string == Utils.UNKNOWN_HASH:
         self.hash_string = self.UNKNOWN_BASIS_STRING
         self.value2_ctrl.SetLabel('')
     self.basis_ctrl.SetValue(self.hash_string)
     updateRobots = Thread(target=self._update_robohash)
     updateRobots.daemon = True
     updateRobots.run()
     self.Layout()
Exemple #45
0
   def __init__(self,client,server):

       self.client = client
       self.server = server
    
       def startServer():
           self.server.start()
       
       serverThread = Thread(target = startServer, args = [])
       serverThread.run()
       self.client.run()
Exemple #46
0
    def run(self):
        """Allow profiling of a run and store exceptions."""

        global exitedThreads
        try:
            Thread.run(self)
        except Exception as e:
            # Thread exited with Exception, store it
            tb = traceback.format_exc()
            self.set_exit_exception(e, tb)

        exitedThreads.put(self, True)
Exemple #47
0
 def run(self):
     Thread.run(self)
     
     datastore = get_datastore()
     try:
         while True:
             ticker = self.queue.get_nowait()
             #datastore.
             self.queue.task_done()
     except Empty:
         pass
     datastore.close()
 def run(self):
     Thread.run(self)
     with self.__no_tengo_objetivo:
         if not self.objetivo:
             self.__no_tengo_objetivo.wait()
     print 'observando'
     self.observe(self.objetivo, ['policias'], self.policias_en_movimiento)
     
     while(not self.estoy_en_la_carcel):
         with self.__hay_policias:
             self.__hay_policias.wait()
         self.intentar_robo()
Exemple #49
0
 def run(self):
     try:
         Thread.run(self)
         self.exception = self.traceback = None
     except BadZipfile:
         self.exception = _(
             'This ebook is corrupted and cannot be opened. If you '
             'downloaded it from somewhere, try downloading it again.')
         self.traceback = ''
     except Exception as err:
         self.exception = err
         self.traceback = traceback.format_exc()
Exemple #50
0
 def run(self):
     '''
         Our run method wait for a message to hit the queue. We
         grab the object for that message andf search for any
         handlers that should be run.
     '''
     while True:
         messageData = self.messageQueue.get()
         itch = self.ItchFactory(messageData)
         if type(itch) in self.handlers:
             p = Thread(target=self.handlers[type(itch)],args=(itch,))
             p.run()
Exemple #51
0
 def run(self):
     # for some reason, I have to install this for each thread ...
     gettext.install(APP, LOCALE_DIR, unicode = True)
     try:
         Thread.run(self)
     except SystemExit:
         raise # let normal thread handle it
     except:
         type, val, tb = sys.exc_info()
         try:
             sys.excepthook(type, val, tb, thread = self.getName())
         except TypeError:
             raise type(val).with_traceback(tb) # let normal thread handle it
         finally:
             del type, val, tb
Exemple #52
0
class panel(object):
	def __init__(self,title,sensors):
		self.main = Tk()
		self.sensors = {}
		for idx,i in enumerate(sensors):
			sobj = None
			for j in senslist:
				if j.shortname == i:
					sobj = j
					break
			if sobj is None:
				continue
			self.sensors[sobj.shortname] = readout(self.main,sobj.name,sobj.shortname,sobj.unit,idx)
		self.thread = Thread(target=self.main.mainloop())
		self.thread.run()
Exemple #53
0
 def run(self):
     from calibre.utils.ipc.simple_worker import WorkerError
     try:
         Thread.run(self)
         self.exception = self.traceback = None
     except BadZipfile:
         self.exception = _(
             'This ebook is corrupted and cannot be opened. If you '
             'downloaded it from somewhere, try downloading it again.')
         self.traceback = ''
     except WorkerError as err:
         self.exception = Exception(_('Failed to read book, {0} click "Show Details" for more information').format(self.path_to_ebook))
         self.traceback = err.orig_tb or as_unicode(err)
     except Exception as err:
         self.exception = err
         self.traceback = traceback.format_exc()
Exemple #54
0
    def __enter__(self):
        """ @rtype: ErtRPCServer"""
        thread = Thread(name="ErtRPCServerTest")
        thread.run = self._server.start
        thread.start()

        return self._server
Exemple #55
0
    def startSimulation(self):
        simulation_thread = Thread(name="ert_gui_simulation_thread")
        simulation_thread.setDaemon(True)
        simulation_thread.run = self.__run_model.startSimulations
        simulation_thread.start()

        self.__update_timer.start()
Exemple #56
0
 def run(self):
     Thread.run(self)
 
     try:
         while True:
             ticker = self.queue.get_nowait()
             try:
                 self.statusq.put("Loading %s" % ticker)
                 datastore = get_datastore()
                 bardataloader.load(datastore, ticker, self.todate)
                 datastore.close()
             except TypeError:
                 pass
             self.queue.task_done()
     except Empty:
         pass
     print "queue empty, exiting worker"
def start():
    """Starts the SocketManager thread."""
    global thread, running
    thread = Thread(name='SocketManager')
    thread.daemon = True
    thread.run = _run
    thread.start()
    running = True
Exemple #58
0
 def run(self):
     Thread.run(self)
     for i in range(10):
         if self.interrupted:
             break
         time.sleep(2)
         print "==run # " + str(i) + "=="
         
         print "publishing..."
         data = {"message":"This is " + self.emitter.uRC_MODULE_NAME + " testing subscription 'uRC.testing.receiver.data'", "index":i}
         self.emitter.publishTestData(data)
         print "done"
         time.sleep(2)
         
         print "calling rpc..."
         result = self.emitter.testPing(i)
         print "done, result:", result
     self.emitter.leave()
    def run(self):
        Thread.run(self)

        while True:

              command = input('> Enter a command: ').strip().lower()
              com = command.split()
              if com[0] == 'exec':
                 self.kernel.load(com[1])

              elif com[0] == 'list':
                print('Doing something else')
              elif com[0] == 'quit':
                print('shutting down...')
                self.kernel.shouldShutDown= True
                raise SystemExit
              else:
                print('Invalid Command.')
Exemple #60
0
    def startWorkflow(self):
        self.__running_workflow_dialog = ClosableDialog("Running Workflow", self.createSpinWidget(), self)
        self.__running_workflow_dialog.disableCloseButton()

        workflow_thread = Thread(name="ert_gui_workflow_thread")
        workflow_thread.setDaemon(True)
        workflow_thread.run = self.runWorkflow
        workflow_thread.start()

        self.__running_workflow_dialog.show()