_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q63700
|
parseNumericLiteral
|
test
|
function parseNumericLiteral(AST) {
var literal = [], value;
while(hasNext() && validNum(peek())) {
literal[literal.length] = next();
}
value = parseFloat(literal.join(''));
/**
* Thanks to CMS's answer on StackOverflow:
* http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
*/
if(!isNaN(value) && isFinite(value)) {
newNode(value, newNode('=', AST).nodes);
} else {
unexpectedTokenException('numeric');
}
}
|
javascript
|
{
"resource": ""
}
|
q63701
|
stage1
|
test
|
function stage1(AST) {
if(hasNext()) {
switch (peek()) {
case 'a':
parseArray(AST);
break;
case 'o':
parseObject(AST);
break;
default:
if (/[nsSbfdr_]/.test(peek())) {
parseGeneric(AST,peek());
} else {
unexpectedTokenException('one of (a,o,n,s,S,b,f,d,r,_)');
}
}
}
return AST;
}
|
javascript
|
{
"resource": ""
}
|
q63702
|
curry
|
test
|
function curry(fun, args) {
return function (x) {
return fun.apply(bindingContext, args.concat([x]));
};
}
|
javascript
|
{
"resource": ""
}
|
q63703
|
matchArray
|
test
|
function matchArray(m,a) {
var from = 0, rest = false, restBindingResult, index, matcher, item,
matchResult, restOfArray = [], i, result = {
result: false,
param: a
};
// If this isn't an array then it can't match
if (!is(a, '[object Array]')) {
return result;
}
// If there are more matchers than array elements it also can't match unless the
// last matcher is a rest matcher
if (m.length > a.length && !m[m.length - 1].name) {
return result;
}
/**
* If there are no predicates at all, this matches because it is
* already ensured that argument a is an array.
*/
if(m.length === 0) {
result.result = true;
return result;
}
for(index=0;index<a.length;index++) {
matcher = m[index];
item = a[index];
if(!matcher) {
return result;
}
matchResult = matcher(item);
if(!matchResult.result) {
return result;
}
/**
* If the rest of an array is matched, the predicate will
* return an object that has a'rest' parameter. We can't
* recognize the rest predicate by it's function name, because
* it might be hidden behind a 'bind' call.
*/
if(matchResult.rest) {
restBindingResult = matchResult;
from = index;
rest = true;
break;
}
}
if(rest && restBindingResult.this_binding) {
for(i = from; i < a.length; i++) {
restOfArray[restOfArray.length] = a[i];
}
bindingContext[restBindingResult.this_binding] = restOfArray;
}
result.result = true;
return result;
}
|
javascript
|
{
"resource": ""
}
|
q63704
|
compileNode
|
test
|
function compileNode(ast) {
var result = [], index, node, matcher;
for(index=0;index<ast.length;index++) {
node = ast[index];
switch(node.type) {
case 'a':
matcher = curry(matchArray, [compileNode(node.nodes)]);
break;
case 'o':
matcher = curry(matchObject, [compileNode(node.nodes)]);
break;
case '.':
matcher = curry(hasProperty, [compileNode(node.nodes), node.name ]);
break;
case ':':
matcher = curry(hasPrototypeProperty, [compileNode(node.nodes), node.name ]);
break;
case '=':
matcher = curry(equals, [node.nodes[0].type]);
break;
case 'd=':
matcher = curry(equalsDate, [node.nodes[0].type]);
break;
case 'r=':
matcher = curry(matchesRegex, [node.nodes[0].type]);
break;
case '||':
matcher = curry(or, [compileNode(node.nodes)]);
break;
case 'n':
matcher = curry(matchType, ['number']);
break;
case 's':
matcher = curry(matchType, ['string']);
break;
case 'S':
matcher = matchNonBlankString;
break;
case 'b':
matcher = curry(matchType, ['boolean']);
break;
case 'f':
matcher = curry(matchType, ['function']);
break;
case '_':
matcher = any;
break;
case '|':
matcher = rest;
break;
case '()':
matcher = matchEmptyArray;
break;
case 'd':
matcher = curry(matchInstanceOf, ['[object Date]']);
break;
case 'r':
matcher = curry(matchInstanceOf, ['[object RegExp]']);
break;
default:
throw "Unknown AST entity: " + node.type;
}
// Bind requested. Wrap the matcher function with a call to bind.
if (node.binding) {
matcher = curry(bind, [node.binding, matcher]);
}
result[result.length] = matcher;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q63705
|
getName
|
test
|
function getName(tag) {
return tag.name ? tag.name.value.toLowerCase() : `#${tag.type}`;
}
|
javascript
|
{
"resource": ""
}
|
q63706
|
eatAttributeValue
|
test
|
function eatAttributeValue(stream) {
const start = stream.pos;
if (eatQuoted(stream)) {
// Should return token that points to unquoted value.
// Use stream readers’ public API to traverse instead of direct
// manipulation
const current = stream.pos;
let valueStart, valueEnd;
stream.pos = start;
stream.next();
valueStart = stream.start = stream.pos;
stream.pos = current;
stream.backUp(1);
valueEnd = stream.pos;
const result = token(stream, valueStart, valueEnd);
stream.pos = current;
return result;
}
return eatPaired(stream) || eatUnquoted(stream);
}
|
javascript
|
{
"resource": ""
}
|
q63707
|
isUnquoted
|
test
|
function isUnquoted(code) {
return !isNaN(code) && !isQuote(code) && !isSpace(code) && !isTerminator(code);
}
|
javascript
|
{
"resource": ""
}
|
q63708
|
setDefault
|
test
|
function setDefault(obj, key, val) {
if (_.isUndefined(obj[key])) {
obj[key] = val;
return val;
}
return obj[key];
}
|
javascript
|
{
"resource": ""
}
|
q63709
|
getXml
|
test
|
function getXml(path, finish) {
fs.readFile(path, function(err, data) {
if (err) throw err;
xmlParser.parseString(data, function (err, result) {
if (err) throw err;
finish(result);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q63710
|
appendUISource
|
test
|
function appendUISource(client){
angoose.getLogger('angoose').debug("Appending angoose-ui sources");
// client.source += " \n;console.log('####################----------- angoose-ui -----------##############');\n";
var output="";
output += readFile(path.resolve(__dirname, 'angular-modules.js'));
output += concatFilesInDirectory(['services', 'controllers', 'directives', 'filters']); //'directives',
output += concatTemplates();
client.source+="\n\n" + output;
}
|
javascript
|
{
"resource": ""
}
|
q63711
|
error
|
test
|
function error(msg, addHint) {
console.log('\x1b[31m');
console.log('The compiler has stopped on an error')
console.log(`\x1b[1;31mError: ${msg}\x1b[0m`);
if (addHint)
console.log(`\nPlease use -h to show the usage`);
process.exit(1);
}
|
javascript
|
{
"resource": ""
}
|
q63712
|
compile
|
test
|
function compile(modelName, schema, dependencies) {
logger.trace("Compiling schema ", modelName)
var model = function AngooseModule(data) {
//@todo proper clone
for (var i in data) {
this[i] = data[i];
}
};
model.toString = function() {
return "PROXY: function " + modelName + "()";
}
// static methods
for (var name in schema.statics) {
model[name] = createProxy(model, name, schema.statics[name], 'static');
}
for (var name in schema.methods) {
model.prototype[name] = createProxy(model, name, schema.methods[name], 'instance');
}
//model.angoose$ = staticInvoker;
model.dependencies$ = dependencies;
model.schema = schema;
//model.prototype.angoose$ = instanceInvoker;
//model.prototype.classname$ = modelName;
//model.prototype.schema$ = schema;
model.prototype.get = getter;
model.prototype.set = setter;
model.modelName = modelName; // this is to be compatible with backend mongoose
model.name = modelName;
// merge data into this instance
model.prototype.mergeData = function(source) {
if ( typeof source != "object")
throw "Invalid source object, must be an model instance";
//@todo: proper implementation
for (var i in source) {
this[i] = source[i];
}
}
AngooseClient.models = AngooseClient.models || {};
AngooseClient.models[modelName] = model;
return model;
}
|
javascript
|
{
"resource": ""
}
|
q63713
|
addProps
|
test
|
function addProps(props, options) {
if (!props) return '## No props'
const keys = Object.keys(props).filter(key =>
filterProps(key, props[key], options),
)
const filteredProps = keys.reduce(
(last, key) => ({ ...last, [key]: props[key] }),
{},
)
let output = '\n## Props\n'
let isFlow = false
const items = [
TABLE_HEADERS,
...keys.map(key => {
const prop = filteredProps[key]
if (isFlowType(prop)) isFlow = true
const row = [
isFlowType(prop) ? key : getKey(key, getType(prop)),
getTypeName(getType(prop)),
getDefaultValue(prop),
prop.required,
prop.description,
]
return row.map(rowValue => {
if (typeof rowValue === 'string') {
return rowValue.split('\n').join('<br>')
}
return rowValue
})
}),
]
output += `${table(items)}\n`
// Add subtypes
if (!isFlow) {
const subTypes = describeSubTypes(filteredProps)
if (subTypes.length) {
output += '\n## Complex Props\n'
output += subTypes
}
}
return output
}
|
javascript
|
{
"resource": ""
}
|
q63714
|
debounce
|
test
|
function debounce(quietMillis, fn, ctx ) {
ctx = ctx || undefined;
var timeout;
return function () {
var args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
fn.apply(ctx, args);
}, quietMillis);
};
}
|
javascript
|
{
"resource": ""
}
|
q63715
|
matroshka
|
test
|
function matroshka(fn) {
var babushka = fn;
Object.keys(process.namespaces).forEach(function (name) {
babushka = process.namespaces[name].bind(babushka);
});
return babushka;
}
|
javascript
|
{
"resource": ""
}
|
q63716
|
findTagged
|
test
|
function findTagged(modelClass,tag){
if(!modelClass || !modelClass.schema) return [];
var cols = [];
Object.keys(modelClass.schema.paths).forEach(function(path){
var data = modelClass.schema.paths[path];
if(data.options.tags && data.options.tags.indexOf(tag)>=0)
cols.push(data);
});
return cols;
}
|
javascript
|
{
"resource": ""
}
|
q63717
|
error
|
test
|
function error(msg) {
if (exports.error)
exports.error(msg);
else
console.log('Error: ' + msg);
}
|
javascript
|
{
"resource": ""
}
|
q63718
|
call
|
test
|
function call(name, isLong) {
var obj = isLong ? long[name] : short[name];
if (!obj)
return error(`Unknown argument '${name}'`);
if (n + obj.length > count)
return error(`Too few arguments after '${name}'`);
var arr = process.argv.slice(n, n + obj.length);
n += obj.length;
obj.callback(arr);
}
|
javascript
|
{
"resource": ""
}
|
q63719
|
findInputElement
|
test
|
function findInputElement(templateElement) {
return angular.element(templateElement.find('input')[0] || templateElement.find('select')[0] || templateElement.find('textarea')[0]);
}
|
javascript
|
{
"resource": ""
}
|
q63720
|
getValidationMessageMap
|
test
|
function getValidationMessageMap(originalElement) {
// Find all the <validator> child elements and extract their (key, message) info
var validationMessages = {};
angular.forEach(originalElement.find('validator'), function(element) {
// Wrap the element in jqLite/jQuery
element = angular.element(element);
// Store the message info to be provided to the scope later
// The content of the validation element may include interpolation {{}}
// so we will actually store a function created by the $interpolate service
// To get the interpolated message we will call this function with the scope. e.g.
// var messageString = getMessage(scope);
validationMessages[element.attr('key')] = $interpolate(element.text());
});
return validationMessages;
}
|
javascript
|
{
"resource": ""
}
|
q63721
|
registerClass
|
test
|
function registerClass(nameOrOpts, claz){
var opts = typeof(nameOrOpts) == 'object'?nameOrOpts: {name: nameOrOpts};
var className = opts.name;
if(!className) throw "Missing module name: "+ className
if(beans[className])
logger.warn("Overriding existing bean: ", className);
if(claz._angoosemeta && (claz._angoosemeta.baseClass == 'Service' || claz._angoosemeta.baseClass == 'Model') ){
// already mixed
}
else{
if(typeof(claz) === 'function' && claz.schema && claz.modelName )
opts.baseClass = 'Model';
else if(claz instanceof getMongoose().Schema){
opts.baseClass = 'Model';
claz = getMongoose().model(className, claz);
}
else
opts.baseClass = 'Service';
angoose.Remotable.mixin(opts, claz);
}
_.extend(claz._angoosemeta, nameOrOpts);
beans[className] = claz;
//if(!nameOrOpts.isExtension)
logger.debug("Registered module", claz._angoosemeta.baseClass, className);
return claz;
// if(claz._angoosemeta && (claz._angoosemeta.baseClass == 'Service' || claz._angoosemeta.baseClass == 'Model') ){
//
// }
// else{
// throw "Invalid class: must be a Model or Service class: " + claz;
// }
}
|
javascript
|
{
"resource": ""
}
|
q63722
|
config
|
test
|
function config(path, val){
if(!path) return options; /**@todo: probably a deep copy */
if(!angoose.initialized && typeof(path) == 'string') throw "Cannot call config(" + path+") before angoose is intialized";
//if(angoose.initialized && typeof(conf) == 'object') throw "Cannot config Angoose after startup";
if(typeof (path) === 'string'){
if(val === undefined)
return toolbox.getter(options, path);
toolbox.setter(options, path, val);
}
if(typeof(path) === 'object'){
// deep merge
options = toolbox.merge(options, path);
}
}
|
javascript
|
{
"resource": ""
}
|
q63723
|
connect
|
test
|
function connect (url, next) {
log('connecting to %s', url);
mongo.Db.connect(url, { db: { w: 1 }}, next);
}
|
javascript
|
{
"resource": ""
}
|
q63724
|
startShell
|
test
|
function startShell (db, program, files) {
var repl = global.repl = term(db);
createContext(db, repl, function () {
var code = program.eval;
if (code) {
executeJS(code);
if (!program.shell) {
repl.emit('exit');
return;
}
}
if (files.length) {
executeFiles(files);
printCloseMsg();
}
repl.prompt = prompt;
repl.displayPrompt()
});
}
|
javascript
|
{
"resource": ""
}
|
q63725
|
executeFiles
|
test
|
function executeFiles (files) {
var dir = process.cwd();
files.forEach(function (file) {
require(dir + '/' + file);
});
}
|
javascript
|
{
"resource": ""
}
|
q63726
|
wrap
|
test
|
function wrap (proto, name) {
var old = proto[name];
proto[name] = function () {
if (global.repl) global.repl.bufferStart();
var args = slice(arguments);
var last = args[args.length-1];
if ('function' == typeof last) {
args[args.length-1] = function () {
if (global.repl) global.repl.bufferEnd()
if (p != last) console.log();
last.apply(null, arguments)
if (global.repl) {
global.repl.displayPrompt();
global.repl.moveCursorToEnd();
}
}
} else {
args.push(function () {
if (global.repl) global.repl.bufferEnd()
p.apply(null, arguments);
if (global.repl) global.repl.moveCursorToEnd();
});
}
old.apply(this, args);
}
if (old.help) {
proto[name].help = old.help;
}
}
|
javascript
|
{
"resource": ""
}
|
q63727
|
handleError
|
test
|
function handleError (err, cb) {
if (err) {
if (cb) {
return process.nextTick(function(){
cb(err);
});
}
console.error(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q63728
|
tablature
|
test
|
function tablature(conf) {
const {
keys = [],
data = [],
headings = {},
replacements = {},
centerValues = [],
centerHeadings = [],
} = conf
const [i] = data
if (!i) return ''
const cv = makeBinaryHash(centerValues)
const hv = makeBinaryHash(centerHeadings)
const k = Object.keys(i).reduce((acc, key) => {
const h = headings[key]
return {
...acc,
[key]: h ? h.length : key.length, // initialise with titles lengths
}
}, {})
const widths = data.reduce((dac, d) => {
const res = Object.keys(d).reduce((acc, key) => {
const maxLength = dac[key]
const val = d[key]
const r = getReplacement(replacements, key)
const { length } = r(val)
return {
...acc,
[key]: Math.max(length, maxLength),
}
}, {})
return res
}, k)
const kk = keys.reduce((acc, key) => {
const h = headings[key]
return {
...acc,
[key]: h || key,
}
}, {})
const hr = keys.reduce((acc, key) => {
return {
...acc,
[key]: heading,
}
}, {})
const hl = getLine(keys, kk, widths, hr, hv)
const rl = data.map((row) => {
const line = getLine(keys, row, widths, replacements, cv)
return line
})
return [
hl,
...rl,
].join('\n')
}
|
javascript
|
{
"resource": ""
}
|
q63729
|
_save
|
test
|
function _save() {
if (db.source && db.write && writeOnChange) {
var str = JSON.stringify(db.object);
if (str !== db._checksum) {
db._checksum = str;
return db.write(db.source, db.object);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q63730
|
Picklr
|
test
|
function Picklr (startDir, options) {
options = options || {};
let defaultExcludeDirsRe;
if (/^\./.test(startDir)) {
defaultExcludeDirsRe = /\/\.|node_modules/i;
} else {
defaultExcludeDirsRe = /^\.|\/\.|node_modules/i;
}
this.totalFileCount = 0;
this.matchedFileCount = 0;
this.startDir = startDir || '.';
this.targetText = options.targetText || '';
this.replacementText = options.replacementText || '';
this.action = options.action || 'echo';
this.includeExts = options.includeExts || ['.js'];
this.excludeDirs = options.excludeDirsRe || defaultExcludeDirsRe;
this.logger = options.logger || console.log;
this.picklrActions = picklrActions;
}
|
javascript
|
{
"resource": ""
}
|
q63731
|
test
|
function (p) {
fs.readdirSync(p).forEach(function (file) {
const curPath = path.join(p, path.sep, file);
const stats = fs.statSync(curPath);
if (this.isDirectory(stats, curPath)) {
this.recurseFiles(curPath);
} else if (this.isFile(stats, curPath)) {
this.picklrActions[this.action].call(this, curPath);
}
}, this);
if (p === this.startDir) {
this.logger('Total file count = ' + this.totalFileCount);
if (this.action !== 'echo') {
this.logger('Matched file count = ' + this.matchedFileCount);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63732
|
test
|
function (stats, p) {
let result = stats.isFile();
if (result) {
const ext = path.extname(p);
result = this.includeExts.indexOf(ext) !== -1;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q63733
|
test
|
function (stats, p) {
let result = stats.isDirectory();
if (result) {
result = !this.excludeDirs.test(p);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q63734
|
processAllFiles
|
test
|
function processAllFiles (startDir, options) {
const picklr = new Picklr(startDir, options);
picklr.recurseFiles(startDir);
}
|
javascript
|
{
"resource": ""
}
|
q63735
|
processFile
|
test
|
function processFile (filePath, update) {
let change, found = false;
const lines = fs.readFileSync(filePath, { encoding: 'utf8' }).split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].indexOf(this.targetText) !== -1) {
found = true;
change = lines[i].replace(
this.targetText, this.replacementText
);
if (update) {
lines[i] = change;
} else {
// log the line that would be edited.
this.logger('*** File: ' + filePath);
this.logger('@@@ Found: ' + lines[i]);
this.logger('--- Change: ' + change);
}
this.matchedFileCount++;
break;
}
}
if (!found && !update) {
// log the file that would be omitted
this.logger('*** Omitted: ' + filePath);
}
if (found && update) {
fs.writeFileSync(filePath, lines.join('\n'), { encoding: 'utf8' });
// log the updated file
this.logger('@@@ Updated: ' + filePath);
}
this.totalFileCount++;
}
|
javascript
|
{
"resource": ""
}
|
q63736
|
initHTTPServer
|
test
|
async function initHTTPServer({
ENV = {},
HOST = '127.0.0.1',
PORT = 8080,
MAX_HEADERS_COUNT = 800,
KEEP_ALIVE_TIMEOUT = ms('5m'),
TIMEOUT = ms('2m'),
MAX_CONNECTIONS,
httpRouter,
log = noop,
}) {
const sockets = ENV.DESTROY_SOCKETS ? new Set() : {}.undef;
const httpServer = http.createServer(httpRouter);
const listenPromise = new Promise(resolve => {
httpServer.listen(PORT, HOST, () => {
log('info', `HTTP Server listening at "http://${HOST}:${PORT}".`);
resolve(httpServer);
});
});
const errorPromise = new Promise((resolve, reject) => {
httpServer.once('error', reject);
});
httpServer.timeout = TIMEOUT;
httpServer.keepAliveTimeout = KEEP_ALIVE_TIMEOUT;
httpServer.maxHeadersCount = MAX_HEADERS_COUNT;
httpServer.maxConnections = MAX_CONNECTIONS;
if ('undefined' !== typeof MAX_CONNECTIONS) {
httpServer.maxConnections = MAX_CONNECTIONS;
}
if (ENV.DESTROY_SOCKETS) {
httpServer.on('connection', socket => {
sockets.add(socket);
socket.on('close', () => {
sockets.delete(socket);
});
});
}
return Promise.race([listenPromise, errorPromise]).then(() => ({
service: httpServer,
errorPromise,
dispose: () =>
new Promise((resolve, reject) => {
log('debug', 'Closing HTTP server.');
// Avoid to keepalive connections on shutdown
httpServer.timeout = 1;
httpServer.keepAliveTimeout = 1;
httpServer.close(err => {
if (err) {
reject(err);
return;
}
log('debug', 'HTTP server closed');
resolve();
});
if (ENV.DESTROY_SOCKETS) {
for (const socket of sockets.values()) {
socket.destroy();
}
}
}),
}));
}
|
javascript
|
{
"resource": ""
}
|
q63737
|
sortAndAddFirstElement
|
test
|
function sortAndAddFirstElement(array, sortBy, element) {
return _(array)
.sortBy(sortBy)
.unshift(element)
.value();
}
|
javascript
|
{
"resource": ""
}
|
q63738
|
objectInterface
|
test
|
function objectInterface(config) {
return function(obj) {
var result = {};
for (var i = 0; i < config.length; i++) {
var OR, NEXT, REAL;
if ((OR = config[i].split('/')) && OR[1]) {
result[OR[0]] = obj[OR[0]] || Function('return ' + OR[1])();
}
else if ((NEXT = config[i].split('|')) && NEXT[1]) {
result[NEXT[0]] = Function('return ' + NEXT[1]).call(obj);
}
else if ((REAL = config[i].split(':')) && REAL[1]) {
result[REAL[0]] = Function('return ' + REAL[1])();
}
else {
result[config[i]] = obj[config[i]];
}
}
return result;
}
}
|
javascript
|
{
"resource": ""
}
|
q63739
|
httpTransaction
|
test
|
function httpTransaction(req, res) {
let initializationPromise;
/* Architecture Note #3.1: New Transaction
The idea is to maintain a hash of each pending
transaction. To do so, we create a transaction
object that contains useful informations about
the transaction and we store it into the
`TRANSACTIONS` hash.
Each transaction has a unique id that is either
generated or picked up in the `Transaction-Id`
request header. This allows to trace
transactions end to end with that unique id.
*/
return Promise.resolve().then(() => {
const request = {
url: req.url,
method: req.method.toLowerCase(),
headers: req.headers,
body: req,
};
const transaction = {
protocol: req.connection.encrypted ? 'https' : 'http',
ip:
(req.headers['x-forwarded-for'] || '').split(',')[0] ||
req.connection.remoteAddress,
startInBytes: req.socket.bytesRead,
startOutBytes: req.socket.bytesWritten,
startTime: time(),
url: req.url,
method: req.method,
reqHeaders: req.headers,
errored: false,
};
const delayPromise = delay.create(TIMEOUT);
let id = req.headers['transaction-id'] || uniqueId();
// Handle bad client transaction ids
if (TRANSACTIONS[id]) {
initializationPromise = Promise.reject(
new HTTPError(400, 'E_TRANSACTION_ID_NOT_UNIQUE', id),
);
id = uniqueId();
} else {
initializationPromise = Promise.resolve();
}
transaction.id = id;
TRANSACTIONS[id] = transaction;
return [
request,
{
id,
start: startTransaction.bind(
null,
{ id, req, res, delayPromise },
initializationPromise,
),
catch: catchTransaction.bind(null, { id, req, res }),
end: endTransaction.bind(null, { id, req, res, delayPromise }),
},
];
});
}
|
javascript
|
{
"resource": ""
}
|
q63740
|
dateDifference
|
test
|
function dateDifference(date1, date2, differenceType) {
var diffMilliseconds = Math.abs(date1 - date2);
switch(differenceType) {
case 'days':
return dates._getDaysDiff(diffMilliseconds);
case 'hours':
return dates._differenceInHours(diffMilliseconds);
case 'minutes':
return dates._differenceInMinutes(diffMilliseconds);
case 'milliseconds':
return diffMilliseconds;
default:
return {
days: dates._getDaysDiff(diffMilliseconds),
hours: dates._getHoursDiff(diffMilliseconds),
minutes: dates._getMinutesDiff(diffMilliseconds),
milliseconds: diffMilliseconds
}
}
}
|
javascript
|
{
"resource": ""
}
|
q63741
|
initErrorHandler
|
test
|
function initErrorHandler({
ENV = {},
DEBUG_NODE_ENVS = DEFAULT_DEBUG_NODE_ENVS,
STRINGIFYERS = DEFAULT_STRINGIFYERS,
}) {
return Promise.resolve(errorHandler);
/**
* Handle an HTTP transaction error and
* map it to a serializable response
* @param {String} transactionId
* A raw NodeJS HTTP incoming message
* @param {Object} responseSpec
* The response specification
* @param {HTTPError} err
* The encountered error
* @return {Promise}
* A promise resolving when the operation
* completes
*/
function errorHandler(transactionId, responseSpec, err) {
return Promise.resolve().then(() => {
const response = {};
response.status = err.httpCode || 500;
response.headers = Object.assign({}, err.headers || {}, {
// Avoid caching errors
'cache-control': 'private',
// Fallback to the default stringifyer to always be
// able to display errors
'content-type':
responseSpec &&
responseSpec.contentTypes[0] &&
STRINGIFYERS[responseSpec.contentTypes[0]]
? responseSpec.contentTypes[0]
: Object.keys(STRINGIFYERS)[0],
});
response.body = {
error: {
code: err.code || 'E_UNEXPECTED',
// Enjoy nerdy stuff:
// https://en.wikipedia.org/wiki/Guru_Meditation
guruMeditation: transactionId,
},
};
if (ENV && DEBUG_NODE_ENVS.includes(ENV.NODE_ENV)) {
response.body.error.stack = err.stack;
response.body.error.params = err.params;
}
return response;
});
}
}
|
javascript
|
{
"resource": ""
}
|
q63742
|
dateDifferenceFromNow
|
test
|
function dateDifferenceFromNow(date, differenceType) {
var now = new Date(),
diffMilliseconds = Math.abs(date - now);
switch(differenceType) {
case 'days':
return dates._getDaysDiff(diffMilliseconds);
case 'hours':
return dates._differenceInHours(diffMilliseconds);
case 'minutes':
return dates._differenceInMinutes(diffMilliseconds);
case 'milliseconds':
return diffMilliseconds;
default:
return {
days: dates._getDaysDiff(diffMilliseconds),
hours: dates._getHoursDiff(diffMilliseconds),
minutes: dates._getMinutesDiff(diffMilliseconds),
milliseconds: diffMilliseconds
}
}
}
|
javascript
|
{
"resource": ""
}
|
q63743
|
consumePair
|
test
|
function consumePair(stream, close, open) {
const start = stream.pos;
if (stream.eat(close)) {
while (!stream.sol()) {
if (stream.eat(open)) {
return true;
}
stream.pos--;
}
}
stream.pos = start;
return false;
}
|
javascript
|
{
"resource": ""
}
|
q63744
|
consumeArray
|
test
|
function consumeArray(stream, arr) {
const start = stream.pos;
let consumed = false;
for (let i = arr.length - 1; i >= 0 && !stream.sol(); i--) {
if (!stream.eat(arr[i])) {
break;
}
consumed = i === 0;
}
if (!consumed) {
stream.pos = start;
}
return consumed;
}
|
javascript
|
{
"resource": ""
}
|
q63745
|
isIdent
|
test
|
function isIdent(c) {
return c === COLON || c === DASH || isAlpha(c) || isNumber(c);
}
|
javascript
|
{
"resource": ""
}
|
q63746
|
onCycle
|
test
|
function onCycle(event) {
if(objectPool.length == 0) {
throw new Error('Pool ran out of objects');
}
console.log(String(event.target));
initPool();
}
|
javascript
|
{
"resource": ""
}
|
q63747
|
json
|
test
|
function json(file) {
var filename = path.basename(file.path, path.extname(file.path)) + ".json";
return optional(path.join(path.dirname(file.path), filename)) || {};
}
|
javascript
|
{
"resource": ""
}
|
q63748
|
test
|
function (event) {
if (event.name === 'goToLevel'
&& event.level !== self.level) {
self.pushLevel(event.level);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63749
|
test
|
function (event) {
if (event.name === 'goToLevel') {
if (event.level === self.level) {
this.transitionTo(open);
} else {
self.pushLevel(event.level);
this.transitionTo(moving);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63750
|
decryptGCM
|
test
|
function decryptGCM(encryptedComponents, keyDerivationInfo) {
// Extract the components
const encryptedContent = encryptedComponents.content;
const iv = new Buffer(encryptedComponents.iv, "hex");
const { auth: tagHex, salt } = encryptedComponents;
// Prepare tool
const decryptTool = crypto.createDecipheriv(ENC_ALGORITHM_GCM, keyDerivationInfo.key, iv);
// Add additional auth data
decryptTool.setAAD(new Buffer(`${encryptedComponents.iv}${keyDerivationInfo.salt}`, "utf8"));
// Set auth tag
decryptTool.setAuthTag(new Buffer(tagHex, "hex"));
// Perform decryption
const decryptedText = decryptTool.update(encryptedContent, "base64", "utf8");
return Promise.resolve(`${decryptedText}${decryptTool.final("utf8")}`);
}
|
javascript
|
{
"resource": ""
}
|
q63751
|
encryptCBC
|
test
|
function encryptCBC(text, keyDerivationInfo, iv) {
return Promise.resolve().then(() => {
const ivHex = iv.toString("hex");
const encryptTool = crypto.createCipheriv(ENC_ALGORITHM_CBC, keyDerivationInfo.key, iv);
const hmacTool = crypto.createHmac(HMAC_ALGORITHM, keyDerivationInfo.hmac);
const { rounds } = keyDerivationInfo;
// Perform encryption
let encryptedContent = encryptTool.update(text, "utf8", "base64");
encryptedContent += encryptTool.final("base64");
// Generate hmac
hmacTool.update(encryptedContent);
hmacTool.update(ivHex);
hmacTool.update(keyDerivationInfo.salt);
const hmacHex = hmacTool.digest("hex");
// Output encrypted components
return {
mode: "cbc",
auth: hmacHex,
iv: ivHex,
salt: keyDerivationInfo.salt,
rounds,
content: encryptedContent
};
});
}
|
javascript
|
{
"resource": ""
}
|
q63752
|
encryptGCM
|
test
|
function encryptGCM(text, keyDerivationInfo, iv) {
return Promise.resolve().then(() => {
const ivHex = iv.toString("hex");
const { rounds } = keyDerivationInfo;
const encryptTool = crypto.createCipheriv(ENC_ALGORITHM_GCM, keyDerivationInfo.key, iv);
// Add additional auth data
encryptTool.setAAD(new Buffer(`${ivHex}${keyDerivationInfo.salt}`, "utf8"));
// Perform encryption
let encryptedContent = encryptTool.update(text, "utf8", "base64");
encryptedContent += encryptTool.final("base64");
// Handle authentication
const tag = encryptTool.getAuthTag();
// Output encrypted components
return {
mode: "gcm",
iv: ivHex,
salt: keyDerivationInfo.salt,
rounds,
content: encryptedContent,
auth: tag.toString("hex")
};
});
}
|
javascript
|
{
"resource": ""
}
|
q63753
|
unpackEncryptedContent
|
test
|
function unpackEncryptedContent(encryptedContent) {
const [content, iv, salt, auth, roundsRaw, methodRaw] = encryptedContent.split("$");
// iocane was originally part of Buttercup's core package and used defaults from that originally.
// There will be 4 components for pre 0.15.0 archives, and 5 in newer archives. The 5th component
// is the pbkdf2 round count, which is optional:
const rounds = roundsRaw ? parseInt(roundsRaw, 10) : PBKDF2_ROUND_DEFAULT;
// Originally only "cbc" was supported, but GCM was added in version 1
const method = methodRaw || "cbc";
return {
content,
iv,
salt,
auth,
rounds,
method
};
}
|
javascript
|
{
"resource": ""
}
|
q63754
|
deriveFromPassword
|
test
|
function deriveFromPassword(pbkdf2Gen, password, salt, rounds, generateHMAC = true) {
if (!password) {
return Promise.reject(new Error("Failed deriving key: Password must be provided"));
}
if (!salt) {
return Promise.reject(new Error("Failed deriving key: Salt must be provided"));
}
if (!rounds || rounds <= 0) {
return Promise.reject(new Error("Failed deriving key: Rounds must be greater than 0"));
}
const bits = generateHMAC ? (PASSWORD_KEY_SIZE + HMAC_KEY_SIZE) * 8 : PASSWORD_KEY_SIZE * 8;
return pbkdf2Gen(password, salt, rounds, bits)
.then(derivedKeyData => derivedKeyData.toString("hex"))
.then(function(derivedKeyHex) {
const dkhLength = derivedKeyHex.length;
const keyBuffer = generateHMAC
? new Buffer(derivedKeyHex.substr(0, dkhLength / 2), "hex")
: new Buffer(derivedKeyHex, "hex");
const output = {
salt: salt,
key: keyBuffer,
rounds: rounds
};
if (generateHMAC) {
output.hmac = new Buffer(derivedKeyHex.substr(dkhLength / 2, dkhLength / 2), "hex");
}
return output;
});
}
|
javascript
|
{
"resource": ""
}
|
q63755
|
pbkdf2
|
test
|
function pbkdf2(password, salt, rounds, bits) {
return new Promise((resolve, reject) => {
deriveKey(password, salt, rounds, bits / 8, DERIVED_KEY_ALGORITHM, (err, key) => {
if (err) {
return reject(err);
}
return resolve(key);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q63756
|
createEncodeStream
|
test
|
function createEncodeStream(schema) {
const stream = new BinaryStream({
readableObjectMode: false,
writableObjectMode: true,
transform: transformEncode,
});
stream[kschema] = schema;
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q63757
|
createDecodeStream
|
test
|
function createDecodeStream(bufOrSchema) {
let schema = null;
const isBuffer = Buffer.isBuffer(bufOrSchema);
if (!isBuffer) {
schema = bufOrSchema;
}
const stream = new BinaryStream({
transform: transformDecode,
readableObjectMode: true,
writableObjectMode: false,
});
stream[kschema] = schema;
if (isBuffer) {
stream.append(bufOrSchema);
}
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q63758
|
erdosRenyi
|
test
|
function erdosRenyi(GraphClass, options) {
if (!isGraphConstructor(GraphClass))
throw new Error('graphology-generators/random/erdos-renyi: invalid Graph constructor.');
var order = options.order,
probability = options.probability,
rng = options.rng || Math.random;
var graph = new GraphClass();
// If user gave a size, we need to compute probability
if (typeof options.approximateSize === 'number') {
var densityFunction = density[graph.type + 'Density'];
probability = densityFunction(order, options.approximateSize);
}
if (typeof order !== 'number' || order <= 0)
throw new Error('graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.');
if (typeof probability !== 'number' || probability < 0 || probability > 1)
throw new Error('graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\'s density.');
if (typeof rng !== 'function')
throw new Error('graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.');
for (var i = 0; i < order; i++)
graph.addNode(i);
if (probability <= 0)
return graph;
if (order > 1) {
var iterator = combinations(range(order), 2),
path,
step;
while ((step = iterator.next(), !step.done)) {
path = step.value;
if (graph.type !== 'directed') {
if (rng() < probability)
graph.addUndirectedEdge(path[0], path[1]);
}
if (graph.type !== 'undirected') {
if (rng() < probability)
graph.addDirectedEdge(path[0], path[1]);
if (rng() < probability)
graph.addDirectedEdge(path[1], path[0]);
}
}
}
return graph;
}
|
javascript
|
{
"resource": ""
}
|
q63759
|
erdosRenyiSparse
|
test
|
function erdosRenyiSparse(GraphClass, options) {
if (!isGraphConstructor(GraphClass))
throw new Error('graphology-generators/random/erdos-renyi: invalid Graph constructor.');
var order = options.order,
probability = options.probability,
rng = options.rng || Math.random;
var graph = new GraphClass();
// If user gave a size, we need to compute probability
if (typeof options.approximateSize === 'number') {
var densityFunction = density[graph.type + 'Density'];
probability = densityFunction(order, options.approximateSize);
}
if (typeof order !== 'number' || order <= 0)
throw new Error('graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.');
if (typeof probability !== 'number' || probability < 0 || probability > 1)
throw new Error('graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\'s density.');
if (typeof rng !== 'function')
throw new Error('graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.');
for (var i = 0; i < order; i++)
graph.addNode(i);
if (probability <= 0)
return graph;
var w = -1,
lp = Math.log(1 - probability),
lr,
v;
if (graph.type !== 'undirected') {
v = 0;
while (v < order) {
lr = Math.log(1 - rng());
w += 1 + ((lr / lp) | 0);
// Avoiding self loops
if (v === w) {
w++;
}
while (v < order && order <= w) {
w -= order;
v++;
// Avoiding self loops
if (v === w)
w++;
}
if (v < order)
graph.addDirectedEdge(v, w);
}
}
w = -1;
if (graph.type !== 'directed') {
v = 1;
while (v < order) {
lr = Math.log(1 - rng());
w += 1 + ((lr / lp) | 0);
while (w >= v && v < order) {
w -= v;
v++;
}
if (v < order)
graph.addUndirectedEdge(v, w);
}
}
return graph;
}
|
javascript
|
{
"resource": ""
}
|
q63760
|
single_curve
|
test
|
function single_curve(d, ctx) {
var centroids = compute_centroids(d);
var cps = compute_control_points(centroids);
ctx.moveTo(cps[0].e(1), cps[0].e(2));
for (var i = 1; i < cps.length; i += 3) {
if (__.showControlPoints) {
for (var j = 0; j < 3; j++) {
ctx.fillRect(cps[i+j].e(1), cps[i+j].e(2), 2, 2);
}
}
ctx.bezierCurveTo(cps[i].e(1), cps[i].e(2), cps[i+1].e(1), cps[i+1].e(2), cps[i+2].e(1), cps[i+2].e(2));
}
}
|
javascript
|
{
"resource": ""
}
|
q63761
|
color_path
|
test
|
function color_path(d, ctx) {
ctx.beginPath();
if ((__.bundleDimension !== null && __.bundlingStrength > 0) || __.smoothness > 0) {
single_curve(d, ctx);
} else {
single_path(d, ctx);
}
ctx.stroke();
}
|
javascript
|
{
"resource": ""
}
|
q63762
|
paths
|
test
|
function paths(data, ctx) {
ctx.clearRect(-1, -1, w() + 2, h() + 2);
ctx.beginPath();
data.forEach(function(d) {
if ((__.bundleDimension !== null && __.bundlingStrength > 0) || __.smoothness > 0) {
single_curve(d, ctx);
} else {
single_path(d, ctx);
}
});
ctx.stroke();
}
|
javascript
|
{
"resource": ""
}
|
q63763
|
brushUpdated
|
test
|
function brushUpdated(newSelection) {
__.brushed = newSelection;
events.brush.call(pc,__.brushed);
pc.renderBrushed();
}
|
javascript
|
{
"resource": ""
}
|
q63764
|
selected
|
test
|
function selected() {
var actives = d3.keys(__.dimensions).filter(is_brushed),
extents = actives.map(function(p) { return brushes[p].extent(); });
// We don't want to return the full data set when there are no axes brushed.
// Actually, when there are no axes brushed, by definition, no items are
// selected. So, let's avoid the filtering and just return false.
//if (actives.length === 0) return false;
// Resolves broken examples for now. They expect to get the full dataset back from empty brushes
if (actives.length === 0) return __.data;
// test if within range
var within = {
"date": function(d,p,dimension) {
if (typeof __.dimensions[p].yscale.rangePoints === "function") { // if it is ordinal
return extents[dimension][0] <= __.dimensions[p].yscale(d[p]) && __.dimensions[p].yscale(d[p]) <= extents[dimension][1]
} else {
return extents[dimension][0] <= d[p] && d[p] <= extents[dimension][1]
}
},
"number": function(d,p,dimension) {
if (typeof __.dimensions[p].yscale.rangePoints === "function") { // if it is ordinal
return extents[dimension][0] <= __.dimensions[p].yscale(d[p]) && __.dimensions[p].yscale(d[p]) <= extents[dimension][1]
} else {
return extents[dimension][0] <= d[p] && d[p] <= extents[dimension][1]
}
},
"string": function(d,p,dimension) {
return extents[dimension][0] <= __.dimensions[p].yscale(d[p]) && __.dimensions[p].yscale(d[p]) <= extents[dimension][1]
}
};
return __.data
.filter(function(d) {
switch(brush.predicate) {
case "AND":
return actives.every(function(p, dimension) {
return within[__.dimensions[p].type](d,p,dimension);
});
case "OR":
return actives.some(function(p, dimension) {
return within[__.dimensions[p].type](d,p,dimension);
});
default:
throw new Error("Unknown brush predicate " + __.brushPredicate);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q63765
|
consecutive
|
test
|
function consecutive(first, second) {
var length = d3.keys(__.dimensions).length;
return d3.keys(__.dimensions).some(function(d, i) {
return (d === first)
? i + i < length && __.dimensions[i + 1] === second
: false;
});
}
|
javascript
|
{
"resource": ""
}
|
q63766
|
convertProperty
|
test
|
function convertProperty(originalKey, originalValue, isRtl) {
const key = getPropertyDoppelganger(originalKey, isRtl)
const value = getValueDoppelganger(key, originalValue, isRtl)
return {key, value}
}
|
javascript
|
{
"resource": ""
}
|
q63767
|
getPropertyDoppelganger
|
test
|
function getPropertyDoppelganger(property, isRtl) {
const convertedProperty = isRtl
? propertiesToConvert.rtl[property]
: propertiesToConvert.ltr[property]
return convertedProperty || property
}
|
javascript
|
{
"resource": ""
}
|
q63768
|
ReadFileCache
|
test
|
function ReadFileCache(sourceDir, charset) {
assert.ok(this instanceof ReadFileCache);
assert.strictEqual(typeof sourceDir, "string");
this.charset = charset;
EventEmitter.call(this);
Object.defineProperties(this, {
sourceDir: { value: sourceDir },
sourceCache: { value: {} }
});
}
|
javascript
|
{
"resource": ""
}
|
q63769
|
done
|
test
|
function done(err, resource) {
totalRequestElapsed += ((new Date().getTime()) - started);
++totalRequests;
stats.avgFetchTime = parseInt(totalRequestElapsed / totalRequests);
if (err || verbose) util.log('cache|execute|done|err='+err+'|result='+(resource ? 'found':'null'));
if (err) {
++stats.failed;
}
if (!err && defaultCacheTTL) { // ttl === 0 --> expire imediatly.
if (stats.inCache >= defaultCacheSize) {
weedOutCache();
}
var now = new Date().getTime();
resourceCache[key] = {
'key' : key,
'epoch' : now,
'access': now,
'expire': defaultCacheTTL,
'hits' : 0,
'data' : resource
};
++stats.inCache;
}
var pendingRequests = requestQueue[key];
delete requestQueue[key];
for (var i = 0, size = pendingRequests.length ; i < size ; ++i) {
if (debug) util.log('cache|calling='+i+'|err='+err+'|resource='+(resource ? 'found':'null'));
if (!err && defaultCacheTTL) {
++resourceCache[key].hits;
}
pendingRequests[i].call(this, err, resource, resourceCache[key]);
--stats.waiting;
}
--stats.fetching;
if (stats.fetching === 0 && stats.waiting === 0) {
self.emit('stats', stats);
} else {
bufferedEmitter.call(self, 'stats', stats);
}
}
|
javascript
|
{
"resource": ""
}
|
q63770
|
test
|
function(options) {
options = (options||{});
this.agent = options.agent;
this.defaults = options.defaults||{};
this.log = options.logger||(new Ax({ level: "info" }));
this._sharedCookieJar = new CookieJar();
this.logCurl = options.logCurl || false;
}
|
javascript
|
{
"resource": ""
}
|
|
q63771
|
test
|
function(level,message) {
var debug = (level=="debug"||level=="error");
if (!message) { return message.toString(); }
if (typeof(message) == "object") {
if (message instanceof Error && debug) {
return message.stack;
} else {
return inspect(message);
}
} else {
return message.toString();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63772
|
test
|
function(options) {
this.log = options.logger;
this.cookieJar = options.cookieJar;
this.encoding = options.encoding;
this.logCurl = options.logCurl;
processOptions(this,options||{});
createRequest(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q63773
|
test
|
function(request,options) {
request.log.debug("Processing request options ..");
// We'll use `request.emitter` to manage the `on` event handlers.
request.emitter = (new Emitter);
request.agent = options.agent;
// Set up the handlers ...
if (options.on) {
for (var key in options.on) {
if (options.on.hasOwnProperty(key)) {
request.emitter.on(key, options.on[key]);
}
}
}
// Make sure we were give a URL or a host
if (!options.url && !options.host) {
request.emitter.emit("request_error",
new Error("No url or url options (host, port, etc.)"));
return;
}
// Allow for the [use of a proxy](http://www.jmarshall.com/easy/http/#proxies).
if (options.url) {
if (options.proxy) {
request.url = options.proxy;
request.path = options.url;
} else {
request.url = options.url;
}
}
// Set the remaining options.
request.query = options.query||options.parameters||request.query ;
request.method = options.method;
request.setHeader("user-agent",options.agent||"Shred");
request.setHeaders(options.headers);
if (request.cookieJar) {
var cookies = request.cookieJar.getCookies( CookieAccessInfo( request.host, request.path ) );
if (cookies.length) {
var cookieString = request.getHeader('cookie')||'';
for (var cookieIndex = 0; cookieIndex < cookies.length; ++cookieIndex) {
if ( cookieString.length && cookieString[ cookieString.length - 1 ] != ';' )
{
cookieString += ';';
}
cookieString += cookies[ cookieIndex ].name + '=' + cookies[ cookieIndex ].value + ';';
}
request.setHeader("cookie", cookieString);
}
}
// The content entity can be set either using the `body` or `content` attributes.
if (options.body||options.content) {
request.content = options.body||options.content;
}
request.timeout = options.timeout;
}
|
javascript
|
{
"resource": ""
}
|
|
q63774
|
test
|
function(event) {
var emitter = request.emitter;
var textStatus = STATUS_CODES[response.status] ? STATUS_CODES[response.status].toLowerCase() : null;
if (emitter.listeners(response.status).length > 0 || emitter.listeners(textStatus).length > 0) {
emitter.emit(response.status, response);
emitter.emit(textStatus, response);
} else {
if (emitter.listeners(event).length>0) {
emitter.emit(event, response);
} else if (!response.isRedirect) {
emitter.emit("response", response);
//console.warn("Request has no event listener for status code " + response.status);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63775
|
test
|
function (req) {
var headers = req.getHeaders();
var headerString = "";
for (var key in headers) {
headerString += '-H "' + key + ": " + headers[key] + '" ';
}
var bodyString = ""
if (req.content) {
bodyString += "-d '" + req.content.body + "' ";
}
var query = req.query ? '?' + req.query : "";
console.log("curl " +
"-X " + req.method.toUpperCase() + " " +
req.scheme + "://" + req.host + ":" + req.port + req.path + query + " " +
headerString +
bodyString
);
}
|
javascript
|
{
"resource": ""
}
|
|
q63776
|
test
|
function(raw, request, callback) {
var response = this;
this._raw = raw;
// The `._setHeaders` method is "private"; you can't otherwise set headers on
// the response.
this._setHeaders.call(this,raw.headers);
// store any cookies
if (request.cookieJar && this.getHeader('set-cookie')) {
var cookieStrings = this.getHeader('set-cookie');
var cookieObjs = []
, cookie;
for (var i = 0; i < cookieStrings.length; i++) {
var cookieString = cookieStrings[i];
if (!cookieString) {
continue;
}
if (!cookieString.match(/domain\=/i)) {
cookieString += '; domain=' + request.host;
}
if (!cookieString.match(/path\=/i)) {
cookieString += '; path=' + request.path;
}
try {
cookie = new Cookie(cookieString);
if (cookie) {
cookieObjs.push(cookie);
}
} catch (e) {
console.warn("Tried to set bad cookie: " + cookieString);
}
}
request.cookieJar.setCookies(cookieObjs);
}
this.request = request;
this.client = request.client;
this.log = this.request.log;
// Stream the response content entity and fire the callback when we're done.
// Store the incoming data in a array of Buffers which we concatinate into one
// buffer at the end. We need to use buffers instead of strings here in order
// to preserve binary data.
var chunkBuffers = [];
var dataLength = 0;
raw.on("data", function(chunk) {
chunkBuffers.push(chunk);
dataLength += chunk.length;
});
raw.on("end", function() {
var body;
if (typeof Buffer === 'undefined') {
// Just concatinate into a string
body = chunkBuffers.join('');
} else {
// Initialize new buffer and add the chunks one-at-a-time.
body = new Buffer(dataLength);
for (var i = 0, pos = 0; i < chunkBuffers.length; i++) {
chunkBuffers[i].copy(body, pos);
pos += chunkBuffers[i].length;
}
}
var setBodyAndFinish = function (body) {
response._body = new Content({
body: body,
type: response.getHeader("Content-Type")
});
callback(response);
}
if (zlib && response.getHeader("Content-Encoding") === 'gzip'){
zlib.gunzip(body, function (err, gunzippedBody) {
if (Iconv && response.request.encoding){
body = Iconv.fromEncoding(gunzippedBody,response.request.encoding);
} else {
body = gunzippedBody.toString();
}
setBodyAndFinish(body);
})
}
else{
if (response.request.encoding){
body = Iconv.fromEncoding(body,response.request.encoding);
}
setBodyAndFinish(body);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q63777
|
test
|
function(constructor) {
constructor.prototype.getHeader = function(name) { return getHeader(this,name); };
constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); };
}
|
javascript
|
{
"resource": ""
}
|
|
q63778
|
test
|
function(constructor) {
constructor.prototype._setHeader = function(key,value) { return setHeader(this,key,value); };
constructor.prototype._setHeaders = function(hash) { return setHeaders(this,hash); };
}
|
javascript
|
{
"resource": ""
}
|
|
q63779
|
test
|
function(constructor) {
constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); };
constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); };
}
|
javascript
|
{
"resource": ""
}
|
|
q63780
|
test
|
function(constructor) {
constructor.prototype.getHeader = function(name) { return getHeader(this,name); };
constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); };
constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); };
constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); };
}
|
javascript
|
{
"resource": ""
}
|
|
q63781
|
test
|
function(encoding) {
var enc = encoding || "utf8";
var codecOptions = undefined;
while (1) {
if (getType(enc) === "String")
enc = enc.replace(/[- ]/g, "").toLowerCase();
var codec = iconv.encodings[enc];
var type = getType(codec);
if (type === "String") {
// Link to other encoding.
codecOptions = {originalEncoding: enc};
enc = codec;
}
else if (type === "Object" && codec.type != undefined) {
// Options for other encoding.
codecOptions = codec;
enc = codec.type;
}
else if (type === "Function")
// Codec itself.
return codec(codecOptions);
else
throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63782
|
test
|
function(options) {
// Prepare chars if needed
if (!options.chars || (options.chars.length !== 128 && options.chars.length !== 256))
throw new Error("Encoding '"+options.type+"' has incorrect 'chars' (must be of len 128 or 256)");
if (options.chars.length === 128)
options.chars = asciiString + options.chars;
if (!options.charsBuf) {
options.charsBuf = new Buffer(options.chars, 'ucs2');
}
if (!options.revCharsBuf) {
options.revCharsBuf = new Buffer(65536);
var defChar = iconv.defaultCharSingleByte.charCodeAt(0);
for (var i = 0; i < options.revCharsBuf.length; i++)
options.revCharsBuf[i] = defChar;
for (var i = 0; i < options.chars.length; i++)
options.revCharsBuf[options.chars.charCodeAt(i)] = i;
}
return {
toEncoding: function(str) {
str = ensureString(str);
var buf = new Buffer(str.length);
var revCharsBuf = options.revCharsBuf;
for (var i = 0; i < str.length; i++)
buf[i] = revCharsBuf[str.charCodeAt(i)];
return buf;
},
fromEncoding: function(buf) {
buf = ensureBuffer(buf);
// Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
var charsBuf = options.charsBuf;
var newBuf = new Buffer(buf.length*2);
var idx1 = 0, idx2 = 0;
for (var i = 0, _len = buf.length; i < _len; i++) {
idx1 = buf[i]*2; idx2 = i*2;
newBuf[idx2] = charsBuf[idx1];
newBuf[idx2+1] = charsBuf[idx1+1];
}
return newBuf.toString('ucs2');
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q63783
|
test
|
function(options) {
var table = options.table, key, revCharsTable = options.revCharsTable;
if (!table) {
throw new Error("Encoding '" + options.type +"' has incorect 'table' option");
}
if(!revCharsTable) {
revCharsTable = options.revCharsTable = {};
for (key in table) {
revCharsTable[table[key]] = parseInt(key);
}
}
return {
toEncoding: function(str) {
str = ensureString(str);
var strLen = str.length;
var bufLen = strLen;
for (var i = 0; i < strLen; i++)
if (str.charCodeAt(i) >> 7)
bufLen++;
var newBuf = new Buffer(bufLen), gbkcode, unicode,
defaultChar = revCharsTable[iconv.defaultCharUnicode.charCodeAt(0)];
for (var i = 0, j = 0; i < strLen; i++) {
unicode = str.charCodeAt(i);
if (unicode >> 7) {
gbkcode = revCharsTable[unicode] || defaultChar;
newBuf[j++] = gbkcode >> 8; //high byte;
newBuf[j++] = gbkcode & 0xFF; //low byte
} else {//ascii
newBuf[j++] = unicode;
}
}
return newBuf;
},
fromEncoding: function(buf) {
buf = ensureBuffer(buf);
var bufLen = buf.length, strLen = 0;
for (var i = 0; i < bufLen; i++) {
strLen++;
if (buf[i] & 0x80) //the high bit is 1, so this byte is gbkcode's high byte.skip next byte
i++;
}
var newBuf = new Buffer(strLen*2), unicode, gbkcode,
defaultChar = iconv.defaultCharUnicode.charCodeAt(0);
for (var i = 0, j = 0; i < bufLen; i++, j+=2) {
gbkcode = buf[i];
if (gbkcode & 0x80) {
gbkcode = (gbkcode << 8) + buf[++i];
unicode = table[gbkcode] || defaultChar;
} else {
unicode = gbkcode;
}
newBuf[j] = unicode & 0xFF; //low byte
newBuf[j+1] = unicode >> 8; //high byte
}
return newBuf.toString('ucs2');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63784
|
encodeUserAuth
|
test
|
function encodeUserAuth(user) {
if (!user) {
return null;
}
var token = user.token;
if (token) {
var sha1 = typeof token === 'object' ? token.sha1 : token;
return 'token ' + sha1;
}
return 'Basic ' + base64.encode(user.username + ':' + user.password)
}
|
javascript
|
{
"resource": ""
}
|
q63785
|
Vec4
|
test
|
function Vec4() {
switch ( arguments.length ) {
case 1:
// array or VecN argument
var argument = arguments[0];
this.x = argument.x || argument[0] || 0.0;
this.y = argument.y || argument[1] || 0.0;
this.z = argument.z || argument[2] || 0.0;
this.w = argument.w || argument[3] || 0.0;
break;
case 4:
// individual component arguments
this.x = arguments[0];
this.y = arguments[1];
this.z = arguments[2];
this.w = arguments[3] || 0.0;
break;
default:
this.x = 0.0;
this.y = 0.0;
this.z = 0.0;
this.w = 0.0;
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q63786
|
create
|
test
|
function create(EConstructor) {
FormattedError.displayName = EConstructor.displayName || EConstructor.name
return FormattedError
function FormattedError(format) {
if (format) {
format = formatter.apply(null, arguments)
}
return new EConstructor(format)
}
}
|
javascript
|
{
"resource": ""
}
|
q63787
|
Mat44
|
test
|
function Mat44( that ) {
that = that || [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
if ( that instanceof Array ) {
this.data = that;
} else {
this.data = new Array( 16 );
this.data[0] = that.data[0];
this.data[1] = that.data[1];
this.data[2] = that.data[2];
this.data[3] = that.data[3];
this.data[4] = that.data[4];
this.data[5] = that.data[5];
this.data[6] = that.data[6];
this.data[7] = that.data[7];
this.data[8] = that.data[8];
this.data[9] = that.data[9];
this.data[10] = that.data[10];
this.data[11] = that.data[11];
this.data[12] = that.data[12];
this.data[13] = that.data[13];
this.data[14] = that.data[14];
this.data[15] = that.data[15];
}
}
|
javascript
|
{
"resource": ""
}
|
q63788
|
Vec2
|
test
|
function Vec2() {
switch ( arguments.length ) {
case 1:
// array or VecN argument
var argument = arguments[0];
this.x = argument.x || argument[0] || 0.0;
this.y = argument.y || argument[1] || 0.0;
break;
case 2:
// individual component arguments
this.x = arguments[0];
this.y = arguments[1];
break;
default:
this.x = 0;
this.y = 0;
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q63789
|
Quaternion
|
test
|
function Quaternion() {
switch ( arguments.length ) {
case 1:
// array or Quaternion argument
var argument = arguments[0];
if ( argument.w !== undefined ) {
this.w = argument.w;
} else if ( argument[0] !== undefined ) {
this.w = argument[0];
} else {
this.w = 1.0;
}
this.x = argument.x || argument[1] || 0.0;
this.y = argument.y || argument[2] || 0.0;
this.z = argument.z || argument[3] || 0.0;
break;
case 4:
// individual component arguments
this.w = arguments[0];
this.x = arguments[1];
this.y = arguments[2];
this.z = arguments[3];
break;
default:
this.w = 1;
this.x = 0;
this.y = 0;
this.z = 0;
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q63790
|
Vec3
|
test
|
function Vec3() {
switch ( arguments.length ) {
case 1:
// array or VecN argument
var argument = arguments[0];
this.x = argument.x || argument[0] || 0.0;
this.y = argument.y || argument[1] || 0.0;
this.z = argument.z || argument[2] || 0.0;
break;
case 3:
// individual component arguments
this.x = arguments[0];
this.y = arguments[1];
this.z = arguments[2];
break;
default:
this.x = 0.0;
this.y = 0.0;
this.z = 0.0;
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q63791
|
test
|
function() {
if (!document.getElementById("snackbar-container")) {
var snackbarContainer = document.createElement("div");
snackbarContainer.setAttribute("id", "snackbar-container");
document.body.appendChild(snackbarContainer);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q63792
|
test
|
function(element) {
var __self = this;
// Adding event listener for when user clicks on the snackbar to remove it
element.addEventListener("click", function(){
if (typeof __self.callback == "function") {
__self.callback();
}
element.setAttribute("class", "snackbar");
__self.destroy(element);
});
// Stopping the timer when user hovers on the snackbar
element.addEventListener("mouseenter",function(){
__self.timer.pause();
});
element.addEventListener("mouseout",function(){
__self.timer.resume();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q63793
|
test
|
function(newOptions) {
var __self = this,
options = newOptions || {};
for (var opt in this.options) {
if (__self.options.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) {
options[opt] = __self.options[opt];
}
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
|
q63794
|
test
|
function(Vue){
var __self = this;
Vue.prototype.$snackbar = {};
Vue.prototype.$snackbar.create = function(data, options, callback){
__self.create(data, options, callback);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q63795
|
Transform
|
test
|
function Transform( that ) {
that = that || {};
if ( that.data instanceof Array ) {
// Mat33 or Mat44, extract transform components
that = that.decompose();
this.rotation = that.rotation;
this.translation = that.translation || new Vec3();
this.scale = that.scale;
} else {
// set individual components, by value
this.rotation = that.rotation ? new Quaternion( that.rotation ) : new Quaternion();
this.translation = that.translation ? new Vec3( that.translation ) : new Vec3();
if ( typeof that.scale === 'number' ) {
this.scale = new Vec3( that.scale, that.scale, that.scale );
} else {
this.scale = that.scale ? new Vec3( that.scale ) : new Vec3( 1, 1, 1 );
}
}
}
|
javascript
|
{
"resource": ""
}
|
q63796
|
Triangle
|
test
|
function Triangle() {
switch ( arguments.length ) {
case 1:
// array or object argument
var arg = arguments[0];
this.a = new Vec3( arg[0] || arg.a );
this.b = new Vec3( arg[1] || arg.b );
this.c = new Vec3( arg[2] || arg.c );
break;
case 3:
// individual vector arguments
this.a = new Vec3( arguments[0] );
this.b = new Vec3( arguments[1] );
this.c = new Vec3( arguments[2] );
break;
default:
this.a = new Vec3( 0, 0, 0 );
this.b = new Vec3( 1, 0, 0 );
this.c = new Vec3( 1, 1, 0 );
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q63797
|
bash
|
test
|
function bash(str, pattern, options) {
if (typeof str !== 'string') {
throw new TypeError('expected a string');
}
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
if (isWindows()) {
throw new Error('bash-match does not work on windows');
}
try {
var opts = createOptions(pattern, options);
var res = spawn.sync(getBashPath(), cmd(str, pattern, opts), opts);
var err = toString(res.stderr);
if (err) {
return handleError(err, opts);
}
return !!toString(res.stdout);
} catch (err) {
return handleError(err, opts);
}
}
|
javascript
|
{
"resource": ""
}
|
q63798
|
cmd
|
test
|
function cmd(str, pattern, options) {
var valid = ['dotglob', 'extglob', 'failglob', 'globstar', 'nocaseglob', 'nullglob'];
var args = [];
for (var key in options) {
if (options.hasOwnProperty(key) && valid.indexOf(key) !== -1) {
args.push('-O', key);
}
}
args.push('-c', 'IFS=$"\n"; if [[ "' + str + '" = ' + pattern + ' ]]; then echo true; fi');
return args;
}
|
javascript
|
{
"resource": ""
}
|
q63799
|
createOptions
|
test
|
function createOptions(pattern, options) {
if (options && options.normalized === true) return options;
var opts = extend({cwd: process.cwd()}, options);
if (opts.nocase === true) opts.nocaseglob = true;
if (opts.nonull === true) opts.nullglob = true;
if (opts.dot === true) opts.dotglob = true;
if (!opts.hasOwnProperty('globstar') && pattern.indexOf('**') !== -1) {
opts.globstar = true;
}
if (!opts.hasOwnProperty('extglob') && isExtglob(pattern)) {
opts.extglob = true;
}
opts.normalized = true;
return opts;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.