since imaplib doesn't support IMAP4r1 IDLE, we'll do it by hand
333708
def _idle(self):
        
        socket = None

        try:
            # build a new command tag (Xnnn) as bytes:
            self.command_tag = (self.command_tag + 1) % 1000
            command_tag = b"X" + bytes(str(self.command_tag).zfill(3), "ascii")

            # make sure we have selected anything before idling:
            directories = self.mailbox.split(",")
            self.connection.select(directories[0])

            socket = self.connection.socket()

            # send IDLE command and check response:
            socket.write(command_tag + b" IDLE\r\n")
            try:
                response = socket.read(4096).decode("ascii")
            except socket_error:
                raise imaplib.IMAP4.abort("Server didn't respond to 'IDLE' in time")
            if not response.lower().startswith("+ idling"):
                raise imaplib.IMAP4.abort("While initializing IDLE: " + str(response))

            # wait for changes (EXISTS, EXPUNGE, etc.):
            socket.settimeout(self.cache_timeout)
            while True:
                try:
                    response = socket.read(4096).decode("ascii")
                    if response.upper().startswith("* OK"):
                        continue  # ignore '* OK Still here'
                    else:
                        break
                except socket_error:  # IDLE timed out
                    break

        finally:  # terminate IDLE command gracefully
            if socket is None:
                return

            socket.settimeout(self.read_timeout)
            socket.write(b"DONE\r\n")  # important! Can't query IMAP again otherwise
            try:
                response = socket.read(4096).decode("ascii")
            except socket_error:
                raise imaplib.IMAP4.abort("Server didn't respond to 'DONE' in time")

            # sometimes, more messages come in between reading and DONEing; so read them again:
            if response.startswith("* "):
                try:
                    response = socket.read(4096).decode("ascii")
                except socket_error:
                    raise imaplib.IMAP4.abort(
                        "Server sent more continuations, but no 'DONE' ack"
                    )

            expected_response = (command_tag + b" OK").decode("ascii")
            if not response.lower().startswith(expected_response.lower()):
                raise imaplib.IMAP4.abort("While terminating IDLE: " + response)
979369
def idle_task(self):
        ''''''
        if self.fix_type >= 3:
            # don't do anything if we have a fix
            return
        if self.mpstate.status.armed:
            # do not upload data over telemetry link if we are armed
            # perhaps we should just limit rate instead.
            return
        now = time.time()
        if self.auto:
            if now-self.last_auto > 2:
                self.last_auto = now
                print("Doing auto things")
                if self.idle_upload_mga_dbd():
                    self.auto_status = "DBD uploaded"

                if not self.idle_upload_mga_online():
                    self.auto_status = "Online uploaded"

                if not self.idle_upload_mga_offline():
                    self.auto_status = "Offline uploaded"
354144
private synchronized void complete(String message) {
    
    // This is a weird problem with writing stuff while idling. Need to investigate it more, but
    // for now just ignore it.
    if (MESSAGE_COULDNT_BE_FETCHED_REGEX.matcher(message).matches()) {
      log.warn("Some messages in the batch could not be fetched for {}\n" +
          "---cmd---\n{}\n---wire---\n{}\n---end---\n", new Object[] {
          config.getUsername(),
          getCommandTrace(),
          getWireTrace()
      });
      errorStack.push(new Error(completions.peek(), message, wireTrace.list()));
      final CommandCompletion completion = completions.peek();
      String errorMsg = "Some messages in the batch could not be fetched for user " + config.getUsername();
      RuntimeException ex = new RuntimeException(errorMsg);
      if (completion != null) {
        completion.error(errorMsg, new MailHandlingException(getWireTrace(), errorMsg, ex));
        completions.poll();
      } else {
        throw ex;
      }
    }

    CommandCompletion completion = completions.peek();
    if (completion == null) {
      if ("+ idling".equalsIgnoreCase(message)) {
        synchronized (idleMutex) {
          idler.idleStart();
          log.trace("IDLE entered.");
          idleAcknowledged.set(true);
        }
      } else {
        log.error("Could not find the completion for message {} (Was it ever issued?)", message);
        errorStack.push(new Error(null, "No completion found!", wireTrace.list()));
      }
      return;
    }
    
    if (completion.complete(message)) {
      completions.poll();
    }
  }
823826
def pickle_dumps(inbox):
    
    # http://bugs.python.org/issue4074
    gc.disable()
    str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL)
    gc.enable()
    return str_
1027295
async def on_raw_317(self, message):
        
        target, nickname, idle_time = message.params[:3]
        info = {
            'idle': int(idle_time),
        }

        if nickname in self._pending['whois']:
            self._whois_info[nickname].update(info)
306058
def loop(self, sleep_time=1, callback=None):
        

        self.log("No supported libraries found: using polling-method.")
        self._running = True
        self.trigger_init()
        self._scan(trigger=False)  # put after the trigger
        if self._warn:
            print("""
You should install a third-party library so I don't eat CPU.
Supported libraries are:
  - pyinotify (Linux)
  - pywin32 (Windows)
  - MacFSEvents (OSX)

Use pip or easy_install and install one of those libraries above.
""")
        while self._running:
            self._scan()
            if isinstance(callback, collections.Callable):
                callback()
            time.sleep(sleep_time)
149404
def server(addr, id, privkey=nil, linger=1000)
      fail IOError unless addr && id

      socket = Celluloid::ZMQ::RouterSocket.new
      fail IOError unless socket
      begin
        set_server_key socket, privkey
        socket.identity = id
        socket.bind(addr)
        socket.linger = linger
      rescue IOError
        socket.close
        raise
      end
      addr = socket.get(::ZMQ::LAST_ENDPOINT).strip
      [socket, addr]
    end
474881
def im_open(self, *, user: str, **kwargs) -> SlackResponse:
        
        kwargs.update({"user": user})
        return self.api_call("im.open", json=kwargs)
290467
def imap_connect(self):
        
        self.mailbox = imaplib.IMAP4_SSL(self.imap_string, self.port)
        self.mailbox.login(self.uname, self.pwd)
        self.mailbox.select()
174793
def pack_command(self, *args):
        ""
        args_output = SYM_EMPTY.join([
            SYM_EMPTY.join(
                (SYM_DOLLAR, str(len(k)).encode(), SYM_CRLF, k, SYM_CRLF))
            for k in imap(self.encoder.encode, args)])
        output = SYM_EMPTY.join(
            (SYM_STAR, str(len(args)).encode(), SYM_CRLF, args_output))
        return output
907957
def do_rawpart(self, subcmd, opts, message):
        
        client = MdClient(self.maildir, filesystem=self.filesystem)
        partid = getattr(opts, "part", None)
        if not partid:
            client.getrawpart(message, self.stdout)
        else:
            client.getrawpartid(message, partid, self.stdout)
885080
def main():
    

    listname = sys.argv[2]
    hostname = sys.argv[1]

    # We must get the list unlocked here because it is already locked in
    # ArchRunner. This is safe because we aren't actually changing our list
    # object. ArchRunner's lock plus pipermail's archive lock will prevent
    # any race conditions.
    mlist = MailList.MailList(listname, lock=False)

    # We need a seekable file for processUnixMailbox()
    f = StringIO(sys.stdin.read())

    # If we don't need a Message.Message instance, we can skip the next and
    # the imports of email and Message above.
    msg = email.message_from_file(f, Message.Message)

    h = HyperArch.HyperArchive(mlist)
    # Get the message number for the next message
    sequence = h.sequence
    # and add the message.
    h.processUnixMailbox(f)
    f.close()

    # Get the archive name, etc.
    archive = h.archive
    msgno = '%06d' % sequence
    filename = msgno + '.html'
    filepath = os.path.join(h.basedir, archive, filename)
    h.close()

    url = '%s%s/%s' % (mlist.GetBaseArchiveURL(), archive, filename)

    ext_process(listname, hostname, url, filepath, msg)
400276
function idleLoop(deadline) {
  var
    length = getLength(qidle, qidlex),
    didTimeout = deadline.didTimeout
  ;
  if (length) {
    // reschedule upfront next idle callback
    requestIdleCallback(idleLoop, {timeout: next.maxIdle});
    // this prevents the need for a try/catch within the while loop
    // reassign qidlex cleaning current idle queue
    qidlex = qidle.splice(0, didTimeout ? 1 : length);
    while (qidlex.length && (didTimeout || deadline.timeRemaining()))
      exec(qidlex.shift());
  } else {
    // all idle callbacks have been executed
    // we can actually stop asking for idle operations
    idleRunning = false;
  }
}
1002976
def do_raw(self, subcmd, opts, message):
        
        client = MdClient(self.maildir)
        client.getraw(message, self.stdout)
515786
def do_rm(self, subcmd, opts, message):
        
        maildir = self.maildir
        client = MdClient(maildir, filesystem=self.filesystem)
        try:
            client.remove(message)
        except KeyError:
            return 1
1060528
def wrap_io_os_err(e):
    ''''''
    msg = ''
    if e.strerror:
        msg = e.strerror
    if e.message:
        msg = ' '.join([e.message, msg])
    if e.filename:
        msg = ': '.join([msg, e.filename])
    return msg
940854
def await_idle(self, parent_id, timeout):
        """"""
        while True:
            # Get a message from the kernel iopub channel
            msg = self.get_message(timeout=timeout, stream='iopub') # raises Empty on timeout!

            if msg['parent_header'].get('msg_id') != parent_id:
                continue
            if msg['msg_type'] == 'status':
                if msg['content']['execution_state'] == 'idle':
                    break