_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q33400 | bootstrap | train | function bootstrap(next) {
if (!options.commands || !options.commands.length) {
return next();
}
var hasErr;
self.ssh({
keys: options.keys,
server: options.server,
commands: options.commands,
remoteUser: options.remoteUser,
tunnel: options.tunnel
}).on('error', function (err) {
if (!hasErr) {
hasErr = true;
next(err);
}
}).on('complete', function (server, stdout) {
if (!hasErr) {
next(null, stdout);
}
});
} | javascript | {
"resource": ""
} |
q33401 | fixOutputPaths | train | function fixOutputPaths(output, files) {
// map directories to use for index files
var dirMap = {};
u.each(files, function(file) {
dirMap[ppath.dirname(file.path)] = true;
// edge case - treat /foo/ as directory too
if (/\/$/.test(file.path) && ppath.dirname(file.path) !== file.path) {
dirMap[file.path] = true;
}
});
// default output file extension is .html
var extension = 'extension' in output ? (output.extension || '') : '.html';
var indexFile = output.indexFile || 'index';
u.each(files, function(file) {
if (dirMap[file.path]) {
debug('index file for %s', file.path);
file.path = ppath.join(file.path, indexFile);
}
if (!/\.[^/]*$/.test(file.path)) {
file.path = file.path + extension;
}
});
} | javascript | {
"resource": ""
} |
q33402 | addModuleToParentPom | train | function addModuleToParentPom (parentPomPath, properties, yoFs) {
var pomStr = yoFs.read(parentPomPath);
var pomEditor = mavenPomModule(pomStr);
pomEditor.addModule(properties.artifactId);
yoFs.write(parentPomPath, pomEditor.getPOMString());
} | javascript | {
"resource": ""
} |
q33403 | processModules | train | function processModules (resourcesPath, targetPath, directory, modules, parentPomPath, properties, yoFs) {
modules.forEach(module => {
debug('Processing module', module);
var modulePath = path.join(directory, module.dir);
properties.artifactId = pathFiltering.filter(module.dir, properties);
addModuleToParentPom(parentPomPath, properties, yoFs);
var pomPath = copyPom(resourcesPath, targetPath, modulePath, properties, yoFs);
processFileSets(resourcesPath, targetPath, modulePath, module.fileSets, properties, yoFs);
processModules(resourcesPath, targetPath, modulePath, module.modules, pomPath, properties, yoFs);
});
} | javascript | {
"resource": ""
} |
q33404 | filesFromFileSet | train | function filesFromFileSet (dirname, fileset) {
if (!fileset.includes || !fileset.includes.length) {
return [];
}
return fileset.includes
.filter(include => !glob.hasMagic(include))
.map(include => path.join(dirname, include));
} | javascript | {
"resource": ""
} |
q33405 | globsToExcludeFromFileSet | train | function globsToExcludeFromFileSet (dirname, fileset) {
if (fileset.excludes && fileset.excludes.length) {
return fileset.excludes.map(exclude => '!' + path.join(dirname, exclude));
} else {
return [];
}
} | javascript | {
"resource": ""
} |
q33406 | filter | train | function filter(selector) {
var arr = [], $ = this.air;
this.each(function(el) {
var selections;
if(typeof selector === 'function') {
if(selector.call(el)) {
arr.push(el);
}
}else{
selections = $(selector);
if(~selections.dom.indexOf(el)) {
arr.push(el);
}
}
});
return $(arr);
} | javascript | {
"resource": ""
} |
q33407 | exec | train | function exec() {
var result;
while(scripts.length) {
var script = scripts.shift();
if(typeof(script) == 'function') {
result = script();
if(result && typeof(result) == 'object' && typeof(result.then) == 'function') {
result.then(exec);
break;
}
} else {
eval(script);
}
}
} | javascript | {
"resource": ""
} |
q33408 | WalletService | train | function WalletService() {
if (!initialized)
throw new Error('Server not initialized');
this.lock = lock;
this.storage = storage;
this.blockchainExplorer = blockchainExplorer;
this.blockchainExplorerOpts = blockchainExplorerOpts;
this.messageBroker = messageBroker;
this.fiatRateService = fiatRateService;
this.notifyTicker = 0;
} | javascript | {
"resource": ""
} |
q33409 | initialize | train | function initialize() {
switch (this.type) {
case 'ga':
ga('create', this.key, this.domain);
ga('send', 'pageview');
break;
case 'segment':
default:
window.analytics.load(this.key);
window.analytics.page();
break;
}
} | javascript | {
"resource": ""
} |
q33410 | map | train | function map(data) {
var result = {}
, i = this.properties.length;
while (i--) result[this.properties[i]] = data[i];
return result;
} | javascript | {
"resource": ""
} |
q33411 | log | train | function log(e) {
var data = $(e.element).get('track').split(';');
// Revenue only allows numbers remove it if it is not a number.
if ('number' !== typeof data[3]) data.splice(3);
analytics.track(data.splice(0, 1), this.map(data));
} | javascript | {
"resource": ""
} |
q33412 | google | train | function google(e) {
var tracker = this.tracking.ga;
if (!tracker) return;
ga(function done() {
ga.getByName(tracker).send.apply(
tracker,
[ 'event' ].concat($(e.element).get('track').split(';'))
);
});
} | javascript | {
"resource": ""
} |
q33413 | fetchGitHub | train | function fetchGitHub(url) {
return fetch(url).then(res => {
if (res.status === STATUS_NOT_FOUND) {
throw new Error('USER_NOT_FOUND');
} else if (res.status !== STATUS_OK) {
throw new Error('CANNOT_FETCH_DATA');
}
return res.text();
});
} | javascript | {
"resource": ""
} |
q33414 | getStreaks | train | function getStreaks(contributions) {
const start = contributions[0].date;
const end = contributions.slice(-1)[0].date;
const streak = {days: 0, start: null, end: null, unmeasurable: false};
let currentStreak = Object.assign({}, streak);
let longestStreak = Object.assign({}, streak);
contributions.forEach(ret => {
if (ret.count > 0) {
currentStreak.days += 1;
currentStreak.end = ret.date;
if (!currentStreak.start) {
currentStreak.start = ret.date;
}
if (currentStreak.days >= longestStreak.days) {
longestStreak = Object.assign({}, currentStreak);
}
} else if (ret.date !== end) {
currentStreak = Object.assign({}, streak);
}
});
if (currentStreak.start === start && currentStreak.end === end) {
currentStreak.unmeasurable = true;
longestStreak.unmeasurable = true;
}
return {currentStreak, longestStreak};
} | javascript | {
"resource": ""
} |
q33415 | parseCalendar | train | function parseCalendar($calendar) {
const data = [];
$calendar.find('rect').each((i, elm) => {
const $rect = cheerio(elm);
const date = $rect.attr('data-date');
if (!date) {
return;
}
data.push({
date,
count: parseInt($rect.attr('data-count'), 10)
});
});
return data;
} | javascript | {
"resource": ""
} |
q33416 | summarizeContributions | train | function summarizeContributions(contributions) {
let busiestDay = null;
let total = 0;
contributions.forEach(d => {
if (d.count > 0 && (!busiestDay || d.count > busiestDay.count)) {
busiestDay = d;
}
total += d.count;
});
return {
busiestDay,
end: contributions.slice(-1)[0].date,
start: contributions[0].date,
total
};
} | javascript | {
"resource": ""
} |
q33417 | reload_file | train | function reload_file(arg_file_path)
{
const file_name = path.basename(arg_file_path)
const this_file_name = path.basename(__filename)
if (file_name == this_file_name)
{
console.info('Need to reload after change on ' + this_file_name)
return
}
const exts = ['.js', '.json']
const ext = path.extname(arg_file_path)
const full_path = path.resolve(arg_file_path)
if ((exts.indexOf(ext) > -1) && (full_path in require.cache))
{
console.info('Reloading: ' + full_path)
// console.log(require.cache[full_path].parent.children[0])
delete require.cache[full_path]
require(full_path)
}
} | javascript | {
"resource": ""
} |
q33418 | watch | train | function watch(arg_src_dir)
{
console.info('Watching for change on: ' + arg_src_dir)
const watch_settings = { ignored: /[\/\\]\./, persistent: true }
var watcher = chokidar.watch(arg_src_dir, watch_settings)
watcher.on('change', reload_file)
return watcher
} | javascript | {
"resource": ""
} |
q33419 | rxServer | train | function rxServer(val) { // {{{2
/**
* Called, when received "server" message as a client.
*/
if (! (
val.space === this.peer.space.name &&
val.peer === this.peer.name
)) {
O.log.error(this, 'This is not the right peer');
this.close();
return;
}
this.rx = rxConfirm;
this.tx({
space: O.here.space.name,
peer: O.here.name,
});
return;
} | javascript | {
"resource": ""
} |
q33420 | _setVadrDeviceCookie | train | function _setVadrDeviceCookie(){
// setting cookie valid for years set in constants
const cookieValidFor = constants.cookieValidForYears;
const deviceCookieName = constants.deviceCookieName;
const currentDate = new Date();
const laterDate = new Date();
laterDate.setFullYear(currentDate.getFullYear() + cookieValidFor);
const deviceId = utils.getToken();
utils.setCookie(deviceCookieName, deviceId, laterDate, false);
return deviceId;
} | javascript | {
"resource": ""
} |
q33421 | remove | train | function remove() {
var i, el;
for(i = 0;i < this.length;i++) {
el = this.dom[i];
// if for some reason this point to the document element
// an exception will occur, pretty hard to reproduce so
// going to let it slide
if(el.parentNode) {
el.parentNode.removeChild(el);
this.dom.splice(i, 1);
i--;
}
}
return this;
} | javascript | {
"resource": ""
} |
q33422 | getEnvNumericalValue | train | function getEnvNumericalValue(envValue, defaultVal) {
var limit = defaultVal;
if (envValue) {
limit = parseInt(envValue,10);
if (isNaN(limit)) {
limit = defaultVal;
}
}
return limit;
} | javascript | {
"resource": ""
} |
q33423 | setApplication | train | function setApplication(appId, token, version){
appConfig['appId'] = appId;
appConfig['appToken'] = token;
appConfig['version'] = version;
} | javascript | {
"resource": ""
} |
q33424 | featureNameFromProperty | train | function featureNameFromProperty(instance, defaultName, candidateMap) {
for (var key in candidateMap) {
if (typeof instance[key] !== 'undefined') {
return candidateMap[key];
}
}
console.warn('no feature name detected for '+ defaultName +' using default');
return defaultName;
} | javascript | {
"resource": ""
} |
q33425 | train | function(pDefaultMessage, pError, pRequest, pResponse, fNext)
{
var tmpErrorMessage = pDefaultMessage;
var tmpErrorCode = 1;
var tmpScope = null;
var tmpParams = null;
var tmpSessionID = null;
if (typeof(pError) === 'object')
{
tmpErrorMessage = pError.Message;
if (pError.Code)
tmpErrorCode = pError.Code;
}
else if (typeof(pError) === 'string')
{
tmpErrorMessage += ' ' + pError;
}
if (pRequest.DAL)
{
tmpScope = pRequest.DAL.scope;
}
if (pRequest.params)
{
tmpParams = pRequest.params;
}
if (pRequest.UserSession)
{
tmpSessionID = pRequest.UserSession.SessionID;
}
_Log.warn('API Error: '+tmpErrorMessage, {SessionID: tmpSessionID, RequestID:pRequest.RequestUUID, RequestURL:pRequest.url, Scope: tmpScope, Parameters: tmpParams, Action:'APIError'}, pRequest);
pResponse.send({Error:tmpErrorMessage, ErrorCode: tmpErrorCode});
return fNext();
} | javascript | {
"resource": ""
} | |
q33426 | train | function(pMessage, pRequest, pResponse, fNext)
{
var tmpSessionID = null;
if (pRequest.UserSession)
{
tmpSessionID = pRequest.UserSession.SessionID;
}
_Log.warn('API Error: '+pMessage, {SessionID: tmpSessionID, RequestID:pRequest.RequestUUID, RequestURL:pRequest.url, Action:'APIError'}, pRequest);
pResponse.send({Error:pMessage});
return fNext();
} | javascript | {
"resource": ""
} | |
q33427 | startWorkers | train | function startWorkers() {
_.range(0, numWorkers).forEach(function (index) {
workers.push(startWorker(startPort + index));
});
} | javascript | {
"resource": ""
} |
q33428 | startWorker | train | function startWorker(port) {
var worker = child.fork(serverWorker, [
'--port', port,
'--server', serverFile,
'--allowForcedExit', allowForcedExit,
'--config', JSON.stringify(config.app || {}),
'--title', workerTitle
]);
worker.on('exit', createWorkerExitHandler(port));
return worker;
} | javascript | {
"resource": ""
} |
q33429 | createWorkerExitHandler | train | function createWorkerExitHandler(port) {
return function (code, signal) {
var workerIndex = port - startPort;
workers[workerIndex] = null;
if (code !== 0 || code === null) {
console.log('Worker exited with code: ' + code);
if (!shuttingDown) {
// Start worker again after 1 sec
setTimeout(function () {
if (!workers[workerIndex]) {
workers[workerIndex] = startWorker(port);
}
}, 1000);
}
}
};
} | javascript | {
"resource": ""
} |
q33430 | condor_simple | train | function condor_simple(cmd, opts) {
var deferred = Q.defer();
var p = spawn(cmd, opts, {env: get_condor_env()});//, {cwd: __dirname});
//load event
var stdout = "";
p.stdout.on('data', function (data) {
stdout += data;
});
var stderr = "";
p.stderr.on('data', function (data) {
stderr += data;
});
p.on('error', deferred.reject);
p.on('close', function (code, signal) {
if (signal) {
deferred.reject(cmd+ " was killed by signal "+ signal);
} else if (code !== 0) {
deferred.reject(cmd+ " failed with exit code "+ code+ "\nSTDERR:"+ stderr + "\nSTDOUT:"+ stdout);
} else {
deferred.resolve(stdout, stderr);
}
});
return deferred.promise;
} | javascript | {
"resource": ""
} |
q33431 | describe | train | function describe(composer, trailing) {
return function (method) {
return new Descriptor(function (key, previousValues) {
if ( method !== undefined)
previousValues[trailing ? 'push' : 'unshift' ](method)
//console.log(previousValues)
return reduce(previousValues, function(merged, next, idx){
return trailing
? composer(next, merged)
: composer(merged, next)
})
})
}
} | javascript | {
"resource": ""
} |
q33432 | parseTaskObject | train | function parseTaskObject(task, options) {
if (Array.isArray(task)) {
return task;
} else {
return task.bind(null, gulp, ...options.params);
}
} | javascript | {
"resource": ""
} |
q33433 | registerTask | train | function registerTask(file, options) {
const task = require(file.path);
const taskName = path.basename(file.path, file.ext);
const taskObject = parseTaskObject(task, options);
// Register this task with Gulp.
gulp.task.call(gulp, taskName, taskObject);
debug(`registered "${taskName}" task`);
} | javascript | {
"resource": ""
} |
q33434 | parseFile | train | function parseFile(dir, filename) {
const filePath = path.join(dir, filename);
const fileStat = fs.statSync(filePath);
const fileExt = path.extname(filename);
return {
path: filePath,
stat: fileStat,
ext: fileExt
};
} | javascript | {
"resource": ""
} |
q33435 | handleFile | train | function handleFile(dir, options) {
return filename => {
const file = parseFile(dir, filename);
debug(`found "${filename}"`);
// Exit early if this item is not a file.
if (!file.stat.isFile()) {
debug(`skipped "${filename}" (not a file)`);
return;
}
// Exit early if this item is not the right file type.
if (!options.extensions.includes(file.ext)) {
debug(`skipped "${filename}" (incorrect file type)`);
return;
}
registerTask(file, options);
};
} | javascript | {
"resource": ""
} |
q33436 | extendDefaultOptions | train | function extendDefaultOptions(options) {
return Object.assign({
dir: DEFAULT_DIRECTORY,
extensions: DEFAULT_EXTENSIONS,
params: DEFAULT_PARAMS
}, options);
} | javascript | {
"resource": ""
} |
q33437 | importTasks | train | function importTasks(options) {
const opts = parseOptions(options);
const cwd = process.cwd();
const dir = path.join(cwd, opts.dir);
debug(`importing tasks from "${dir}"...`);
// This synchronously reads the contents within the chosen directory then
// loops through each item, verifies that it is in fact a file of the correct
// file type, then creates the tasks object and registers it with gulp.
fs.readdirSync(dir).forEach(
handleFile(dir, opts)
);
debug(`finished importing tasks`);
} | javascript | {
"resource": ""
} |
q33438 | onmessage | train | function onmessage(data) {
if (!handshaked) {
handshaked = true;
// The handshake output is in the form of URI.
var result = url.parse(data, true).query;
// A newly issued id for HTTP transport. It is used to identify which HTTP transport
// is associated with which HTTP exchange. Don't confuse it with an id for socket,
// `cettia-id`.
self.id = result["cettia-transport-id"];
// And then fire `open` event.
self.emit("open");
} else {
// `code` is a first character of a message and used to recognize that delivered
// message is text message or binary message.
var code = data.substring(0, 1);
data = data.substring(1);
switch (code) {
// If the `code` is `1`, the remainder of message is a plain text message. Fires
// `text` event.
case "1":
self.emit("text", data);
break;
// If the `code` is `2`, the remainder of message is a Base64-encoded binary
// message. Decodes it in Base64 and fires `binary` event.
case "2":
self.emit("binary", new Buffer(data, "base64"));
break;
// Otherwise, it is invalid. Fires an error and closes the connection.
default:
self.emit("error", new Error("protocol"));
self.close();
break;
}
}
} | javascript | {
"resource": ""
} |
q33439 | loginTo | train | function loginTo (endpoint, config) {
return global.IS_BROWSER
? loginFromBrowser(endpoint, config)
: loginFromNode(endpoint, config)
} | javascript | {
"resource": ""
} |
q33440 | loginFromBrowser | train | function loginFromBrowser (endpoint, config) {
let uri
switch (endpoint) {
case AUTH_ENDPOINTS.PRIMARY:
uri = config.authEndpoint || window.location.origin + window.location.pathname
break
case AUTH_ENDPOINTS.SECONDARY:
uri = config.fallbackAuthEndpoint
break
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.withCredentials = true
xhr.addEventListener('load', () => {
resolve(xhr.getResponseHeader('user') || null)
})
xhr.addEventListener('error', err => {
reject(err)
})
xhr.open('HEAD', uri)
xhr.send()
})
} | javascript | {
"resource": ""
} |
q33441 | loginFromNode | train | function loginFromNode (endpoint, config) {
if (!(config.key && config.cert)) {
throw new Error('Must provide TLS key and cert when running in node')
}
let uri
switch (endpoint) {
case AUTH_ENDPOINTS.PRIMARY:
uri = config.authEndpoint
break
case AUTH_ENDPOINTS.SECONDARY:
uri = config.fallbackAuthEndpoint
break
}
let fs, https, url
if (!global.IS_BROWSER) {
fs = require('fs')
https = require('https')
url = require('url')
}
return Promise.all([config.key, config.cert].map(filename =>
new Promise((resolve, reject) => {
fs.readFile(filename, (err, data) => err ? reject(err) : resolve(data))
})
)).then(([keyBuf, certBuf]) => {
const parsedUrl = url.parse(uri)
const options = {
method: 'HEAD',
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.path,
timeout: 5000,
key: keyBuf,
cert: certBuf
}
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
resolve(res.headers['user'] || null)
})
req.on('error', reject)
req.end()
})
})
} | javascript | {
"resource": ""
} |
q33442 | midi | train | function midi (note) {
if ((typeof note === 'number' || typeof note === 'string') &&
note > 0 && note < 128) return +note
var p = Array.isArray(note) ? note : parse(note)
if (!p || p.length < 2) return null
return p[0] * 7 + p[1] * 12 + 12
} | javascript | {
"resource": ""
} |
q33443 | find | train | function find() {
// If there is no remaining URI, fires `error` and `close` event as it means that all
// tries failed.
if (uris.length === 0) {
// Now that `connecting` event is being fired, there is no `error` and `close` event user
// added. Delays to fire them a little while.
setTimeout(function() {
self.emit("error", new Error());
self.emit("close");
}, 0);
return;
}
// A temporal variable to be used while finding working one.
var testTransport;
// Get the first uri by removing it from `uris`. For example, `[1,2].shift()` returns `1`
// and make the array `[2]`.
var uri = uris.shift();
// Transport handles only the specific types of URIs. It finds which transport factory can
// handle this `uri` among ones specified by `transports` option.
for (var i = 0; i < options.transports.length; i++) {
// A transport factory creates and returns a transport object if it can handle the given
// URI and nothing if not.
testTransport = options.transports[i](uri, options);
// If the factory handles this type of URI,
if (testTransport) {
break;
}
}
// If there is no transport matching with the given URI, try with the next URI.
if (!testTransport) {
find();
return;
}
// This is to stop the whole process to find a working transport when the `close` method
// is called before `open` event.
function stop() {
testTransport.removeListener("close", find);
testTransport.close();
}
// Until the socket is opened, `close` method should trigger `stop` function as well.
self.once("close", stop);
// It establishes a connection.
testTransport.open();
// If it fails, it should remove stop listener and try with the next URI. These event handlers
// will be removed once this transport is recognized as working.
testTransport.on("close", function() {
self.removeListener("close", stop);
});
testTransport.on("close", find);
// Node.js kills the process by default when an `error` event is fired if there is no
// listener for it. However, a user doesn't need to be notified of an error from this
// transport being tested.
testTransport.on("error", function() {
});
// If it succeeds, it means that the process to find working transport is done. The first
// transport text message is used to handshake the socket protocol. Note that `once`
// registers one-time event handler.
testTransport.once("text", function(text) {
// The handshake output is in the form of URI. Query params starting with `cettia-`
// represent protocol header.
var headers = url.parse(text, true).query;
// The server prints an id of the socket as a `cettia-id` param, `id` header,
// every time the transport connects. If the server issues a new id,
if (id !== headers["cettia-id"]) {
// That means there was no `id` or the server socket whose id is `id` was deleted in
// the server due to long-term disconnection.
id = headers["cettia-id"];
// Fires a `new` event as a new socket is created.
self.emit("new");
}
// To maintain an alive connection, `heartbeat` is used.
options.heartbeat = +headers["cettia-heartbeat"];
// `_heartbeat` is for testing so it should be not passed from the server in production.
// The default value is `5000`.
options._heartbeat = +headers["cettia-_heartbeat"] || 5000;
// Now that the working transport is found and handshaking is completed, it stops
// a process to find a working transport by removing `close` event handler `find` and
// associates the working transport with the socket.
testTransport.removeListener("close", find);
transport = testTransport;
// When an event object is created from `text` or `binary` event,
function onevent(event) {
// Event should have the following properties:
// * `id: string`: an event identifier.
// * `type: string`: an event type.
// * `data: any`: an event data.
// * `reply: boolean`: `true` if this event requires the reply.
// If the server sends a plain event, dispatch it.
if (!event.reply) {
self.emit(event.type, event.data);
} else {
var latch;
// A function to create a function.
function reply(success) {
// A controller function.
return function(value) {
// This latch prevents double reply.
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: value, exception: !success});
}
};
}
// Here, the controller is passed to the event handler as 2nd argument and
// allows to call the server's `resolved` or `rejected` callback by sending
// `reply` event.
self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
}
}
// When the transport has received a text message from the server,
// it deserializes a text message into an event object in the JSON format and deals with it.
transport.on("text", function(text) {
onevent(JSON.parse(text));
});
// When the transport has received a binary message from the server.
// it deserializes a binary message into an event object in the
// [MessagePack](http://msgpack.org) format and deals with it.
transport.on("binary", function(binary) {
onevent(msgpack.decode(binary));
});
// When any error has occurred.
transport.on("error", function(error) {
self.emit("error", error);
});
// When the transport has been closed for any reason.
transport.on("close", function() {
self.emit("close");
});
// Now that the working transport is associated and the communication is possible,
// it removes `close` event handler `stop` and fires `open` event.
self.removeListener("close", stop);
self.emit("open");
});
} | javascript | {
"resource": ""
} |
q33444 | onevent | train | function onevent(event) {
// Event should have the following properties:
// * `id: string`: an event identifier.
// * `type: string`: an event type.
// * `data: any`: an event data.
// * `reply: boolean`: true if this event requires the reply.
// If the client sends a plain event, dispatch it.
if (!event.reply) {
self.emit(event.type, event.data);
} else {
var latch;
// A function to create a function.
function reply(success) {
// A controller function.
return function(value) {
// This latch prevents double reply.
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: value, exception: !success});
}
};
}
// Here, the controller is passed to the event handler as 2nd argument and allows
// to call the server's `resolved` or `rejected` callback by sending `reply` event.
self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
}
} | javascript | {
"resource": ""
} |
q33445 | insertGlyphsRules | train | function insertGlyphsRules(rule, result) {
// Reverse order
// make sure to insert the characters in ascending order
let glyphs = result.glyphs.slice(0);
let glyphLen = glyphs.length;
while (glyphLen--) {
let glyph = glyphs[glyphLen];
let node = postcss.rule({
selector: '.' + result.opts.fontName + '-' + glyph.name + ':before'
});
node.append(postcss.decl({
prop: 'content',
value: '\'\\' +
glyph.unicode[0]
.charCodeAt(0)
.toString(16)
.toUpperCase()
+ '\''
}));
rule.parent.insertAfter(rule, node);
}
let node = postcss.rule({
selector: '[class^="' + result.opts.fontName + '-"], [class*=" ' + result.opts.fontName + '-"]'
});
[
{prop: 'font-family', value: '\'' + result.opts.fontName + '\''},
{prop: 'speak', value: 'none'},
{prop: 'font-style', value: 'normal'},
{prop: 'font-weight', value: 'normal'},
{prop: 'font-variant', value: 'normal'},
{prop: 'text-transform', value: 'none'},
{prop: 'line-height', value: 1},
{prop: '-webkit-font-smoothing', value: 'antialiased'},
{prop: '-moz-osx-font-smoothing', value: 'grayscale'}
].forEach(function (item) {
node.append(postcss.decl({
prop: item.prop,
value: item.value
}));
});
rule.parent.insertAfter(rule, node);
} | javascript | {
"resource": ""
} |
q33446 | extractTypeSourcesFromMarkdown | train | function extractTypeSourcesFromMarkdown(mdSource) {
var types = lang.string.lines(mdSource).reduce((typesAkk, line) => {
if (line.trim().startsWith("//")) return typesAkk;
if (typesAkk.current && !line.trim().length) {
typesAkk.types.push(typesAkk.current); typesAkk.current = [];
} else if (typesAkk.current && line.indexOf("```") > -1) {
typesAkk.types.push(typesAkk.current); typesAkk.current = null;
} else if (!typesAkk.current && line.indexOf("```js") > -1) {
typesAkk.current = [];
} else if (typesAkk.current) typesAkk.current.push(line);
return typesAkk;
}, {current: null, types: []}).types;
return lang.arr.invoke(types, "join", "\n");
} | javascript | {
"resource": ""
} |
q33447 | cartesian | train | function cartesian(list)
{
var last, init, keys, product = [];
if (Array.isArray(list))
{
init = [];
last = list.length - 1;
}
else if (typeof list == 'object' && list !== null)
{
init = {};
keys = Object.keys(list);
last = keys.length - 1;
}
else
{
throw new TypeError('Expecting an Array or an Object, but `' + (list === null ? 'null' : typeof list) + '` provided.');
}
function add(row, i)
{
var j, k, r;
k = keys ? keys[i] : i;
// either array or not, not expecting objects here
Array.isArray(list[k]) || (typeof list[k] == 'undefined' ? list[k] = [] : list[k] = [list[k]]);
for (j=0; j < list[k].length; j++)
{
r = clone(row);
store(r, list[k][j], k);
if (i >= last)
{
product.push(r);
}
else
{
add(r, i + 1);
}
}
}
add(init, 0);
return product;
} | javascript | {
"resource": ""
} |
q33448 | store | train | function store(obj, elem, key)
{
Array.isArray(obj) ? obj.push(elem) : (obj[key] = elem);
} | javascript | {
"resource": ""
} |
q33449 | nuclearComponent | train | function nuclearComponent(Component, getDataBindings) {
console.warn('nuclearComponent is deprecated, use `connect()` instead');
// support decorator pattern
// detect all React Components because they have a render method
if (arguments.length === 0 || !Component.prototype.render) {
// Component here is the getDataBindings Function
return _connect2['default'](Component);
}
return _connect2['default'](getDataBindings)(Component);
} | javascript | {
"resource": ""
} |
q33450 | train | function (value, defaultValue) {
if (module.exports.isEmpty(value)) {
value = defaultValue
} else if (typeof value === 'string') {
value = value.trim().toLowerCase()
switch (value) {
case 'false':
value = 0
break
case 'true':
value = 1
break
default:
value = Number(value)
}
} else if (typeof value === 'boolean') {
value = Number(value)
} else if (isNaN(value)) {
value = NaN
}
return value
} | javascript | {
"resource": ""
} | |
q33451 | perf | train | function perf(Target) {
if (process.env.NODE_ENV === 'production') {
return Target;
}
// eslint-disable-next-line global-require
var ReactPerf = require('react-addons-perf');
var Perf = function (_Component) {
_inherits(Perf, _Component);
function Perf() {
_classCallCheck(this, Perf);
return _possibleConstructorReturn(this, (Perf.__proto__ || Object.getPrototypeOf(Perf)).apply(this, arguments));
}
_createClass(Perf, [{
key: 'componentDidMount',
value: function componentDidMount() {
ReactPerf.start();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
ReactPerf.stop();
var measurements = ReactPerf.getLastMeasurements();
ReactPerf.printWasted(measurements);
ReactPerf.start();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
ReactPerf.stop();
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(Target, this.props);
}
}]);
return Perf;
}(_react.Component);
Perf.displayName = 'perf(' + (Target.displayName || Target.name || 'Component') + ')';
Perf.WrappedComponent = Target;
return Perf;
} | javascript | {
"resource": ""
} |
q33452 | provideReactor | train | function provideReactor(Component, additionalContextTypes) {
console.warn('`provideReactor` is deprecated, use `<Provider reactor={reactor} />` instead');
// support decorator pattern
if (arguments.length === 0 || typeof arguments[0] !== 'function') {
additionalContextTypes = arguments[0];
return function connectToReactorDecorator(ComponentToDecorate) {
return createComponent(ComponentToDecorate, additionalContextTypes);
};
}
return createComponent.apply(null, arguments);
} | javascript | {
"resource": ""
} |
q33453 | wsConnect | train | function wsConnect() {
var typeOfConnection;
if (location.protocol === 'https:') {
typeOfConnection = 'wss';
} else {
typeOfConnection = 'ws'
}
self.ws = new WebSocket(typeOfConnection + '://' + location.hostname + ':' + location.port);
self.ws.onopen = function (event) {
//send an intial message to server and prove that the connection is built.
self.send('connected', 'WSM: Browser confirms websocket connection.')
reactive(self);
};
self.ws.onmessage = function (event) {
// flags.binary will be set if a binary data is received.
// flags.masked will be set if the data was masked.
//console.log(event.data);
self.processMessage(JSON.parse(event.data));
};
self.ws.onclose = function (event) {
wsConnect();
}
} | javascript | {
"resource": ""
} |
q33454 | getLocalNodeFiles | train | function getLocalNodeFiles(dir) {
dir = path.resolve(dir);
var result = [];
var files = [];
var icons = [];
try {
files = fs.readdirSync(dir);
} catch(err) {
return {files: [], icons: []};
}
files.sort();
files.forEach(function(fn) {
var stats = fs.statSync(path.join(dir,fn));
if (stats.isFile()) {
if (/\.js$/.test(fn)) {
var info = getLocalFile(path.join(dir,fn));
if (info) {
result.push(info);
}
}
} else if (stats.isDirectory()) {
// Ignore /.dirs/, /lib/ /node_modules/
if (!/^(\..*|lib|icons|node_modules|test|locales)$/.test(fn)) {
var subDirResults = getLocalNodeFiles(path.join(dir,fn));
result = result.concat(subDirResults.files);
icons = icons.concat(subDirResults.icons);
} else if (fn === "icons") {
var iconList = scanIconDir(path.join(dir,fn));
icons.push({path:path.join(dir,fn),icons:iconList});
}
}
});
return {files: result, icons: icons};
} | javascript | {
"resource": ""
} |
q33455 | scanTreeForNodesModules | train | function scanTreeForNodesModules(moduleName) {
var dir = settings.coreNodesDir;
var results = [];
var userDir;
if (settings.userDir) {
userDir = path.join(settings.userDir,"node_modules");
results = scanDirForNodesModules(userDir,moduleName);
results.forEach(function(r) { r.local = true; });
}
if (dir) {
var up = path.resolve(path.join(dir,".."));
while (up !== dir) {
var pm = path.join(dir,"node_modules");
if (pm != userDir) {
results = results.concat(scanDirForNodesModules(pm,moduleName));
}
dir = up;
up = path.resolve(path.join(dir,".."));
}
}
return results;
} | javascript | {
"resource": ""
} |
q33456 | validateGeoJson | train | function validateGeoJson(geoJson) {
if (!geoJson)
throw new Error('No geojson passed');
if (geoJson.type !== 'FeatureCollection' &&
geoJson.type !== 'GeometryCollection' &&
geoJson.type !== 'MultiLineString' &&
geoJson.type !== 'LineString' &&
geoJson.type !== 'Feature'
)
throw new Error(`Invalid input type '${geoJson.type}'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature`);
} | javascript | {
"resource": ""
} |
q33457 | getCombinedTemplateDirectory | train | function getCombinedTemplateDirectory(templateDirectories) {
// Automatically track and clean up files at exit.
temp.track();
// Create a temporary directory to hold our template files.
var combinedTemplateDirectory = temp.mkdirSync('templates');
// Copy templates from our source directories into the combined directory.
templateDirectories.reverse().forEach(function(templateDirectory) {
grunt.file.expand(path.join(templateDirectory, '*.html')).forEach(function(srcPath) {
var srcFilename = path.basename(srcPath),
destPath = path.join(combinedTemplateDirectory, srcFilename);
grunt.file.copy(srcPath, destPath);
});
});
return combinedTemplateDirectory;
} | javascript | {
"resource": ""
} |
q33458 | addSwigFilters | train | function addSwigFilters() {
/**
* Zero padding function.
* Used as both a filter and internally here.
*
* @param input
* @param length
* @returns {string}
*/
function zeropad(input, length) {
input = input + ''; // Ensure input is a string.
length = length || 2; // Ensure a length is set.
return input.length >= length ? input : new Array(length - input.length + 1).join('0') + input;
}
/**
* Add a very simple range filter that handles integers with step = 1.
*
* @return []
*/
swig.setFilter('range', function(start, stop, step) {
var range = [];
for(var i = start; i <= stop; i += step) {
range.push(i);
}
return range;
});
/**
* Convert a string in hh:mm format to the number of seconds after midnight it represents.
*
* @return in
*/
swig.setFilter('hhmm_to_seconds', function(hhmm) {
var parts = hhmm.split(':');
return parts[0] * 60 * 60 + parts[1] * 60;
});
/**
*
*/
swig.setFilter('seconds_to_hhmm', function(seconds) {
var date = new Date(seconds * 1000);
return zeropad(date.getUTCHours()) + ':' + zeropad(date.getUTCMinutes());
});
/**
* Add a filter to zero-pad the input to the given length (default 2).
*/
swig.setFilter('zeropad', zeropad);
} | javascript | {
"resource": ""
} |
q33459 | zeropad | train | function zeropad(input, length) {
input = input + ''; // Ensure input is a string.
length = length || 2; // Ensure a length is set.
return input.length >= length ? input : new Array(length - input.length + 1).join('0') + input;
} | javascript | {
"resource": ""
} |
q33460 | rmdirWalk | train | function rmdirWalk( ls, done ) {
if( ls.length === 0 ) return done()
fs.rmdir( ls.shift().path, function( error ) {
if( error ) log( error.message )
rmdirWalk( ls, done )
})
} | javascript | {
"resource": ""
} |
q33461 | Session | train | function Session(context) {
this.context = context
this.cookies = context.cookies
this.update = this.update.bind(this)
} | javascript | {
"resource": ""
} |
q33462 | train | function (symbol) {
return symbolDict[symbol.charCodeAt(0)] && symbolDict[symbol.charCodeAt(0)][symbol.charCodeAt(1)] || symbolDict[symbol.charCodeAt(1)] && symbolDict[symbol.charCodeAt(0)][symbol.charCodeAt(0)];
} | javascript | {
"resource": ""
} | |
q33463 | train | function(){
STATIC_FILES.forEach(function(file){
addFile(fs.createReadStream(__dirname + '/templates/' + file), { name: file });
});
} | javascript | {
"resource": ""
} | |
q33464 | train | function(){
for(var i=0; i<DYNAMIC_FILES.length; i++) {
addFile(dynamicFilesCompiled[i](options), { name: DYNAMIC_FILES[i] });
}
} | javascript | {
"resource": ""
} | |
q33465 | Transport | train | function Transport(settings, levels) {
settings = settings || {};
this.levels = levels;
// Set the base settings
this.settings = {
levels: levels,
timestamp: !!settings.timestamp,
prependLevel: !!settings.prependLevel,
colorize: !!settings.colorize,
name: settings.name
};
// Parse the min logging level
this.settings.minLevel = settings.hasOwnProperty('minLevel') ? settings.minLevel : DEFAULT_MIN_LEVEL;
if (this.settings.minLevel && getLevelIndex(this.settings.minLevel, levels) === -1) {
throw new Error('Invalid minimum logging level "' + this.settings.minLevel + '"');
}
// Determine the stream
if (settings.destination) {
if (typeof settings.destination === 'string' || settings.destination instanceof String) {
ensurePathExists(path.dirname(settings.destination));
this.stream = fs.createWriteStream(settings.destination, {
flags: 'a'
});
this.destination = settings.destination;
if (fs.existsSync(settings.destination)) {
this.lineCount = fs.readFileSync(settings.destination).toString().split('\n').length;
}
if (typeof settings.maxLines != 'undefined') {
this.maxLines = settings.maxLines;
}
} else if (['object', 'function'].indexOf(typeof settings.destination) !== -1 && settings.destination instanceof stream.Writable) {
this.stream = settings.destination;
} else {
throw new Error('Invalid destination specified. A destination must be a string, a writable stream instance, or undefined');
}
}
// Set/create the formatter method
this.formatter = settings.formatter ? settings.formatter : defaultFormatter;
} | javascript | {
"resource": ""
} |
q33466 | Logger | train | function Logger(transports, settings) {
var i, len,
transport,
levels,
transportInstances = [],
names = {};
// Normalize the inputs
if (!transports) {
transports = [{}];
} else if (!Array.isArray(transports)) {
transports = [transports];
}
settings = settings || {};
levels = settings.levels || DEFAULT_LEVELS;
// Create the transports
for (i = 0, len = transports.length; i < len; i++) {
transport = transports[i];
if (transport.name) {
names[transport.name] = 1;
}
transportInstances.push(new Transport(transport, levels));
}
// Create the log methods
levels.forEach(function (level) {
this[level.id] = function log() {
var i, ilen, j, jlen,
p,
messages = Array.prototype.slice.call(arguments, 0),
transportMessages = new Array(messages.length),
areNamed = new Array(messages.length),
areAnyNamed = false,
message,
isNamed;
for (i = 0, ilen = messages.length; i < ilen; i++) {
message = messages[i];
isNamed = false;
if (typeof message === 'object') {
isNamed = true;
for (p in message) {
if (message.hasOwnProperty(p)) {
if (!names[p]) {
isNamed = false;
}
}
}
}
areNamed[i] = isNamed;
areAnyNamed = areAnyNamed || isNamed;
}
for (i = 0, ilen = transportInstances.length; i < ilen; i++) {
if (areAnyNamed) {
for (j = 0, jlen = messages.length; j < jlen; j++) {
if (areNamed[j]) {
transportMessages[j] = messages[j][transportInstances[i].settings.name];
} else {
transportMessages[j] = messages[j];
}
}
transportInstances[i].log(transportMessages, level);
} else {
transportInstances[i].log(messages, level);
}
}
};
}.bind(this));
} | javascript | {
"resource": ""
} |
q33467 | mapAllNames | train | function mapAllNames(path) {
log("[%s] Mapping %s", self.parentModuleName, path);
fs.readdirSync(path).forEach(function(p){
var absPath = PATH.resolve(path+PATH.sep+p);
var lstat = fs.lstatSync(absPath);
if(lstat.isFile() && isModule(p)) {
var name = getModuleName(p);
self.updateNameCache(name, absPath);
} else if(! isIgnoreFolder(p) && lstat.isDirectory()) {
mapAllNames(absPath);
}
});
function isIgnoreFolder(folderName) {
return !folderName || folderName === 'node_modules' || folderName[0] === '.';
}
function isModule(p) {
return p.match(/\.(js|json)$/);
}
function getModuleName(p) {
return p.replace(/\.(js|json)$/, '');
}
} | javascript | {
"resource": ""
} |
q33468 | findProjectRoot | train | function findProjectRoot(startPath) {
log.trace("findProjectRoot startPath = %s", startPath);
if(isDiskRoot()) {
if(hasPackageJson()) {
return startPath;
} else {
throw new Error("Cannot find project root");
}
} else if(hasPackageJson()) {
return startPath;
} else {
return findProjectRoot(PATH.resolve(startPath+PATH.sep+".."));
}
function hasPackageJson() {
return fs.existsSync(startPath+PATH.sep+"package.json");
}
function isDiskRoot() {
return startPath.match(/^([A-Z]:\\\\|\/)$/);
}
} | javascript | {
"resource": ""
} |
q33469 | createLongpollTransport | train | function createLongpollTransport(req, res) {
// The current response which can be used to send a message or close the connection. It's not
// null when it's available and null when it's not available.
var response;
// A flag to mark this transport is aborted. It's used when `response` is not available, if
// user closes the connection.
var aborted;
// A timer to prevent from being idle connection which may happen if the succeeding poll
// request is not arrived.
var closeTimer;
// The parameters of the first request. That of subsequent requests are not used.
var params = req.params;
// A queue containing messages that the server couldn't send.
var queue = [];
// A transport object.
var self = createBaseTransport(req, res);
// In long polling, multiple HTTP exchanges are used to establish a channel for the server to
// write message to client. This function will be called every time the client performs a request.
self.refresh = function(req, res) {
// Any error on request-response should propagate to transport.
req.on("error", function(error) {
self.emit("error", error);
});
res.on("error", function(error) {
self.emit("error", error);
});
// When the underlying connection was terminated abnormally.
res.on("close", function() {
self.emit("close");
});
// When the complete response has been sent.
res.on("finish", function() {
// If this request was to `poll` and this response was ended through `end` not
// `endedWithMessage`, it means it is the end of the transport. Hence, fires the `close`
// event.
if (req.params["cettia-transport-when"] === "poll" && !res.endedWithMessage) {
self.emit("close");
// Otherwise the client will issue `poll` request again. If not, this connection falls
// into limbo. To prevent that, it sets a timer which fires `close` event unless the
// client issues `poll` request in 3s.
} else {
closeTimer = setTimeout(function() {
self.emit("close");
}, 3000);
}
});
// A custom property to show how it was ended through either `endWithMessage` for sending a
// message or `end` for closing the connection. An ended response can't be used again.
res.endedWithMessage = false;
// A custom method to send a message through this response.
res.endWithMessage = function(data) {
// Flags the current response is ended with message.
res.endedWithMessage = true;
// `data` should be either a `Buffer` or a string.
if (typeof data === "string") {
// As for text message, the content-type header should be `text/javascript` for JSONP
// and `text/plain` for the others.
res.setHeader("content-type", "text/" +
// If it's JSONP, `cettia-transport-jsonp` param is `true`.
(params["cettia-transport-jsonp"] === "true" ? "javascript" : "plain") + "; charset=utf-8");
// All the long polling transports have to finish the request after processing. The
// `res`'s `finish` event will be fired after this.
res.end(params["cettia-transport-jsonp"] === "true" ?
// In case of JSONP, the response text is supposed to be a JavaScript code executing a
// callback with data. The callback name is passed as the first request's
// `cettia-transport-callback` param and the data to be returned have to be escaped to
// a JavaScript string literal. For others, no formatting is needed. In any case,
// data should be encoded in `utf-8`.
params["cettia-transport-callback"] + "(" + JSON.stringify(data) + ");" : data, "utf-8");
} else {
// As for binary message, the content-type header should be `application/octet-stream`.
// Old browsers depending on JSONP can't handle binary data so we don't need to consider
// them here.
res.setHeader("content-type", "application/octet-stream");
res.end(data);
}
};
switch (req.params["cettia-transport-when"]) {
// The first request
case "open":
// `script` tag which is a host object used in old browsers to perform long polling
// transport can't read HTTP response headers as well as write HTTP request headers. That's
// why we uses the first response's body as a handshake output instead of HTTP headers. The
// handshake result should be formatted in URI.
res.endWithMessage(url.format({
// Adds the following transport protocol headers:
// * `cettia-transport-id`: an identifier.
// * `cettia-transport-version`: the implemented long polling transport version.
query: {
"cettia-transport-version": "1.0",
"cettia-transport-id": self.id
}
}));
break;
// The succeeding request after the first request
case "poll":
// Resets timer as new exchange is supplied.
clearTimeout(closeTimer);
// If aborted is `true` here, it means the user tried to close the connection but it
// couldn't be done because `response` was null. So ends this incoming exchange. It will
// fire `close` event through `res`'s `finish` event handler.
if (aborted) {
res.end();
} else {
// If the queue is not empty, it means there are remaining messages so that the server
// should send them again.
if (queue.length) {
// Removes the first cached message from the queue and send it. FYI,
// `[1,2,3].shift()` returns in `1` and results in `[2,3]`.
res.endWithMessage(queue.shift());
} else {
// If not, assigns `res` to `response`.
response = res;
}
}
break;
// It shouldn't happen.
default:
self.emit("error", new Error("protocol"));
self.close();
break;
}
};
self.write = function(data) {
// Only when the current response exists, it's possible to send a message.
if (response) {
// After `response.endWithMessage`, `response` can't be used again.
var resp = response;
response = null;
resp.endWithMessage(data);
// If not, the data will be cached and sent in next poll through `refresh` method.
} else {
queue.push(data);
}
};
self.close = function() {
// Only when the current response exists, it's possible to close the
// connection.
if (response) {
// After `response.end`, `response` can't be used again.
var resp = response;
response = null;
resp.end();
// If not, a next poll request will be ended immediately by `aborted` flag through
// `refresh` method.
} else {
aborted = true;
}
return this;
};
// Refreshes with the first exchange.
self.refresh(req, res);
return self;
} | javascript | {
"resource": ""
} |
q33470 | wrapAsyncMethod | train | function wrapAsyncMethod(fn, ctx) {
return function() {
// Obtain function arguments
var args = [].slice.call(arguments);
// Return a thunkified function that receives a done callback
return new Promise(function(resolve, reject) {
// Add a custom callback to provided args
args.push(function(err, result) {
// Failed?
if (err) {
return reject(err);
}
// Success
resolve(result);
});
// Call original function
fn.apply(ctx, args);
});
};
} | javascript | {
"resource": ""
} |
q33471 | wrapAsync | train | function wrapAsync() {
// Traverse async methods
for (var fn in async) {
// Promisify the method
async[fn] = wrapAsyncMethod(async[fn], async);
}
// Return co-friendly async object
return async;
} | javascript | {
"resource": ""
} |
q33472 | Marathon | train | function Marathon(opts) {
if (!(this instanceof Marathon)) {
return new Marathon(opts);
}
opts = opts || {};
if (!opts.baseUrl) {
opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' +
(opts.host || '127.0.0.1') + ':' +
(opts.port || '8080') + '/v2';
}
opts.name = 'marathon';
opts.type = 'json';
papi.Client.call(this, opts);
this.app = new App(this);
this.eventSubscription = new EventSubscription(this);
} | javascript | {
"resource": ""
} |
q33473 | getState | train | function getState(reactor, data) {
var state = {}
each(data, function(value, key) {
state[key] = reactor.evaluate(value)
})
return state
} | javascript | {
"resource": ""
} |
q33474 | fsFileTree | train | function fsFileTree (inputPath, opts, cb) {
let result = {};
if (typeof inputPath === "function") {
cb = inputPath;
inputPath = process.cwd();
opts = {};
} else if (typeof opts === "function") {
cb = opts;
if (typeof inputPath === "object") {
opts = inputPath;
inputPath = process.cwd();
} else {
opts = {};
}
}
readDir(inputPath, (err, items) => {
if (err) { return cb(err); }
sameTime(bindy(items, (c, done) => {
let basename = path.basename(c.path);
if (basename.charAt(0) === "." && !opts.all) {
return done();
}
if (opts.camelCase) {
basename = camelo(basename);
}
if (c.stat.isDirectory()) {
return fsFileTree(c.path, opts, (err, res) => {
if (err) { return done(err); }
result[basename] = res;
done();
});
}
result[basename] = c;
done();
}), err => cb(err, result));
});
} | javascript | {
"resource": ""
} |
q33475 | walkTree | train | function walkTree(element, context, mergeProps, visitor) {
const Component = element.type;
if (typeof Component === 'function') {
const props = assign({}, Component.defaultProps, element.props, (mergeProps || {}));
let childContext = context;
let child;
// Are we are a react class?
// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L66
if (Component.prototype && Component.prototype.isReactComponent) {
const instance = new Component(props, context);
// In case the user doesn't pass these to super in the constructor
instance.props = instance.props || props;
instance.context = instance.context || context;
// Override setState to just change the state, not queue up an update.
// We can't do the default React thing as we aren't mounted "properly"
// however, we don't need to re-render as well only support setState in
// componentWillMount, which happens *before* rendere.
instance.setState = (newState) => {
instance.state = assign({}, instance.state, newState);
};
// This is a poor man's version of
// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L181
if (instance.componentWillMount) {
instance.componentWillMount();
}
if (instance.getChildContext) {
childContext = assign({}, context, instance.getChildContext());
}
// Query we need to resolve first so stop traversing.
if (visitor(element, instance, context) === false) {
return;
}
child = instance.render();
} else { // just a stateless functional
// Query we need to resolve first so stop traversing.
if (visitor(element, null, context) === false) {
return;
}
child = Component(props, context);
}
if (child) {
walkTree(child, childContext, null, visitor);
}
} else { // a basic string or dom element, just get children
// Query we need to resolve first so stop traversing.
if (visitor(element, null, context) === false) {
return;
}
// Multiple children, traverse each one.
if (element.props && element.props.children) {
React.Children.forEach(element.props.children, (child) => {
if (child) {
walkTree(child, context, null, visitor);
}
});
}
}
} | javascript | {
"resource": ""
} |
q33476 | getDataFromTree | train | function getDataFromTree(rootElement, rootContext, fetchRoot, mergeProps, isTopLevel){
//console.log(`Now searching element (${rootElement.type.name || rootElement.type.displayName}):`, rootElement);
// Get array of queries (fetchData promises) from tree
// This will traverse down recursively looking for fetchData() methods
let queries = getQueriesFromTree(rootElement, rootContext, fetchRoot, mergeProps);
// No queries found. We're done!
if (!queries.length) {
return Promise.resolve();
}
// We've traversed down as far as possible in thecurrent tree branch ...
// Wait on each query that we found, re-rendering the subtree when it's done.
const mappedQueries = queries.map(({ query, element, context }) => {
return query.then((newProps) => {
const displayName = element.type.displayName;
if (!displayName){
// TODO: Use Promise.reject and catch()
throw new Error('[React Component Data] When resolving component data recursively each component must have a displayName set.');
}
// Add to finalData array that will be returned
finalData[displayName] = newProps;
// Traverse children
// Component will use newProps returned by the query so we can find any children it might have as a result
return getDataFromTree(element, context, false, newProps);
})
});
return Promise.all(mappedQueries).then((values) => {
// Only return final data at top level
// Not inside recursive getDataFromTree calls
if (isTopLevel){
return finalData;
}
});
} | javascript | {
"resource": ""
} |
q33477 | jsonSpec | train | function jsonSpec() {
return parsedArgs.specFile ?
read(parsedArgs.specFile).then(JSON.parse) :
require("../index").fetch(parsedArgs.urls)
.then(mdSource => require("../index").parse(mdSource))
} | javascript | {
"resource": ""
} |
q33478 | createWebSocketTransport | train | function createWebSocketTransport(ws) {
// A transport object.
var self = new events.EventEmitter();
// Transport URI contains information like protocol header as query.
self.uri = ws.upgradeReq.url;
// Simply delegates WebSocket's events to transport and transport's behaviors to WebSocket.
ws.onmessage = function(event) {
// `event.data` is a message. It is string if text frame is sent and Buffer if binary frame
// is sent.
if (typeof event.data === "string") {
self.emit("text", event.data);
} else {
self.emit("binary", event.data);
}
};
ws.onerror = function(error) {
self.emit("error", error);
};
// A flag to check the transport is opened.
var opened = true;
ws.onclose = function() {
opened = false;
self.emit("close");
};
self.send = function(data) {
// Allows to send data only it is opened. If not, fires an error.
if (opened) {
// If `data` is string, a text frame is sent, and if it's Buffer, a binary frame is sent.
ws.send(data);
} else {
self.emit("error", new Error("notopened"));
}
return this;
};
self.close = function() {
ws.close();
return this;
};
return self;
} | javascript | {
"resource": ""
} |
q33479 | cloneStateDef | train | function cloneStateDef(stateDef) {
stateDef = (stateDef || {});
return function () {
var ctx = this;
return Object.keys(stateDef).reduce((state, k) => {
var value = stateDef[k];
state[k] = (typeof value === 'function' ? value.call(ctx) : value);
return state;
}, {});
};
} | javascript | {
"resource": ""
} |
q33480 | createUnits | train | function createUnits(conversions, withNames=false) {
const result = {};
conversions.forEach(c => c.names.forEach(name =>
result[unitToLower(normalizeUnitName(name))] = {
name: c.names[0],
prefix: c.prefix,
scale: c.scale,
toBase: c.toBase,
fromBase: c.fromBase,
names: withNames ? c.names : null
}
));
return result;
} | javascript | {
"resource": ""
} |
q33481 | createUnitRegex | train | function createUnitRegex(units) {
return Object.keys(units)
.sort((a, b) => b.length - a.length)
.map(unit => unit.length > 2 ? caseInsensitivePart(unit) : unit)
.join('|');
} | javascript | {
"resource": ""
} |
q33482 | train | function (url, key, password) {
var deferred, options, headers, liveapicreator;
liveapicreator = _.extend({}, SDK);
liveapicreator.url = this.stripWrappingSlashes(url);
liveapicreator.params = _.pick(URL.parse(url), 'host', 'path', 'port');
liveapicreator.params.headers = {};
if (url.match('https')) {
liveapicreator.req = https;
}
//passed a url with a defined port
if (liveapicreator.isUrlWithPort(liveapicreator.params.host)) {
liveapicreator.params.host = liveapicreator.stripUrlPort(liveapicreator.params.host);
}
deferred = Q.defer();
liveapicreator.connection = deferred.promise;
//Is this a username/password combo
if (password) {
options = liveapicreator.setOptions({method: 'POST'});
options.headers['Content-Type'] ='application/json';
options.path += liveapicreator.authEndpoint;
var req = liveapicreator.req.request(options, function (res) {
if (res.statusCode == 503) {
deferred.reject(res.statusCode);
}
res.setEncoding('utf8');
res.on('data', function (data) {
data = JSON.parse(data);
liveapicreator.apiKey = data.apikey;
liveapicreator.params.headers.Authorization = 'CALiveAPICreator ' + data.apikey + ':1';
deferred.resolve();
});
});
req.end(JSON.stringify({username: key, password: password}));
req.on('error', function(e) {
deferred.reject('Authentication failed, please confirm the username and/or password');
});
} else {
//liveapicreatorsdk.connect() was directly passed an API key
liveapicreator.apiKey = key;
liveapicreator.params.headers.Authorization = 'CALiveAPICreator ' + key + ':1';
deferred.resolve();
}
return liveapicreator;
} | javascript | {
"resource": ""
} | |
q33483 | train | function (options, headers) {
if (!headers) { headers = {}; }
if (options.headers) {
var headers = options.headers;
headers = _.extend(headers, this.headers, headers);
}
return options;
} | javascript | {
"resource": ""
} | |
q33484 | verifyParameters | train | function verifyParameters(replacements, value, decl, environment) {
if (undefined === replacements[value]) {
throw decl.error(
'Unknown variable ' + value,
{ plugin: plugin.name }
);
}
if (undefined === replacements[value][environment]) {
throw decl.error(
'No suitable replacement for "' + value +
'" in environment "' + environment + '"',
{ plugin: plugin.name }
);
}
} | javascript | {
"resource": ""
} |
q33485 | walkDeclaration | train | function walkDeclaration(decl, environment, replacements) {
decl.value = decl.value.replace(functionRegex, function (match, value) {
verifyParameters(replacements, value, decl, environment);
return replacements[value][environment];
});
} | javascript | {
"resource": ""
} |
q33486 | Chronos | train | function Chronos(opts) {
if (!(this instanceof Chronos)) {
return new Chronos(opts);
}
opts = opts || {};
if (!opts.baseUrl) {
opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' +
(opts.host || '127.0.0.1') + ':' +
(opts.port || '4400') + '/scheduler';
}
opts.name = 'chronos';
opts.type = 'json';
papi.Client.call(this, opts);
this.job = new Job(this);
this.task = new Task(this);
} | javascript | {
"resource": ""
} |
q33487 | train | function (testOverride) {
var ret = '127.0.0.1'
os = testOverride || os
var interfaces = os.networkInterfaces()
Object.keys(interfaces).forEach(function (el) {
interfaces[el].forEach(function (el2) {
if (!el2.internal && el2.family === 'IPv4') {
ret = el2.address
}
})
})
return ret
} | javascript | {
"resource": ""
} | |
q33488 | train | function (string) {
if (!string || string === '' || string.indexOf('\r\n') === -1) {
return {
version: 'HTTP/1.1',
statusText: ''
}
}
var lines = string.split('\r\n')
var status = lines.shift()
// Remove empty strings
lines = lines.filter(Boolean)
// Parse status line
var output = this.parseStartLine(status)
// init headers object & array
output.headersObj = {}
output.headersArr = []
// Parse headers
var header
for (var i = lines.length; i--;) {
header = this.parseHeaderLine(lines[i])
output.headersArr.push(header)
output.headersObj[header.name] = header.value
}
return output
} | javascript | {
"resource": ""
} | |
q33489 | train | function (line) {
var pieces = line.split(' ')
// Header string pieces
var output = {
version: pieces.shift(),
status: parseFloat(pieces.shift()),
statusText: pieces.join(' ')
}
return output
} | javascript | {
"resource": ""
} | |
q33490 | train | function (obj) {
// sanity check
if (!obj || typeof obj !== 'object') {
return []
}
var results = []
Object.keys(obj).forEach(function (name) {
// nested values in query string
if (typeof obj[name] === 'object') {
obj[name].forEach(function (value) {
results.push({
name: name,
value: value
})
})
return
}
results.push({
name: name,
value: obj[name]
})
})
return results
} | javascript | {
"resource": ""
} | |
q33491 | train | function (headers, key, def) {
if (headers instanceof Array) {
var regex = new RegExp(key, 'i')
for (var i = 0; i < headers.length; i++) {
if (regex.test(headers[i].name)) {
return headers[i].value
}
}
}
return def !== undefined ? def : false
} | javascript | {
"resource": ""
} | |
q33492 | train | function (req) {
var keys = Object.keys(req.headers)
var values = keys.map(function (key) {
return req.headers[key]
})
var headers = req.method + req.url + keys.join() + values.join()
// startline: [method] [url] HTTP/1.1\r\n = 12
// endline: \r\n = 2
// every header + \r\n = * 2
// add 2 for each combined header
return new Buffer(headers).length + (keys.length * 2) + 2 + 12 + 2
} | javascript | {
"resource": ""
} | |
q33493 | train | function () {
var done = this.async();
var questions = [];
var choices = [
{
name: 'Standard Preset',
value: 'standard'
},
{
name: 'Minimum Preset',
value: 'minimum'
},
{
name: 'Custom Configuration (Advanced)',
value: 'custom'
}
];
var defaultType = 'standard';
if (!this.skipWelcomeMessage) {
this.log(yosay('Welcome to ' + this.pkg.name + ' v' + this.pkg.version));
}
if (!this.configType) {
if (this.config.existed) {
choices.splice(2, 0, {
name: 'User Preset',
value: 'user'
});
defaultType = 'user';
}
questions.push({
type: 'list',
name: 'configType',
message: 'Setup Type',
choices: choices,
default: defaultType
});
}
this.prompt(questions, function (answers) {
if (typeof answers.configType !== 'undefined') {
this.configType = answers.configType;
}
// Preset for skipping prompt
switch (this.configType) {
case 'standard':
this.preset = standardPreset;
break;
case 'minimum':
this.preset = minimumPreset;
break;
case 'user':
this.preset = this.config.getAll();
break;
case 'custom':
this.preset = {};
break;
}
// Initial settings
this.settings = _.assign({}, defaultConfig, this.config.getAll());
done();
}.bind(this));
} | javascript | {
"resource": ""
} | |
q33494 | train | function () {
this.cfg = {};
// Copy from prompt settings
Object.keys(this.settings).forEach(function (key) {
this.cfg[key] = this.settings[key];
}.bind(this));
// Boolean config
options.forEach(function (option) {
var name = option.name;
option.choices.forEach(function (choice) {
var value = choice.value;
switch (option.type) {
case 'list':
this.cfg[value] = value === this.cfg[name];
break;
case 'checkbox':
this.cfg[value] = _.includes(this.cfg[name], value);
break;
}
}.bind(this));
}.bind(this));
// Extra config
this.cfg.slugName = _s.slugify(this.cfg.name);
this.cfg.testing = this.cfg.mocha || this.cfg.jasmine;
this.cfg.cssSourceMap = (this.cfg.css && this.cfg.autoprefixer) ||
this.cfg.sass ||
(this.cfg.less && (this.cfg.autoprefixer || this.cfg.cssmin));
this.cfg.jsSourceMap = this.cfg.coffee;
} | javascript | {
"resource": ""
} | |
q33495 | Wallet | train | function Wallet (options) {
this.priv = typeof options.priv === 'string' ?
bitcoin.ECKey.fromWIF(options.priv) :
options.priv
typeforce(typeforce.Object, this.priv)
typeforce({
blockchain: typeforce.Object,
networkName: typeforce.String
}, options)
assert(options.networkName in bitcoin.networks, 'unknown network: ' + options.networkName)
this.txs = []
this.pub = this.priv.pub
this.networkName = options.networkName
this.address = this.pub.getAddress(bitcoin.networks[this.networkName])
this.addressString = this.address.toString()
this.blockchain = options.blockchain
} | javascript | {
"resource": ""
} |
q33496 | visitTypedVariableDeclarator | train | function visitTypedVariableDeclarator(traverse, node, path, state) {
var ctx = new Context(state);
if (node.init) {
utils.catchup(node.init.range[0], state);
utils.append(ctx.getProperty('check') + '(', state);
traverse(node.init, path, state);
utils.catchup(node.init.range[1], state);
utils.append(', ' + ctx.getType(node.id.typeAnnotation.typeAnnotation) + ')', state);
}
utils.catchup(node.range[1], state);
return false;
} | javascript | {
"resource": ""
} |
q33497 | visitTypedFunction | train | function visitTypedFunction(traverse, node, path, state) {
var klass = getParentClassDeclaration(path);
var generics = klass && klass.typeParameters ? toLookup(klass.typeParameters.params.map(getName)) : {};
if (node.typeParameters) {
generics = mixin(generics, toLookup(node.typeParameters.params.map(getName)));
}
var ctx = new Context(state, generics);
var rest = node.rest ? ', ' + ctx.getType(node.rest.typeAnnotation.typeAnnotation) : '';
var types = [];
var params = [];
node.params.forEach(function (param) {
var type = ctx.getType(param.typeAnnotation ? param.typeAnnotation.typeAnnotation : null);
types.push(param.optional ? ctx.getProperty('optional') + '(' + type + ')' : type);
params.push(param.name);
});
utils.catchup(node.body.range[0] + 1, state);
if (params.length || rest) {
utils.append(ctx.getProperty('check') + '(arguments, ' + ctx.getProperty('arguments') + '([' + types.join(', ') + ']' + rest + '));', state);
}
if (node.returnType) {
var returnType = ctx.getType(node.returnType.typeAnnotation);
utils.append(' var ret = (function (' + params.join(', ') + ') {', state);
traverse(node.body, path, state);
utils.catchup(node.body.range[1] - 1, state);
utils.append('}).apply(this, arguments); return ' + ctx.getProperty('check') + '(ret, ' + returnType + ');', state);
} else {
traverse(node.body, path, state);
}
return false;
} | javascript | {
"resource": ""
} |
q33498 | visitTypeAlias | train | function visitTypeAlias(traverse, node, path, state) {
var ctx = new Context(state);
utils.catchup(node.range[1], state);
utils.append('var ' + node.id.name + ' = ' + ctx.getType(node.right) + ';', state);
return false;
} | javascript | {
"resource": ""
} |
q33499 | train | function (type) {
var handlers = { 'html': beautify.html, 'css': beautify.css, 'js': beautify.js };
if (type === undefined) {
return beautify;
}
if (type in handlers) {
return handlers[type];
}
throw new Error('Unrecognized beautifier type:', type);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.