_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q52700
|
train
|
function(options) {
var t = this,
json = {id: t.get('probeId')};
// Transfer all non-monitor attrs
_.each(t.toJSON(options), function(value, key) {
if (!(key in t.defaults)) {
json[key] = value;
}
});
return json;
}
|
javascript
|
{
"resource": ""
}
|
|
q52701
|
train
|
function(name, params, callback) {
var t = this,
controlFn = t[name + '_control'],
startTime = Date.now(),
errMsg,
logId = 'onControl.' + t.probeClass + '.' + name;
params = params || {};
callback = callback || function(){};
log.info(logId, t.get('id'), params);
if (!controlFn) {
errMsg = 'No control function: ' + name;
log.error(logId, errMsg);
return callback({msg: errMsg});
}
var whenDone = function(error) {
if (error) {
log.error(logId + '.whenDone', error);
return callback(error);
}
var duration = Date.now() - startTime;
log.info(logId, params);
stat.time(t.logId, duration);
callback.apply(null, arguments);
};
// Run the control on next tick. This provides a consistent callback
// chain for local and remote probes.
setTimeout(function(){
try {
controlFn.call(t, params, whenDone);
} catch (e) {
errMsg = 'Error calling control: ' + t.probeClass + ':' + name;
whenDone({msg:errMsg, err: e.toString()});
}
}, 0);
}
|
javascript
|
{
"resource": ""
}
|
|
q52702
|
train
|
function(attrs, callback) {
var t = this,
writableAttributes = t.get('writableAttributes') || [];
// Validate the attributes are writable
if (writableAttributes !== '*') {
for (var attrName in attrs) {
if (writableAttributes.indexOf(attrName) < 0) {
return callback({code:'NOT_WRITABLE', msg: 'Attribute not writable: ' + attrName});
}
}
}
// Set the data
var error = null;
if (!t.set(attrs)) {
error = {code:'VALIDATION_ERROR', msg:'Data set failed validation'};
log.warn('set_control', error);
}
return callback(error);
}
|
javascript
|
{
"resource": ""
}
|
|
q52703
|
train
|
function(options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
options = options || {};
callback = callback || function(){};
var t = this, server = t.get('server'), error,
startTime = Date.now(),
port = options.port || Config.Monitor.serviceBasePort,
attempt = options.attempt || 1,
allowExternalConnections = Config.Monitor.allowExternalConnections;
// Recursion detection. Only scan for so many ports
if (attempt > Config.Monitor.portsToScan) {
error = {err:'connect:failure', msg: 'no ports available'};
log.error('start', error);
return callback(error);
}
// Bind to an existing server, or create a new server
if (server) {
t.bindEvents(callback);
} else {
server = Http.createServer();
// Try next port if a server is listening on this port
server.on('error', function(err) {
if (err.code === 'EADDRINUSE') {
// Error if the requested port is in use
if (t.get('port')) {
log.error('portInUse',{host:host, port:port});
return callback({err:'portInUse'});
}
// Try the next port
log.info('portInUse',{host:host, port:port});
return t.start({port:port + 1, attempt:attempt + 1}, callback);
}
// Unknown error
callback(err);
});
// Allow connections from INADDR_ANY or LOCALHOST only
var host = allowExternalConnections ? '0.0.0.0' : '127.0.0.1';
// Start listening, callback on success
server.listen(port, host, function(){
// Set a default NODE_APP_INSTANCE based on the available server port
if (!process.env.NODE_APP_INSTANCE) {
process.env.NODE_APP_INSTANCE = '' + (port - Config.Monitor.serviceBasePort + 1);
}
// Record the server & port, and bind incoming events
t.set({server: server, port: port});
t.bindEvents(callback);
log.info('listening', {
appName: Config.Monitor.appName,
NODE_APP_INSTANCE: process.env.NODE_APP_INSTANCE,
listeningOn: host,
port: port
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52704
|
train
|
function(callback) {
var t = this, server = t.get('server'), router = Monitor.getRouter();
callback = callback || function(){};
// Call the callback, but don't stop more than once.
if (!t.isListening) {
return callback();
}
// Release resources
t.connections.each(router.removeConnection, router);
t.connections.reset();
// Shut down the server
t.isListening = false;
server.close();
// Send notices
t.trigger('stop');
return callback();
}
|
javascript
|
{
"resource": ""
}
|
|
q52705
|
train
|
function(firewall) {
var t = Monitor.getRouter(); // This is a static method
t.firewall = firewall;
log.info('setFirewall', firewall);
}
|
javascript
|
{
"resource": ""
}
|
|
q52706
|
train
|
function(options) {
var t = this;
options.gateway = false; // New connection can't be an inbound gateway
options.firewall = true; // Gateways are for outbound requests only
return t.defaultGateway = t.addConnection(options);
}
|
javascript
|
{
"resource": ""
}
|
|
q52707
|
train
|
function() {
var localStorage = root.localStorage;
if (!hostName) {
if (localStorage) {hostName = localStorage.hostName;}
hostName = hostName || Monitor.generateUniqueId();
if (localStorage) {localStorage.hostName = hostName;}
}
return hostName;
}
|
javascript
|
{
"resource": ""
}
|
|
q52708
|
train
|
function(options) {
var t = this,
startTime = Date.now();
// Default the firewall value
if (_.isUndefined(options.firewall)) {
options = _.extend({},options, {firewall: t.firewall});
}
// Generate a unique ID for the connection
options.id = Monitor.generateUniqueCollectionId(t.connections);
var connStr = 'Conn_' + options.id;
if (options.hostName) {
connStr += ' - ' + options.hostName + ':' + options.hostPort;
}
log.info('addConnection', connStr);
// Instantiate and add the connection for use, once connected
var connection = new Connection(options);
// Add a connect and disconnect function
var onConnect = function(){
t.trigger('connection:add', connection);
log.info('connected', connStr, (Date.now() - startTime) + 'ms');
};
var onDisconnect = function(){
t.removeConnection(connection);
connection.off('connect', onConnect);
connection.off('disconnect', onConnect);
log.info('disconnected', connStr, (Date.now() - startTime) + 'ms');
};
connection.on('connect', onConnect);
connection.on('disconnect', onDisconnect);
// Add to the connections
t.connections.add(connection);
return connection;
}
|
javascript
|
{
"resource": ""
}
|
|
q52709
|
train
|
function(connection) {
var t = this;
log.info('removeConnection', 'Conn_' + connection.id);
connection.disconnect('connection_removed');
t.connections.remove(connection);
t.trigger('connection:remove', connection);
}
|
javascript
|
{
"resource": ""
}
|
|
q52710
|
train
|
function(monitor, reason, callback) {
callback = callback || function(){};
var t = this, probe = monitor.probe, probeId = monitor.get('probeId');
// The monitor must be connected
if (!probe) {return callback('Monitor must be connected');}
// Called upon disconnect (internal or external)
var onDisconnect = function(error) {
if (error) {
return callback(error);
}
probe.off('change', monitor.probeChange);
monitor.set({probeId:null});
monitor.probe = monitor.probeChange = null;
return callback(null, reason);
};
// Disconnect from an internal or external probe
if (probe.connection) {
t.disconnectExternal(probe.connection, probeId, onDisconnect);
} else {
t.disconnectInternal(probeId, onDisconnect);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52711
|
train
|
function(probeJSON) {
var probeKey = probeJSON.probeClass,
initParams = probeJSON.initParams;
// Allow probes to be externally identified by name
if (probeJSON.probeName) {
return probeJSON.probeName;
}
if (initParams) {
_.keys(initParams).sort().forEach(function(key){
probeKey += ':' + key + '=' + initParams[key];
});
}
return probeKey;
}
|
javascript
|
{
"resource": ""
}
|
|
q52712
|
train
|
function(hostName, appName, appInstance) {
var t = this, thisInstance = 0;
return t.connections.find(function(conn) {
// Host or app matches if not specified or if specified and equal
var matchesHost = !hostName || conn.isThisHost(hostName);
var matchesApp = !appName || appName === conn.get('remoteAppName');
var matchesInstance = !appInstance || appInstance === conn.get('remoteAppInstance');
var remoteFirewall = conn.get('remoteFirewall');
// This is a match if host + app + instance matches, and it's not firewalled
return (!remoteFirewall && matchesHost && matchesApp && matchesInstance);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52713
|
train
|
function(hostName, appName) {
var t = this;
return t.connections.filter(function(conn) {
// Host or app matches if not specified or if specified and equal
var matchesHost = !hostName || conn.isThisHost(hostName);
var matchesApp = !appName || appName === conn.get('remoteAppName');
var remoteFirewall = conn.get('remoteFirewall');
// This is a match if host + app matches, and it's not firewalled
return (!remoteFirewall && matchesHost && matchesApp);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52714
|
train
|
function(hostName, callback) {
var t = this,
errStr = '',
connectedPorts = [],
portStart = Config.Monitor.serviceBasePort,
portEnd = Config.Monitor.serviceBasePort + Config.Monitor.portsToScan - 1;
// Create an array to hold callbacks for this host
if (!t.addHostCallbacks[hostName]) {
t.addHostCallbacks[hostName] = [];
}
// Remember this callback and return if we're already adding connections for this host
if (t.addHostCallbacks[hostName].push(callback) > 1) {
return;
}
// Called when done
var doneAdding = function(error) {
t.addHostCallbacks[hostName].forEach(function(cb) {
cb(error);
});
delete t.addHostCallbacks[hostName];
};
// Build the list of ports already connected
t.connections.each(function(connection){
var host = connection.get('hostName').toLowerCase();
var port = connection.get('hostPort');
if (host === hostName && port >= portStart && port <= portEnd) {
connectedPorts.push(port);
}
});
// Scan non-connected ports
var portsToScan = Config.Monitor.portsToScan - connectedPorts.length;
if (portsToScan === 0) {
errStr = 'All monitor ports in use. Increase the Config.Monitor.portsToScan configuration';
log.error('addHostConnections', errStr);
return doneAdding(errStr);
}
var doneScanning = function() {
var conn = this; // called in the context of the connection
conn.off('connect disconnect error', doneScanning);
if (--portsToScan === 0) {
return doneAdding();
}
};
for (var i = portStart; i <= portEnd; i++) {
if (connectedPorts.indexOf(i) < 0) {
var connection = t.addConnection({hostName:hostName, hostPort:i});
connection.on('connect disconnect error', doneScanning, connection);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52715
|
train
|
function(error) {
t.addHostCallbacks[hostName].forEach(function(cb) {
cb(error);
});
delete t.addHostCallbacks[hostName];
}
|
javascript
|
{
"resource": ""
}
|
|
q52716
|
train
|
function(probeId, callback) {
var t = this, probeImpl = t.runningProbesById[probeId];
if (!probeImpl) {return callback('Probe not running');}
if (--probeImpl.refCount === 0) {
// Release probe resources & internal references if still no references after a while
setTimeout(function() {
if (probeImpl.refCount === 0) {
try {
probeImpl.release();
} catch (e){}
delete t.runningProbesByKey[probeImpl.probeKey];
delete t.runningProbesById[probeId];
}
}, PROBE_TIMEOUT_MS);
}
callback(null, probeImpl);
}
|
javascript
|
{
"resource": ""
}
|
|
q52717
|
train
|
function(monitorJSON, connection, callback) {
// Build a key for this probe from the probeClass and initParams
var t = this,
errStr = '',
probeKey = t.buildProbeKey(monitorJSON);
// Get the probe proxy
var probeId = connection.remoteProbeIdsByKey[probeKey];
var probeProxy = connection.remoteProbesById[probeId];
if (!probeProxy) {
// Connect with the remote probe
connection.emit('probe:connect', monitorJSON, function(error, probeJSON){
if (error) {
errStr = "probe:connect returned an error for probeClass '" + monitorJSON.probeClass +
"' on " + Monitor.toServerString(monitorJSON);
return callback({err: error, msg: errStr});
}
probeId = probeJSON.id;
// See if the proxy was created while waiting for return
probeProxy = connection.remoteProbesById[probeId];
if (probeProxy) {
probeProxy.refCount++;
log.info('connectExternal.connected.existingProxy', {probeId: probeId, refCount: probeProxy.refCount, whileWaiting: true});
return callback(null, probeProxy);
}
// Create the probe proxy
probeProxy = new Probe(probeJSON);
probeProxy.refCount = 1;
probeProxy.connection = connection;
connection.remoteProbeIdsByKey[probeKey] = probeId;
connection.remoteProbesById[probeId] = probeProxy;
connection.addEvent('probe:change:' + probeId, function(attrs){probeProxy.set(attrs);});
log.info('connectExternal.connected.newProxy', {probeId: probeId});
return callback(null, probeProxy);
});
return;
}
// Probes are released based on reference count
probeProxy.refCount++;
log.info('connectExternal.connected.existingProxy', {probeId: probeId, refCount: probeProxy.refCount});
return callback(null, probeProxy);
}
|
javascript
|
{
"resource": ""
}
|
|
q52718
|
train
|
function(connection, probeId, callback) {
var t = this, proxy = connection.remoteProbesById[probeId];
if (!proxy) {return callback('Probe not running');}
if (--proxy.refCount === 0) {
// Release probe resources
proxy.release();
proxy.connection = null;
delete connection.remoteProbesById[probeId];
delete connection.remoteProbeIdsByKey[proxy.probeKey];
connection.removeEvent('probe:change:' + probeId);
return connection.emit('probe:disconnect', {probeId:probeId}, function(error){
return callback(error);
});
}
callback(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q52719
|
train
|
function(error) {
// Don't connect the instance monitor if errors
if (error) {
return callback(error);
}
// Called to disconnect the listeners
var disconnectListeners = function() {
logger.info('disconnectLiveSync', t.className, model.toJSON());
model.off('change', modelListener);
model.syncMonitor.off('change', monitorListener);
model.syncMonitor.disconnect();
model.syncMonitor = null;
};
// Client-side listener - for persisting changes to the server
var modelListener = function(changedModel, options) {
options = options || {};
// Don't persist unless the model is different
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(model.syncMonitor.get('model'))))) {
logger.info('modelListener.noChanges', t.className, model.toJSON());
return;
}
// Disconnect listeners if the ID changes
if (model.get('id') !== modelId) {
logger.info('modelListener.alteredId', t.className, model.toJSON());
return disconnectListeners();
}
// Persist changes to the server (unless the changes originated from there)
if (!options.isSyncChanging) {
logger.info('modelListener.saving', t.className, model.toJSON());
model.save();
}
};
// Server-side listener - for updating server changes into the model
var monitorListener = function(changedModel, options) {
// Don't update unless the model is different
var newModel = model.syncMonitor.get('model');
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(newModel)))) {
logger.info('monitorListener.noChanges', t.className, newModel);
return;
}
// Disconnect if the model was deleted or the ID isn't the same
var isDeleted = (_.size(newModel) === 0);
if (isDeleted || newModel.id !== modelId) {
logger.info('modelListener.deleted', t.className, newModel);
disconnectListeners();
}
// Forward changes to the model (including server-side delete)
var newOpts = {isSyncChanging:true};
if (isDeleted) {
logger.info('modelListener.deleting', t.className, newModel);
model.clear(newOpts);
} else {
// Make sure the model is set to exactly the new contents (vs. override)
logger.info('modelListener.setting', t.className, newModel);
model.clear({silent:true});
model.set(newModel, newOpts);
}
};
// Connect the listeners
model.on('change', modelListener);
model.syncMonitor.on('change', monitorListener);
// Send back the initial data model
logger.info('connectInstanceMonitor.done', t.className, model.toJSON());
callback(null, model.syncMonitor.get('model'));
}
|
javascript
|
{
"resource": ""
}
|
|
q52720
|
train
|
function() {
logger.info('disconnectLiveSync', t.className, model.toJSON());
model.off('change', modelListener);
model.syncMonitor.off('change', monitorListener);
model.syncMonitor.disconnect();
model.syncMonitor = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q52721
|
train
|
function(changedModel, options) {
options = options || {};
// Don't persist unless the model is different
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(model.syncMonitor.get('model'))))) {
logger.info('modelListener.noChanges', t.className, model.toJSON());
return;
}
// Disconnect listeners if the ID changes
if (model.get('id') !== modelId) {
logger.info('modelListener.alteredId', t.className, model.toJSON());
return disconnectListeners();
}
// Persist changes to the server (unless the changes originated from there)
if (!options.isSyncChanging) {
logger.info('modelListener.saving', t.className, model.toJSON());
model.save();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52722
|
train
|
function(params, callback) {
var t = this,
connectError = false,
monitors = t.get('monitors');
if (t.get('started')) {
var err = {code:'RUNNING', msg:'Cannot start - the recipe is already running.'};
logger.warn(err);
return callback(err);
}
// Called when a monitor has connected
var onConnect = function(error) {
if (connectError) {return;}
if (error) {
var err = {code:'CONNECT_ERROR', err: error};
connectError = true;
logger.error('start', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (!t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:true});
t.connectListeners(true);
callback();
};
// Connect all monitors
for (var name2 in monitors) {
t.monitors[name2] = new Monitor(monitors[name2]);
t.monitors[name2].connect(onConnect);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52723
|
train
|
function(error) {
if (connectError) {return;}
if (error) {
var err = {code:'CONNECT_ERROR', err: error};
connectError = true;
logger.error('start', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (!t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:true});
t.connectListeners(true);
callback();
}
|
javascript
|
{
"resource": ""
}
|
|
q52724
|
train
|
function(params, callback) {
var t = this,
disconnectError = false;
if (!t.get('started')) {
var err = {code:'NOT_RUNNING', msg:'The recipe is already stopped.'};
logger.warn('precondition', err);
return callback(err);
}
// Called when a monitor has disconnected
var onDisconnect = function(error) {
if (disconnectError) {return;}
if (error) {
var err = {code:'DISONNECT_ERROR', err: error};
disconnectError = true;
logger.error('onDisconnect', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:false});
t.compiledScript = null;
callback();
};
// Disconnect all monitors
t.connectListeners(false);
t.context = null;
for (var name2 in t.monitors) {
t.monitors[name2].disconnect(onDisconnect);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52725
|
train
|
function(error) {
if (disconnectError) {return;}
if (error) {
var err = {code:'DISONNECT_ERROR', err: error};
disconnectError = true;
logger.error('onDisconnect', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:false});
t.compiledScript = null;
callback();
}
|
javascript
|
{
"resource": ""
}
|
|
q52726
|
train
|
function(connect) {
var t = this,
triggeredBy = t.get('triggeredBy'),
onTrigger = t.onTrigger.bind(t);
// Default to listen on changes to all monitors
if (!triggeredBy) {
for (var monitorName in t.monitors) {
t.monitors[monitorName][connect ? 'on' : 'off']('change', t.onTrigger, t);
}
return;
}
// Process the elements in triggeredBy
for (var name in triggeredBy) {
var value = triggeredBy[name];
// Construct a new cron job
if (name === 'cron') {
if (connect) {
t.cronJob = new Cron.CronJob(value, onTrigger);
}
else {
if (t.cronJob.initiated) {
clearInterval(t.CronJob.timer);
}
else {
setTimeout(function(){clearInterval(t.cronJob.timer);}, 1000);
}
}
}
// Set a polling interval
else if (name === 'interval') {
if (connect) {
t.interval = setInterval(onTrigger, value);
}
else {
clearInterval(t.interval);
t.interval = null;
}
}
// Must be a monitor name
else {
t.monitors[name][connect ? 'on' : 'off'](value, onTrigger);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52727
|
train
|
function(params, callback) {
var t = this,
error = null;
if (!t.get('started')) {
error = {code:'NOT_RUNNING', msg:'Cannot run - recipe not started.'};
logger.warn(error);
return callback(error);
}
// Name the probe
t.name = t.get('probeName') || t.get('id');
// Build a context to pass onto the script. The context contains
// a console, a logger, and each monitor by name.
if (!t.context) {
t.context = vm ? vm.createContext({}) : {};
t.context.console = console;
t.context.logger = Monitor.getLogger('Recipe.run.' + t.name);
for (var monitorName in t.monitors) {
t.context[monitorName] = t.monitors[monitorName];
}
}
// Run the script
try {
t.run(t.context);
} catch(e) {
error = "Error running script: " + e.toString();
logger.error('run_control', error);
}
callback(error);
}
|
javascript
|
{
"resource": ""
}
|
|
q52728
|
train
|
function(context) {
var varName,
localVars = [];
for (varName in context) {
localVars.push('var ' + varName + ' = context.' + varName + ';');
}
return localVars.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
|
q52729
|
train
|
function(item) {
var t = this,
now = Date.now(),
msSinceLastSend = now - t.lastSendTime;
// Queue the item
t.queue.push(item);
// Send the bundle?
if (msSinceLastSend > t.interval) {
// It's been a while since the last send. Send it now.
t._send();
}
else {
// Start the timer if it's not already running
if (!t.timer) {
t.timer = setTimeout(function(){
t._send();
}, t.interval - msSinceLastSend);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52730
|
train
|
function() {
var t = this,
now = Date.now();
// This kicks off the send
t.lastSendTime = now;
t.set({
bundle: t.queue,
sequence: t.get('sequence') + 1
});
// Reset
t.queue = [];
if (t.timer) {
clearTimeout(t.timer);
t.timer = null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52731
|
train
|
function(error, content) {
var isInitializing = (callback !== null),
initCallback = callback;
callback = null;
if (error && error.code === 'ENOENT') {
// File doesn't exist. Set the model to null.
t.set({model: {}}, {silent: isInitializing});
// Convert the code from the sync probe spec
error.code = 'NOTFOUND';
}
if (error) {
if (isInitializing) {
t.release();
var err = {code: error.code, msg: 'LiveSync requires the file to exist and be readable'};
initCallback(err);
}
return;
}
// Parse the JSON content into a JS object.
try {
content = JSON.parse(content);
logger.info('fileParse', {id: t.get('modelId'), content: content});
} catch (e) {
// Fail the probe on first load error
if (isInitializing) {
t.release();
initCallback({code: 'BAD_FORMAT', msg: 'Non-JSON formatted file'});
}
// Nothing productive to do if the file can't be parsed. Just log it.
logger.error('fileParse', {error: e, id: t.get('modelId'), content: content});
return;
}
// Set the content into the model if it's different
// Have to compare raw objects because toJSON returns deep references to models
var priorModel = t.get('model');
if (!priorModel || !_.isEqual(content, JSON.parse(JSON.stringify(priorModel)))) {
t.set({model: content}, {silent: isInitializing});
}
// Call the initialization callback on first load
if (isInitializing) {
initCallback();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52732
|
train
|
function(args, callback) {
// Make sure the ID exists
var t = this, model = args.model;
if (!model || !model.id) {
return callback({msg:'SyncProbe create - Data model with ID not present'});
}
// Make sure the file doesn't already exist
t.getFullPath(model.id, function(error, response) {
if (error) {
return callback(error);
}
if (response.stats) {
return callback({msg:'Document with this ID already exists'});
}
// Forward to the update control
t.update_control(args, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52733
|
train
|
function(modelId, callback) {
var t = this,
dirPath = t.dirPath;
// Don't allow relative paths
var fullPath = Path.join(t.dirPath, modelId);
if (fullPath.indexOf(dirPath) !== 0) {
return callback({msg: 'Model ID ' + modelId + ' cannot represent a relative path'});
}
// See if the path represents a directory
FS.stat(fullPath, function(error, stats){
// If this is an existing directory, return a path to dir/index.json
if (!error && stats.isDirectory()) {
return t.getFullPath(modelId + '/index', callback);
}
// Normal case - return the path & stat to the json file
fullPath += '.json';
FS.stat(fullPath, function(error, stats){
// Not an error if error == ENOENT
if (error && error.code === 'ENOENT') {
error = null; stats = null;
}
// Process other FS errors
if (error) {
return callback({err: error, msg: "Error while observing file: " + fullPath});
}
// Forward the callback
return callback(null, {path: fullPath, stats: stats});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52734
|
extend
|
train
|
function extend() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !typeof target === 'function')
target = {};
var isPlainObject = function(obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval)
return false;
var has_own_constructor = hasOwnProperty.call(obj, "constructor");
var has_is_property_of_method = hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf");
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
return false;
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var last_key;
for (key in obj)
last_key = key;
return typeof last_key === "undefined" || hasOwnProperty.call(obj, last_key);
};
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) !== null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy)
continue;
// Recurse if we're merging object literal values or arrays
if (deep && copy && (isPlainObject(copy) || Array.isArray(copy))) {
var clone = src && (isPlainObject(src) || Array.isArray(src)) ? src : Array.isArray(copy) ? [] : {};
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (typeof copy !== "undefined")
target[name] = copy;
}
}
}
// Return the modified object
return target;
}
|
javascript
|
{
"resource": ""
}
|
q52735
|
transformFactory
|
train
|
function transformFactory(methods) {
var length = methods.length
return transformer
// Transformer.
function transformer(cst) {
visit(cst, visitor)
}
function visitor(node, position, parent) {
var index = -1
if (node.type === punctuation || node.type === symbol) {
while (++index < length) {
methods[index](node, position, parent)
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q52736
|
oldschool
|
train
|
function oldschool(node) {
if (node.value === threeDashes) {
node.value = emDash
} else if (node.value === twoDashes) {
node.value = enDash
}
}
|
javascript
|
{
"resource": ""
}
|
q52737
|
inverted
|
train
|
function inverted(node) {
if (node.value === threeDashes) {
node.value = enDash
} else if (node.value === twoDashes) {
node.value = emDash
}
}
|
javascript
|
{
"resource": ""
}
|
q52738
|
backticks
|
train
|
function backticks(node) {
if (node.value === twoBackticks) {
node.value = openingDoubleQuote
} else if (node.value === twoSingleQuotes) {
node.value = closingDoubleQuote
}
}
|
javascript
|
{
"resource": ""
}
|
q52739
|
all
|
train
|
function all(node) {
backticks(node)
if (node.value === backtick) {
node.value = openingSingleQuote
} else if (node.value === singleQuote) {
node.value = closingSingleQuote
}
}
|
javascript
|
{
"resource": ""
}
|
q52740
|
ellipses
|
train
|
function ellipses(node, index, parent) {
var value = node.value
var siblings = parent.children
var position
var nodes
var sibling
var type
var count
var queue
// Simple node with three dots and without white-space.
if (threeFullStopsExpression.test(node.value)) {
node.value = ellipsis
return
}
if (!fullStopsExpression.test(value)) {
return
}
// Search for dot-nodes with white-space between.
nodes = []
position = index
count = 1
// It’s possible that the node is merged with an adjacent word-node. In that
// code, we cannot transform it because there’s no reference to the
// grandparent.
while (--position > 0) {
sibling = siblings[position]
if (sibling.type !== whiteSpace) {
break
}
queue = sibling
sibling = siblings[--position]
type = sibling && sibling.type
if (
sibling &&
(type === punctuation || type === symbol) &&
fullStopsExpression.test(sibling.value)
) {
nodes.push(queue, sibling)
count++
continue
}
break
}
if (count < 3) {
return
}
siblings.splice(index - nodes.length, nodes.length)
node.value = ellipsis
}
|
javascript
|
{
"resource": ""
}
|
q52741
|
quotes
|
train
|
function quotes(node, index, parent) {
var siblings = parent.children
var value = node.value
var next
var nextNext
var prev
var nextValue
if (value !== doubleQuote && value !== singleQuote) {
return
}
prev = siblings[index - 1]
next = siblings[index + 1]
nextNext = siblings[index + 2]
nextValue = next && nlcstToString(next)
if (
next &&
nextNext &&
(next.type === punctuation || next.type === symbol) &&
nextNext.type !== word
) {
// Special case if the very first character is a quote followed by
// punctuation at a non-word-break. Close the quotes by brute force.
node.value = closingQuotes[value]
} else if (
nextNext &&
(nextValue === doubleQuote || nextValue === singleQuote) &&
nextNext.type === word
) {
// Special case for double sets of quotes:
// `He said, "'Quoted' words in a larger quote."`
node.value = openingQuotes[value]
next.value = openingQuotes[nextValue]
} else if (next && decadeExpression.test(nextValue)) {
// Special case for decade abbreviations: `the '80s`
node.value = closingQuotes[value]
} else if (
prev &&
next &&
(prev.type === whiteSpace ||
prev.type === punctuation ||
prev.type === symbol) &&
next.type === word
) {
// Get most opening single quotes.
node.value = openingQuotes[value]
} else if (
prev &&
(prev.type !== whiteSpace &&
prev.type !== symbol &&
prev.type !== punctuation)
) {
// Closing quotes.
node.value = closingQuotes[value]
} else if (
!next ||
next.type === whiteSpace ||
((value === singleQuote || value === apostrophe) && nextValue === 's')
) {
node.value = closingQuotes[value]
} else {
node.value = openingQuotes[value]
}
}
|
javascript
|
{
"resource": ""
}
|
q52742
|
padToEven
|
train
|
function padToEven(value) {
var a = value; // eslint-disable-line
if (typeof a !== 'string') {
throw new Error(`[ethjs-util] while padding to even, value must be string, is currently ${typeof a}, while padToEven.`);
}
if (a.length % 2) {
a = `0${a}`;
}
return a;
}
|
javascript
|
{
"resource": ""
}
|
q52743
|
arrayContainsArray
|
train
|
function arrayContainsArray(superset, subset, some) {
if (Array.isArray(superset) !== true) { throw new Error(`[ethjs-util] method arrayContainsArray requires input 'superset' to be an array got type '${typeof superset}'`); }
if (Array.isArray(subset) !== true) { throw new Error(`[ethjs-util] method arrayContainsArray requires input 'subset' to be an array got type '${typeof subset}'`); }
return subset[Boolean(some) && 'some' || 'every']((value) => (superset.indexOf(value) >= 0));
}
|
javascript
|
{
"resource": ""
}
|
q52744
|
toUtf8
|
train
|
function toUtf8(hex) {
const bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex');
return bufferValue.toString('utf8');
}
|
javascript
|
{
"resource": ""
}
|
q52745
|
toAscii
|
train
|
function toAscii(hex) {
var str = ''; // eslint-disable-line
var i = 0, l = hex.length; // eslint-disable-line
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i += 2) {
const code = parseInt(hex.substr(i, 2), 16);
str += String.fromCharCode(code);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q52746
|
prompForPassword
|
train
|
function prompForPassword(done) {
inquirer.prompt([
{
type: 'password',
message: 'Enter the password',
name: 'password',
validate(input) {
return input.length > 0;
}
}
], answers => {
done(answers.password);
});
}
|
javascript
|
{
"resource": ""
}
|
q52747
|
parseOptions
|
train
|
function parseOptions(options) {
let opts = {};
_.each(nodecipher.defaults, (defaultVal, name) => {
if (!_.isUndefined(options[name])) {
opts[name] = options[name];
}
});
return opts;
}
|
javascript
|
{
"resource": ""
}
|
q52748
|
cipher
|
train
|
function cipher(command, input, output, options) {
if (_.isUndefined(options.password)) {
prompForPassword(password => {
cipher(command, input, output, options, _.assign(options, { password }));
});
} else {
let opts = _.assign(parseOptions(options), { input, output });
nodecipher[command](opts, err => {
handleCipher(opts, err);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q52749
|
handleCipher
|
train
|
function handleCipher(opts, err) {
if (err) {
switch (err.name) {
case nodecipher.errors.BAD_ALGORITHM:
handleInvalidAlgorithm(opts, err);
break;
case nodecipher.errors.BAD_DIGEST:
handleInvalidHash(opts, err);
break;
case nodecipher.errors.BAD_FILE:
handleEnoentError(opts, err);
break;
case nodecipher.errors.BAD_DECRYPT:
handleBadDecrypt(opts, err);
break;
default:
handleUnknownErrors(opts, err);
}
process.exit(1);
} else {
handleCipherSuccess(opts, err);
}
}
|
javascript
|
{
"resource": ""
}
|
q52750
|
handleEnoentError
|
train
|
function handleEnoentError(opts, err) {
console.log(chalk.red(
'\nError: ' + err.name + '. "' + err.path + '" does not exist.\n'
));
}
|
javascript
|
{
"resource": ""
}
|
q52751
|
train
|
function () {
var toolbarHeight = $toolbar[0].offsetHeight;
var toolbarWidth = $toolbar[0].offsetWidth;
var spacing = 5;
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var boundary = range.getBoundingClientRect();
var topPosition = boundary.top;
var leftPosition = boundary.left;
// if there isn't enough space at the top, place it at the bottom
// of the selection
if(boundary.top < (toolbarHeight + spacing)) {
scope.position.top = topPosition + boundary.height + spacing;
// tell me if it's above or below the selection
// used in the template to place the triangle above or below
scope.position.below = true;
} else {
scope.position.top = topPosition - toolbarHeight - spacing;
scope.position.below = false;
}
// center toolbar above selected text
scope.position.left = leftPosition - (toolbarWidth/2) + (boundary.width/2);
// cross-browser window scroll positions
var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
// add the scroll positions
// because getBoundingClientRect gives us the position
// relative to the viewport, not to the page
scope.position.top += scrollTop;
scope.position.left += scrollLeft;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q52752
|
train
|
function (e) {
// if you click something from the toolbar
// don't do anything
if(e && e.target && $toolbar.find(e.target).length) {
return false;
}
var newSelection = window.getSelection();
// get selection node
var anchorNode = newSelection.anchorNode;
// if nothing selected, hide the toolbar
if(newSelection.toString().trim() === '' || !anchorNode) {
// hide the toolbar
return $timeout(function() {
scope.model.showToolbar = false;
});
}
// check if selection is in the current editor/directive container
var parentNode = anchorNode.parentNode;
while (parentNode.tagName !== undefined && parentNode !== element[0]) {
parentNode = parentNode.parentNode;
}
// if the selection is in the current editor
if(parentNode === element[0]) {
// show the toolbar
$timeout(function() {
scope.model.showToolbar = true;
setToolbarPosition();
});
// check selection styles and active buttons based on it
checkActiveButtons(newSelection);
} else {
// hide the toolbar
$timeout(function() {
scope.model.showToolbar = false;
});
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q52753
|
train
|
function (selection) {
var parentNode = selection.anchorNode;
if (!parentNode.tagName) {
parentNode = selection.anchorNode.parentNode;
}
var childNode = parentNode.childNodes[0];
if(childNode && childNode.tagName && childNode.tagName.toLowerCase() in generatedTags) {
parentNode = parentNode.childNodes[0];
}
$timeout(function() {
// get real styles of selected element
scope.styles = window.getComputedStyle(parentNode, null);
if(scope.styles.fontSize !== scope.size.label + 'px') {
// set font size selector
angular.forEach(scope.sizeOptions, function(size, i) {
if(scope.styles.fontSize === (size.label + 'px')) {
scope.size = scope.sizeOptions[i].value;
return false;
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52754
|
replaceResponse
|
train
|
function replaceResponse(res) {
// copy for response.headers.hasOwnProperty is undefined case
// https://github.com/oauthjs/node-oauth2-server/pull/486
const newResponse = {
headers: {},
};
for (const property in res) {
if (property !== 'headers') {
newResponse[property] = res[property];
}
}
for (const field in res.headers) {
newResponse.headers[field] = res.headers[field];
}
newResponse.header = newResponse.headers;
return newResponse;
}
|
javascript
|
{
"resource": ""
}
|
q52755
|
train
|
function(url, callback) {
logger('Fetching URL resource: ' + url);
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
} else {
var errorString = [
'There was an error loading the requested resource',
'>>> ' + url
];
if (error) {
errorString.push(error.toString('utf8'));
}
errorHandler(errorString.join('\n'));
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52756
|
train
|
function(filePath, callback) {
if (!fs.existsSync(filePath)) {
errorHandler("File " + filePath + " does not exist. Please specify a valid path.");
}
var body = '';
var reader = fs.createReadStream(filePath);
reader.on('data', function(chunks) {
body += chunks;
}).on('end', function() {
callback(body);
}).on('error', function(e) {
throw e;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52757
|
getName
|
train
|
function getName(str) {
var name = path.basename(str);
if (name.lastIndexOf('.') === -1) {
name += '.json';
}
return name;
}
|
javascript
|
{
"resource": ""
}
|
q52758
|
handleOutput
|
train
|
function handleOutput(destConfig, jsonString) {
var type = destConfig.type,
destPath = destConfig.path,
defaultFileName = destConfig.defaultFileName,
force = destConfig.force,
pretty = destConfig.pretty;
if (!type || type === "omit") {
// don't even bother
return;
}
if (pretty) {
jsonString = prettyData.pd.json(jsonString);
}
switch (type) {
case IOType.FILE:
writeFile(jsonString, destPath, defaultFileName, force);
break;
case IOType.STDOUT:
stdout(jsonString);
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q52759
|
train
|
function ( name, opts ) {
if ( ! name ) {
return cbk( new Error( "Geocoder.selectProvider requires a name.") );
}
this.provider = name;
this.providerOpts = opts || {};
this.providerObj = require("./providers/"+name);
}
|
javascript
|
{
"resource": ""
}
|
|
q52760
|
train
|
function ( loc, cbk, opts ) {
if ( ! loc ) {
return cbk( new Error( "Geocoder.geocode requires a location.") );
}
return this.providerObj.geocode(this.providerOpts, loc, cbk, opts);
}
|
javascript
|
{
"resource": ""
}
|
|
q52761
|
concurrent
|
train
|
function concurrent(scripts) {
const {colors, scripts: quotedScripts, names} = Object.keys(scripts)
.reduce(reduceScripts, {
colors: [],
scripts: [],
names: [],
})
const flags = [
'--kill-others-on-fail',
`--prefix-colors "${colors.join(',')}"`,
'--prefix "[{name}]"',
`--names "${names.join(',')}"`,
shellEscape(quotedScripts),
]
const concurrently = runBin('concurrently')
return `${concurrently} ${flags.join(' ')}`
function reduceScripts(accumulator, scriptName, index) {
let scriptObj = scripts[scriptName]
if (!scriptObj) {
return accumulator
} else if (typeof scriptObj === 'string') {
scriptObj = {script: scriptObj}
}
const {
script,
color = defaultColors[index % defaultColors.length],
} = scriptObj
if (!script) {
return accumulator
}
accumulator.names.push(scriptName)
accumulator.colors.push(color)
accumulator.scripts.push(script)
return accumulator
}
}
|
javascript
|
{
"resource": ""
}
|
q52762
|
includePackage
|
train
|
function includePackage(packageNameOrOptions) {
const packageScriptsPath = typeof packageNameOrOptions === 'string' ?
`./packages/${packageNameOrOptions}/package-scripts.js` :
packageNameOrOptions.path
const startingDir = process.cwd().split('\\').join('/')
const relativeDir = path
.relative(startingDir, path.dirname(packageScriptsPath))
.split('\\')
.join('/')
const relativeReturn = path
.relative(relativeDir, startingDir)
.split('\\')
.join('/')
const scripts = require(packageScriptsPath)
// eslint-disable-next-line
function replace(obj, prefix) {
const retObj = {}
const dot = prefix ? '.' : ''
for (const key in obj) {
if (key === 'description') {
retObj[key] = obj[key]
} else if (key === 'script') {
retObj[key] = series(
`cd ${relativeDir}`,
`npm start ${prefix}`,
`cd "${relativeReturn}"`,
)
} else if (typeof obj[key] === 'string') {
retObj[key] = series(
`cd ${relativeDir}`,
`npm start ${prefix}${dot}${key}`,
)
} else {
retObj[key] = Object.assign(
{},
replace(obj[key], `${prefix}${dot}${key}`, `cd "${startingDir}"`),
)
}
}
return retObj
}
return replace(scripts.scripts, '')
}
|
javascript
|
{
"resource": ""
}
|
q52763
|
getBin
|
train
|
function getBin(packageName, binName = packageName) {
const packagePath = require.resolve(`${packageName}/package.json`)
const concurrentlyDir = path.dirname(packagePath)
let {bin: binRelativeToPackage} = require(packagePath)
if (typeof binRelativeToPackage === 'object') {
binRelativeToPackage = binRelativeToPackage[binName]
}
const fullBinPath = path.join(concurrentlyDir, binRelativeToPackage)
return path.relative(process.cwd(), fullBinPath)
}
|
javascript
|
{
"resource": ""
}
|
q52764
|
done
|
train
|
function done(failures, fn, reportersWithDone, waitFor = identity) {
const count = reportersWithDone.length;
const waitReporter = waitOn((r, f) => r.done(failures, f));
const progress = v => debug('Awaiting on %j reporters to invoke done callback.', count - v);
promiseProgress(reportersWithDone.map(waitReporter), progress)
.then(() => {
debug('All reporters invoked done callback.');
})
.then(waitFor)
.then(() => fn && fn(failures));
}
|
javascript
|
{
"resource": ""
}
|
q52765
|
needsSubtitution
|
train
|
function needsSubtitution(prop) {
var needsSub = false;
if (typeof prop === 'string') {
if (prop.indexOf('#{INDEX}') !== -1) needsSub = true;
} else if (typeof prop === 'object') {
var str = JSON.stringify(prop);
if (str.indexOf('#{INDEX}') !== -1) needsSub = true;
}
return needsSub;
}
|
javascript
|
{
"resource": ""
}
|
q52766
|
substituteFnWhereNeeded
|
train
|
function substituteFnWhereNeeded(actions) {
actions = actions || [];
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
if ((key === 'get' || key === 'head' || key === 'put' || key === 'post' || key === 'del' || key === 'patch') &&
needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return action[key].replace(/\#\{INDEX\}/g, tokens.INDEX);
};
} else if (key === 'json' && needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return JSON.parse(JSON.stringify(action[key]).replace(/\#\{INDEX\}/g, tokens.INDEX));
};
} else if (key === 'body' && typeof action.body === 'string' && needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return action[key].replace(/\#\{INDEX\}/g, tokens.INDEX);
};
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
}
|
javascript
|
{
"resource": ""
}
|
q52767
|
bindSubtituteFnsWithTokens
|
train
|
function bindSubtituteFnsWithTokens(actions, tokens) {
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
// if it is list of sub keys, and is a fn, then bind with tokens
if (SUBSTITUTED_KEYS.indexOf(key) !== -1 && typeof action[key] === 'function') {
accum[key] = action[key].bind(null, tokens);
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
}
|
javascript
|
{
"resource": ""
}
|
q52768
|
execAnySubFns
|
train
|
function execAnySubFns(actions) {
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
// if it is list of sub keys, and is a fn, then bind with tokens
if (SUBSTITUTED_KEYS.indexOf(key) !== -1 && typeof action[key] === 'function') {
accum[key] = action[key](); // exec fn to get value
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
}
|
javascript
|
{
"resource": ""
}
|
q52769
|
train
|
function(scope, element, attrs, autoCtrl){
element.bind('mouseenter', function() {
autoCtrl.preSelect(attrs.val);
autoCtrl.setIndex(attrs.index);
});
element.bind('mouseleave', function() {
autoCtrl.preSelectOff();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52770
|
train
|
function (data) {
var lines = data.match(/[^\r\n]+/g); //cut lines
return lines.map(function (line) {
try {
return JSON.parse(line);
} catch (e) {
return line;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52771
|
playback
|
train
|
function playback(resHeaders, resBody) {
if (!forceLive) {
var headerContent = fs.readFileSync(filename + '.headers');
resHeaders = JSON.parse(headerContent);
}
var socket = new EventEmitter();
socket.setTimeout = socket.setEncoding = function() {};
// Needed for node 0.8.x
socket.destroy = socket.pause = socket.resume = function() {};
req.socket = socket;
req.emit('socket', socket);
if (resHeaders.timeout) {
socket.emit('timeout');
req.emit('error', new Error('Timeout'));
return;
}
if (resHeaders.error) {
req.emit('error', resHeaders.error);
return;
}
var res = new http.IncomingMessage(socket);
res.headers = resHeaders.headers || {};
res.statusCode = resHeaders.statusCode;
if (callback) {
callback(res);
}
if (!forceLive) {
resBody = fs.readFileSync(filename);
}
req.emit('response', res);
if (res.push) {
// node 0.10.x
res.push(resBody);
res.push(null);
} else {
// node 0.8.x
res.emit('data', resBody);
res.emit('end');
}
}
|
javascript
|
{
"resource": ""
}
|
q52772
|
train
|
function( arg ) {
var listItems, listItem, i, len, results;
var options = _callMethod( this, "option" );
var searched = arg instanceof $.Event ? arg.target.value : arg;
var bselect = _callMethod( this, "element" );
if ( this[ 0 ].disabled ) {
return this;
}
// Avoid searching for nothing
if ( searched === "" ) {
_callMethod( this, "clearSearch" );
}
if ( !( arg instanceof $.Event ) ) {
bselect.find( ".bselect-search" ).val( searched );
}
// Same search/few chars? We won't search then!
if (
( searched === options.lastSearch ) ||
( searched.length < options.minSearchInput )
) {
return;
}
// Initialize the result collection
results = $();
listItems = bselect.find( "li" ).hide();
for ( i = 0, len = listItems.length; i < len; i++ ) {
listItem = listItems[ i ];
if ( listItem.textContent.toLowerCase().indexOf( searched.toLowerCase() ) > -1 ) {
results = results.add( $( listItem ).show() );
}
}
if ( results.length === 0 ) {
showNoOptionsAvailable( this );
} else {
bselect.find( ".bselect-message" ).hide();
}
this.trigger( "bselectsearch", [ searched, results ] );
adjustDropdownHeight( listItems.end() );
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q52773
|
train
|
function() {
var bselect = _callMethod( this, "element" );
var optionList = bselect.find( ".bselect-option-list" ).empty();
var mapping = {};
var i = 0;
bselect.toggleClass( "disabled", this.prop( "disabled" ) );
this.find( "option, > optgroup" ).each(function() {
var classes, li;
var isOption = $( this ).is( "option" );
if ( isOption && !this.value ) {
return;
}
if ( isOption ) {
classes = "bselect-option";
if ( $( this ).closest( "optgroup" ).length ) {
classes += " grouped";
}
} else {
classes = "bselect-option-group";
}
li = $( "<li />" ).attr({
"class": classes,
// While there aren't roles for optgroup, we'll stick with the role option.
role: "option",
tabindex: isOption ? 2 : -1,
"aria-selected": "false"
});
if ( isOption ) {
li.data( "value", this.value );
mapping[ this.value ] = i;
li.html( "<a href='#'>" + this.text + "</a>" );
} else {
li.text( this.label );
}
li.appendTo( optionList );
i++;
});
if ( i === 0 ) {
showNoOptionsAvailable( this );
}
this.data( dataName ).itemsMap = mapping;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q52774
|
adjustDropdownHeight
|
train
|
function adjustDropdownHeight( $elem ) {
var list = $elem.find( ".bselect-option-list" );
var len = list.find( "li:visible" ).length;
list.innerHeight( parseInt( list.css( "line-height" ), 10 ) * 1.5 * ( len < 5 ? len : 5 ) );
}
|
javascript
|
{
"resource": ""
}
|
q52775
|
updateOptions
|
train
|
function updateOptions( $elem, prev, curr ) {
var bselect = _callMethod( $elem, "element" );
$.each( prev, function(key, val) {
if ( curr[ key ] !== val ) {
if ( key === "size" ) {
var sizes = $.map( bootstrapButtonSizes.slice( 0 ), function( size ) {
return "bselect-" + size;
}).join( " " );
bselect.removeClass( sizes );
if ( bootstrapButtonSizes.indexOf( curr.size ) > -1 ) {
bselect.addClass( "bselect-" + curr.size );
}
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q52776
|
showNoOptionsAvailable
|
train
|
function showNoOptionsAvailable( $elem ) {
var bselect = _callMethod( $elem, "element" );
bselect.find( ".bselect-message" ).text( $.bselect.i18n.noOptionsAvailable ).show();
}
|
javascript
|
{
"resource": ""
}
|
q52777
|
setup
|
train
|
function setup( elem, options ) {
var caret, label, container, id, dropdown;
var $elem = $( elem );
// First of, let's build the base HTML of BSelect
id = ++elements;
container = $( "<div class='bselect' />", {
id: "bselect-" + id
});
dropdown = $( "<div class='bselect-dropdown' />" );
// Configure the search input
if ( options.searchInput === true ) {
var search = $( "<div class='bselect-search' />" );
$( "<input type='text' class='bselect-search-input' />" ).attr({
role: "combobox",
tabindex: 1,
"aria-expanded": "false",
"aria-owns": "bselect-option-list-" + id
// The W3C documentation says that role="combobox" should have aria-autocomplete,
// but the validator tells us that this is invalid. Very strange.
//"aria-autocomplete": "list"
}).appendTo( search );
$( "<span class='bselect-search-icon' />" )
.append( "<i class='icon-search'></i>" )
.appendTo( search );
search.appendTo( dropdown );
}
$( "<div class='bselect-message' role='status' />" ).appendTo( dropdown );
$( "<ul class='bselect-option-list' />" ).attr({
id: "bselect-option-list-" + id,
role: "listbox"
}).appendTo( dropdown );
container.append( dropdown ).insertAfter( $elem );
// Save some precious data in the original select now, as we have the container in the DOM
$elem.data( dataName, {
options: options,
element: container,
open: false
});
updateOptions( $elem, $.bselect.defaults, options );
_callMethod( $elem, "refresh" );
$elem.bind( "bselectselect.bselect", options.select );
$elem.bind( "bselectselected.bselect", options.selected );
$elem.bind( "bselectsearch.bselect", options.search );
label = $( "<span />" ).addClass( "bselect-label" ).text( getPlaceholder( $elem ) );
caret = $( "<button type='button' />" ).addClass( "bselect-caret" )
.html( "<span class='caret'></span>" );
container.prepend( caret ).prepend( label );
label.outerWidth( $elem.outerWidth() - caret.outerWidth() );
// Hide this ugly select!
$elem.addClass( "bselect-inaccessible" );
// We'll cache the container for some actions
instances.push( $elem );
// Event binding
container.find( ".bselect-search-input" ).keyup( $.proxy( methods.search, $elem ) );
container.on( "click", ".bselect-option", $.proxy( methods.select, $elem ) );
container.on( "click", ".bselect-caret, .bselect-label", $.proxy( methods.toggle, $elem ) );
container.on( "keydown", ".bselect-option, .bselect-search-input", handleKeypress );
// Issue #6 - Listen to the change event and update the selected value
$elem.bind( "change.bselect", function() {
var data = $elem.data( dataName );
var index = data.itemsMap[ this.value ];
if ( data.tempDisable ) {
data.tempDisable = false;
return;
}
_callMethod( $elem, "select", index );
}).trigger( "change.bselect" );
}
|
javascript
|
{
"resource": ""
}
|
q52778
|
someCollections
|
train
|
function someCollections(db, collections, next) {
var last = ~~collections.length, counter = 0;
if (last === 0) { // empty set
return next(null);
}
collections.forEach(function(collection) {
db.collection(collection, function(err, collection) {
logger('select collection ' + collection.collectionName);
if (err) {
return last === ++counter ? next(err) : error(err);
}
collection.drop(function(err) {
if (err) {
error(err); // log if missing
}
return last === ++counter ? next(null) : null;
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q52779
|
strFromEnvironmentVarSetting
|
train
|
function strFromEnvironmentVarSetting(functionsVar, envVar) {
if (!process.env[envVar]) {
const msg = `${envVar} does not exist on within environment variables`
warn(msg)
return ''
}
return `${functionsVar}="${process.env[envVar]}"`
}
|
javascript
|
{
"resource": ""
}
|
q52780
|
createConfigSetString
|
train
|
function createConfigSetString(mapEnvSettings) {
const settingsStrsArr = map(mapEnvSettings, strFromEnvironmentVarSetting)
const settingsStr = compact(settingsStrsArr).join(' ')
// Get project from passed options, falling back to branch name
const projectKey = getProjectKey(mapEnvSettings)
return `firebase functions:config:set ${settingsStr} -P ${projectKey}`
}
|
javascript
|
{
"resource": ""
}
|
q52781
|
mergeResults
|
train
|
function mergeResults(jsRes, coffeeRes) {
if (!coffeeRes) {
return jsRes;
}
jsRes.reports = jsRes.reports.concat(coffeeRes.reports);
return escomplex.processResults(jsRes, cli.nocoresize || false);
}
|
javascript
|
{
"resource": ""
}
|
q52782
|
train
|
function(file, cb) {
zip.entry(fs.createReadStream(file.path), { name: file.name }, cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q52783
|
hmacSha1
|
train
|
function hmacSha1 (options) {
return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
}
|
javascript
|
{
"resource": ""
}
|
q52784
|
readFile
|
train
|
function readFile(file) {
return new Promise(
(resolve, reject) => {
fs.readFile(
file, 'utf8', (error, contents) => {
if (error) {
reject(error);
} else {
// console.log('readFile', [file, contents]);
resolve(contents);
}
}
)
}
);
}
|
javascript
|
{
"resource": ""
}
|
q52785
|
writeFile
|
train
|
function writeFile(file, contents) {
return new Promise(
(resolve, reject) => {
fs.writeFile(
file, contents, error => {
if (error) {
reject(error);
} else {
// console.log('writeFile', [file, contents]);
resolve(contents);
}
}
)
}
);
}
|
javascript
|
{
"resource": ""
}
|
q52786
|
writeFile
|
train
|
function writeFile(filepath, data, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof cb !== 'function') {
return writeFile.promise.apply(null, arguments);
}
if (typeof filepath !== 'string') {
cb(new TypeError('expected filepath to be a string'));
return;
}
mkdirp(path.dirname(filepath), options, function(err) {
if (err) {
cb(err);
return;
}
var preparedData = data;
if (options && options.ensureNewLine && data.slice(-1) !== "\n") {
preparedData += "\n";
}
fs.writeFile(filepath, preparedData, options, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
q52787
|
errorHandler
|
train
|
function errorHandler(errorKey, nativeError, alternate) {
const errorMessages = {
add_characteristic_exists_error: `Characteristic ${alternate} already exists.`,
characteristic_error: `Characteristic ${alternate} not found. Add ${alternate} to device using addCharacteristic or try another characteristic.`,
connect_gatt: `Could not connect to GATT. Device might be out of range. Also check to see if filters are vaild.`,
connect_server: `Could not connect to server on device.`,
connect_service: `Could not find service.`,
disconnect_timeout: `Timed out. Could not disconnect.`,
disconnect_error: `Could not disconnect from device.`,
improper_characteristic_format: `${alternate} is not a properly formatted characteristic.`,
improper_properties_format: `${alternate} is not a properly formatted properties array.`,
improper_service_format: `${alternate} is not a properly formatted service.`,
issue_disconnecting: `Issue disconnecting with device.`,
new_characteristic_missing_params: `${alternate} is not a fully supported characteristic. Please provide an associated primary service and at least one property.`,
no_device: `No instance of device found.`,
no_filters: `No filters found on instance of Device. For more information, please visit http://sabertooth.io/#method-newdevice`,
no_read_property: `No read property on characteristic: ${alternate}.`,
no_write_property: `No write property on this characteristic.`,
not_connected: `Could not disconnect. Device not connected.`,
parsing_not_supported: `Parsing not supported for characterstic: ${alternate}.`,
read_error: `Cannot read value on the characteristic.`,
_returnCharacteristic_error: `Error accessing characteristic ${alternate}.`,
start_notifications_error: `Not able to read stream of data from characteristic: ${alternate}.`,
start_notifications_no_notify: `No notify property found on this characteristic: ${alternate}.`,
stop_notifications_not_notifying: `Notifications not established for characteristic: ${alternate} or you have not started notifications.`,
stop_notifications_error: `Issue stopping notifications for characteristic: ${alternate} or you have not started notifications.`,
user_cancelled: `User cancelled the permission request.`,
uuid_error: `Invalid UUID. For more information on proper formatting of UUIDs, visit https://webbluetoothcg.github.io/web-bluetooth/#uuids`,
write_error: `Could not change value of characteristic: ${alternate}.`,
write_permissions: `${alternate} characteristic does not have a write property.`
}
throw new Error(errorMessages[errorKey]);
return false;
}
|
javascript
|
{
"resource": ""
}
|
q52788
|
styleFn
|
train
|
function styleFn(prefix, cssProp) {
return function (style) {
if (!style.size) {
return {};
}
var value = style.filter(function (val) {
return val.startsWith(prefix);
}).first();
if (value) {
var newVal = value.replace(prefix, '');
return _defineProperty({}, (0, _lodash2.default)(cssProp), newVal);
}
return {};
};
}
|
javascript
|
{
"resource": ""
}
|
q52789
|
findModuleFromOptions
|
train
|
function findModuleFromOptions(host, options) {
if (options.hasOwnProperty('skipImport') && options.skipImport) {
return undefined;
}
if (!options.module) {
const pathToCheck = (options.sourceDir || '') + '/' + (options.path || '')
+ (options.flat ? '' : '/' + strings_1.dasherize(options.name));
return core_1.normalize(findModule(host, pathToCheck));
}
else {
const modulePath = core_1.normalize('/' + options.sourceDir + '/' + (options.appRoot || options.path) + '/' + options.module);
const moduleBaseName = core_1.normalize(modulePath).split('/').pop();
if (host.exists(modulePath)) {
return core_1.normalize(modulePath);
}
else if (host.exists(modulePath + '.ts')) {
return core_1.normalize(modulePath + '.ts');
}
else if (host.exists(modulePath + '.module.ts')) {
return core_1.normalize(modulePath + '.module.ts');
}
else if (host.exists(modulePath + '/' + moduleBaseName + '.module.ts')) {
return core_1.normalize(modulePath + '/' + moduleBaseName + '.module.ts');
}
else {
throw new Error('Specified module does not exist');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q52790
|
findModule
|
train
|
function findModule(host, generateDir) {
let dir = host.getDir('/' + generateDir);
const moduleRe = /\.module\.ts$/;
const routingModuleRe = /-routing\.module\.ts/;
while (dir) {
const matches = dir.subfiles.filter(p => moduleRe.test(p) && !routingModuleRe.test(p));
if (matches.length == 1) {
return core_1.join(dir.path, matches[0]);
}
else if (matches.length > 1) {
throw new Error('More than one module matches. Use skip-import option to skip importing '
+ 'the component into the closest module.');
}
dir = dir.parent;
}
throw new Error('Could not find an NgModule for the new component. Use the skip-import '
+ 'option to skip importing components in NgModule.');
}
|
javascript
|
{
"resource": ""
}
|
q52791
|
buildRelativePath
|
train
|
function buildRelativePath(from, to) {
from = core_1.normalize(from);
to = core_1.normalize(to);
// Convert to arrays.
const fromParts = from.split('/');
const toParts = to.split('/');
// Remove file names (preserving destination)
fromParts.pop();
const toFileName = toParts.pop();
const relativePath = core_1.relative(core_1.normalize(fromParts.join('/')), core_1.normalize(toParts.join('/')));
let pathPrefix = '';
// Set the path prefix for same dir or child dir, parent dir starts with `..`
if (!relativePath) {
pathPrefix = '.';
}
else if (!relativePath.startsWith('.')) {
pathPrefix = `./`;
}
if (pathPrefix && !pathPrefix.endsWith('/')) {
pathPrefix += '/';
}
return pathPrefix + (relativePath ? relativePath + '/' : '') + toFileName;
}
|
javascript
|
{
"resource": ""
}
|
q52792
|
getPreciseType
|
train
|
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
|
javascript
|
{
"resource": ""
}
|
q52793
|
setCanvasSize
|
train
|
function setCanvasSize (width, height) {
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
}
|
javascript
|
{
"resource": ""
}
|
q52794
|
getPointRelativeToCanvas
|
train
|
function getPointRelativeToCanvas (point) {
return {
x: point.x / canvas.width,
y: point.y / canvas.height
};
}
|
javascript
|
{
"resource": ""
}
|
q52795
|
getCursorRelativeToCanvas
|
train
|
function getCursorRelativeToCanvas (e) {
var cur = {};
if (isTouchEvent(e)) {
cur.x = e.touches[0].pageX - canvas.offsetLeft;
cur.y = e.touches[0].pageY - canvas.offsetTop;
} else {
var rect = that.canvas.getBoundingClientRect();
cur.x = e.clientX - rect.left;
cur.y = e.clientY - rect.top;
}
return getPointRelativeToCanvas(cur);
}
|
javascript
|
{
"resource": ""
}
|
q52796
|
clearCanvas
|
train
|
function clearCanvas () {
context.clearRect(0, 0, canvas.width, canvas.height);
if (opts.backgroundColor) {
context.fillStyle = opts.backgroundColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
}
|
javascript
|
{
"resource": ""
}
|
q52797
|
normalizePoint
|
train
|
function normalizePoint (point) {
return {
x: point.x * canvas.width,
y: point.y * canvas.height
};
}
|
javascript
|
{
"resource": ""
}
|
q52798
|
drawStroke
|
train
|
function drawStroke (stroke) {
context.beginPath();
for (var j = 0; j < stroke.points.length - 1; j++) {
var start = normalizePoint(stroke.points[j]);
var end = normalizePoint(stroke.points[j + 1]);
context.moveTo(start.x, start.y);
context.lineTo(end.x, end.y);
}
context.closePath();
context.strokeStyle = stroke.color;
context.lineWidth = normalizeLineSize(stroke.size);
context.lineJoin = stroke.join;
context.lineCap = stroke.cap;
context.miterLimit = stroke.miterLimit;
context.stroke();
}
|
javascript
|
{
"resource": ""
}
|
q52799
|
redraw
|
train
|
function redraw () {
clearCanvas();
for (var i = 0; i < that.strokes.length; i++) {
drawStroke(that.strokes[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.