Handle timed out inference

@param {{path: string, type: string}} response - the response from node domain
347467
function handleTimedOut(response) {

        var detectedExclusions  = PreferencesManager.get("jscodehints.detectedExclusions") || [],
            filePath            = response.file;

        // Don't exclude the file currently being edited
        if (isFileBeingEdited(filePath)) {
            return;
        }

        // Handle file that is already excluded
        if (detectedExclusions.indexOf(filePath) !== -1) {
            console.log("JavaScriptCodeHints.handleTimedOut: file already in detectedExclusions array timed out: " + filePath);
            return;
        }

        // Save detected exclusion in project prefs so no further time is wasted on it
        detectedExclusions.push(filePath);
        PreferencesManager.set("jscodehints.detectedExclusions", detectedExclusions, { location: { scope: "project" } });

        // Show informational dialog
        Dialogs.showModalDialog(
            DefaultDialogs.DIALOG_ID_INFO,
            Strings.DETECTED_EXCLUSION_TITLE,
            StringUtils.format(
                Strings.DETECTED_EXCLUSION_INFO,
                StringUtils.breakableUrl(filePath)
            ),
            [
                {
                    className : Dialogs.DIALOG_BTN_CLASS_PRIMARY,
                    id        : Dialogs.DIALOG_BTN_OK,
                    text      : Strings.OK
                }
            ]
        );
    }
1013431
public void execute(ProgramResponse response, int timeout) {
        ProcessBuilder builder = createProcessBuilder(response);
        invokeProgram(builder, response, timeout);
    }
848630
def readWithTimeout(socket, length, timeout)
      rc = IO.select([socket], nil, nil, timeout)
      if ! rc
        raise "Waiting for response from UDP tracker #{@host}:#{@trackerPort} timed out after #{@timeout} seconds"
      elsif rc[0].size > 0
        socket.recvfrom(length)[0]
      else
        raise "Error receiving response from UDP tracker #{@host}:#{@trackerPort}"
      end
    end
489468
def _handle_response(self, url, res, suppress_empty=True):
        
        result = Connection._handle_response(self, url, res, suppress_empty)
        if 'X-Rate-Limit-Time-Reset-Ms' in res.headers:
            self.rate_limit = dict(ms_until_reset=int(res.headers['X-Rate-Limit-Time-Reset-Ms']),
                                   window_size_ms=int(res.headers['X-Rate-Limit-Time-Window-Ms']),
                                   requests_remaining=int(res.headers['X-Rate-Limit-Requests-Left']),
                                   requests_quota=int(res.headers['X-Rate-Limit-Requests-Quota']))
            if self.rate_limiting_management:
                if self.rate_limiting_management['min_requests_remaining'] >= self.rate_limit['requests_remaining']:
                    if self.rate_limiting_management['wait']:
                        sleep(ceil(float(self.rate_limit['ms_until_reset']) / 1000))
                    if self.rate_limiting_management.get('callback_function'):
                        callback = self.rate_limiting_management['callback_function']
                        args_dict = self.rate_limiting_management.get('callback_args')
                        if args_dict:
                            callback(args_dict)
                        else:
                            callback()

        return result
2690
private void processBatchRequestResponse(CloseableHttpResponse response) throws IOException,
      UnexpectedResponseException {
    String entityStr = EntityUtils.toString(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode >= 400) {
      throw new RuntimeException("Failed due to " + entityStr + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }

    JsonObject jsonBody = new JsonParser().parse(entityStr).getAsJsonObject();
    if (!jsonBody.get("hasErrors").getAsBoolean()) {
      return;
    }

    JsonArray results = jsonBody.get("results").getAsJsonArray();
    for (JsonElement jsonElem : results) {
      JsonObject json = jsonElem.getAsJsonObject();
      int subStatusCode = json.get("statusCode").getAsInt();
      if (subStatusCode < 400) {
        continue;
      } else if (subStatusCode == 400
                 && Operation.INSERT_ONLY_NOT_EXIST.equals(operation)) {
        JsonElement resultJsonElem = json.get("result");
        Preconditions.checkNotNull(resultJsonElem, "Error response should contain result property");
        JsonObject resultJsonObject = resultJsonElem.getAsJsonArray().get(0).getAsJsonObject();
        if (isDuplicate(resultJsonObject, subStatusCode)) {
          continue;
        }
      }
      throw new RuntimeException("Failed due to " + jsonBody + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }
  }
381811
function _reportError(e, file) {
    if (e instanceof Infer.TimedOut) {
        // Post a message back to the main thread with timedout info
        self.postMessage({
            type: MessageIds.TERN_INFERENCE_TIMEDOUT,
            file: file
        });
    } else {
        _log("Error thrown in tern_node domain:" + e.message + "\n" + e.stack);
    }
}
1248976
function(path) {
        let req = null;
        let i;
        let j;
        let matchingReq = null;
        let expectedReq = null;
        let testResponse = null;
        for (i = 0; i < this.requests.length; i++) {
            req = this.requests[i];
            for (j = 0; j < this.expectedRequests.length; j++) {
                expectedReq = this.expectedRequests[j];
                if (path && path !== expectedReq.path) {
                    continue;
                }
                if (expectedReq.method === req.method &&
                        req.path.indexOf(expectedReq.path) !== -1) {
                    if (!expectedReq.data || (JSON.stringify(expectedReq.data) ===
                            JSON.stringify(req.data))) {
                        matchingReq = expectedReq;
                        this.expectedRequests.splice(j, 1);
                        break;
                    }
                }
            }

            if (matchingReq) {
                // remove from request queue
                this.requests.splice(i, 1);
                i--;

                for (j = 0; j < matchingReq.checks.length; j++) {
                    matchingReq.checks[j](req);
                }
                testResponse = matchingReq.response;
                console.log(`${Date.now()}    responding to ${matchingReq.path}`);

                let body = testResponse.body;
                if (Object.prototype.toString.call(body) == "[object Function]") {
                    body = body(req.path, req.data, req);
                }

                if (!testResponse.rawBody) {
                    body = JSON.stringify(body);
                }
                req.callback(
                    testResponse.err, testResponse.response, body,
                );
                matchingReq = null;
            }
        }
        if (testResponse) {  // flushed something
            return true;
        }
        return false;
    }
438376
def handle_response(response)
      if response.is_a?(Result)
        token = response.token
        if (result = OperationResult.from_results(response))
          if result.non_delivery?
            @non_delivery_stats.update(result.content.nil? ? "nil" : result.content)
          elsif result.error?
            @result_error_stats.update(result.content.nil? ? "nil" : result.content)
          end
          @result_stats.update(result.status)
        else
          @result_stats.update(response.results.nil? ? "nil" : response.results)
        end

        if (pending_request = @pending_requests[token])
          if result && result.non_delivery? && pending_request.kind == :send_request
            if result.content == OperationResult::TARGET_NOT_CONNECTED
              # Log and temporarily ignore so that timeout retry mechanism continues, but save reason for use below if timeout
              # Leave purging of associated request until final response, i.e., success response or retry timeout
              if (parent_token = pending_request.retry_parent_token)
                @pending_requests[parent_token].non_delivery = result.content
              else
                pending_request.non_delivery = result.content
              end
              Log.info("Non-delivery of <#{token}> because #{result.content}")
            elsif result.content == OperationResult::RETRY_TIMEOUT && pending_request.non_delivery
              # Request timed out but due to another non-delivery reason, so use that reason since more germane
              response.results = OperationResult.non_delivery(pending_request.non_delivery)
              deliver_response(response, pending_request)
            else
              deliver_response(response, pending_request)
            end
          else
            deliver_response(response, pending_request)
          end
        elsif result && result.non_delivery?
          Log.info("Non-delivery of <#{token}> because #{result.content}")
        else
          Log.debug("No pending request for response #{response.to_s([])}")
        end
      end
      true
    end
995001
function _ParseTokenResponse(err, body, callback)
	{
		if (err)
		{
			if (callback) callback("Request error: " + err);
			return;
		}

		// try to parse result
		var responseJSON;
		try
		{
			responseJSON = JSON.parse(body);
		}
		catch (JSONerror)
		{
			if (callback) callback("JSON Parse error: " + JSONerror);
			return;
		}

		// check server response for error
		if (responseJSON.error_description)
		{
			if (callback) callback("Server response error " + responseJSON.error_code + ": " + responseJSON.error_description);
			return;
		}

		// check we got an access token
		if (!responseJSON.access_token)
		{
			if (callback) callback("No access token received from PSN OAuth");
			return;
		}

		Log("Got successful OAuth result");

		// store our new tokens
		auth_obj.access_token = 	responseJSON.access_token;
		auth_obj.refresh_token = 	responseJSON.refresh_token;
		// calculate expire time of these tokens (shave off half a minute)
		auth_obj.expire_time =		(new Date().getTime()) + ((responseJSON.expires_in - 30) * 1000);

		// save the data object
		DoSave(function()
			{
				// return no error
				if (callback) callback(false);
			}
		);
	}
469215
function expressResponseError_silent(response, message) {
  let errorMessage = "there was an error in the request";
  if(message)
    errorMessage = message
  response.json({ success: false, error: errorMessage });
}
1303790
function reply(req, res, timeout) {
  var _timer;

  if(timeout) {
    //console.dir(timeout);
    //console.error(Date.now());
    _timer = setTimeout(this.onTimeout, timeout);
    this._busy = true;
  }

  function onClose(code, signal) {
    //console.dir('close called: ' + signal);
    //console.dir(code);
    //console.dir(signal);
    this.ps.removeAllListeners();
    clearTimeout(_timer);
    this.ps = null;
    this._busy = false;
    this._written = false;
    var msg, err = new StoreError(
      null, 'script execution process exited with code: %s', code || 0);
    if(signal === 'SIGQUIT') {
      msg = 'error running script (call to %s): '
      msg += '@user_script: script killed by user with SCRIPT KILL';
      err = new StoreError(null, msg, this._script || 'user_script');
    }
    res.send(err);
  }

  function onMessage(msg) {
    var cmd, args;

    //console.dir(msg);

    // getting the current script name
    if(msg.event === 'eval') {
      this._script = msg.data;
      return;

    // calling out to execute a command
    }else if(msg.event === 'call') {
      req.cmd = msg.cmd;
      req.args = msg.args;

      //console.dir('got call event');

      var exec = this._commands[req.cmd];
      if(exec && exec.definition && exec.definition.write) {
        this._written = true;
        //console.dir('marking command as writing data...');
      }

      function onCommand(err, reply) {
        // restore req and res
        req.cmd = cmd;
        req.args = args;
        req.script = false;
        delete res.cb;

        var data = err ? err.message : reply;
        if(reply instanceof Buffer) reply = reply.toString();
        this.ps.send(
          {event: msg.event, err: (err instanceof Error), data: data});
      }

      req.script = true;

      res.cb = onCommand.bind(this);
      this.emit('command', req, res);
      //this.ps.once('message', onMessage.bind(this));
      return;
    }

    // ps may be null if script was killed
    if(this.ps) {
      this.ps.removeAllListeners();
    }

    clearTimeout(_timer);

    // sending data back to the client
    this._busy = false;
    this._written = false;
    var data = msg.data;
    if(msg.err) return res.send(new Error(data));
    if(msg.str) data = new String(data);
    return res.send(null, data);
  }

  this.ps.on('message', onMessage.bind(this));
  this.ps.once('close', onClose.bind(this));
}
1196594
function (reqId, connection) {
            connection.onreadystatechange = Aria.empty;
            ariaCoreIO.clearTimeout(reqId);

            if (this._inProgress(connection)) {
                connection.abort();
                return true;
            } // else the request completed but after the abort timeout (it happens in IE)

            return false;
        }
1111031
public void assertCorrectResonse(JSONObject response) throws JSONException {
		Integer lastHTTPResponseCode = getLastHTTPResponseCode();
		if(lastHTTPResponseCode != null) {
			//if a response code is set, check it. Selenium requests do not let you query this which is why we can't check this in case of a selenium API call
			assertEquals("The https response code should be 200 (OK)", new Integer(HttpURLConnection.HTTP_OK), lastHTTPResponseCode);
		}
		assertNotNull("The request should result in a response", response);	
	}
978964
function timeout(timeoutMS) {
        var id;
        return new Promise(
            function (c) {
                if (timeoutMS) {
                    id = _Global.setTimeout(c, timeoutMS);
                } else {
                    _BaseCoreUtils._setImmediate(c);
                }
            },
            function () {
                if (id) {
                    _Global.clearTimeout(id);
                }
            }
        );
    }
1101477
public void onTimeout(ResponseType responseType) throws DispatcherException
	{
		if(!proxy.getAckReceived()) {
			this.cancel();
			if(responseType == ResponseType.FINAL) {
				cancel1xxTimer();
			}
			this.timedOut = true;
			if(originalRequest != null) {
				List<ProxyBranchListener> proxyBranchListeners = originalRequest.getSipSession().getSipApplicationSession().getSipContext().getListeners().getProxyBranchListeners();
				if(proxyBranchListeners != null) {
					for (ProxyBranchListener proxyBranchListener : proxyBranchListeners) {
						proxyBranchListener.onProxyBranchResponseTimeout(responseType, this);
					}
				}
			}
			// Just do a timeout response
			proxy.onBranchTimeOut(this);
			logger.warn("Proxy branch has timed out");
		} else {
			logger.debug("ACKed proxybranch has timeout");
		}
	}
1106608
function (response, expectedResponseType) {
            if (expectedResponseType == "text") {
                if (!response.responseText && response.responseJSON != null) {
                    // convert JSON to text
                    if (ariaUtilsType.isString(response.responseJSON)) {
                        // this case is important for JSON-P services which return a simple string
                        // we simply use that string as text
                        // (could be useful to load templates through JSON-P, for example)
                        response.responseText = response.responseJSON;
                    } else {
                        // really convert the JSON structure to a string
                        response.responseText = ariaUtilsJson.convertToJsonString(response.responseJSON);
                    }
                }
            } else if (expectedResponseType == "json") {
                if (response.responseJSON == null && response.responseText != null) {
                    // convert text to JSON
                    var errorMsg = (require("../utils/String")).substitute(this.JSON_PARSING_ERROR, [response.url,
                            response.responseText]);
                    if (response.responseText === "") {
                        var undef;
                        response.responseJSON = undef;
                    } else {
                        response.responseJSON = ariaUtilsJson.load(response.responseText, this, errorMsg);
                    }
                }
            }

        }
1050954
function() {
            if(!aborted) {
                if(!options.attempts || ++attempts != options.attempts) {
                    xhr.abort();
                    sending = false;
                    promise.send();
                }
                else {
                    handleError('Timeout (' + url + ')');
                }
            }
        }