Example #1
0
 def _connect(self, server):
     """Performs a connection to the server by creating a Connection object,
     connecting it, and then registering the new Connection with the
     ConnectionManager."""
     server.reset()
     t = Thread(target=self._try_connect, args=(server,))
     t.start()
Example #2
0
def test_multiple_monitors(client):
    xfail_if_xenbus(client)

    n_events = 5
    events = {}

    latch = Latch(2 + 1)

    def monitor_and_check(token):
        with client.monitor() as m:
            m.watch(b"/foo/bar", token)
            latch.ready()
            events[current_thread().ident] = list(islice(m.wait(), n_events))

    t1 = Thread(target=monitor_and_check, args=(b"boo",))
    t1.start()
    t2 = Thread(target=monitor_and_check, args=(b"baz",))
    t2.start()

    latch.ready()
    for i in range(n_events):
        client[b"/foo/bar"] = str(i).encode()

    t1.join()
    t2.join()

    assert len(events) == 2
    events1 = events[t1.ident]
    events2 = events[t2.ident]
    assert len(events1) == len(events2) == n_events
    assert set(events1) == set([Event(b"/foo/bar", b"boo")])
    assert set(events2) == set([Event(b"/foo/bar", b"baz")])
Example #3
0
 def __init__(self, port, buff, exit_event, blocklen=1024, sendlen=0, migrate_event=None, debug=None):
     """
     @param port: Source port.
     @param buff: Control data buffer (FIFO).
     @param exit_event: Exit event.
     @param blocklen: Block length.
     @param sendlen: Block length of the send function (on guest)
     @param migrate_event: Event indicating port was changed and is ready.
     @param debug: Set the execution mode, when nothing run normal.
     """
     Thread.__init__(self)
     self.port = port
     self.buff = buff
     self.exitevent = exit_event
     self.migrate_event = migrate_event
     self.blocklen = blocklen
     self.idx = 0
     self.sendlen = sendlen + 1  # >=
     self.ret_code = 1  # sets to 0 when finish properly
     self.debug = debug  # see the self.run_* docstrings for details
     # self.sendidx is the maxiaml number of skipped/duplicated values
     # 1) autoreload when the host socket is reconnected. In this case
     #    it waits <30s for migrate_event and reloads sendidx to sendlen
     # 2) manual write to this value (eg. before you reconnect guest port).
     #    RecvThread decreases this value whenever data loss/dup occurs.
     self.sendidx = -1
Example #4
0
 def download_500px_image(self, url, index, total):
     while self.thread_count >= self.max_threads:
         sleep(0.1)
     self.thread_count += 1
     args = (url, index, total)
     t = Thread(target=self.download_500px_image_thread, args=args)
     t.start()
Example #5
0
 def __init__(self, uri, name, outdir=".", fps=3.0, duration=60, cache=10, verbose=False):
     """Build a Recorder object.
     
     :param uri: The uri to the ip camera's jpg capture.
     :param name: The name of the ip camera.
     :param fps: The frames per second to record download / record at.
     :param duration: Duration of a single video. If duration <= 0, the 
                      video is recorded indefinitely
     :param cache: Number of videos to cache before overwriting the first
                   video.
     :param verbose:   
     """
     Thread.__init__(self)
     self.daemon = True
     self.quit = Event()
     if fps < 3:
         print("WARNING: With fps<3.0 most codecs failed render correctly")
     if not os.path.exists(outdir):
         os.makedirs(outdir)
     self.outdir = outdir
     self.outdir = outdir
     self.fps = fps
     self.name = name
     self.cache = cache
     self.verbose = verbose
     self.camera = IPCamera(uri, fps, duration, name, self.quit, verbose)
Example #6
0
 def __init__(self, proc):
     Thread.__init__(self)
     self.proc = proc
     self.queue = Queue()
     self.daemon = True
     self.active = True
     self.start()
 def __init__(self, internal_server, hostname, port):
     Thread.__init__(self)
     self.socket_server = None
     self.hostname = hostname
     self.port = port
     self.iserver = internal_server
     self._cond = Condition()
Example #8
0
    def __init__(self, name="reader1", readPwr=2300, portStr="/dev/robot/RFIDreader", antFuncs=[], callbacks=[]):

        Thread.__init__(self)
        self.should_run = True

        try:
            rospy.init_node("rfid_m5e_" + name)
        except rospy.ROSException:
            pass

        self.mode = ""
        self.name = name + "_reader"

        rospy.logout("ROS_M5e: Launching RFID Reader")
        rospy.logout("ROS_M5e: Please check out our related work @ http://www.hsi.gatech.edu/hrl/project_rfid.shtml")
        rospy.logout("ROS_M5e: " + self.name + " Building & Connecting to reader")

        def prin(x):
            rospy.logout("ROS_M5e: lib_M5e: " + x)  # use rospy.logout in underlying lib's output

        self.reader = M5e(readPwr=readPwr, portSTR=portStr, verbosity_func=prin)
        self.antFuncs = antFuncs
        self.callbacks = callbacks + [self.broadcast]

        rospy.logout("ROS_M5e: publishing RFID reader with type RFIDread to channel /rfid/" + name + "_reader")
        self.channel = rospy.Publisher("/rfid/" + name + "_reader", RFIDread)
        self.pub_arr = rospy.Publisher("/rfid/" + name + "_reader_arr", RFIDreadArr)
        self._mode_service_obj = rospy.Service("/rfid/" + name + "_mode", RfidSrv, self._mode_service)

        rospy.logout("ROS_M5e: " + self.name + " Inialized and awaiting instructions")

        self.start()  # Thread: calls self.run()
Example #9
0
    def start(self, name="Generic-Callback", wait=True):
        """
        Start the asynchronous thread.

        Creates a new thread and calls the _loop() method.
        """
        assert self._state == "STATE_INIT", "Already (done) running"
        assert isinstance(name, str)
        assert isinstance(wait, bool), "WAIT has invalid type: %s" % type(wait)
        if __debug__:
            dprint()
        with self._lock:
            self._state = "STATE_PLEASE_RUN"
            if __debug__:
                dprint("STATE_PLEASE_RUN")

        thread = Thread(target=self._loop, name=name)
        thread.daemon = True
        thread.start()

        if wait:
            # Wait until the thread has started
            while self._state == "STATE_PLEASE_RUN":
                sleep(0.01)

        return self.is_running
Example #10
0
 def join(self):
     if self.ffwd_server is not None:
         self.ffwd_server.shutdown()
     self.ssh_client.close()
     del self.ffwd_server
     del self.ssh_client
     Thread.join(self)
def main(queue, threaded):
    queue.put((parse_search_results, start_url, True))

    if threaded:

        def worker():
            while True:
                job = Q.get()
                try:
                    apply(job[0], job[1:])
                except Exception as e:
                    print "EXCEPTION", job, e
                    raise
                Q.task_done()

        for i in xrange(3):
            t = Thread(target=worker)
            # t.daemon = True
            t.start()

        queue.join()
    else:
        while 1:
            try:
                job = queue.get()
            except Queue.Empty:
                break
            print job
            apply(job[0], job[1:])
Example #12
0
    def __init__(
        self,
        ssh_server,
        local_port=0,
        ssh_port=22,
        remote_host="localhost",
        remote_port=None,
        username=None,
        password=None,
    ):
        Thread.__init__(self)
        if Random:
            Random.atfork()
        if remote_port is None:
            remote_port = local_port
        self.local_port = local_port
        self.remote_host = remote_host
        self.remote_port = remote_port

        self.ssh_client = paramiko.SSHClient()
        self.ssh_client.load_system_host_keys()
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh_client.connect(ssh_server, ssh_port, username=username, password=password, look_for_keys=True)

        transport = self.ssh_client.get_transport()

        class SubHandler(Handler):
            chain_host = remote_host
            chain_port = remote_port
            ssh_transport = transport

        self.ffwd_server = ForwardServer(("", self.local_port), SubHandler)
        self.ip, self.local_port = self.ffwd_server.server_address
Example #13
0
 def download_cache_details(self, cache, sync=False):
     """
     Download or update *detailed* information for a specific geocache.
     
     location -- Geographic boundaries (see cachedownloader.get_overview for details)
     sync -- Perform actions synchronized, i.e., don't use threads.
     
     """
     if not sync:
         t = Thread(
             target=self._download_upload_helper,
             args=[
                 "self.cachedownloader.update_coordinate",
                 self._download_cache_details_complete,
                 cache,
                 self.settings["download_num_logs"],
             ],
         )
         t.daemon = True
         t.start()
         # t.join()
         return False
     else:
         full = self.cachedownloader.update_coordinate(cache, self.settings["download_num_logs"])
         return self._download_cache_details_complete(full, sync)
Example #14
0
 def download_overview(self, location, sync=False, skip_callback=None):
     """
     Downloads an *overview* of geocaches within the boundaries given in location.
     
     location -- Geographic boundaries (see cachedownloader.get_overview for details)
     sync -- Perform actions synchronized, i.e., don't use threads.
     skip_callback -- A callback function which gets the geocache id and its found status as input. If it returns true, the geocache's details are not downloaded.
     """
     if not sync:
         t = Thread(
             target=self._download_upload_helper,
             args=[
                 "self.cachedownloader.get_overview",
                 self._download_overview_complete,
                 location,
                 self.get_geocache_by_name_async,
                 skip_callback,
             ],
         )
         t.daemon = True
         t.start()
         return False
     else:
         return self._download_overview_complete(
             self.cachedownloader.get_overview(location, self.get_geocache_by_name, skip_callback), True
         )
Example #15
0
 def __init__(self, rep_manager):
     Thread.__init__(self)
     self.__rep_manager = rep_manager
     self.workers = [Worker(self, None) for i in range(Settings.max_threads)]
     self.tasks = []
     self.__canceled = False
     self.__lock = Lock()
Example #16
0
 def __init__(self):
     Thread.__init__(self)
     self.onjob = Event()
     self.onquit = Event()
     self._waiting_job = None
     self._executed = 0
     self._requests = 0
Example #17
0
    def send_email(self, email_addr, subject, email_text):
        """Send an email

        :param email_addr: email address
        :type email_addr: str.
        :param subject: subject
        :type subject: str.
        :param email_text: email text
        :type email_text: str.
        :raises: AAAException if smtp_server and/or sender are not set
        """
        if not (self._conf["fqdn"] and self.sender):
            raise AAAException("SMTP server or sender not set")
        msg = MIMEMultipart("alternative")
        msg["Subject"] = subject
        msg["From"] = self.sender
        msg["To"] = email_addr
        if isinstance(email_text, bytes):
            email_text = email_text.encode("utf-8")

        part = MIMEText(email_text, "html")
        msg.attach(part)
        msg = msg.as_string()

        log.debug("Sending email using %s" % self._conf["fqdn"])

        if self.use_threads:
            thread = Thread(target=self._send, args=(email_addr, msg))
            thread.start()
            self._threads.append(thread)

        else:
            self._send(email_addr, msg)
    def populate_userdata_callback(self, sp, resp):

        # Send screen size
        self.send_command("sp/log", [41, 1, 0, 0, 0, 0], None)

        self.username = resp["user"]
        self.country = resp["country"]
        self.account_type = resp["catalogue"]

        # If you're thinking about changing this: don't.
        # I don't want to play cat and mouse with Spotify.
        # I just want an open-library that works for paying
        # users.
        magic = base64.b64encode(resp["catalogue"]) == "cHJlbWl1bQ=="
        self.is_logged_in = True if magic else False

        if not magic:
            Logging.error("Please upgrade to Premium")
            self.disconnect()
        else:
            heartbeat_thread = Thread(target=self.heartbeat_handler)
            heartbeat_thread.daemon = True
            heartbeat_thread.start()

        if self.login_callback:
            self.do_login_callback(self.is_logged_in)
        else:
            self.logged_in_marker.set()
Example #19
0
 def start(self):
     if self.mode in (ANALYZING, INVERSE_ANALYZING):
         t = Thread(target=self.__startBlocking, name=fident(self.__startBlocking))
         t.daemon = True
         t.start()
     else:
         self.__startBlocking()
Example #20
0
 def __init__(self, irc, channel, delay, callback):
     Thread.__init__(self)
     self.daemon = True
     self.delay = delay
     self.callback = callback
     self.irc = irc
     self.channel = channel
    def __init__(self, url, dirname, urlfile):
        """
        Creates a random secret, instantiates a ListableNode with that secret,
        starts a Thread with the ListableNode's _start method (making sure the
        Thread is a daemon so it will quit when the application quits),
        reads all the URLs from the URL file and introduces the Node to
        them. Finally, sets up the GUI.
        """
        # Give the server a head start:
        try:
            sleep(HEAD_START)
            self.server = ServerProxy(url)
            super(Client, self).__init__()
            self.secret = randomString(SECRET_LENGTH)
            n = ListableNode(url, dirname, self.secret)
            t = Thread(target=n._start)
            t.setDaemon(1)
            t.start()
            for line in open(urlfile):
                line = line.strip()
                self.server.hello(line)

        except:
            print "init fail"
            exit(1)
Example #22
0
 def __init__(self, sitedict, entry_id_lists):
     Thread.__init__(self)
     self._stop = threading.Event()
     self.stop = False
     thongbao.thongbao = " da tao object post"
     self.postlog = ""
     self.session = requests.session()
     self.khoitaohtml()
     self.login_flag = 1
     self.sitedict = sitedict
     self.entry_id_lists = entry_id_lists
     self.save_post_log_path = (
         "/post_log_" + sitedict["url"].replace("www.", "").replace("http://.", "").replace("/.", "") + ".html"
     )
     self.sitename = sitedict["url"].replace("www.", "").replace("http://.", "").replace("/.", "")
     try:
         self.is_reply = sitedict["is_reply"]
     except:
         self.is_reply = False
     self.replyWithEnry = False
     if self.is_reply:
         self.newthread_url = sitedict["url_thread_for_reply"]  # for find token
         if "showthread" in self.newthread_url:
             self.loai_forum = 0
             self.url_reply = self.newthread_url.replace("showthread.php?", "newreply.php?do=postreply&")
     else:
         self.newthread_url = sitedict["newthread_url"]
         if "newthread.php?do" in self.newthread_url:
             self.loai_forum = 0
Example #23
0
 def __init__(self, args, i, j):
     Thread.__init__(self)
     self.args = args
     self.results = [[] for k in range(_SIZE)]
     self.i = i
     self.j = j
     self.s = _SIZE
Example #24
0
 def __init__(self, asset_list, asset_list_mutex):
     Thread.__init__(self)
     self.asset_list = asset_list
     self.mutex = asset_list_mutex
     self.assets_rebuilt = 0
     self.exit = False
     self.error = None
Example #25
0
def SendMail():
    msg = Message("test", sender="36838082@qq.com", recipients=["hermasTang@hotmail.com"])
    msg.body = "text body"
    msg.html = "<b>HTML</b>body"
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return "send mail done"
 def __init__(self, stationBase):
     Thread.__init__(self)
     self.stationBase = stationBase
     self.imageVirtuelle = None
     self.anciennePosRobot = []
     self.police = cv2.FONT_HERSHEY_SIMPLEX
     self.chargerImageVirtuelle()
Example #27
0
 def __init__(self, interval_sec, get_connection_holders):
     Thread.__init__(self, name="Connection heartbeat")
     self._interval = interval_sec
     self._get_connection_holders = get_connection_holders
     self._shutdown_event = Event()
     self.daemon = True
     self.start()
 def __init__(self, repo_id, url, ca, cert):
     Thread.__init__(self)
     self.repo_id = repo_id
     self.url = url
     self.ca = ca
     self.cert = cert
     self.finished = False
Example #29
0
    def test03_ThreadedTransactions(self):
        if verbose:
            print "\n", "-=" * 30
            print "Running %s.test03_ThreadedTransactions..." % self.__class__.__name__

        threads = []
        for x in range(self.writers):
            wt = Thread(
                target=self.writerThread, args=(self.d, self.records, x), name="writer %d" % x
            )  # verbose = verbose)
            threads.append(wt)

        for x in range(self.readers):
            rt = Thread(target=self.readerThread, args=(self.d, x), name="reader %d" % x)  # verbose = verbose)
            threads.append(rt)

        dt = Thread(target=self.deadlockThread)
        dt.start()

        for t in threads:
            t.start()
        for t in threads:
            t.join()

        self.doLockDetect = False
        dt.join()
Example #30
0
class Gpi:
    def __init__(self, name):
        self.name = name
        self.system_run = True
        self.order = Queue()
        self.output = Queue()
        self.busy = False

    def run(self):
        while self.system_run:
            if not self.order.empty():
                self.order.get()
                print("{0}雞排攤得到一份訂單\n".format(self.name))
                self.busy = True
                sleep(1)
                self.busy = False
                print("{0}雞排攤:炸好1份{0}雞排\n".format(self.name))
                self.output.put("{}雞排".format(self.name))
            else:
                print(self.name, "雞排攤,正在休息....")
            sleep(1)

        print("生意冷清{}雞排攤老闆抱怨沒訂單...".format(self.name))

    def start(self):
        self.th = Thread(target=self.run)
        self.th.start()

    def stop(self):
        self.system_run = False

    def join(self):
        self.th.join()
        print("{}雞排攤因為沒訂單收攤了".format(self.name))