Use the search suggestions provider to obtain a live cursor.  This will be called
in a worker thread, so it's OK if the query is slow (e.g. round trip for suggestions).
The results will be processed in the UI thread and changeCursor() will be called.
355286
@Override
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        if (DBG) Log.d(LOG_TAG, "runQueryOnBackgroundThread(" + constraint + ")");
        String query = (constraint == null) ? "" : constraint.toString();
        /**
         * for in app search we show the progress spinner until the cursor is returned with
         * the results.
         */
        Cursor cursor = null;
        if (mSearchView.getVisibility() != View.VISIBLE
                || mSearchView.getWindowVisibility() != View.VISIBLE) {
            return null;
        }
        //mSearchView.getWindow().getDecorView().post(mStartSpinnerRunnable); // TODO:
        try {
            cursor = getSuggestions(query, QUERY_LIMIT);
            // trigger fill window so the spinner stays up until the results are copied over and
            // closer to being ready
            if (cursor != null) {
                cursor.getCount();
                return cursor;
            }
        } catch (RuntimeException e) {
            Log.w(LOG_TAG, "Search suggestions query threw an exception.", e);
        }
        // If cursor is null or an exception was thrown, stop the spinner and return null.
        // changeCursor doesn't get called if cursor is null
        // mSearchView.getWindow().getDecorView().post(mStopSpinnerRunnable); // TODO:
        return null;
    }
729187
def cursor():
    """"""
    try:
        cur = conn.cursor()
        yield cur
    except (db.Error, Exception) as e:
        cur.close()
        if conn:
            conn.rollback()
        print(e.message)
        raise
    else:
        conn.commit()
        cur.close()
198383
function () {
            // this._cfg can be null due to the following execution chain: native focus -> native blur -> AutoComplete
            // bound value update in the data model -> bindRefreshTo section refresh
            if (this._firstFocus && this._cfg && this._cfg.autoselect) {
                // this allow to click again and put the cursor at a given position
                this._firstFocus = false;
                var field = this.getTextInputField();
                var start = 0;
                var end = (field.value.length) ? field.value.length : 0;
                if (end) {
                    this.setCaretPosition(start, end);
                }
            }
        }
267736
function _updateCursorInfo(event, editor) {
        editor = editor || EditorManager.getActiveEditor();

        // compute columns, account for tab size
        var cursor = editor.getCursorPos(true);

        var cursorStr = StringUtils.format(Strings.STATUSBAR_CURSOR_POSITION, cursor.line + 1, cursor.ch + 1);

        var sels = editor.getSelections(),
            selStr = "";

        if (sels.length > 1) {
            //Send analytics data for multicursor use
            HealthLogger.sendAnalyticsData(
                "multiCursor",
                "usage",
                "multiCursor",
                "use"
            );
            selStr = StringUtils.format(Strings.STATUSBAR_SELECTION_MULTIPLE, sels.length);
        } else if (editor.hasSelection()) {
            var sel = sels[0];
            if (sel.start.line !== sel.end.line) {
                var lines = sel.end.line - sel.start.line + 1;
                if (sel.end.ch === 0) {
                    lines--;  // end line is exclusive if ch is 0, inclusive otherwise
                }
                selStr = _formatCountable(lines, Strings.STATUSBAR_SELECTION_LINE_SINGULAR, Strings.STATUSBAR_SELECTION_LINE_PLURAL);
            } else {
                var cols = editor.getColOffset(sel.end) - editor.getColOffset(sel.start);  // end ch is exclusive always
                selStr = _formatCountable(cols, Strings.STATUSBAR_SELECTION_CH_SINGULAR, Strings.STATUSBAR_SELECTION_CH_PLURAL);
            }
        }
        $cursorInfo.text(cursorStr + selStr);
    }
770836
public void setLiveSearch(final boolean liveSearch) {
        if (liveSearch)
            attrMixin.setAttribute(LIVE_SEARCH, Boolean.toString(true));
        else
            attrMixin.removeAttribute(LIVE_SEARCH);
    }
26038
def on_change(self, path, event_type):
        
        # I can do all this work in a sql statement, but
        # for debugging it's easier to do it in stages.
        sql = """SELECT collection_id
                 FROM collection_table
                 WHERE path == ?
        """
        cursor = self._execute(sql, (path,))
        results = cursor.fetchall()
        # there should always be exactly one result, but
        # there's no harm in using a loop to process the
        # single result
        for result in results:
            collection_id = result[0]
            # remove all keywords in this collection
            sql = """DELETE from keyword_table
                     WHERE collection_id == ?
            """
            cursor = self._execute(sql, (collection_id,))
            self._load_keywords(collection_id, path=path)
469199
function () {
        var that = this,
            fullQuery = that.extendedCurrentValue(),
            currentValue = that.el.val(),
            resolver = $.Deferred();

        resolver
            .done(function (suggestion) {
                that.selectSuggestion(suggestion, 0, currentValue, { hasBeenEnriched: true });
                that.el.trigger('suggestions-fixdata', suggestion);
            })
            .fail(function () {
                that.selection = null;
                that.el.trigger('suggestions-fixdata');
            });

        if (that.isQueryRequestable(fullQuery)) {
            that.currentValue = fullQuery;
            that.getSuggestions(fullQuery, { count: 1, from_bound: null, to_bound: null })
                .done(function (suggestions) {
                    // data fetched
                    var suggestion = suggestions[0];
                    if (suggestion) {
                        resolver.resolve(suggestion);
                    } else {
                        resolver.reject();
                    }
                })
                .fail(function () {
                    // no data fetched
                    resolver.reject();
                });
        } else {
            resolver.reject();
        }
    }
1052639
def query(querystr, connection=None, **connectkwargs):
    
    if connection is None:
        connection = connect(**connectkwargs)
    cursor = connection.cursor()
    cursor.execute(querystr)
    return cursor.fetchall()
185194
def enable_busy_cursor(self):
        """"""
        QgsApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor)
        )
660545
def waitForInput(self):
        
        self._waitingForInput = False
        
        try:
            if self.isDestroyed() or self.isReadOnly():
                return
        except RuntimeError:
            return
        
        self.moveCursor(QTextCursor.End)
        if self.textCursor().block().text() == '>>> ':
            return
        
        # if there is already text on the line, then start a new line
        newln = '>>> '
        if projex.text.nativestring(self.textCursor().block().text()):
            newln = '\n' + newln
        
        # insert the text
        self.setCurrentMode('standard')
        self.insertPlainText(newln)
        self.scrollToEnd()
        
        self._blankCache = ''
973908
def _get_result_wrapper(self, query):
        
        cursor = RowsCursor(self._rows, self._cursor.description)
        return query._get_cursor_wrapper(cursor)
678088
def search(self):
        

        self.__interrupt_search()

        search_pattern = self.Search_comboBox.currentText()
        replacement_pattern = self.Replace_With_comboBox.currentText()
        if not search_pattern:
            return False

        SearchAndReplace.insert_pattern(search_pattern, self.__search_patterns_model)
        SearchAndReplace.insert_pattern(replacement_pattern, self.__replace_with_patterns_model)

        location = umbra.ui.common.parse_location(
            foundations.strings.to_string(self.Where_lineEdit.text()) or
            self.__targets_format.format(self.__default_target))
        self.__ignore_hidden_files and location.filters_out.append("\\\.|/\.")

        settings = self.__get_settings()

        self.__search_worker_thread = Search_worker(self, search_pattern, location, settings)
        # Signals / Slots.
        self.__search_worker_thread.searchFinished.connect(self.__search_worker_thread__searchFinished)

        self.__container.engine.worker_threads.append(self.__search_worker_thread)
        self.__container.engine.start_processing("Searching In Files ...")
        self.__search_worker_thread.start()
        return True
792472
private void cmdExecuteQueryActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_buttonExecuteActionPerformed
		try {
			// TODO Handle this such that there is a listener checking the progress of the execution
			Thread queryRunnerThread = new Thread(() -> {
				String queryString = queryTextPane.getText();
                OBDADataQueryAction<?> action = null;
				if (queryString.isEmpty()){
					JOptionPane.showMessageDialog(QueryInterfacePanel.this, "Query editor cannot be empty.");
				} else if (SPARQLQueryUtility.isSelectQuery(queryString)) {
					action = QueryInterfacePanel.this.getExecuteSelectAction();
				} else if (SPARQLQueryUtility.isAskQuery(queryString)){
					action = QueryInterfacePanel.this.getExecuteAskAction();
                } else if ((SPARQLQueryUtility.isConstructQuery(queryString) || SPARQLQueryUtility.isDescribeQuery(queryString)) ){
                    action = QueryInterfacePanel.this.getExecuteGraphQueryAction();
                } else {
                    JOptionPane.showMessageDialog(QueryInterfacePanel.this, "This type of SPARQL expression is not handled. Please use SELECT, ASK, DESCRIBE, or CONSTRUCT.");
                }
				if(action!=null) {
					action.run(queryString);
					execTime = action.getExecutionTime();
					do {
						int rows = action.getNumberOfRows();
						updateStatus(rows);
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							break;
						}
					} while (action.isRunning());
					int rows = action.getNumberOfRows();
						updateStatus(rows);

				}
            });
			queryRunnerThread.start();
		} catch (Exception e) {
			DialogUtils.showQuickErrorDialog(QueryInterfacePanel.this, e);
		}
	}
737776
def setCurrentQuery( self, query ):
        
        self.clear()
        
        for entry in query:
            self.addLineWidget(entry)
        
        # make sure we have the minimum number of widgets
        for i in range(self.minimumCount() - len(query)):
            self.addLineWidget()
569014
async function searchText(node, callback, query, limit) {
	  var cursor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
	  var desc = arguments[5];

	  var seen = {};
	  console.log('cursor', cursor, 'query', query, 'desc', desc);
	  var q = desc ? { '<': cursor, '-': desc } : { '>': cursor, '-': desc };
	  node.get({ '.': q, '%': 20 * 1000 }).once().map().on(function (value, key) {
	    console.log('searchText', value, key);
	    if (key.indexOf(query) === 0) {
	      if (typeof limit === 'number' && _Object$keys(seen).length >= limit) {
	        return;
	      }
	      if (seen.hasOwnProperty(key)) {
	        return;
	      }
	      if (value && _Object$keys(value).length > 1) {
	        seen[key] = true;
	        callback({ value: value, key: key });
	      }
	    }
	  });
	}
616986
private void rewriteQueryFromSuggestion(int position) {
        CharSequence oldQuery = mQueryTextView.getText();
        Cursor c = mSuggestionsAdapter.getCursor();
        if (c == null) {
            return;
        }
        if (c.moveToPosition(position)) {
            // Get the new query from the suggestion.
            CharSequence newQuery = mSuggestionsAdapter.convertToString(c);
            if (newQuery != null) {
                // The suggestion rewrites the query.
                // Update the text field, without getting new suggestions.
                setQuery(newQuery);
            } else {
                // The suggestion does not rewrite the query, restore the user's query.
                setQuery(oldQuery);
            }
        } else {
            // We got a bad position, restore the user's query.
            setQuery(oldQuery);
        }
    }
1350266
@Override
    protected boolean moveCursor() throws SQLException, OntopConnectionException {
        boolean foundFreshRow;
        List<Object> currentKey;
        do{
           foundFreshRow = rs.next();
           // Cannot use this in the while condition: limit case where the last row was a duplicate
           if(!foundFreshRow) {
               break;
           }
           currentKey = computeRowKey(rs);
        } while(!rowKeys.add(currentKey));

        return foundFreshRow;
    }