Example #1
1
    def flush_next(self):

        if len(self._trs_to_flush) > 0:

            td = self._last_flush + self._THROTTLING_DELAY - datetime.now()
            # Python 2.7 has this built in, python < 2.7 don't...
            if hasattr(td, "total_seconds"):
                delay = td.total_seconds()
            else:
                delay = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10.0 ** 6

            if delay <= 0:
                tr = self._trs_to_flush.pop()
                self._last_flush = datetime.now()
                logging.debug("Flushing transaction %d" % tr.get_id())
                try:
                    tr.flush()
                except Exception, e:
                    logging.exception(e)
                    self.tr_error(tr)
                    self.flush_next()
            else:
                # Wait a little bit more
                if tornado.ioloop.IOLoop.instance().running():
                    tornado.ioloop.IOLoop.instance().add_timeout(time.time() + delay, lambda: self.flush_next())
                elif self._flush_without_ioloop:
                    # Tornado is no started (ie, unittests), do it manually: BLOCKING
                    time.sleep(delay)
                    self.flush_next()
Example #2
1
    def testSendMessageWithSpecifiedAddresses(self):
        # Make sure addresses specified in call override those in message.
        m = email.mime.text.MIMEText("A test message")
        m["From"] = "foo@bar.com"
        m["To"] = "John, Dinsdale"
        smtp = smtplib.SMTP(HOST, self.port, local_hostname="localhost", timeout=3)
        smtp.send_message(m, from_addr="joe@example.com", to_addrs="foo@example.net")
        # XXX (see comment in testSend)
        time.sleep(0.01)
        smtp.quit()

        self.client_evt.set()
        self.serv_evt.wait()
        self.output.flush()
        # Add the X-Peer header that DebuggingServer adds
        m["X-Peer"] = socket.gethostbyname("localhost")
        mexpect = "%s%s\n%s" % (MSG_BEGIN, m.as_string(), MSG_END)
        self.assertEqual(self.output.getvalue(), mexpect)
        debugout = smtpd.DEBUGSTREAM.getvalue()
        sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
        self.assertRegex(debugout, sender)
        for addr in ("John", "Dinsdale"):
            to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE)
            self.assertNotRegex(debugout, to_addr)
        recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
        self.assertRegex(debugout, recip)
Example #3
1
    def testSendMessageResent(self):
        m = email.mime.text.MIMEText("A test message")
        m["From"] = "foo@bar.com"
        m["To"] = "John"
        m["CC"] = "Sally, Fred"
        m["Bcc"] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
        m["Resent-Date"] = "Thu, 1 Jan 1970 17:42:00 +0000"
        m["Resent-From"] = "holy@grail.net"
        m["Resent-To"] = "Martha <my_mom@great.cooker.com>, Jeff"
        m["Resent-Bcc"] = "doe@losthope.net"
        smtp = smtplib.SMTP(HOST, self.port, local_hostname="localhost", timeout=3)
        smtp.send_message(m)
        # XXX (see comment in testSend)
        time.sleep(0.01)
        smtp.quit()

        self.client_evt.set()
        self.serv_evt.wait()
        self.output.flush()
        # The Resent-Bcc headers are deleted before serialization.
        del m["Bcc"]
        del m["Resent-Bcc"]
        # Add the X-Peer header that DebuggingServer adds
        m["X-Peer"] = socket.gethostbyname("localhost")
        mexpect = "%s%s\n%s" % (MSG_BEGIN, m.as_string(), MSG_END)
        self.assertEqual(self.output.getvalue(), mexpect)
        debugout = smtpd.DEBUGSTREAM.getvalue()
        sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
        self.assertRegex(debugout, sender)
        for addr in ("my_mom@great.cooker.com", "Jeff", "doe@losthope.net"):
            to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE)
            self.assertRegex(debugout, to_addr)
Example #4
1
def scrape_keyword_result(keyword, useragent_list, start_url, result_dir):
    br = start_browser(useragent_list)
    br.get(start_url)
    all_result_list = []
    if "sorry/IndexRedirect" in br.current_url or "400" in br.title:
        br.quit()
        return None
    else:
        result_list = scrape_the_page(br)
        all_result_list.extend(result_list)
        time.sleep(random.randint(5, 10))
        while True:
            try:
                br.find_element_by_id("pnnext")
            # Google's next page button have id 'pnnext'
            # if we can not find it. we should have get all the pages
            except NoSuchElementException:
                break
            else:
                br.find_element_by_id("pnnext").click()
                result_list = scrape_the_page(br)
                all_result_list.extend(result_list)
                time.sleep(random.randint(5, 10))
        save_result_to_file(keyword, all_result_list, result_dir)
        br.quit()
        return True
Example #5
1
def debugging_server(serv, serv_evt, client_evt):
    serv_evt.set()

    try:
        if hasattr(select, "poll"):
            poll_fun = asyncore.poll2
        else:
            poll_fun = asyncore.poll

        n = 1000
        while asyncore.socket_map and n > 0:
            poll_fun(0.01, asyncore.socket_map)

            # when the client conversation is finished, it will
            # set client_evt, and it's then ok to kill the server
            if client_evt.is_set():
                serv.close()
                break

            n -= 1

    except socket.timeout:
        pass
    finally:
        if not client_evt.is_set():
            # allow some time for the client to read the result
            time.sleep(0.5)
            serv.close()
        asyncore.close_all()
        serv_evt.set()
Example #6
1
    def test_resize_server_revert(self):
        # The server's RAM and disk space should return to its original
        # values after a resize is reverted

        previous_flavor_ref, new_flavor_ref = self._detect_server_image_flavor(self.server_id)

        resp, server = self.client.resize(self.server_id, new_flavor_ref)
        self.assertEqual(202, resp.status)
        self.client.wait_for_server_status(self.server_id, "VERIFY_RESIZE")

        self.client.revert_resize(self.server_id)
        self.client.wait_for_server_status(self.server_id, "ACTIVE")

        # Need to poll for the id change until lp#924371 is fixed
        resp, server = self.client.get_server(self.server_id)
        start = int(time.time())

        while server["flavor"]["id"] != previous_flavor_ref:
            time.sleep(self.build_interval)
            resp, server = self.client.get_server(self.server_id)

            if int(time.time()) - start >= self.build_timeout:
                message = (
                    "Server %s failed to revert resize within the \
                required time (%s s)."
                    % (self.server_id, self.build_timeout)
                )
                raise exceptions.TimeoutException(message)
Example #7
1
 def call_runtime(self):
     """
     Execute the runtime
     """
     cache = self.gather_cache()
     chunks = self.get_chunks()
     interval = self.opts["thorium_interval"]
     recompile = self.opts.get("thorium_recompile", 300)
     r_start = time.time()
     while True:
         events = self.get_events()
         if not events:
             time.sleep(interval)
             continue
         start = time.time()
         self.state.inject_globals["__events__"] = events
         self.state.call_chunks(chunks)
         elapsed = time.time() - start
         left = interval - elapsed
         if left > 0:
             time.sleep(left)
         self.state.reset_run_num()
         if (start - r_start) > recompile:
             cache = self.gather_cache()
             chunks = self.get_chunks()
             if self.reg_ret is not None:
                 self.returners["{0}.save_reg".format(self.reg_ret)](chunks)
             r_start = time.time()
    def hookup(self):
        print "Loading Emails... takes some time :)"
        if self.emails is None:
            self.load_emails()

        print "Thread started"
        print "Emails: ", len(self.emails)
        self.client, self.address = self.socket.accept()
        print "Connected..."
        i = 0
        while 1:
            time.sleep(0.45)
            try:
                self.sim_date_time += datetime.timedelta(milliseconds=random.randint(10000, 60000))
                if self.sim_date_time.year > 2015:
                    break
                if self.sim_date_time.weekday() == 7 or self.sim_date_time.weekday() == 6:
                    continue
                if i < len(self.emails) - 1:
                    i += 1
                else:
                    i = 0
                row = self.emails.iloc[i]

                fr = "~".join(list(self.get_name(row["mailfrom"])))
                to = "~".join(list(self.get_name(row["torecipients"])))
                subj = row["subject"]
                msg = row["content"]

                self.write(fr + "|" + to + "|" + subj.replace("|", " ") + "|" + msg.replace("|", " "))

            except Exception as e:
                print e.message
                self.client, self.address = self.socket.accept()
Example #9
0
    def keep_alive_fn(command, *a, **kws):
        """
        Function to run to keep command alive.  Can be used to ensure a command
        doesn't die, or to run a command periodically (every keep_alive seconds)
        """
        while True:
            try:
                # Don't kill on command exit
                with settings(warn_only=True):
                    r(command, *a, **kws)
                logger.warn(
                    "Command {} with args {} and kwargs {} died. " "Restarting after 1 second.".format(command, a, kws)
                )
            except:
                logger.exception(
                    "Command {} with args {} and kwargs {} "
                    "caused an exception. Restarting after 1 second.".format(command, a, kws)
                )
            finally:
                if callable(keep_alive):
                    # If keep alive is a function, call it
                    keep_alive(command, *a, **kws)
                else:
                    import time

                    # Else, it hsould be an integer
                    time.sleep(keep_alive)
Example #10
0
def main(argv):
    for line in sys.stdin:
        for char in line:
            sys.stdout.write(char)
            sys.stdout.flush()

            time.sleep(timings.get(char, default))
Example #11
0
 def run(self):
     global PausedPrint
     global GCodeQueue
     global InstructionNumber
     PausedPrint = False
     while True:
         if len(GCodeQueue) > 1 and not PausedPrint:
             Log.Info("Queue : " + str(len(GCodeQueue)))
             Line = GCodeQueue[0]
             if (
                 Line == None
                 or Line == ""
                 or Line == "\r"
                 or Line == "\n"
                 or Line == "\r\n"
                 or Line == "\n\r"
                 or list(Line)[0] == ";"
             ):
                 del GCodeQueue[0]
             else:
                 Printer.Send("N" + str(InstructionNumber) + " " + Line)
                 InstructionNumber = InstructionNumber + 1
                 while True:
                     if "ok" in Printer.Read():
                         break
                     time.sleep(0.01)
                 del GCodeQueue[0]
Example #12
0
    def EmergencyStop(self):
        global EmergencyMode
        global GCodeQueue
        global InstructionNumber

        InstructionNumber = 0

        if self.PrinterInterface.isOpen() and EmergencyMode == 0:
            Log.Warning("Emergency ! Mode:" + str(EmergencyMode))
            GCodeQueue.insert(0, "M112")

        if self.PrinterInterface.isOpen() and EmergencyMode == 1:
            Log.Warning("Emergency ! Mode:" + str(EmergencyMode))
            GCodeQueue.insert(0, "M112")
            Log.Warning("DTR: On")
            self.PrinterInterface.setDTR(1)
            time.sleep(1)
            Log.Warning("DTR: Off")
            self.PrinterInterface.setDTR(0)

        if self.PrinterInterface.isOpen() and EmergencyMode == 2:
            Log.Warning("Emergency ! Mode:" + str(EmergencyMode))
            GCodeQueue.insert(0, "M112")
            self.Disconnect()
            self.Connect(self.port, self.baudrate)
Example #13
0
    def test_abnormal_typechecker_exit_message(self):
        """
        Tests that the monitor outputs a useful message when its typechecker
        exits abnormally.
        """

        self.write_load_config()
        # Start a fresh server and monitor.
        launch_logs = self.check_cmd(["No errors!"])
        self.assertIn("Server launched with the following command", launch_logs)
        self.assertIn("Logs will go to", launch_logs)
        log_file_pattern = re.compile("Logs will go to (.*)")
        monitor_log_match = log_file_pattern.search(launch_logs)
        self.assertIsNotNone(monitor_log_match)
        monitor_log_path = monitor_log_match.group(1)
        self.assertIsNotNone(monitor_log_path)
        with open(monitor_log_path) as f:
            monitor_logs = f.read()
            m = re.search("Just started typechecker server with pid: ([0-9]+)", monitor_logs)
            self.assertIsNotNone(m)
            pid = m.group(1)
            self.assertIsNotNone(pid)
            os.kill(int(pid), signal.SIGTERM)
            # For some reason, waitpid in the monitor after the kill signal
            # sent above doesn't preserve ordering - maybe because they're
            # in separate processes? Give it some time.
            time.sleep(1)
            client_error = self.check_cmd(["No errors!"])
            self.assertIn("Last server killed by signal", client_error)
Example #14
0
    def test_start_pause_stop(self):
        """Test Replay() start/pause/stop."""

        # Create objects for reading data.
        reader = ReadDirectory(LOG_PATH, message=True)

        # Create object for replay.
        replay = Replay(reader)

        # Start replaying data.
        self.assertTrue(replay.start())
        self.assertTrue(replay.is_alive())
        self.assertFalse(replay.start())

        # Pause replaying data.
        self.assertTrue(replay.pause())
        self.assertFalse(replay.is_alive())
        self.assertFalse(replay.pause())
        self.assertTrue(replay.start())

        # Stop replaying data.
        self.assertTrue(replay.stop())
        self.assertFalse(replay.is_alive())
        self.assertFalse(replay.stop())

        # Allow threads to fully shut down.
        time.sleep(0.1)
Example #15
0
    def test_start_stop(self):
        """Test ScheduleBroadcasts() start/stop."""

        # Create objects for scheduling data.
        read = ReadDirectory(LOG_PATH, message=True)
        data = BufferData(read)
        data.start()

        # Wait for buffer to fill.
        start_wait = time.time()
        while not data.is_ready() and ((time.time() - start_wait) < TIMEOUT):
            time.sleep(0.1)

        # Schedule data.
        scheduler = ScheduleBroadcasts(data.queue)

        # Start scheduling data.
        self.assertTrue(scheduler.start())
        self.assertTrue(scheduler.is_alive())
        self.assertFalse(scheduler.start())

        # Stop scheduling data.
        self.assertTrue(scheduler.stop())
        self.assertFalse(scheduler.is_alive())
        self.assertFalse(scheduler.stop())

        # Allow threads to fully shut down.
        time.sleep(0.1)
Example #16
0
def index(req):
    if req.session["kirjautunut"] == "ok":
        # latauksen indikaattoria varten
        time.sleep(1)
        con = sqlite.connect("/nashome3/sajukaru/html/hidden/kanta/kanta")
        con.text_factory = str
        con.row_factory = sqlite.Row

        req.content_type = "text/plain; charset=UTF-8"
        treeniid = req.form.getfirst("treeniid")

        sql = """
             DELETE FROM Treeni
             WHERE TreeniID = :treeniid
       """
        treenityypit = {}
        cur = con.cursor()
        try:
            cur.execute(sql, {"treeniid": treeniid})
            con.commit()
            req.write("poisto onnistui")
        except:
            req.write(str(sys.exc_info()[0]))
            req.write("poisto ei onnistunut")

        return
Example #17
0
    def rescue(self, error_list, sleep_interval):
        error_files = []
        error_msg = []

        for city in error_list:
            try:
                print "[start ] fetching deals in", city
                page_num = self.crawler.fetch_deal_in(city)
                print "[finish] fetching deals in", city

                if page_num == 1 or page_num == None:
                    self.parser.parse(os.path.join(self.source, city))
                else:
                    for i in xrange(1, page_num + 1):
                        if i == 1:
                            self.parser.parse(os.path.join(self.source, city))
                        else:
                            self.parser.parse(os.path.join(self.source, city + "_" + str(i)))

                wait_time = random.randint(sleep_interval[0], sleep_interval[1])
                print "wait", wait_time, "seconds"
                time.sleep(wait_time)

            except Exception, e:
                error_files.append(city)
                error_msg.append(str(e))
                print "Error in parsing data in", city
                print e
    def _get_log_data(self, log_address, log_dir, filename):
        gzipped = False
        source_url = log_address + log_dir + filename
        try:
            r = urllib.request.urlopen(source_url)
        except urllib.error.URLError:
            try:
                r = urllib.request.urlopen(source_url + ".gz")
                gzipped = True
            except:
                raise
        except:
            raise

        raw_buf = r.read()
        # Hack to read all of Jenkins console logs as they upload
        # asynchronously. Make one attempt per second for up to 60 seconds to
        # retrieve the entire file. Short circuit when the end of file string
        # for console logs, '\n</pre>\n', is read.
        if self.retry and not gzipped and raw_buf[-8:].decode("utf-8") != "\n</pre>\n":
            content_len = len(raw_buf)
            for i in range(60):
                # Try for up to 60 seconds to retrieve the complete log file.
                try:
                    req = urllib.request.Request(source_url)
                    req.add_header("Range", "bytes=" + str(content_len) + "-")
                    r = urllib.request.urlopen(req)
                    raw_buf += r.read()
                    content_len = len(raw_buf)
                finally:
                    if raw_buf[-8:].decode("utf-8") == "\n</pre>\n":
                        break
                    time.sleep(1)

        return gzipped, raw_buf
Example #19
0
    def _read_input(self):
        log_entry = {}
        while True:
            try:
                line = self.input_stream.readline()
            except KeyboardInterrupt:
                return

            if not line:
                time.sleep(0.2)
            else:
                line = line.strip()
                if line == "end":
                    return log_entry
                elif line == "quit":
                    return
                else:
                    try:
                        field, value = line.split("=", 1)
                        if field.find(":") > -1:
                            field, validator = field.split(":", 1)
                            if validator == "timestamp":
                                value = int(float(value) * 1000)
                            else:
                                value = str(value)
                        log_entry[field] = value
                    except Exception, e:
                        self.logger.critical(str(e))
                        pass
                self.logger.debug(line)
Example #20
0
    def call(self, context, method, *args, **kwargs):
        """Call a glance client method.

        If we get a connection error,
        retry the request according to CONF.glance_num_retries.
        """
        version = kwargs.pop("version", self.version)

        retry_excs = (
            glanceclient.exc.ServiceUnavailable,
            glanceclient.exc.InvalidEndpoint,
            glanceclient.exc.CommunicationError,
        )
        num_attempts = 1 + CONF.glance_num_retries

        for attempt in range(1, num_attempts + 1):
            client = self.client or self._create_onetime_client(context, version)
            try:
                controller = getattr(client, kwargs.pop("controller", "images"))
                return getattr(controller, method)(*args, **kwargs)
            except retry_excs as e:
                netloc = self.netloc
                extra = "retrying"
                error_msg = _LE("Error contacting glance server " "'%(netloc)s' for '%(method)s', " "%(extra)s.")
                if attempt == num_attempts:
                    extra = "done trying"
                    LOG.exception(error_msg, {"netloc": netloc, "method": method, "extra": extra})
                    raise exception.GlanceConnectionFailed(reason=e)

                LOG.exception(error_msg, {"netloc": netloc, "method": method, "extra": extra})
                time.sleep(1)
            except glanceclient.exc.HTTPOverLimit as e:
                raise exception.ImageLimitExceeded(e)
Example #21
0
    def run(self):
        while not self.__stop:
            val = readMessage(self.__sock)
            if val is None:
                time.sleep(0.01)
                continue
            (data, addr) = val

            env = parseEnvelope(data)

            mid = env.getMessageId()
            if self.__midMap.has_key(mid):
                continue
            else:
                self.__midMap[mid] = 0

            iid = env.getInstanceId()
            mid = env.getMessageId()
            if iid > 0:
                mnum = env.getMessageNumber()
                key = addr[0] + ":" + str(addr[1]) + ":" + str(iid)
                if mid is not None and len(mid) > 0:
                    key = key + ":" + mid
                if not self.__iidMap.has_key(key):
                    self.__iidMap[key] = iid
                else:
                    tmnum = self.__iidMap[key]
                    if mnum > tmnum:
                        self.__iidMap[key] = mnum
                    else:
                        continue

            self.__observer.envReceived(env, addr)
Example #22
0
    def command(self, what, param=0):
        if self.frontend:
            cmd = eDVBDiseqcCommand()
            if what == "moveWest":
                string = "e03169" + ("%02x" % param)
            elif what == "moveEast":
                string = "e03168" + ("%02x" % param)
            elif what == "moveTo":
                string = "e0316b" + ("%02x" % param)
            elif what == "store":
                string = "e0316a" + ("%02x" % param)
            elif what == "limitOn":
                string = "e0316a00"
            elif what == "limitOff":
                string = "e03163"
            elif what == "limitEast":
                string = "e03166"
            elif what == "limitWest":
                string = "e03167"
            else:
                string = "e03160"  # positioner stop

            print "diseqc command:",
            print string
            cmd.setCommandString(string)
            self.frontend.setTone(iDVBFrontend.toneOff)
            sleep(0.015)  # wait 15msec after disable tone
            self.frontend.sendDiseqc(cmd)
            if string == "e03160":  # positioner stop
                sleep(0.05)
                self.frontend.sendDiseqc(cmd)  # send 2nd time
Example #23
0
 def run(self):
     self.pipe = sp.Popen(self.command, shell=True, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
     self.status = 1
     time.sleep(5)
     self.pid = self.pipe.pid
     self.data = self.pipe.stdout.read()
     self.status = 2
 def run(self):
     if self.gui.is_game_over:
         self._delete()
     while not self.gui.is_game_over:
         self.queue.put({"move": self.snake_points})
         time.sleep(0.2)
         self.move()
Example #25
0
    def testSendMessageWithAddresses(self):
        m = email.mime.text.MIMEText("A test message")
        m["From"] = "foo@bar.com"
        m["To"] = "John"
        m["CC"] = "Sally, Fred"
        m["Bcc"] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
        smtp = smtplib.SMTP(HOST, self.port, local_hostname="localhost", timeout=3)
        smtp.send_message(m)
        # XXX (see comment in testSend)
        time.sleep(0.01)
        smtp.quit()
        # make sure the Bcc header is still in the message.
        self.assertEqual(m["Bcc"], 'John Root <root@localhost>, "Dinsdale" ' "<warped@silly.walks.com>")

        self.client_evt.set()
        self.serv_evt.wait()
        self.output.flush()
        # Add the X-Peer header that DebuggingServer adds
        m["X-Peer"] = socket.gethostbyname("localhost")
        # The Bcc header should not be transmitted.
        del m["Bcc"]
        mexpect = "%s%s\n%s" % (MSG_BEGIN, m.as_string(), MSG_END)
        self.assertEqual(self.output.getvalue(), mexpect)
        debugout = smtpd.DEBUGSTREAM.getvalue()
        sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
        self.assertRegex(debugout, sender)
        for addr in ("John", "Sally", "Fred", "root@localhost", "warped@silly.walks.com"):
            to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE)
            self.assertRegex(debugout, to_addr)
Example #26
0
def sendCmd(tty, command):
    ackSignal = "" + chr(0x90) + chr(0x41) + chr(0xFF)
    cplSignal = "" + chr(0x90) + chr(0x51) + chr(0xFF)

    tty.write(command)
    counter = 0
    while tty.inWaiting() < len(ackSignal):
        time.sleep(1)
        counter += 1

        if counter == 10:
            print "Camera would not acknowledge our command.  Aborting."
            exit(1)

    data = tty.read(len(ackSignal))

    if data == ackSignal:
        print "Command was acknowledged"

    counter = 0
    while tty.inWaiting() < len(cplSignal):
        time.sleep(1)
        counter += 1

        if counter == 10:
            print "Camera could not complete command.  Aborting."
            exit(1)

    data = tty.read(len(cplSignal))

    if data == cplSignal:
        print "Command was completed"
        return True
Example #27
0
    def testSendMessageWithMultipleFrom(self):
        # Sender overrides To
        m = email.mime.text.MIMEText("A test message")
        m["From"] = "Bernard, Bianca"
        m["Sender"] = "the_rescuers@Rescue-Aid-Society.com"
        m["To"] = "John, Dinsdale"
        smtp = smtplib.SMTP(HOST, self.port, local_hostname="localhost", timeout=3)
        smtp.send_message(m)
        # XXX (see comment in testSend)
        time.sleep(0.01)
        smtp.quit()

        self.client_evt.set()
        self.serv_evt.wait()
        self.output.flush()
        # Add the X-Peer header that DebuggingServer adds
        m["X-Peer"] = socket.gethostbyname("localhost")
        mexpect = "%s%s\n%s" % (MSG_BEGIN, m.as_string(), MSG_END)
        self.assertEqual(self.output.getvalue(), mexpect)
        debugout = smtpd.DEBUGSTREAM.getvalue()
        sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
        self.assertRegex(debugout, sender)
        for addr in ("John", "Dinsdale"):
            to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE)
            self.assertRegex(debugout, to_addr)
    def update_config(self):
        if self._restart:
            print >>sys.stderr, "[hosted.py] restarting service (restart_on_update set)"
            import thread, time

            thread.interrupt_main()
            time.sleep(100)
            return

        def parse_recursive(options, config, target):
            # print 'parsing', config
            for option in options:
                if not "name" in option:
                    continue
                if option["type"] == "list":
                    items = []
                    for item in config[option["name"]]:
                        parsed = {}
                        parse_recursive(option["items"], item, parsed)
                        items.append(parsed)
                    target[option["name"]] = items
                    continue
                target[option["name"]] = types[option["type"]](config[option["name"]])

        parsed = {}
        parse_recursive(self._options, self._config, parsed)
        print >>sys.stderr, "[hosted.py] updated config"
        self._parsed = parsed
Example #29
0
File: pr.py Project: navan93/gtfs
def main():

    i = 0
    employees = [random_mac() for _ in range(13)]
    for edge in edges[sys.argv[1]]:
        time.sleep(0.5)
        i += 1
        jsond = json.dumps(
            {
                "position": {"lat": edge[1], "lng": edge[0]},
                "trip_id": sys.argv[1],
                "time": datetime.datetime.now().strftime("%y-%m-%d-%H-%M-%S"),
                "det": {
                    "trip_id": "617_EY_PATTOM" + sys.argv[1],
                    "emp": employees,
                    "stops_visited": stops_visited,
                    "stops_rem": stops_rem,
                },
            }
        )
        redispub(jsond)
        print(jsond)
        if i == 30:
            i = 0
            employees.pop(0)
            employees.append(random_mac())
            place = stops_rem.pop(0)
            stops_visited.append(place)
            time.sleep(3)
Example #30
0
 def test_simplehelp(self):
     """A simple test of 'help' command and its output."""
     res = lldb.SBCommandReturnObject()
     self.ci.HandleCommand("help", res)
     time.sleep(0.1)
     self.assertTrue(res.Succeeded())
     self.assertTrue(res.GetOutput().startswith("The following is a list of built-in, permanent debugger commands"))