Will perform longpoll request for changes in the user's Dropbox
account and display those changes. This is more efficient that
periodic polling the endpoint.
162585
public static void longpoll(DbxAuthInfo auth, String path) throws IOException {
        long longpollTimeoutSecs = TimeUnit.MINUTES.toSeconds(2);

        // need 2 Dropbox clients for making calls:
        //
        // (1) One for longpoll requests, with its read timeout set longer than our polling timeout
        // (2) One for all other requests, with its read timeout set to the default, shorter timeout
        //
        StandardHttpRequestor.Config config = StandardHttpRequestor.Config.DEFAULT_INSTANCE;
        StandardHttpRequestor.Config longpollConfig = config.copy()
            // read timeout should be greater than our longpoll timeout and include enough buffer
            // for the jitter introduced by the server. The server will add a random amount of delay
            // to our longpoll timeout to avoid the stampeding herd problem. See
            // DbxFiles.listFolderLongpoll(String, long) documentation for details.
            .withReadTimeout(5, TimeUnit.MINUTES)
            .build();

        DbxClientV2 dbxClient = createClient(auth, config);
        DbxClientV2 dbxLongpollClient = createClient(auth, longpollConfig);

        try {
            // We only care about file changes, not existing files, so grab latest cursor for this
            // path and then longpoll for changes.
            String cursor = getLatestCursor(dbxClient, path);

            System.out.println("Longpolling for changes... press CTRL-C to exit.");
            while (true) {
                // will block for longpollTimeoutSecs or until a change is made in the folder
                ListFolderLongpollResult result = dbxLongpollClient.files()
                    .listFolderLongpoll(cursor, longpollTimeoutSecs);

                // we have changes, list them
                if (result.getChanges()) {
                    cursor = printChanges(dbxClient, cursor);
                }

                // we were asked to back off from our polling, wait the requested amount of seconds
                // before issuing another longpoll request.
                Long backoff = result.getBackoff();
                if (backoff != null) {
                    try {
                        System.out.printf("backing off for %d secs...\n", backoff.longValue());
                        Thread.sleep(TimeUnit.SECONDS.toMillis(backoff));
                    } catch (InterruptedException ex) {
                        System.exit(0);
                    }
                }
            }
        } catch (DbxApiException ex) {
            // if a user message is available, try using that instead
            String message = ex.getUserMessage() != null ? ex.getUserMessage().getText() : ex.getMessage();
            System.err.println("Error making API call: " + message);
            System.exit(1);
        } catch (NetworkIOException ex) {
            System.err.println("Error making API call: " + ex.getMessage());
            if (ex.getCause() instanceof SocketTimeoutException) {
                System.err.println("Consider increasing socket read timeout or decreasing longpoll timeout.");
            }
            System.exit(1);
        } catch (DbxException ex) {
            System.err.println("Error making API call: " + ex.getMessage());
            System.exit(1);
        }
    }
1087177
def process_long_poll(result)
      case result
      when Exceptions::Unauthorized, Exceptions::ConnectivityFailure, Exceptions::RetryableError, Exceptions::InternalServerError
        # Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff
        @connect_interval = CONNECT_INTERVAL
        update_listen_state(:choose, backoff_reconnect_interval)
        result = nil
      when Exception
        ErrorTracker.track(self, result)
        update_listen_state(:choose, backoff_reconnect_interval)
        result = nil
      else
        @reconnect_interval = RECONNECT_INTERVAL
        @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks
        update_listen_state(:choose)
      end
      result
    end
1131364
private String requestAccountName(DropboxAPI<AndroidAuthSession> dropboxApi) {
        String accountName = null;
        if (dropboxApi != null) {
            try {
                accountName = dropboxApi.accountInfo().displayName;
            } catch (DropboxException e) {
                // Do nothing.
            }
        }
        return accountName;
    }
356153
function () {
        var self = this;

        async.waterfall([

          function (next) {
            if (!self.events) {
              self.events = new Datastore();
              self.events.ensureIndex({
                fieldName: 'event_id',
                unique: true
              });
              self.events.ensureIndex({
                fieldName: 'recorded_at',
                sparse: true
              });
              self.events.ensureIndex({
                fieldName: 'created_at',
              }, next);
            } else {
              next();
            }
          },
          function (next) {
            if (!self.keepPolling) {
              self.keepPolling = true;

              async.whilst(function () {
                return self.keepPolling;
              }, _.bind(self._emit, self), _.noop);
              next(null, true);
            } else {
              next(null, false);
            }
          },

          function (doLongPoll, next) {
            if (doLongPoll) {
              async.whilst(function () {
                return self.keepPolling;
              }, _.bind(self._longPoll, self), function (err) {
                if (err) {
                  /**
                   * Fires when an error occurs during long-polling.
                   * @event Connection#"polling.error"
                   * @type {Error}
                   * @see {@link Connection#startLongPolling}
                   */
                  self.emit('polling.error', err);
                } else if (!self.keepPolling) {
                  /**
                   * Fires when a running long-polling process ends.
                   * @event Connection#"polling.end"
                   * @see {@link Connection#stopLongPolling}
                   */
                  self.emit('polling.end');
                }
              });
            }
            next();
          }
        ], _.noop);
      }
195189
public ChangesResult getChanges() {
        final URI uri = this.databaseHelper.changesUri("feed", "normal");
        return client.get(uri, ChangesResult.class);
    }
154911
def _handle_poll(self, relpath, params):
    """"""
    request = json.loads(params.get('q')[0])
    ret = {}
    # request is a polling request for multiple files. For each file:
    #  - id is some identifier assigned by the client, used to differentiate the results.
    #  - path is the file to poll.
    #  - pos is the last byte position in that file seen by the client.
    for poll in request:
      _id = poll.get('id', None)
      path = poll.get('path', None)
      pos = poll.get('pos', 0)
      if path:
        abspath = os.path.normpath(os.path.join(self._root, path))
        if os.path.isfile(abspath):
          with open(abspath, 'rb') as infile:
            if pos:
              infile.seek(pos)
            content = infile.read()
            ret[_id] = content.decode("utf-8")
    content = json.dumps(ret).encode("utf-8")
    self._send_content(content, 'application/json')
756443
def response_change(self, request, obj):
        
        r = super(FolderAdmin, self).response_change(request, obj)
        # Code borrowed from django ModelAdmin to determine changelist on the
        # fly
        if r['Location']:
            # it was a successful save
            if (r['Location'] in ['../'] or
                    r['Location'] == self._get_post_url(obj)):
                if obj.parent:
                    url = reverse('admin:filer-directory_listing',
                                  kwargs={'folder_id': obj.parent.id})
                else:
                    url = reverse('admin:filer-directory_listing-root')
                url = "%s%s%s" % (url, popup_param(request),
                                  selectfolder_param(request, "&"))
                return HttpResponseRedirect(url)
            else:
                # this means it probably was a save_and_continue_editing
                pass
        return r
530126
protected function fetch_dropbox_content($endpoint, $data = []) {
        $url = $this->get_content_endpoint($endpoint);
        $this->cleanopt();
        $this->resetHeader();

        $options['CURLOPT_POST'] = 1;
        $this->setHeader('Content-Type: ');
        $this->setHeader('Dropbox-API-Arg: ' . json_encode($data));

        $response = $this->request($url, $options);

        $this->check_and_handle_api_errors($response);
        return $response;
    }
116080
private boolean askToSave() {
        if (mainFrame.isProjectChanged()) {
            int response = JOptionPane.showConfirmDialog(mainFrame, L10N.getLocalString("dlg.save_current_changes",
                    "The current project has been changed, Save current changes?"), L10N.getLocalString("dlg.save_changes",
                            "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);

            if (response == JOptionPane.YES_OPTION) {
                if (mainFrame.getSaveFile() != null) {
                    save();
                } else {
                    saveAs();
                }
            } else if (response == JOptionPane.CANCEL_OPTION)
            {
                return true;
                // IF no, do nothing.
            }
        }
        return false;
    }
292562
private void submitRevisions(final List<DocumentChange> changes) {
        synchronized (changesLock) {
            try {
                java.net.URI remoteUri = remote.toURI();
                for (DocumentChange change : changes) {
                    // Skip revisions that originally came from the database I'm syncing to:
                    URL source = change.getSource();
                    if (source != null && source.toURI().equals(remoteUri))
                        continue;
                    RevisionInternal rev = change.getAddedRevision();
                    if (rev == null)
                        continue;
                    if (getLocalDatabase().runFilter(filter, filterParams, rev)) {
                        if (doneBeginReplicating) {
                            pauseOrResume();
                            waitIfPaused();
                            // if not running state anymore, exit from loop.
                            if (!isRunning())
                                break;
                            RevisionInternal nuRev = rev.copyWithoutBody();
                            addToInbox(nuRev);
                        } else {
                            RevisionInternal nuRev = rev.copyWithoutBody();
                            queueChanges.add(nuRev);
                        }
                    }
                }
            } catch (java.net.URISyntaxException uriException) {
                // Not possible since it would not be an active replicator.
                // However, until we refactor everything to use java.net,
                // I'm not sure we have a choice but to swallow this.
                Log.e(TAG, "Active replicator found with invalid URI", uriException);
            }
        }
    }
414557
function (callback) {
            async.until(
                // conditions for stopping the poll
                function () {
                    waitTimeOver = elapsed > constants.WAIT_TIMEOUT;
                    return waitTimeOver || domHasChanged;
                },
                function (callback) {
                    // polls the page at an interval
                    setTimeout(function () {
                        elapsed += constants.POLL_INTERVAL;
                        getData.takeSnapshot(page, ph, function (error, page, ph, newDom) {
                            if (error) {
                                callback(error);
                                return;
                            }
                            domHasChanged = helpers.domIsDifferent(originalDom, newDom);
                            callback();
                        });
                    }, constants.POLL_INTERVAL);
                },

                function (error) {
                    if (waitTimeOver) {
                        callback('Timeout while waiting for dom to change');
                        return;
                    }
                    callback(error);
                }
            );
        }
151277
public static int poll(Selector selector, PollItem[] items, int count, long timeout)
    {
        Utils.checkArgument(items != null, "items have to be supplied for polling");
        if (count == 0) {
            if (timeout <= 0) {
                return 0;
            }
            LockSupport.parkNanos(TimeUnit.NANOSECONDS.convert(timeout, TimeUnit.MILLISECONDS));
            return 0;
        }
        long now = 0L;
        long end = 0L;

        HashMap<SelectableChannel, SelectionKey> saved = new HashMap<SelectableChannel, SelectionKey>();
        for (SelectionKey key : selector.keys()) {
            if (key.isValid()) {
                saved.put(key.channel(), key);
            }
        }

        for (int i = 0; i < count; i++) {
            PollItem item = items[i];
            if (item == null) {
                continue;
            }

            SelectableChannel ch = item.getChannel(); // mailbox channel if ZMQ socket
            SelectionKey key = saved.remove(ch);

            if (key != null) {
                if (key.interestOps() != item.interestOps()) {
                    key.interestOps(item.interestOps());
                }
                key.attach(item);
            }
            else {
                try {
                    ch.register(selector, item.interestOps(), item);
                }
                catch (ClosedSelectorException e) {
                    // context was closed asynchronously, exit gracefully
                    return -1;
                }
                catch (ClosedChannelException e) {
                    throw new ZError.IOException(e);
                }
            }
        }

        if (!saved.isEmpty()) {
            for (SelectionKey deprecated : saved.values()) {
                deprecated.cancel();
            }
        }

        boolean firstPass = true;
        int nevents = 0;
        int ready;

        while (true) {
            //  Compute the timeout for the subsequent poll.
            long waitMillis;
            if (firstPass) {
                waitMillis = 0L;
            }
            else if (timeout < 0L) {
                waitMillis = -1L;
            }
            else {
                waitMillis = TimeUnit.NANOSECONDS.toMillis(end - now);
                if (waitMillis == 0) {
                    waitMillis = 1L;
                }
            }

            //  Wait for events.
            try {
                int rc;
                if (waitMillis < 0) {
                    rc = selector.select(0);
                }
                else if (waitMillis == 0) {
                    rc = selector.selectNow();
                }
                else {
                    rc = selector.select(waitMillis);
                }

                for (SelectionKey key : selector.keys()) {
                    PollItem item = (PollItem) key.attachment();
                    ready = item.readyOps(key, rc);
                    if (ready < 0) {
                        return -1;
                    }

                    if (ready > 0) {
                        nevents++;
                    }
                }
                selector.selectedKeys().clear();

            }
            catch (ClosedSelectorException e) {
                // context was closed asynchronously, exit gracefully
                return -1;
            }
            catch (IOException e) {
                throw new ZError.IOException(e);
            }
            //  If timeout is zero, exit immediately whether there are events or not.
            if (timeout == 0) {
                break;
            }

            if (nevents > 0) {
                break;
            }

            //  At this point we are meant to wait for events but there are none.
            //  If timeout is infinite we can just loop until we get some events.
            if (timeout < 0) {
                if (firstPass) {
                    firstPass = false;
                }
                continue;
            }

            //  The timeout is finite and there are no events. In the first pass
            //  we get a timestamp of when the polling have begun. (We assume that
            //  first pass have taken negligible time). We also compute the time
            //  when the polling should time out.
            if (firstPass) {
                now = Clock.nowNS();
                end = now + TimeUnit.MILLISECONDS.toNanos(timeout);
                if (now == end) {
                    break;
                }
                firstPass = false;
                continue;
            }

            //  Find out whether timeout have expired.
            now = Clock.nowNS();
            if (now >= end) {
                break;
            }
        }
        return nevents;
    }
521318
private static void modifyAccountBySettingClient() {
    try {
      AccountUpdateResponse response = Account.updater()
        .city("Test city")
        .client(client)
        .update();
      System.out.println(response);
    } catch (PlivoRestException | IOException e) {
      e.printStackTrace();
    }
  }
991157
private void pollAndUpdateProgress(Stage stage, String name, WorkAllocations.Work work, Job parentJob, Job subJob) {
    pollAndUpdateProgress(stage, name, work, parentJob, subJob, false);
  }
1021412
function pollTexture(storageId) {

  var url = getNoCdnUrlFromStorageId(storageId)

  return poll(function (resolve, reject, next) {

    checkIfFileExists(url).then(function(exists){
      exists ? resolve() : next()
    })

  })

}
1011469
private boolean peekOrPoll(@Nullable Duration claimTtl, EventSink rawSink) {
        // If dedup activity is disabled then we're in the process of falling back to regular non-dedup'd channels.
        // Don't do anything that might move events around--we're likely racing a call to moveToRawChannel().
        if (!_dedupEnabled.get()) {
            return false;
        }

        // When polling, protect from bad pollers that never ack.
        if (claimTtl != null && _eventStore.getClaimCount(_readChannel) >= Limits.MAX_CLAIMS_OUTSTANDING) {
            return false;
        }

        TrackingEventSink sink = new TrackingEventSink(rawSink);

        // There are three places in which to look for events:
        // 1. Read channel
        // 2. Persistent sorted queue
        // 3. Write channel
        // This code is designed to, in the *common* case, poll only one of those sources.  As things transition
        // between the following 3 phases it will occasionally poll multiple sources, but hopefully a server will
        // spend most of its time in one particular phase, resulting in efficient polling overall.
        // Phase 1: Try to keep the read channel empty.  Start by draining the read channel of un-acked events.
        // Phase 2: When readers are slower than writers, events build up in the sorted queue.  Source from the sorted queue.
        // Phase 3: When readers are faster than writers, the sorted queue isn't useful.  Source directly from the write channel.

        // The read channel only contains unclaimed events when (a) claims have expired because something has gone
        // wrong (crash, restart, timeout, etc.) or (b) polling the sorted queue or write channel pulled more items
        // than the sink would accept and we had to write the overflow to the read channel.  Neither is the common
        // case, so rely on the DefaultEventStore "empty channel" cache to rate limit actual reads to one-per-second.
        boolean moreRead = peekOrPollReadChannel(claimTtl, sink);
        if (sink.isDone()) {
            return moreRead || !getQueue().isEmpty() || !isWriteChannelEmpty();
        }

        // Do NOT dedup events in-memory between the read channel and the other sources.  Once an event makes it to
        // the read channel we can't dedup it with anything else.  That lets us support the following sequence:
        // 1. process A adds EventX
        // 2. process B polls EventX and begins working on it
        // 3. process A makes a change and adds EventX to be re-evaluated
        // 4. process B acks EventX
        // The event added in step 3 must be kept separate from the event added in step 1 so it doesn't get acked
        // in step 4.  Essentially, once a poller starts working on an event (indicated by its presence in the read
        // channel) we can't dedup/consolidate that event with any other events.
        Set<ByteBuffer> unique = Sets.newHashSet();

        // Search for events in the write channel, copying them to the sorted queue or, under certain circumstances,
        // copying them directly to the read channel before returning.
        boolean moreWrite = peekOrPollWriteChannel(claimTtl, sink, unique);
        if (moreWrite) {
            // There are more unconsumed write channel events.  Move them asynchronously to the sorted queue.
            _asyncFiller.start();
        }

        // Search for events in the sorted queue, copying them to the read channel before returning.
        boolean moreSorted = peekOrPollSortedQueue(claimTtl, sink, unique);

        return moreWrite || moreSorted;
    }
751388
public function change()
    {
        $table = $this->table('polls');
        $table->addColumn('author', 'string', array('limit' => 16))
              ->addColumn('question', 'string')
              ->addColumn('ended', 'boolean', array('null' => false, 'default' => 0))
              ->addColumn('bottom', 'boolean', array('null' => false, 'default' => 0))
              ->addColumn('hide_results', 'boolean', array('null' => false, 'default' => 0))
              ->create();

        $table->addForeignKey('author', 'user', 'user', array('delete'=> 'CASCADE', 'update'=> 'CASCADE'))
              ->save();

        $table = $this->table('polls_option');
        $table->addColumn('poll', 'integer')
              ->addColumn('text', 'string')
              ->create();

        $table->addForeignKey('poll', 'polls', 'id', array('delete'=> 'CASCADE', 'update'=> 'CASCADE'))
              ->save();

        $table = $this->table('polls_response');
        $table->addColumn('poll', 'integer')
              ->addColumn('option', 'integer')
              ->addColumn('ip', 'string')
              ->addColumn('useragent', 'string')
              ->create();

        $table->addForeignKey('poll', 'polls', 'id', array('delete'=> 'CASCADE', 'update'=> 'CASCADE'))
              ->addForeignKey('option', 'polls_option', 'id', array('delete'=> 'CASCADE', 'update'=> 'CASCADE'))
              ->save();

        $table = $this->table('article_polls');
        $table->addColumn('poll', 'integer')
              ->addColumn('article', 'integer')
              ->create();

        $table->addForeignKey('poll', 'polls', 'id', array('delete'=> 'CASCADE', 'update'=> 'CASCADE'))
              ->addForeignKey('article', 'article', 'id', array('delete'=> 'CASCADE', 'update'=> 'CASCADE'))
              ->save();

    }