Issue 110: https://bitbucket.org/telestax/telscale-restcomm/issue/110
770000
@Override
    public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) {
        final CallDetailRecordList list = (CallDetailRecordList) object;

        writer.startNode("Calls");
        writer.addAttribute("page", String.valueOf(page));
        writer.addAttribute("numpages", String.valueOf(getTotalPages()));
        writer.addAttribute("pagesize", String.valueOf(pageSize));
        writer.addAttribute("total", String.valueOf(getTotalPages()));
        writer.addAttribute("start", getFirstIndex());
        writer.addAttribute("end", getLastIndex(list));
        writer.addAttribute("uri", pathUri);
        writer.addAttribute("firstpageuri", getFirstPageUri());
        writer.addAttribute("previouspageuri", getPreviousPageUri());
        writer.addAttribute("nextpageuri", getNextPageUri(list));
        writer.addAttribute("lastpageuri", getLastPageUri());

        for (final CallDetailRecord cdr : list.getCallDetailRecords()) {
            context.convertAnother(cdr);
        }
        writer.endNode();
    }
184126
function claimBackOldTextcoins(to_address, days){
	db.query(
		"SELECT mnemonic FROM sent_mnemonics LEFT JOIN unit_authors USING(address) \n\
		WHERE mnemonic!='' AND unit_authors.address IS NULL AND creation_date<"+db.addTime("-"+days+" DAYS"),
		function(rows){
			async.eachSeries(
				rows,
				function(row, cb){
					receiveTextCoin(row.mnemonic, to_address, function(err, unit, asset){
						if (err)
							console.log("failed claiming back old textcoin "+row.mnemonic+": "+err);
						else
							console.log("claimed back mnemonic "+row.mnemonic+", unit "+unit+", asset "+asset);
						cb();
					});
				}
			);
		}
	);
}
678837
def publish_kb
      response = @http.put(
        "#{BASE_URL}/#{@knowledgebase_id}"
      )

      case response.code
      when 204
        nil
      when 400
        raise BadArgumentError, response.parse['error']['message'].join(' ')
      when 401
        raise UnauthorizedError, response.parse['error']['message']
      when 403
        raise ForbiddenError, response.parse['error']['message']
      when 404
        raise NotFoundError, response.parse['error']['message']
      when 409
        raise ConflictError, response.parse['error']['message']
      else
        raise UnknownError, "Oh no! (#{response.code})"
      end
    end
1208130
public static void setHTTPVersion(Stub stub, boolean http10) {
        stub._setProperty(MessageContext.HTTP_TRANSPORT_VERSION,
                          (http10)
                          ? HTTPConstants.HEADER_PROTOCOL_V10
                          : HTTPConstants.HEADER_PROTOCOL_V11);
    }
104842
function expectBobSendMessageRequest() {
    return expectSendMessageRequest(bobTestClient.httpBackend).then(function(content) {
        bobMessages.push(content);
        const aliKeyId = "curve25519:" + aliDeviceId;
        const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId];
        expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]);
        const ciphertext = content.ciphertext[aliDeviceCurve25519Key];
        expect(ciphertext).toBeTruthy();
        return ciphertext;
    });
}
909632
function f_urun_teklif_kontrol(_tahta_id, _urun_id) {
        return result.dbQ.smembers(result.kp.urun.ssetTeklifleri(_tahta_id, _urun_id));
    }
595918
function sn_api_user_queueInstructionURL(topic, parameters) {
    var url = sn_api_user_baseURL(this) + "/instr/add?nodeId=" + this.nodeId + "&topic=" + encodeURIComponent(topic);
    if (Array.isArray(parameters)) {
      var i, len;
      for (i = 0, len = parameters.length; i < len; i++) {
        url += "&" + encodeURIComponent("parameters[" + i + "].name") + "=" + encodeURIComponent(parameters[i].name) + "&" + encodeURIComponent("parameters[" + i + "].value") + "=" + encodeURIComponent(parameters[i].value);
      }
    }
    return url;
  }
641090
function NexmoErrorStatus(response) {
  MessagingServiceStatus.call(this, 'nexmo');

  // There was an error when attempting to send message
  this.state.message = response.messages[0].status + ': ' + response.messages[0]['error-text'];

  // See https://docs.nexmo.com/index.php/sms-api/send-message#response_code for details
  var statusCode = parseInt(response.messages[0].status);
  if (statusCode == 1) this.state.code = this.StatusCodes.LIMIT_EXCEEDED;
  else if (statusCode == 2) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 3) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 4) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 5) this.state.code = this.StatusCodes.SERVICE_DOWN;
  else if (statusCode == 6) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 7) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 8) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 9) this.state.code = this.StatusCodes.LIMIT_EXCEEDED;
  else if (statusCode == 11) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 12) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 13) this.state.code = this.StatusCodes.SERVICE_DOWN;
  else if (statusCode == 14) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 15) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 16) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 19) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 20) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 29) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else this.state.code = this.StatusCodes.DEFAULT;
}
600895
def response
      response = ::RestClient.post( Pxpay::Base.pxpay_request_url,  self.post )
      return ::Pxpay::Notification.new( response )
    end
350328
def claimToken(self):
        
        response = self._session.get('https://plex.tv/api/claim/token.json', headers=self._headers(), timeout=TIMEOUT)
        if response.status_code not in (200, 201, 204):  # pragma: no cover
            codename = codes.get(response.status_code)[0]
            errtext = response.text.replace('\n', ' ')
            log.warning('BadRequest (%s) %s %s; %s' % (response.status_code, codename, response.url, errtext))
            raise BadRequest('(%s) %s %s; %s' % (response.status_code, codename, response.url, errtext))
        return response.json()['token']
834607
@Override
    public void logLegacyMessage() {
        // 366860 - if we're on the z/os CR, use the legacy message service
        if (getHttpConfig().isControlRegion() && writingHeaders()) {
            HttpPlatformUtils utils = (HttpPlatformUtils) HttpDispatcher.getFramework().lookupService(HttpPlatformUtils.class);
            if (null != utils) {
                utils.logLegacyMessage(this);
            }
        }
    }
1268751
def _get_fix_my_django_submission_url(self, tb_info, sanitized_tb):
        
        err_post_create_path = '/create/'
        url = '{0}{1}'.format(base_url, err_post_create_path)
        return '{url}?{query}'.format(
            url=url,
            query=urlencode({
                'exception_type': clean_exception_type(tb_info['parsed_traceback']['exc_type']),
                'error_message': tb_info['parsed_traceback']['exc_msg'],
                'django_version': '{0[0]}.{0[1]}'.format(django.VERSION),
                'traceback': sanitized_tb
            }))
1119584
function() {
    this.cantWebsocket = vAPI.cantWebsocket;
    this.reBadDomainOptChars = /[*+?^${}()[\]\\]/;
    this.reHostnameRule1 = /^[0-9a-z][0-9a-z.-]*[0-9a-z]$/i;
    this.reHostnameRule2 = /^[0-9a-z][0-9a-z.-]*[0-9a-z]\^?$/i;
    this.reCleanupHostnameRule2 = /\^$/g;
    this.reCanTrimCarets1 = /^[^*]*$/;
    this.reCanTrimCarets2 = /^\^?[^^]+[^^][^^]+\^?$/;
    this.reHasUppercase = /[A-Z]/;
    this.reIsolateHostname = /^(\*?\.)?([^\x00-\x24\x26-\x2C\x2F\x3A-\x5E\x60\x7B-\x7F]+)(.*)/;
    this.reHasUnicode = /[^\x00-\x7F]/;
    this.reWebsocketAny = /^ws[s*]?(?::\/?\/?)?\*?$/;
    this.reBadCSP = /(?:^|;)\s*report-(?:to|uri)\b/;
    this.domainOpt = '';
    this.noTokenHash = µb.urlTokenizer.noTokenHash;
    this.unsupportedTypeBit = this.bitFromType('unsupported');
    // All network request types to bitmap
    //   bring origin to 0 (from 4 -- see typeNameToTypeValue)
    //   left-shift 1 by the above-calculated value
    //   subtract 1 to set all type bits
    this.allNetRequestTypeBits = (1 << (otherTypeBitValue >>> 4)) - 1;
    this.reset();
}
1066920
def Uri(self):
		
		return ("%s://%s%s" % (("https", "http")[self._noSsl == True], self._name, (":" + str(self._port), "")[
			(((self._noSsl == False) and (self._port == 80)) or ((self._noSsl == True) and (self._port == 443)))]))
1053207
private JSONObject getDataFromRestCallPost(GitHubParsed gitHubParsed, GitHubRepo repo, String password, String personalAccessToken, JSONObject query) throws MalformedURLException, HygieiaException {
        ResponseEntity<String> response = makeRestCallPost(gitHubParsed.getGraphQLUrl(), repo.getUserId(), password, personalAccessToken, query);
        JSONObject data = (JSONObject) parseAsObject(response).get("data");
        JSONArray errors = getArray(parseAsObject(response), "errors");

        if (CollectionUtils.isEmpty(errors)) {
            return data;
        }

        JSONObject error = (JSONObject) errors.get(0);

        if (!error.containsKey("type") || !error.get("type").equals("NOT_FOUND")) {
            throw new HygieiaException("Error in GraphQL query:" + errors.toJSONString(), HygieiaException.JSON_FORMAT_ERROR);
        }

        RedirectedStatus redirectedStatus = checkForRedirectedRepo(repo);

        if (!redirectedStatus.isRedirected()) {
            throw new HygieiaException("Error in GraphQL query:" + errors.toJSONString(), HygieiaException.JSON_FORMAT_ERROR);
        }

        String redirectedUrl = redirectedStatus.getRedirectedUrl();
        LOG.debug("Repo was redirected from: " + repo.getRepoUrl() + " to " + redirectedUrl);
        repo.setRepoUrl(redirectedUrl);
        gitHubParsed.updateForRedirect(redirectedUrl);

        JSONParser parser = new JSONParser();
        try {
            JSONObject variableJSON = (JSONObject) parser.parse(str(query, "variables"));
            variableJSON.put("name", gitHubParsed.getRepoName());
            variableJSON.put("owner", gitHubParsed.getOrgName());
            query.put("variables", variableJSON.toString());
        } catch (ParseException e) {
            LOG.error("Could not parse JSON String", e);
        }
        return getDataFromRestCallPost(gitHubParsed, repo, password, personalAccessToken, query);
    }
1109601
public static void showUsage(String errMessage) {
        System.out.println("Error: " + errMessage);
        System.out.println("");
        System.out
                .println("Usage: AutoModify host:port user password "
                        + "directives-filepath log-filepath protocol [validate-only-option] [context]");
        System.out.println("Note: protocol must be either http or https.");
    }
876475
def _rest_request_to_json(self, url, instance, object_path, tags, *args, **kwargs):
        
        service_check_tags = ['url:{}'.format(self._get_url_base(url))] + tags
        service_check_tags = list(set(service_check_tags))

        if object_path:
            url = self._join_url_dir(url, object_path)

        # Add args to the url
        if args:
            for directory in args:
                url = self._join_url_dir(url, directory)

        auth = None

        # Authenticate our connection to JMX endpoint if required
        kerberos = instance.get('kerberos')
        username = instance.get('username')
        password = instance.get('password')
        if username is not None and password is not None:
            auth = (username, password)
        elif kerberos is not None:
            if kerberos not in KERBEROS_STRATEGIES:
                raise Exception('Invalid Kerberos strategy `{}`'.format(kerberos))

            auth = requests_kerberos.HTTPKerberosAuth(
                mutual_authentication=KERBEROS_STRATEGIES[kerberos],
                delegate=is_affirmative(instance.get('kerberos_delegate', False)),
                force_preemptive=is_affirmative(instance.get('kerberos_force_initiate', False)),
                hostname_override=instance.get('kerberos_hostname'),
                principal=instance.get('kerberos_principal'),
            )

        ssl_verify = is_affirmative(instance.get('ssl_verify', True))

        old_keytab_path = None
        if 'kerberos_keytab' in instance:
            old_keytab_path = os.getenv('KRB5_CLIENT_KTNAME')
            os.environ['KRB5_CLIENT_KTNAME'] = instance['kerberos_keytab']

        self.log.debug('Attempting to connect to "{}"'.format(url))

        # Add kwargs as arguments
        if kwargs:
            query = '&'.join(['{}={}'.format(key, value) for key, value in iteritems(kwargs)])
            url = urljoin(url, '?' + query)

        try:
            response = requests.get(url, auth=auth, verify=ssl_verify, timeout=self.default_integration_http_timeout)
            response.raise_for_status()
            response_json = response.json()

        except Timeout as e:
            self.service_check(
                SERVICE_CHECK_NAME,
                AgentCheck.CRITICAL,
                tags=service_check_tags,
                message="Request timeout: {}, {}".format(url, e),
            )
            raise

        except (HTTPError, InvalidURL, ConnectionError, SSLError) as e:
            self.service_check(
                SERVICE_CHECK_NAME,
                AgentCheck.CRITICAL,
                tags=service_check_tags,
                message="Request failed: {}, {}".format(url, e),
            )
            raise

        except ValueError as e:
            self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=str(e))
            raise

        else:
            self.service_check(
                SERVICE_CHECK_NAME,
                AgentCheck.OK,
                tags=service_check_tags,
                message="Connection to {} was successful".format(url),
            )

            return response_json

        finally:
            if old_keytab_path is not None:
                os.environ['KRB5_CLIENT_KTNAME'] = old_keytab_path