_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q14900
|
getInstanceInfo
|
train
|
function getInstanceInfo(machineName, versionKey, instanceKey) {
let route = getInstanceInfoRoute(machineName, versionKey, instanceKey);
return jsonfile.readFileSync(repositoryPath + "/" + route);
}
|
javascript
|
{
"resource": ""
}
|
q14901
|
setInstanceInfo
|
train
|
function setInstanceInfo(machineName, versionKey, instanceKey, info, withCommit, message) {
let route = getInstanceInfoRoute(machineName, versionKey, instanceKey);
jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2});
if(withCommit) {
return _commit(null, [route],
message || "Changed the info for the " + instanceKey + " of the " +
versionKey + " of the '" + machineName + "' machine");
}
}
|
javascript
|
{
"resource": ""
}
|
q14902
|
addInstance
|
train
|
function addInstance(machineName, versionKey) {
return co(function*() {
debug("Adding a new instance to the " + versionKey + " of the '" + machineName + "' machine");
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let versionInfo = getVersionInfo(machineName, versionKey);
if(!versionInfo.isSealed) {
throw new Error("The version is not sealed yet");
}
let newInstanceKey = "instance" + (Object.keys(version.instances).length + 1);
let instanceDirPath = version.route + "/instances/" + newInstanceKey;
let instanceSnapshotsDirPath = instanceDirPath + "/snapshots";
version.instances[newInstanceKey] = {
"route": instanceDirPath,
"snapshots": {}
};
let infoFile = instanceDirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + instanceDirPath);
fs.mkdirSync(repositoryPath + "/" + instanceSnapshotsDirPath);
debug("Creating the instance info.json file");
let info = {
"hasStarted": false,
"hasEnded": false
};
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", infoFile],
"Created the "+newInstanceKey+" for the "+versionKey+" of the '" + machineName + "' machine");
return newInstanceKey;
});
}
|
javascript
|
{
"resource": ""
}
|
q14903
|
getSnapshotsKeys
|
train
|
function getSnapshotsKeys(machineName, versionKey, instanceKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
return Object.keys(instance.snapshots);
}
|
javascript
|
{
"resource": ""
}
|
q14904
|
getSnapshotRoute
|
train
|
function getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
let snapshot = instance.snapshots[snapshotKey];
if (!snapshot) {
throw new Error("Snapshot does not exists");
}
return snapshot.route;
}
|
javascript
|
{
"resource": ""
}
|
q14905
|
getSnapshotInfoRoute
|
train
|
function getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey) {
return getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey) + "/info.json";
}
|
javascript
|
{
"resource": ""
}
|
q14906
|
getSnapshotInfo
|
train
|
function getSnapshotInfo(machineName, versionKey, instanceKey, snapshotKey) {
let route = getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey);
return jsonfile.readFileSync(repositoryPath + "/" + route);
}
|
javascript
|
{
"resource": ""
}
|
q14907
|
addSnapshot
|
train
|
function addSnapshot(machineName, versionKey, instanceKey, info) {
return co(function*() {
debug("Adding a new snapshot to the " + instanceKey + " of the " + versionKey + " of the '" + machineName + "' machine");
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
let newSnapshotKey = "snapshot" + (Object.keys(instance.snapshots).length + 1);
let snapshotDirPath = instance.route + "/snapshots/" + newSnapshotKey;
instance.snapshots[newSnapshotKey] = {
"route": snapshotDirPath
};
let infoFile = snapshotDirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + snapshotDirPath);
debug("Creating the snapshot info.json file");
let info = {
};
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", infoFile],
"Created the "+newSnapshotKey+" for the "+instanceKey+" of the "+
versionKey+" of the '" + machineName + "' machine");
return newSnapshotKey;
});
}
|
javascript
|
{
"resource": ""
}
|
q14908
|
writeSourceMap
|
train
|
function writeSourceMap(srcpath, destpath, options, f) {
var path = require('path')
, SourceMapGenerator = require('source-map').SourceMapGenerator
, sourceMap = new SourceMapGenerator({file: path.basename(destpath)})
, sourceMapDest = destpath + '.map'
, sourceMappingUrl = encodeURIComponent(path.basename(sourceMapDest))
, res = f(sourceMap) + (options.sourceMap ?
'//@ sourceMappingURL=' + sourceMappingUrl + '\n' : ''
)
, _ = (function(){
if (options.sourceMap) {
grunt.file.write(sourceMapDest, sourceMap.toString());
grunt.file.copy(srcpath, path.join.apply(path, [
path.dirname(destpath),
path.basename(srcpath)
]));
}
}())
;
return res;
}
|
javascript
|
{
"resource": ""
}
|
q14909
|
train
|
function (sig, fn) {
var isArr = toType(fn) === 'array';
sig || (sig = []);
map[sig.join('::').toLowerCase()] = {
fn: isArr ? passObject(fn) : fn,
inject: isArr ? true : (fn.length > sig.length)
};
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q14910
|
train
|
function () {
return function () {
var args = Array.prototype.slice.call(arguments, 0);
var sig = (function () {
var ret = [];
for (var i = 0, len = args.length; i < len; i++) {
ret.push(toType(args[i]));
}
return ret;
})().join('::');
if (map[sig]) {
if (map[sig].inject) args.unshift(input);
return map[sig].fn.apply(ctx || null, args);
}
return input && input.apply(ctx || null, args);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14911
|
request
|
train
|
async function request(cb) {
// get name of current service, stop if it's `config-srv` itself
const name = nconf.get('server:name') || 'test-srv';
let data = {};
if (name === 'config-srv') return cb(null, data);
// setup & connect with config-srv on first run
// if (!client && fs.existsSync(fullProtoPath))
const config = _.clone(nconf.get('config-srv'));
let service;
if (config.transports
&& config.transports.grpc
&& config.transports.service) {
client = new grpcClient.Client(config);
service = await co(client.connect());
} else {
throw new Error('Missing configuration details');
}
await co(service.get({
filter: client.toStruct({ name: name })
}));
// TODO: continue
// fetch the latest configuration data if possible
client.get({ field: [{ name }] }, (err, res) => {
if (err) return cb(err, null);
if (res.data) data = res.data;
// update/mutate the nconf store and return
nconf.use('default', data);
return cb(null, nconf);
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
q14912
|
train
|
function() {
this.force_first = true;
this.relpath = '';
this.root = process.cwd();
this.counters = {
files: 0,
dependencies: 0,
depAddUpd: 0
};
this.error = null;
this.exit = null;
this.temp = '';
this.files = [];
this.dependecies = [];
this.package = null;
this.settings = null;
this.options = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q14913
|
train
|
function(xdata, ndata) {
try {
const npkg = JSON.parse(ndata||'{}');
const xpkg = xdata?JSON.parse(xdata):JSON.parse(ndata||'{}');
_managePkg(npkg, xpkg);
_initPkg(xpkg);
xdata = JSON.stringify(xpkg, null, 2);
_log('package.json managed: %s', xdata);
} catch(err){
console.error(err);
}
return xdata;
}
|
javascript
|
{
"resource": ""
}
|
|
q14914
|
_checkPathX
|
train
|
function _checkPathX(relfolder, skipCreation) {
if (!relfolder) return;
const parts = relfolder.split(path.sep);
var checked = _state.root;
var checkedParts = '';
var index = 0;
var skip = false;
do {
checked = path.join(checked, parts[index]);
if (!fs.existsSync(checked)) {
if (!skipCreation) {
fs.mkdirSync(checked);
checkedParts = path.join(checkedParts, parts[index]);
} else {
skip = true;
}
} else {
checkedParts = path.join(checkedParts, parts[index]);
}
index++;
} while (!skip && index < parts.length);
return checkedParts;
}
|
javascript
|
{
"resource": ""
}
|
q14915
|
getColorScore
|
train
|
function getColorScore(_ref, positions) {
var startRow = _ref.startRow,
endRow = _ref.endRow;
var score = positions.reduce(function (newScore, p) {
if (p.y === endRow) newScore.winners += 1;else newScore.preWinnersPoints += endRow === 0 ? startRow - p.y : p.y;
return newScore;
}, getInitialColorScore());
score.won = score.winners === positions.length;
return score;
}
|
javascript
|
{
"resource": ""
}
|
q14916
|
getScore
|
train
|
function getScore(board) {
var pieces = Board.getPiecesFromBoard(board);
var startEndRows = Board.getStartEndRows(board);
var white = getColorScore(startEndRows.white, pieces.white);
var black = getColorScore(startEndRows.black, pieces.black);
return {
ended: white.won || black.won,
white: white,
black: black
};
}
|
javascript
|
{
"resource": ""
}
|
q14917
|
gatherer
|
train
|
function gatherer(received) {
// delete reference from the wait map
const index = missing.indexOf(received.name);
if (index !== -1) missing.splice(index, 1);
// determine if the response was requested
const requested = received.requestId === event.requestId;
// if already resolved or rejected then exit now, also verify that the event is being listened for
if (pending && requested) {
// store response
if (!received.error) {
result[received.name] = received.data;
debug('Received response to request ' + received.requestId + ' from ' + received.name);
if (config.circuitbreaker && received.circuitbreakerSuccess) {
config.circuitbreaker.success();
}
} else if (config.circuitbreaker && received.circuitbreakerFault) {
debug('Received response to request ' + received.requestId + ' from ' + received.name + ' which triggered a circuitbreaker fault with the error: ' + received.error);
config.circuitbreaker.fault();
} else {
debug('Received response to request ' + received.requestId + ' from ' + received.name + ' as an error: ' + received.error);
}
// all expected responses received and min timeout passed, so resolve the deferred promise
if (missing.length === 0) {
clearTimeout(maxTimeoutId);
debug('Received all expected responses for request ' + received.requestId);
if (minTimeoutReached) {
pending = false;
deferred.resolve(result);
}
}
if (config.each) {
const meta = {
active: pending,
minWaitReached: minTimeoutReached,
missing: missing.slice(0)
};
const done = function (err) {
pending = false;
if (err) return deferred.reject(err);
deferred.resolve(result);
};
config.each(received, meta, done);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14918
|
train
|
function(name, acl) {
if (_.isString(name) && (acl instanceof Parse.ACL)) {
Parse.Object.prototype.constructor.call(this, null, null);
this.setName(name);
this.setACL(acl);
} else {
Parse.Object.prototype.constructor.call(this, name, acl);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14919
|
MultiLine
|
train
|
function MultiLine()
{
MultiLine.prototype.parse_and_print = function(msg, colour)
{
var out = [];
for (var i = 0; i < msg.length; i++)
{
var msg_item = msg[i];
if (typeof msg_item == 'object')
out.push(colour + RESET + util.inspect(msg_item, false, 50, true) + RESET + colour);
else
out.push(msg_item);
}
this.print(colour + out.join(' ') + colour + " " + RESET);
};
MultiLine.prototype.info = function(msg)
{
this.parse_and_print(msg, GREEN);
};
MultiLine.prototype.mark = function(msg)
{
this.parse_and_print(msg, LIGHT_GREEN);
};
MultiLine.prototype.error = function(msg)
{
this.parse_and_print(msg, RED);
};
MultiLine.prototype.warn = function(msg)
{
this.parse_and_print(msg, YELLOW);
};
MultiLine.prototype.print = function(msg)
{
console.log(msg);
};
}
|
javascript
|
{
"resource": ""
}
|
q14920
|
SingleLine
|
train
|
function SingleLine()
{
SingleLine.prototype.print = function(msg)
{
var result = check();
if (result.success)
{
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(msg);
}
else
MultiLine.prototype.print('missed method: ' + result.required_method + ' ' + msg);
};
SingleLine.prototype.info = function(msg)
{
this.parse_and_print(arguments, GREEN);
};
SingleLine.prototype.mark = function(msg)
{
this.parse_and_print(arguments, LIGHT_GREEN);
};
SingleLine.prototype.error = function(msg)
{
this.parse_and_print(arguments, RED);
};
SingleLine.prototype.warn = function(msg)
{
this.parse_and_print(arguments, YELLOW);
};
function check()
{
var check = ['clearLine', 'cursorTo', 'write'];
for (var i = 0; i < check.length; i++)
{
var method = check[i];
if (!(method in process.stdout))
return {required_method: method};
}
return {success: true};
}
}
|
javascript
|
{
"resource": ""
}
|
q14921
|
salute
|
train
|
function salute (cb) {
let value
try {
value = cb()
if (value instanceof Error) value = Promise.reject(value)
} catch (e) {
value = Promise.reject(e)
}
return value
}
|
javascript
|
{
"resource": ""
}
|
q14922
|
run
|
train
|
function run(filepath) {
var startTime = process.hrtime();
var uniqueCommand = command.replace('$path', filepath);
if (!argv.silent) {
console.log('>', uniqueCommand);
}
execshell(uniqueCommand);
if (!argv.silent) {
console.log('Finished in', prettyHrtime(process.hrtime(startTime)));
}
}
|
javascript
|
{
"resource": ""
}
|
q14923
|
getParkings
|
train
|
function getParkings(latitude, longitude, radius, type, params, callback) {
if(!latitude || !longitude || !radius) {
callback(new Error("Parking.getParkings: latitude, longitude and radius required"));
return;
}
params = params || {};
params.latitude = latitude;
params.longitude = longitude;
params.radius = radius;
var subResource;
switch(type) {
case 'bus': subResource = 'BusParkings';
break;
case 'handicap': subResource = 'HandicapParkings';
break;
case 'mc': subResource = 'MCParkings';
break;
case 'private': subResource = 'PrivateParkings';
break;
case 'publicTime': subResource = 'PublicTimeParkings';
break;
case 'publicToll': subResource = 'PublicTollParkings';
break;
case 'residential': subResource = 'ResidentialParkings';
break;
case 'truck': subResource = 'TruckParkings';
break;
default:
callback(new Error("Parking.getParkings: unknown type: " + type));
}
core.callApi('/ParkingService/v1.0/' + subResource, params, callback);
}
|
javascript
|
{
"resource": ""
}
|
q14924
|
getPublicPayMachines
|
train
|
function getPublicPayMachines(latitude, longitude, radius, params, callback) {
if(!latitude || !longitude || !radius) {
callback(new Error("Parking.getPublicPayMachines: latitude, longitude and radius required"));
return;
}
params = params || {};
params.latitude = latitude;
params.longitude = longitude;
params.radius = radius;
core.callApi('/ParkingService/v1.0/PublicPayMachines', params, callback);
}
|
javascript
|
{
"resource": ""
}
|
q14925
|
sessionify
|
train
|
function sessionify (fn, session, context) {
if (!session) {
throw new Error('sessionify expects a session-cache object as `session`');
}
var bind = session.bind;
if (typeof fn === 'object' && fn.on) {
bind = session.bindEmitter;
}
if (context) {
bind.call(session, fn, context);
} else {
bind.call(session, fn);
}
return fn;
}
|
javascript
|
{
"resource": ""
}
|
q14926
|
SpawnError
|
train
|
function SpawnError (message, options) {
return errorBase('SpawnError', function (message, options) {
this.name = 'SpawnError'
this.message = message
this.code = options.code
this.buffer = options.buffer
}).call(this, message, options)
}
|
javascript
|
{
"resource": ""
}
|
q14927
|
train
|
function(api, handler) {
if( 0 === arguments.length )
throw new Error('utils.handler.register needs arguments');
if( ! _.isObject(api) )
throw new Error('utils.handler.register needs an espressojs API');
if( ! (handler instanceof Handler) )
throw new Error('utils.handler.register needs a Handler');
// Add it to _ids
api._ids[ handler.getPattern().getExpression().toString() ] = handler;
// Add it to _names if any
var name = handler.getOption('name');
if( _.isString(name) && ! _.isEmpty(name) )
api._names[ name ] = handler;
}
|
javascript
|
{
"resource": ""
}
|
|
q14928
|
train
|
function(api) {
if( ! _.isObject(api) )
throw new Error('utils.handler.buildResourceTable needs an espressojs API');
api._resources = _( api._ids ).values().reject( _.isUndefined ).value();
}
|
javascript
|
{
"resource": ""
}
|
|
q14929
|
analyzeLine
|
train
|
function analyzeLine(line, rules) {
var result = {
line: line
};
rules.rules.forEach(function (rule) {
if (rule.re.test(line)) {
line = line.replace(rule.re, rule.replace);
if (rule.emitLevel) {
if (result.emitLevel) {
result.emitLevel = Math.min(result.emitLevel, rule.emitLevel);
}
else {
result.emitLevel = rule.emitLevel;
}
}
}
});
if (!result.emitLevel) {
result.emitLevel = rules.defaultEmitLevel || 5;
}
result.colored = line;
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14930
|
getNpm
|
train
|
function getNpm() {
let execResult;
let version;
let version3;
let npm;
if (shell.which('npm')) {
execResult = shell.exec('npm --version', { silent: true });
if (execResult.code === 0) {
version = execResult.stdout;
}
}
if (version !== null && semver.satisfies(version, '>= 3.0.0')) {
npm = 'npm';
}
if (!npm) {
if (shell.which('npm3')) {
execResult = shell.exec('npm3 --version', { silent: true });
if (execResult.code === 0) {
version3 = execResult.stdout;
}
}
if (version3 === null) {
npm = 'npm';
} else {
npm = 'npm3';
}
}
return npm;
}
|
javascript
|
{
"resource": ""
}
|
q14931
|
invoke
|
train
|
function invoke(id) {
this.isPending[id] = true;
this.callbacks[id](this.pendingPayload);
this.isHandled[id] = true;
}
|
javascript
|
{
"resource": ""
}
|
q14932
|
start
|
train
|
function start(payload) {
for (var id in this.callbacks) {
this.isPending[id] = false;
this.isHandled[id] = false;
}
this.isDispatching = true;
this.pendingPayload = payload;
}
|
javascript
|
{
"resource": ""
}
|
q14933
|
train
|
function( rules, options ) {
var priority;
// Backward compatibility.
if ( typeof options == 'number' )
priority = options;
// New version - try reading from options.
else if ( options && ( 'priority' in options ) )
priority = options.priority;
// Defaults.
if ( typeof priority != 'number' )
priority = 10;
if ( typeof options != 'object' )
options = {};
// Add the elementNames.
if ( rules.elementNames )
this.elementNameRules.addMany( rules.elementNames, priority, options );
// Add the attributeNames.
if ( rules.attributeNames )
this.attributeNameRules.addMany( rules.attributeNames, priority, options );
// Add the elements.
if ( rules.elements )
addNamedRules( this.elementsRules, rules.elements, priority, options );
// Add the attributes.
if ( rules.attributes )
addNamedRules( this.attributesRules, rules.attributes, priority, options );
// Add the text.
if ( rules.text )
this.textRules.add( rules.text, priority, options );
// Add the comment.
if ( rules.comment )
this.commentRules.add( rules.comment, priority, options );
// Add root node rules.
if ( rules.root )
this.rootRules.add( rules.root, priority, options );
}
|
javascript
|
{
"resource": ""
}
|
|
q14934
|
train
|
function( rule, priority, options ) {
this.rules.splice( this.findIndex( priority ), 0, {
value: rule,
priority: priority,
options: options
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q14935
|
train
|
function( rules, priority, options ) {
var args = [ this.findIndex( priority ), 0 ];
for ( var i = 0, len = rules.length; i < len; i++ ) {
args.push( {
value: rules[ i ],
priority: priority,
options: options
} );
}
this.rules.splice.apply( this.rules, args );
}
|
javascript
|
{
"resource": ""
}
|
|
q14936
|
train
|
function( priority ) {
var rules = this.rules,
len = rules.length,
i = len - 1;
// Search from the end, because usually rules will be added with default priority, so
// we will be able to stop loop quickly.
while ( i >= 0 && priority < rules[ i ].priority )
i--;
return i + 1;
}
|
javascript
|
{
"resource": ""
}
|
|
q14937
|
train
|
function( context, currentValue ) {
var isNode = currentValue instanceof CKEDITOR.htmlParser.node || currentValue instanceof CKEDITOR.htmlParser.fragment,
// Splice '1' to remove context, which we don't want to pass to filter rules.
args = Array.prototype.slice.call( arguments, 1 ),
rules = this.rules,
len = rules.length,
orgType, orgName, ret, i, rule;
for ( i = 0; i < len; i++ ) {
// Backup the node info before filtering.
if ( isNode ) {
orgType = currentValue.type;
orgName = currentValue.name;
}
rule = rules[ i ];
if ( isRuleApplicable( context, rule ) ) {
ret = rule.value.apply( null, args );
if ( ret === false )
return ret;
// We're filtering node (element/fragment).
// No further filtering if it's not anymore fitable for the subsequent filters.
if ( isNode && ret && ( ret.name != orgName || ret.type != orgType ) )
return ret;
// Update currentValue and corresponding argument in args array.
// Updated values will be used in next for-loop step.
if ( ret != null )
args[ 0 ] = currentValue = ret;
// ret == undefined will continue loop as nothing has happened.
}
}
return currentValue;
}
|
javascript
|
{
"resource": ""
}
|
|
q14938
|
train
|
function( context, currentName ) {
var i = 0,
rules = this.rules,
len = rules.length,
rule;
for ( ; currentName && i < len; i++ ) {
rule = rules[ i ];
if ( isRuleApplicable( context, rule ) )
currentName = currentName.replace( rule.value[ 0 ], rule.value[ 1 ] );
}
return currentName;
}
|
javascript
|
{
"resource": ""
}
|
|
q14939
|
getField
|
train
|
function getField(object, fieldPath) {
let currentObject = object
for (let fieldName of fieldPath.split(".")) {
if (!currentObject.hasOwnProperty(fieldName)) {
return undefined
}
currentObject = currentObject[fieldName]
}
return currentObject
}
|
javascript
|
{
"resource": ""
}
|
q14940
|
setField
|
train
|
function setField(object, fieldPath, value) {
let currentObject = object
let fieldNames = fieldPath.split(".")
for (let fieldName of fieldNames.slice(0, -1)) {
if (!currentObject.hasOwnProperty(fieldName)) {
currentObject[fieldName] = {}
}
currentObject = currentObject[fieldName]
}
currentObject[fieldNames.pop()] = value
}
|
javascript
|
{
"resource": ""
}
|
q14941
|
train
|
function( editor, element ) {
// If editor#addRemoveFotmatFilter hasn't been executed yet value is not initialized.
var filters = editor._.removeFormatFilters || [];
for ( var i = 0; i < filters.length; i++ ) {
if ( filters[ i ]( element ) === false )
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q14942
|
format
|
train
|
function format (type, msg, typeColor, msgColor) {
type = type || '';
msg = msg || '';
typeColor = typeColor || 'blue';
msgColor = msgColor || 'grey';
type = pad(type, 12);
return type[typeColor] + ' · ' + msg[msgColor];
}
|
javascript
|
{
"resource": ""
}
|
q14943
|
createBumpVersion
|
train
|
function createBumpVersion(inPath, type) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
return function bumpVersion() {
return gulp.src(inPath)
.pipe(bump({ type }))
.pipe(gulp.dest(file => file.base));
};
}
|
javascript
|
{
"resource": ""
}
|
q14944
|
createReplaceVersion
|
train
|
function createReplaceVersion(inPath, version, opts = {}) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!version) {
throw new Error('Version argument is required');
}
const dropV = !!opts.dropV;
const versionRegex = dropV ? /[0-9]+\.[0-9]+\.[0-9]+\b/g : /v[0-9]+\.[0-9]+\.[0-9]+\b/g;
const versionString = dropV ? version : `v${version}`;
return function updateVersions() {
return gulp.src(inPath)
.pipe(replace(versionRegex, versionString))
.pipe(gulp.dest(file => file.base));
};
}
|
javascript
|
{
"resource": ""
}
|
q14945
|
extractPackageVersion
|
train
|
function extractPackageVersion(inPath) {
if (!inPath) {
throw new Error('Input path argument is required');
}
// Require here so we have the update version.
const pkg = fs.readFileSync(inPath, 'utf-8');
// index 0 is line that matched, index 1 is first control group (version number in this case)
const matches = /"version": "([0-9]+\.[0-9]+\.[0-9]+)"/.exec(pkg);
const version = matches[1];
return version;
}
|
javascript
|
{
"resource": ""
}
|
q14946
|
train
|
function( tabConfig ) {
if ( !tabConfig )
tabConfig = defaultTabConfig;
var allowedAttrs = [];
if ( tabConfig.id )
allowedAttrs.push( 'id' );
if ( tabConfig.dir )
allowedAttrs.push( 'dir' );
var allowed = '';
if ( allowedAttrs.length )
allowed += '[' + allowedAttrs.join( ',' ) + ']';
if ( tabConfig.classes )
allowed += '(*)';
if ( tabConfig.styles )
allowed += '{*}';
return allowed;
}
|
javascript
|
{
"resource": ""
}
|
|
q14947
|
download
|
train
|
function download(url) {
if (!validator.isURL(url)) return Promise.reject(error(400, 'Invalid URL: ' + url));
// download in progress
if (progress[sha]) return progress[sha];
var sha = hash(url);
return progress[sha] = cache.access(sha).then(function (filename) {
if (filename) return filename;
return request(url)
.redirects(3)
.agent(false)
.then(function (response) {
assert(response.status < 400, response.status, 'Got status code ' + response.status + ' from ' + url);
assert(response.status === 200, 'Got status code ' + response.status + ' from ' + url);
debug('Downloading %s -> %s', url, sha);
return cache.copy(sha, response.response);
});
}).then(function (filename) {
delete progress[sha];
return filename;
}, /* istanbul ignore next */ function (err) {
delete progress[sha];
throw err;
});
}
|
javascript
|
{
"resource": ""
}
|
q14948
|
train
|
function(body) {
if (_.isString(body)) {
return body;
} else if (_.isObject(body) && _.isString(body.error)) {
return body.error;
} else if (_.isObject(body) && _.isString(body.msg)) {
return body.msg;
} else if (_.isObject(body) && _.isObject(body.error)) {
return this._extractError(body.error);
} else if (_.isObject(body) && _.isString(body.message)) {
return body.message;
} else if (_.isObject(body) &&
body.meta &&
_.isString(body.meta.error_message)) {
return body.meta.error_message;
} else {
return 'Unknown Request Error';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14949
|
train
|
function(options) {
options = options || {};
// Set default path
if (!options.url && !options.path) {
options.path = '';
}
// Prepare the request
var requestOptions = {
method: options.method || 'GET',
url: options.url || this.urlRoot + options.path,
qs: options.qs || {},
headers: options.headers || {},
};
// Add `form`, `body`, or `json` as Request Payload (only one per request)
//
// If `json` is a Boolean,
// Request will set` Content-Type`
// and call `JSON.stringify()` on `body`
if (options.body) {
requestOptions.body = options.body;
requestOptions.json = _.isBoolean(options.json) ? options.json : true;
} else if (options.form) {
requestOptions.form = options.form;
requestOptions.headers['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
} else if (_.isBoolean(options.json) || _.isObject(options.json)) {
requestOptions.json = options.json;
}
// Basic HTTP Auth
if (options.auth) {
requestOptions.auth = options.auth;
}
// Access Token
var accessToken = options.access_token || this.get('access_token');
if (accessToken) {
_.defaults(requestOptions.headers, {
Authorization: ['Bearer', accessToken].join(' ')
});
}
// OAuth Token
var oauthToken = options.oauth_token || this.get('oauth_token');
if (oauthToken) {
_.defaults(requestOptions.headers, {
Authorization: ['OAuth', oauthToken].join(' ')
});
}
// Authorization Token (No Scheme)
var authorizationToken = options.authorization_token || this.get('authorization_token');
if (authorizationToken) {
_.defaults(requestOptions.headers, {
Authorization: authorizationToken
});
}
return requestOptions;
}
|
javascript
|
{
"resource": ""
}
|
|
q14950
|
train
|
function(options, callback) {
// Create a promise to defer to later
var deferred = Bluebird.defer();
// Fire the request
request(this._buildRequestOptions(options), function(err, response, body) {
// Handle Errors
if (err) {
// Usually a connection error (server unresponsive)
err = new MuniError(err.message || 'Internal Server Error', err.code || 500);
} else if (response.statusCode >= 400) {
// Usually an intentional error from the server
err = new MuniError(this._extractError(body), response.statusCode);
}
if (err) {
debug.warn('Adapter Request Error with Code: %d', err.code);
callback && callback(err);
return deferred.reject(err);
}
// Handle Success
debug.info('Adapter Request Sent with code: %d', response.statusCode);
callback && callback(null, body);
return deferred.resolve(body);
}.bind(this));
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q14951
|
monitorServer
|
train
|
function monitorServer(server) {
// executes a single check of a server
const checkServer = callback => {
let start = process.hrtime();
// emit a signal indicating we have started the heartbeat
server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name));
server.command(
'admin.$cmd',
{ ismaster: true },
{
monitoring: true,
socketTimeout: server.s.options.connectionTimeout || 2000
},
function(err, result) {
let duration = calculateDurationInMs(start);
if (err) {
server.emit(
'serverHeartbeatFailed',
new ServerHeartbeatFailedEvent(duration, err, server.name)
);
return callback(err, null);
}
const isMaster = result.result;
server.emit(
'serverHeartbeatSucceded',
new ServerHeartbeatSucceededEvent(duration, isMaster, server.name)
);
return callback(null, isMaster);
}
);
};
const successHandler = isMaster => {
server.s.monitoring = false;
// emit an event indicating that our description has changed
server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster));
// schedule the next monitoring process
server.s.monitorId = setTimeout(
() => monitorServer(server),
server.s.options.heartbeatFrequencyMS
);
};
// run the actual monitoring loop
server.s.monitoring = true;
checkServer((err, isMaster) => {
if (!err) {
successHandler(isMaster);
return;
}
// According to the SDAM specification's "Network error during server check" section, if
// an ismaster call fails we reset the server's pool. If a server was once connected,
// change its type to `Unknown` only after retrying once.
// TODO: we need to reset the pool here
return checkServer((err, isMaster) => {
if (err) {
server.s.monitoring = false;
// revert to `Unknown` by emitting a default description with no isMaster
server.emit('descriptionReceived', new ServerDescription(server.description.address));
// do not reschedule monitoring in this case
return;
}
successHandler(isMaster);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14952
|
handleNode
|
train
|
function handleNode (node, ...extraArgs) {
const cbObj = extraArgs[extraArgs.length - 1];
if (!nodeTypeToMethodMap.has(node.nodeType)) {
throw new TypeError('Not a valid `nodeType` value');
}
const methodName = nodeTypeToMethodMap.get(node.nodeType);
if (!cbObj[methodName]) {
return undefined;
}
return cbObj[methodName](node, ...extraArgs);
}
|
javascript
|
{
"resource": ""
}
|
q14953
|
parseColor
|
train
|
function parseColor (str) {
if (str.substr(0,1) === '#') {
// Handle color shorthands (like #abc)
var shorthand = str.length === 4,
m = str.match(shorthand ? /\w/g : /\w{2}/g);
if (!m) return;
m = m.map(function(s) { return parseInt(shorthand ? s+s : s, 16) });
return new nodes.RGBA(m[0],m[1],m[2],1);
}
else if (str.substr(0,3) === 'rgb'){
var m = str.match(/([0-9]*\.?[0-9]+)/g);
if (!m) return;
m = m.map(function(s){return parseFloat(s, 10)});
return new nodes.RGBA(m[0], m[1], m[2], m[3] || 1);
}
else {
var rgb = colors[str];
if (!rgb) return;
return new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1);
}
}
|
javascript
|
{
"resource": ""
}
|
q14954
|
profileBlock
|
train
|
function profileBlock(block, repeat){
repeat = repeat || DEFAULT_REPEAT_COUNT;
let start = process.hrtime();
for (let i = 0; i < repeat; ++i){
block();
}
let diff = process.hrtime(start);
return Math.floor(diff[0] + diff[1] / 1e3);
}
|
javascript
|
{
"resource": ""
}
|
q14955
|
shiftLuminosity
|
train
|
function shiftLuminosity (hue, shiftAmount, huePoints) {
if (hue === 360) {
hue = 0
}
const hueShift = nearestHue(hue, huePoints)
const phi = PHI(hue, hueShift)
if (phi === 0) {
return hue
}
let newHue
if (phi > 0) {
newHue = hue + shiftAmount
} else {
newHue = hue - shiftAmount
}
return limit(newHue, 0, 360)
}
|
javascript
|
{
"resource": ""
}
|
q14956
|
applyToPoint
|
train
|
function applyToPoint(matrix, point) {
return {
x: matrix.a * point.x + matrix.c * point.y + matrix.e,
y: matrix.b * point.x + matrix.d * point.y + matrix.f
};
}
|
javascript
|
{
"resource": ""
}
|
q14957
|
train
|
function(karmaSettings, resolveFn) {
var testServer = new karma.Server(karmaSettings, function(exitCode) {
if (typeof(resolveFn) === 'function') {
resolveFn(exitCode);
} else {
process.exit(exitCode);
}
});
testServer.start();
}
|
javascript
|
{
"resource": ""
}
|
|
q14958
|
clearObject
|
train
|
function clearObject(object) {
var key;
for (key in object) {
if (object.hasOwnProperty(key)) {
// Ensures only writable properties are deleted.
try {
delete object[key];
} catch (e) { }
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14959
|
calledWith
|
train
|
function calledWith() {
var calledWithCount = 0;
var args = [];
var argsLength = arguments.length;
for (var i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
var callsLength = this._calls.length;
CALLS: for (var i = 0; i < callsLength; i++) {
var match = false;
var called = this._calls[i];
var calledLength = called.length;
if (argsLength === 0 && calledLength === 0) {
match = true;
} else {
ARGS: for (var a = 0; a < argsLength; a++) {
match = matchArgs(args[a],called[a]);
if (!match) {
break ARGS;
}
}
}
if (match) {
calledWithCount++;
}
}
return calledWithCount;
}
|
javascript
|
{
"resource": ""
}
|
q14960
|
callbackWith
|
train
|
function callbackWith() {
this._callbackWith = [];
var length = arguments.length;
for (var i = 0; i < length; i++) {
var arg = arguments[i];
this._callbackWith.push(arg);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q14961
|
makeParsedStream
|
train
|
function makeParsedStream() {
var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var defaults = {
useWorker: _compositeDetect2.default.isBrowser === true,
concat: true
};
parameters = Object.assign({}, defaults, parameters);
var _parameters = parameters,
useWorker = _parameters.useWorker,
concat = _parameters.concat;
var mainStream = useWorker ? (0, _workerSpawner2.default)() : (0, _through2.default)((0, _parseStream2.default)());
// concatenate result into a single one if needed (still streaming)
var endStream = concat ? (0, _combining2.default)()(mainStream, (0, _concatStream2.default)()) : mainStream;
return endStream;
}
|
javascript
|
{
"resource": ""
}
|
q14962
|
train
|
function (arr, val) {
debug('Finding all indices...');
debug('Array: %o', arr);
let indexes = [];
for (let i = 0; i < arr.length; i++) {
const
camelCaseVal = camelCase(val),
camelCaseKey = camelCase(arr[i]);
if (arr[i] === val || camelCaseKey === camelCaseVal) {
debug('Matched index: %s', i);
indexes.push(i);
}
}
debug('Found indices: %o', indexes);
return indexes;
}
|
javascript
|
{
"resource": ""
}
|
|
q14963
|
train
|
function (value) {
if (!Array.isArray(value)) {
// null/undefined or anything else must be safely convert to string
value = value + '';
}
if (Array.isArray(value)) {
// map all values again
value = value.map(v => this.parseValue(v));
} else if (validator.isNumeric(value)) {
value = value * 1; // parse as a number
} else if (validator.isBoolean(value)) {
value = (value === 'true');
} else {
// convert to JS date
const date = validator.toDate(value);
// date is valid, assign
if (date !== null) {
value = date;
}
if (value === 'null') {
value = null;
}
if (value === 'undefined') {
value = undefined;
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q14964
|
train
|
function (obj, options) {
debug('Parsing properties...');
debug('Object: %o', obj);
Object.keys(obj)
.map(key => {
let value = obj[key];
debug('Value: %o', value);
// parse current value
value = helpers.parseValue(value);
debug('Parsed value: %o', value);
// replace value with the updated one
obj[key] = value;
});
debug('Parsed options: %o', obj);
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q14965
|
onProgress
|
train
|
function onProgress( e ) {
// change class if the image is loaded or broken
e.img.parentNode.className = e.isLoaded ? '' : 'is-broken';
// update progress element
loadedImageCount++;
updateProgress( loadedImageCount );
}
|
javascript
|
{
"resource": ""
}
|
q14966
|
determineFilename
|
train
|
function determineFilename(file) {
var filename,
filenameMatch;
if (file.hasOwnProperty('httpVersion')) {
// it's an http response
// first let's check if there's a content-disposition header...
if (file.headers['content-disposition']) {
filenameMatch = /filename=(.*)/.exec(file.headers['content-disposition']);
filename = filenameMatch[1];
}
if (!filename) {
// try to get the path of the request url
filename = path.basename(file.client._httpMessage.path);
}
} else if (file.path) {
// it looks like a file, let's just get the path
filename = path.basename(file.path);
}
return filename || 'untitled document';
}
|
javascript
|
{
"resource": ""
}
|
q14967
|
handleError
|
train
|
function handleError(body, response, callback) {
var error;
if (!body) {
response.pipe(concat(function (body) {
body = parseJSONBody(body);
error = body.message || statusText(response.statusCode);
callback(new Error(error), body, response);
}));
} else {
error = body.message || statusText(response.statusCode);
callback(new Error(error), body, response);
}
}
|
javascript
|
{
"resource": ""
}
|
q14968
|
createResponseHandler
|
train
|
function createResponseHandler(callback, okStatusCodes, noBuffer, retryFn) {
if (typeof callback !== 'function') {
callback = function () {};
}
if (typeof okStatusCodes === 'function') {
retryFn = okStatusCodes;
okStatusCodes = null;
noBuffer = retryFn;
}
if (typeof noBuffer === 'function') {
retryFn = noBuffer;
noBuffer = false;
}
okStatusCodes = okStatusCodes || [200];
/**
* Retry the request if a retry function and retry-after headers are present
* @param {HTTPResponse} response The response object
* @returns {void}
*/
function retry(response) {
var retryAfter = response.headers['retry-after'];
if (typeof retryFn === 'function' && retryAfter) {
retryAfter = parseInt(retryAfter, 10);
setTimeout(retryFn, retryAfter * 1000);
return true;
}
return false;
}
function handleResponse(response, body) {
var error;
// the handler expects a parsed response body
if (noBuffer !== true && typeof body === 'undefined') {
response.pipe(concat(function (body) {
handleResponse(response, parseJSONBody(body));
}));
return;
}
if (okStatusCodes.indexOf(response.statusCode) > -1) {
if (!retry(response)) {
if (noBuffer) {
callback(null, response);
} else {
callback(null, body, response);
}
}
} else {
if (response.statusCode === 429) {
if (retry(response)) {
return;
}
}
handleError(body, response, callback);
}
}
return function (error, response) {
if (error) {
callback(error, response);
} else {
handleResponse(response);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q14969
|
retry
|
train
|
function retry(response) {
var retryAfter = response.headers['retry-after'];
if (typeof retryFn === 'function' && retryAfter) {
retryAfter = parseInt(retryAfter, 10);
setTimeout(retryFn, retryAfter * 1000);
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q14970
|
train
|
function (options, callback) {
var query,
handler,
retry = false,
params,
args = arguments;
if (typeof options === 'function') {
callback = options;
params = {};
} else {
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.list.apply(this, args);
}.bind(this);
if (params['created_before']) {
params['created_before'] = getTimestamp(params['created_before']);
}
if (params['created_after']) {
params['created_after'] = getTimestamp(params['created_after']);
}
query = querystring.stringify(params);
if (query) {
query = '?' + query;
}
handler = createResponseHandler(callback, retry);
return req(client.documentsURL + query, handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q14971
|
train
|
function (id, options, callback) {
var query = '',
handler,
retry = false,
fields,
args = arguments;
if (typeof options === 'function') {
callback = options;
fields = '';
} else {
options = extend({}, options);
fields = options.fields || '';
retry = options.retry;
}
if (Array.isArray(fields)) {
fields = fields.join(',');
}
retry = (retry === true) && function () {
this.get.apply(this, args);
}.bind(this);
if (fields) {
query = '?' + querystring.stringify({
fields: fields
});
}
handler = createResponseHandler(callback, retry);
return req(client.documentsURL + '/' + id + query, handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q14972
|
train
|
function (id, data, options, callback) {
var args = arguments,
r,
handler,
retry = false,
requestOptions = {
method: 'PUT',
headers: {
'content-type': 'application/json'
}
};
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.update.apply(this, args);
}.bind(this);
handler = createResponseHandler(callback, retry);
r = req(client.documentsURL + '/' + id, requestOptions, handler);
data = new Buffer(JSON.stringify(data));
r.setHeader('content-length', data.length);
r.end(data);
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q14973
|
train
|
function (id, options, callback) {
var args = arguments,
retry = false,
handler;
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.delete.apply(this, args);
}.bind(this);
handler = createResponseHandler(callback, [204], true, retry);
return req(client.documentsURL + '/' + id, { method: 'DELETE' }, handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q14974
|
train
|
function (file, options, callback) {
var args = arguments,
r,
param,
form,
handler,
params,
retry = false,
requestOptions = {
method: 'POST'
};
if (typeof file === 'string') {
file = fs.createReadStream(file);
}
if (typeof options === 'function') {
callback = options;
params = {};
} else {
options = extend({}, options);
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.uploadFile.apply(this, args);
}.bind(this);
// filename is required for the form to work properly, so try to
// figure out a name...
if (!params.name) {
params.name = determineFilename(file);
}
// if the file is a stream, we cannot retry
if (retry && file.readable) {
throw new Error('Retry option is not supported for streams.');
}
handler = createResponseHandler(callback, [200, 202], retry);
form = new FormData();
for (param in params) {
if (params.hasOwnProperty(param)) {
form.append(param, params[param].toString());
}
}
form.append('file', file, { filename: params.name });
extend(true, requestOptions, {
headers: form.getHeaders()
});
r = req(client.documentsUploadURL, requestOptions, handler);
form.pipe(r);
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q14975
|
train
|
function (url, options, callback) {
var args = arguments,
r,
handler,
params,
data = '',
retry = false,
requestOptions = {
method: 'POST',
headers: {
'content-type': 'application/json'
}
};
if (typeof options === 'function') {
callback = options;
params = {};
} else {
options = extend({}, options);
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.uploadURL.apply(this, args);
}.bind(this);
if (!params.name) {
params.name = path.basename(url);
}
params.url = url;
handler = createResponseHandler(callback, [200, 202], retry);
r = req(client.documentsURL, requestOptions, handler);
data = new Buffer(JSON.stringify(params));
r.setHeader('content-length', data.length);
r.end(data);
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q14976
|
train
|
function (id, width, height, options, callback) {
var args = arguments,
url,
query,
retry = false,
params,
handler;
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.getThumbnail.apply(this, args);
}.bind(this);
params = {
width: width,
height: height
};
handler = createResponseHandler(callback, [200, 202], true, retry);
query = querystring.stringify(params);
url = client.documentsURL + '/' + id + '/thumbnail?' + query;
return req(url, handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q14977
|
train
|
function(main_nutella, net_sub_module) {
// Store a reference to the main module
this.nutella = main_nutella;
this.net = net_sub_module;
this.file_mngr_url = 'http://' + main_nutella.mqtt_client.getHost() + ':57882';
}
|
javascript
|
{
"resource": ""
}
|
|
q14978
|
getFileExtension
|
train
|
function getFileExtension(file) {
return file.name.substring(file.name.lastIndexOf('.')+1, file.name.length).toLowerCase()
}
|
javascript
|
{
"resource": ""
}
|
q14979
|
isAlreadyUploaded
|
train
|
function isAlreadyUploaded(file_mngr_url, filename, file_exists_cb, file_absent_cb) {
var req = new XMLHttpRequest();
req.open("GET", file_mngr_url + "/test/" + filename);
req.onload = function(e) {
var url = JSON.parse(req.response).url;
if (url === undefined)
file_absent_cb();
else
file_exists_cb(url);
};
req.send();
}
|
javascript
|
{
"resource": ""
}
|
q14980
|
upload
|
train
|
function upload(file_mngr_url, file, filename, success, error) {
// Assemble data
var fd = new FormData();
fd.append("filename", filename);
fd.append("file", file);
var req = new XMLHttpRequest();
req.open("POST", file_mngr_url + "/upload");
req.onload = function(e) {
var url = JSON.parse(req.response).url;
if (url === undefined)
error();
else
success(url);
};
req.send(fd);
}
|
javascript
|
{
"resource": ""
}
|
q14981
|
discoverAndReadFiles
|
train
|
function discoverAndReadFiles(options) {
const FILES = {};
const in_queue = Object.create(null);
const queue = [];
const enqueue = (moduleId) => {
if (in_queue[moduleId]) {
return;
}
in_queue[moduleId] = true;
queue.push(moduleId);
};
options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) {
const moduleId = queue.shift();
const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
if (fs.existsSync(dts_filename)) {
const dts_filecontents = fs.readFileSync(dts_filename).toString();
FILES[`${moduleId}.d.ts`] = dts_filecontents;
continue;
}
const js_filename = path.join(options.sourcesRoot, moduleId + '.js');
if (fs.existsSync(js_filename)) {
// This is an import for a .js file, so ignore it...
continue;
}
let ts_filename;
if (options.redirects[moduleId]) {
ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
}
else {
ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
}
const ts_filecontents = fs.readFileSync(ts_filename).toString();
const info = ts.preProcessFile(ts_filecontents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) {
// Ignore vs/css! imports
continue;
}
let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
}
enqueue(importedModuleId);
}
FILES[`${moduleId}.ts`] = ts_filecontents;
}
return FILES;
}
|
javascript
|
{
"resource": ""
}
|
q14982
|
handleDeletions
|
train
|
function handleDeletions() {
return es.mapSync(f => {
if (/\.ts$/.test(f.relative) && !f.contents) {
f.contents = Buffer.from('');
f.stat = { mtime: new Date() };
}
return f;
});
}
|
javascript
|
{
"resource": ""
}
|
q14983
|
uglifyWithCopyrights
|
train
|
function uglifyWithCopyrights() {
const preserveComments = (f) => {
return (_node, comment) => {
const text = comment.value;
const type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
}
else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
};
};
const minify = composer(uglifyes);
const input = es.through();
const output = input
.pipe(flatmap((stream, f) => {
return stream.pipe(minify({
output: {
comments: preserveComments(f),
max_line_len: 1024
}
}));
}));
return es.duplex(input, output);
}
|
javascript
|
{
"resource": ""
}
|
q14984
|
sequence
|
train
|
function sequence(streamProviders) {
const result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
const fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14985
|
train
|
function (what) {
moduleManager.getRecorder().record(33 /* NodeBeginNativeRequire */, what);
try {
return _nodeRequire_1(what);
}
finally {
moduleManager.getRecorder().record(34 /* NodeEndNativeRequire */, what);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14986
|
nls
|
train
|
function nls() {
const input = event_stream_1.through();
const output = input.pipe(event_stream_1.through(function (f) {
if (!f.sourceMap) {
return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
}
let source = f.sourceMap.sources[0];
if (!source) {
return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
}
const root = f.sourceMap.sourceRoot;
if (root) {
source = path.join(root, source);
}
const typescript = f.sourceMap.sourcesContent[0];
if (!typescript) {
return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
}
nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
}));
return event_stream_1.duplex(input, output);
}
|
javascript
|
{
"resource": ""
}
|
q14987
|
bundle
|
train
|
function bundle(entryPoints, config, callback) {
const entryPointsMap = {};
entryPoints.forEach((module) => {
entryPointsMap[module.name] = module;
});
const allMentionedModulesMap = {};
entryPoints.forEach((module) => {
allMentionedModulesMap[module.name] = true;
(module.include || []).forEach(function (includedModule) {
allMentionedModulesMap[includedModule] = true;
});
(module.exclude || []).forEach(function (excludedModule) {
allMentionedModulesMap[excludedModule] = true;
});
});
const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
const loaderModule = { exports: {} };
r.call({}, require, loaderModule, loaderModule.exports);
const loader = loaderModule.exports;
config.isBuild = true;
config.paths = config.paths || {};
if (!config.paths['vs/nls']) {
config.paths['vs/nls'] = 'out-build/vs/nls.build';
}
if (!config.paths['vs/css']) {
config.paths['vs/css'] = 'out-build/vs/css.build';
}
loader.config(config);
loader(['require'], (localRequire) => {
const resolvePath = (path) => {
const r = localRequire.toUrl(path);
if (!/\.js/.test(r)) {
return r + '.js';
}
return r;
};
for (const moduleId in entryPointsMap) {
const entryPoint = entryPointsMap[moduleId];
if (entryPoint.append) {
entryPoint.append = entryPoint.append.map(resolvePath);
}
if (entryPoint.prepend) {
entryPoint.prepend = entryPoint.prepend.map(resolvePath);
}
}
});
loader(Object.keys(allMentionedModulesMap), () => {
const modules = loader.getBuildInfo();
const partialResult = emitEntryPoints(modules, entryPointsMap);
const cssInlinedResources = loader('vs/css').getInlinedResources();
callback(null, {
files: partialResult.files,
cssInlinedResources: cssInlinedResources,
bundleData: partialResult.bundleData
});
}, (err) => callback(err, null));
}
|
javascript
|
{
"resource": ""
}
|
q14988
|
visit
|
train
|
function visit(rootNodes, graph) {
const result = {};
const queue = rootNodes;
rootNodes.forEach((node) => {
result[node] = true;
});
while (queue.length > 0) {
const el = queue.shift();
const myEdges = graph[el] || [];
myEdges.forEach((toNode) => {
if (!result[toNode]) {
result[toNode] = true;
queue.push(toNode);
}
});
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14989
|
topologicalSort
|
train
|
function topologicalSort(graph) {
const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
Object.keys(graph).forEach((fromNode) => {
allNodes[fromNode] = true;
outgoingEdgeCount[fromNode] = graph[fromNode].length;
graph[fromNode].forEach((toNode) => {
allNodes[toNode] = true;
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
inverseEdges[toNode] = inverseEdges[toNode] || [];
inverseEdges[toNode].push(fromNode);
});
});
// https://en.wikipedia.org/wiki/Topological_sorting
const S = [], L = [];
Object.keys(allNodes).forEach((node) => {
if (outgoingEdgeCount[node] === 0) {
delete outgoingEdgeCount[node];
S.push(node);
}
});
while (S.length > 0) {
// Ensure the exact same order all the time with the same inputs
S.sort();
const n = S.shift();
L.push(n);
const myInverseEdges = inverseEdges[n] || [];
myInverseEdges.forEach((m) => {
outgoingEdgeCount[m]--;
if (outgoingEdgeCount[m] === 0) {
delete outgoingEdgeCount[m];
S.push(m);
}
});
}
if (Object.keys(outgoingEdgeCount).length > 0) {
throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
}
return L;
}
|
javascript
|
{
"resource": ""
}
|
q14990
|
getVersion
|
train
|
function getVersion(repo) {
const git = path.join(repo, '.git');
const headPath = path.join(git, 'HEAD');
let head;
try {
head = fs.readFileSync(headPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
if (/^[0-9a-f]{40}$/i.test(head)) {
return head;
}
const refMatch = /^ref: (.*)$/.exec(head);
if (!refMatch) {
return undefined;
}
const ref = refMatch[1];
const refPath = path.join(git, ref);
try {
return fs.readFileSync(refPath, 'utf8').trim();
}
catch (e) {
// noop
}
const packedRefsPath = path.join(git, 'packed-refs');
let refsRaw;
try {
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
let refsMatch;
let refs = {};
while (refsMatch = refsRegex.exec(refsRaw)) {
refs[refsMatch[2]] = refsMatch[1];
}
return refs[ref];
}
|
javascript
|
{
"resource": ""
}
|
q14991
|
safeToArray
|
train
|
function safeToArray(args) {
const seen = [];
const argsArray = [];
let res;
// Massage some arguments with special treatment
if (args.length) {
for (let i = 0; i < args.length; i++) {
// Any argument of type 'undefined' needs to be specially treated because
// JSON.stringify will simply ignore those. We replace them with the string
// 'undefined' which is not 100% right, but good enough to be logged to console
if (typeof args[i] === 'undefined') {
args[i] = 'undefined';
}
// Any argument that is an Error will be changed to be just the error stack/message
// itself because currently cannot serialize the error over entirely.
else if (args[i] instanceof Error) {
const errorObj = args[i];
if (errorObj.stack) {
args[i] = errorObj.stack;
} else {
args[i] = errorObj.toString();
}
}
argsArray.push(args[i]);
}
}
// Add the stack trace as payload if we are told so. We remove the message and the 2 top frames
// to start the stacktrace where the console message was being written
if (process.env.VSCODE_LOG_STACK === 'true') {
const stack = new Error().stack;
argsArray.push({ __$stack: stack.split('\n').slice(3).join('\n') });
}
try {
res = JSON.stringify(argsArray, function (key, value) {
// Objects get special treatment to prevent circles
if (isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
}
seen.push(value);
}
return value;
});
} catch (error) {
return 'Output omitted for an object that cannot be inspected (' + error.toString() + ')';
}
if (res && res.length > MAX_LENGTH) {
return 'Output omitted for a large object that exceeds the limits';
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q14992
|
computeChecksums
|
train
|
function computeChecksums(out, filenames) {
var result = {};
filenames.forEach(function (filename) {
var fullPath = path.join(process.cwd(), out, filename);
result[filename] = computeChecksum(fullPath);
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14993
|
computeChecksum
|
train
|
function computeChecksum(filename) {
var contents = fs.readFileSync(filename);
var hash = crypto
.createHash('md5')
.update(contents)
.digest('base64')
.replace(/=+$/, '');
return hash;
}
|
javascript
|
{
"resource": ""
}
|
q14994
|
readProperty
|
train
|
function readProperty(obj, propertySegments, index) {
const value = obj[propertySegments[index]];
return !!value && (index === propertySegments.length - 1 || readProperty(value, propertySegments, index + 1));
}
|
javascript
|
{
"resource": ""
}
|
q14995
|
generateLocale
|
train
|
function generateLocale(locale, localeData, baseCurrencies) {
// [ localeId, dateTime, number, currency, pluralCase ]
let data = stringify([
locale,
...getDateTimeTranslations(localeData),
...getDateTimeSettings(localeData),
...getNumberSettings(localeData),
...getCurrencySettings(locale, localeData),
generateLocaleCurrencies(localeData, baseCurrencies)
], true)
// We remove "undefined" added by spreading arrays when there is no value
.replace(/undefined/g, 'u');
// adding plural function after, because we don't want it as a string
data = data.substring(0, data.lastIndexOf(']')) + `, plural]`;
return `${HEADER}
const u = undefined;
${getPluralFunction(locale)}
export default ${data};
`;
}
|
javascript
|
{
"resource": ""
}
|
q14996
|
generateLocaleCurrencies
|
train
|
function generateLocaleCurrencies(localeData, baseCurrencies) {
const currenciesData = localeData.main('numbers/currencies');
const currencies = {};
Object.keys(currenciesData).forEach(code => {
let symbolsArray = [];
const symbol = currenciesData[code].symbol;
const symbolNarrow = currenciesData[code]['symbol-alt-narrow'];
if (symbol && symbol !== code) {
symbolsArray.push(symbol);
}
if (symbolNarrow && symbolNarrow !== symbol) {
if (symbolsArray.length > 0) {
symbolsArray.push(symbolNarrow);
} else {
symbolsArray = [undefined, symbolNarrow];
}
}
// if locale data are different, set the value
if ((baseCurrencies[code] || []).toString() !== symbolsArray.toString()) {
currencies[code] = symbolsArray;
}
});
return currencies;
}
|
javascript
|
{
"resource": ""
}
|
q14997
|
getDayPeriods
|
train
|
function getDayPeriods(localeData, dayPeriodsList) {
const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`);
const result = {};
// cleaning up unused keys
Object.keys(dayPeriods).forEach(key1 => { // format / stand-alone
result[key1] = {};
Object.keys(dayPeriods[key1]).forEach(key2 => { // narrow / abbreviated / wide
result[key1][key2] = {};
Object.keys(dayPeriods[key1][key2]).forEach(key3 => {
if (dayPeriodsList.indexOf(key3) !== -1) {
result[key1][key2][key3] = dayPeriods[key1][key2][key3];
}
});
});
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14998
|
getDateTimeTranslations
|
train
|
function getDateTimeTranslations(localeData) {
const dayNames = localeData.main(`dates/calendars/gregorian/days`);
const monthNames = localeData.main(`dates/calendars/gregorian/months`);
const erasNames = localeData.main(`dates/calendars/gregorian/eras`);
const dayPeriods = getDayPeriodsAmPm(localeData);
const dayPeriodsFormat = removeDuplicates([
objectValues(dayPeriods.format.narrow),
objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.wide)
]);
const dayPeriodsStandalone = removeDuplicates([
objectValues(dayPeriods['stand-alone'].narrow),
objectValues(dayPeriods['stand-alone'].abbreviated),
objectValues(dayPeriods['stand-alone'].wide)
]);
const daysFormat = removeDuplicates([
objectValues(dayNames.format.narrow),
objectValues(dayNames.format.abbreviated),
objectValues(dayNames.format.wide),
objectValues(dayNames.format.short)
]);
const daysStandalone = removeDuplicates([
objectValues(dayNames['stand-alone'].narrow),
objectValues(dayNames['stand-alone'].abbreviated),
objectValues(dayNames['stand-alone'].wide),
objectValues(dayNames['stand-alone'].short)
]);
const monthsFormat = removeDuplicates([
objectValues(monthNames.format.narrow),
objectValues(monthNames.format.abbreviated),
objectValues(monthNames.format.wide)
]);
const monthsStandalone = removeDuplicates([
objectValues(monthNames['stand-alone'].narrow),
objectValues(monthNames['stand-alone'].abbreviated),
objectValues(monthNames['stand-alone'].wide)
]);
const eras = removeDuplicates([
[erasNames.eraNarrow['0'], erasNames.eraNarrow['1']],
[erasNames.eraAbbr['0'], erasNames.eraAbbr['1']],
[erasNames.eraNames['0'], erasNames.eraNames['1']]
]);
const dateTimeTranslations = [
...removeDuplicates([dayPeriodsFormat, dayPeriodsStandalone]),
...removeDuplicates([daysFormat, daysStandalone]),
...removeDuplicates([monthsFormat, monthsStandalone]),
eras
];
return dateTimeTranslations;
}
|
javascript
|
{
"resource": ""
}
|
q14999
|
getDateTimeFormats
|
train
|
function getDateTimeFormats(localeData) {
function getFormats(data) {
return removeDuplicates([
data.short._value || data.short,
data.medium._value || data.medium,
data.long._value || data.long,
data.full._value || data.full
]);
}
const dateFormats = localeData.main('dates/calendars/gregorian/dateFormats');
const timeFormats = localeData.main('dates/calendars/gregorian/timeFormats');
const dateTimeFormats = localeData.main('dates/calendars/gregorian/dateTimeFormats');
return [
getFormats(dateFormats),
getFormats(timeFormats),
getFormats(dateTimeFormats)
];
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.