_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q13200
|
train
|
function () {
var message = this.message;
var name = this.name;
var url = this.url;
var result = name;
if (message) {
result += ': ' + message;
}
if (url) {
result += ' (' + url + ')';
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13201
|
train
|
function (err, files) {
if (err) {
grunt.fail.fatal(err);
}
files.forEach(function (file) {
var pathName = path.join(workspacePath, file);
if (fs.statSync(pathName).isDirectory()) {
if (file === activeWebpackage && choices.length > 0) {
choices.splice(0, 0, file);
} else {
choices.push(file);
}
}
});
// get list of webpackages to upload from config
var uploadWebpackages = grunt.config.get('workspaceConfig.uploadWebpackages');
var i = 0;
if (uploadWebpackages && uploadWebpackages.length) {
// create upload list from config
grunt.log.writeln('Webpackages to upload:');
for (i = 0; i < uploadWebpackages.length; i++) {
if (choices.indexOf(uploadWebpackages[i]) >= 0) {
webpackages.push(uploadWebpackages[i]);
grunt.log.writeln((i + 1) + ') ' + uploadWebpackages[i]);
}
}
startUploads();
} else {
// get user decision
choices.push('CANCEL');
grunt.log.writeln('Please select all webpackages to upload ' +
'or to CANCEL: ');
for (i = 0; i < choices.length; i++) {
grunt.log.writeln((i + 1) + ') ' + choices[i]);
}
var options = {
questions: [
{
name: 'selectedWebpackages',
type: 'input',
message: 'Answer:'
}
]
};
inquirer.prompt(options.questions).then(webpackagesSelected);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13202
|
EmitEvent
|
train
|
function EmitEvent(props) {
const event = this;
if ( !(event instanceof EmitEvent) ) {
return new EmitEvent(props);
}
if ( props == undefined ) {
props = '';
}
if ( typeof props == 'string' ) {
props = { type: props };
}
_extend(event, props);
event.timeStamp = Date.now();
}
|
javascript
|
{
"resource": ""
}
|
q13203
|
_extend
|
train
|
function _extend(obj, from) {
for ( let key in from ) if ( hop.call(from, key) ) {
obj[key] = from[key];
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q13204
|
_append
|
train
|
function _append(array, args/*, ...*/) {
var i = array.length
, j
, k = 1
, l
, m = arguments.length
, a
;
for(; k < m; ++k) {
a = arguments[k];
array.length =
l = i + a.length;
for(j = 0; i < l; ++i, ++j) {
array[i] = a[j];
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q13205
|
train
|
function (data, circuitbreakerState, callback) {
const responder = (circuitbreakerState===CB.OPEN) ? config.bypass : config.handler;
// call the handler using its expected paradigm
const promise = responder.length > 1
? new Promise(function(resolve, reject) {
responder(data, function(err, result) {
if (err) return reject(err);
resolve(result);
});
})
: Promise.resolve(responder(data));
// provide an asynchronous response in the expected paradigm
if (typeof callback !== 'function') return promise;
promise.then(
function (data) { callback(null, data); },
function (err) { callback(err, null); }
);
}
|
javascript
|
{
"resource": ""
}
|
|
q13206
|
serviceConfig
|
train
|
function serviceConfig() {
var arg = ld.values(arguments), cfg = {};
// try to load file from global directory
if(typeof arg[0] === 'string') {
var path = arg.shift();
try {
cfg = require('/etc/paukan/'+path+'.json');
} catch (err) { // try to load file directly if global fails
try {
cfg = require(path);
} catch (err) {}
}
}
// append default settings
var localCfg = arg.shift();
if(!ld.isPlainObject(localCfg)) {
throw new Error('at least local config should be specified');
}
ld.defaults(cfg, localCfg);
// load specific field from package.json
var packageCfg = arg.shift();
if(ld.isPlainObject(packageCfg)) {
ld.defaults(cfg, ld.pick(packageCfg, ['version', 'description', 'homepage', 'author']));
}
return cfg;
}
|
javascript
|
{
"resource": ""
}
|
q13207
|
StreamConsole
|
train
|
function StreamConsole(cfg) {
cfg = cfg || {};
this.color = cfg.color || true;
this.timestamp = (typeof cfg.timestamp === 'undefined') ? 'HH:mm:ss ' : cfg.timestamp;
}
|
javascript
|
{
"resource": ""
}
|
q13208
|
InfiniteScrollSetup
|
train
|
function InfiniteScrollSetup (options) {
options || (options = {});
var self = this;
var gap = (options.gap || 20); // defaults to 20
self.events = self.events || {};
assign(self.events, {scroll: 'infiniteScroll'});
self.infiniteScroll = function () {
if (this.el.scrollHeight - this.el.scrollTop <= this.el.clientHeight + gap) {
this.collection.fetchPage(options);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q13209
|
InfiniteScrollView
|
train
|
function InfiniteScrollView (options) {
options || (options = {});
BaseView.call(this, options);
InfiniteScrollSetup.call(this, options);
}
|
javascript
|
{
"resource": ""
}
|
q13210
|
hyperRepeat
|
train
|
function hyperRepeat(store) {
this.compile = compile;
this.state = function(config, state) {
var res = store.get(config.path, state);
if (!res.completed) return false;
return state.set(config.source, res.value);
};
this.children = function(config, state, children) {
var items = state.get(config.source);
var arr = [];
if (!items) return arr;
var target = config.target;
var i, c, child;
var path = ['state', target];
for (i = 0; i < items.length; i++) {
function update() {return items[i]};
for (c = 0; c < children.length; c++) {
child = children[c];
if (!child) continue;
// TODO set the key prop
child = child.updateIn(path, update);
arr.push(child);
}
}
return arr;
};
}
|
javascript
|
{
"resource": ""
}
|
q13211
|
compile
|
train
|
function compile(input) {
var res = input.match(REGEX);
if (!res) throw new Error('Invalid expression: "' + input + '"');
var range = res[3];
var parsedRange;
if (range) {
parsedRange = parser(range);
if (parsedRange === null) throw new Error('Invalid range expression: "' + range + '" in "' + input + '"');
}
var path = res[2];
var source = path.split('.');
// TODO support ranges
if (parsedRange) console.warn('data-hyper-repeat ranges are not supported at this time');
return {
target: res[1],
path: path,
source: source[source.length - 1],
range: parsedRange
};
}
|
javascript
|
{
"resource": ""
}
|
q13212
|
train
|
function(file, type) {
var promise = new Parse.Promise();
if (typeof(FileReader) === "undefined") {
return Parse.Promise.error(new Parse.Error(
Parse.Error.FILE_READ_ERROR,
"Attempted to use a FileReader on an unsupported browser."));
}
var reader = new FileReader();
reader.onloadend = function() {
if (reader.readyState !== 2) {
promise.reject(new Parse.Error(
Parse.Error.FILE_READ_ERROR,
"Error reading file."));
return;
}
var dataURL = reader.result;
var matches = /^data:([^;]*);base64,(.*)$/.exec(dataURL);
if (!matches) {
promise.reject(new Parse.Error(
Parse.ERROR.FILE_READ_ERROR,
"Unable to interpret data URL: " + dataURL));
return;
}
promise.resolve(matches[2], type || matches[1]);
};
reader.readAsDataURL(file);
return promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q13213
|
train
|
function(options) {
options= options || {};
var self = this;
if (!self._previousSave) {
self._previousSave = self._source.then(function(base64, type) {
var data = {
base64: base64,
_ContentType: type
};
return Parse._request({
route: "files",
className: self._name,
method: 'POST',
data: data,
useMasterKey: options.useMasterKey
});
}).then(function(response) {
self._name = response.name;
self._url = response.url;
return self;
});
}
return self._previousSave._thenRunCallbacks(options);
}
|
javascript
|
{
"resource": ""
}
|
|
q13214
|
train
|
function (operation, parameter) {
// TODO the reference to operation.api is not available
if (operation.api && operation.api.parameterMacro) {
return operation.api.parameterMacro(operation, parameter);
} else {
return parameter.defaultValue;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13215
|
train
|
function (model, property) {
// TODO the reference to model.api is not available
if (model.api && model.api.modelPropertyMacro) {
return model.api.modelPropertyMacro(model, property);
} else {
return property.default;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13216
|
baseIsEqual
|
train
|
function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
// Exit early for identical values.
if (value === other) {
// Treat `+0` vs. `-0` as not equal.
return value !== 0 || (1 / value == 1 / other);
}
var valType = typeof value,
othType = typeof other;
// Exit early for unlike primitive values.
if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') ||
value == null || other == null) {
// Return `false` unless both values are `NaN`.
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
}
|
javascript
|
{
"resource": ""
}
|
q13217
|
baseMatchesProperty
|
train
|
function baseMatchesProperty(key, value) {
if (isStrictComparable(value)) {
return function(object) {
return object != null && object[key] === value &&
(typeof value != 'undefined' || (key in toObject(object)));
};
}
return function(object) {
return object != null && baseIsEqual(value, object[key], null, true);
};
}
|
javascript
|
{
"resource": ""
}
|
q13218
|
createBaseEach
|
train
|
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
var length = collection ? collection.length : 0;
if (!isLength(length)) {
return eachFunc(collection, iteratee);
}
var index = fromRight ? length : -1,
iterable = toObject(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
|
javascript
|
{
"resource": ""
}
|
q13219
|
train
|
function(config,callback,patsy){
patsy = typeof config === 'function' && typeof callback === 'object' ? callback : patsy;
callback = typeof config === 'function' ? config : callback;
config = typeof config === 'function' ? undefined : config;
if(typeof config !== 'undefined' && typeof callback !== 'undefined' && typeof callback === 'function'){
try{
config = this.bake(config);
fs.writeFileSync( "patsy.json", JSON.stringify( config, null, 2 ) );
callback(patsy);
} catch(e){
console.log('config.create',e);
return false;
}
} else {
patsy.config.generateDefaultConfiguration();
callback(patsy);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13220
|
train
|
function(patsy, project_path){
if(opts.verbose){
util.print('>>'.cyan + ' Loading project configuration...');
}
if(typeof project_path === 'undefined'){
if(opts.verbose){
patsy.utils.notice();
patsy.utils.notice('No project path set, declaring path to CWD: '.white + String(process.cwd() + path.sep).inverse.cyan + '');
}
project_path = opts.project_path || process.cwd() + path.sep;
} else {
if(opts.verbose){
patsy.utils.ok();
}
}
var _path_to_config = project_path + 'patsy.json';
if(opts.verbose){
util.print('>>'.cyan + ' Reading project configuration file: ' + _path_to_config.inverse.cyan + '...\n');
}
if(!fs.existsSync(_path_to_config)){
patsy.utils.notice();
if(opts.verbose){
patsy.utils.notice('Configuration file not found here, looking elsewhere: ' + _path_to_config.inverse.cyan + '...\n');
}
patsy.scripture.print('[Patsy]'.yellow + ': <stumbling forward>\n');
_path_to_config = this.searchForConfigFile(patsy);
}
if(fs.existsSync(_path_to_config)){
if(opts.verbose){
patsy.utils.ok('File found here: ' + _path_to_config.inverse.cyan);
util.print('>>'.cyan + ' Loading project configuration...');
}
// Read file synchroneously, parse contents as JSON and return config
var _config_json;
try{
_config_json = require(_path_to_config);
} catch (e){
patsy.utils.fail();
}
if(this.validate(_config_json)){
if(opts.verbose){
patsy.utils.ok();
}
} else {
if(opts.verbose){
patsy.utils.fail('Configuration file is not valid!');
}
patsy.scripture.print('[Patsy]'.yellow + ': Sire! The configuration script is not valid! We have to turn around!\n');
process.exit(1);
}
_config_json.project.environment.rel_path = path.relative(_config_json.appPath || '', _config_json.project.environment.abs_path) + path.sep;
return _config_json;
} else {
if(opts.verbose){
util.print('>> FAIL'.red + ': Loading project configuration: Could not find configuration file!'.white + '\n');
}
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13221
|
train
|
function () {
var defaultConfig = JSON.parse(fs.readFileSync(__dirname + '/../patsy.default.json', 'utf8'));
var projectSpecificSettings = {
"project": {
"details" : {
"name" : path.basename(process.cwd())
},
"environment": {
"root" : path.basename(process.cwd()),
"abs_path": process.cwd() + path.sep
}
}
};
var almostDefaultConfig = require('./utils').deepExtend(defaultConfig, projectSpecificSettings);
almostDefaultConfig = JSON.stringify(almostDefaultConfig, null, 2);
fs.writeFileSync("patsy.json", almostDefaultConfig);
}
|
javascript
|
{
"resource": ""
}
|
|
q13222
|
dispatch
|
train
|
function dispatch(request, response) {
return Promise.resolve()
.then(resolveRouters.bind(this, request))
.then(callAction.bind(this, request, response));
}
|
javascript
|
{
"resource": ""
}
|
q13223
|
resolveRouters
|
train
|
function resolveRouters(request) {
for (var i = 0, l = routers.length; i < l; i++) {
var callback = routers[i].resolve(request);
if (null != callback) {
return Promise.resolve(callback);
}
}
return Promise.reject('Route not defined for "' + request.url + '"');
}
|
javascript
|
{
"resource": ""
}
|
q13224
|
callAction
|
train
|
function callAction(request, response, callback) {
if (typeof callback == 'function') {
return Promive.resolve()
.then(callback.bind(null, request, response));
}
try {
var Action = require(ACTION_PATH + '/' + callback.action + '.js');
} catch (error) {
if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') {
return Promise.reject('Action ' + callback.action + ' does not exist.')
.catch(this.onPageNotFound.bind(this, request, response));
}
return Promise.reject(error)
.catch(this.onError.bind(this, request, response));
}
var instance = new Action(request, response);
// Test if method exists
if (!instance[callback.method]) {
return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
}
var promise = Promise.resolve();
if (instance.init && 'function' == typeof instance.init) {
promise = promise.then(function () {
return instance.init();
});
}
promise = promise.then(function () {
return instance[callback.method].apply(instance, callback.arguments);
});
if (instance.onError && 'function' == typeof instance.onError) {
promise = promise.catch(function (error) {
return instance.onError.call(instance, error)
});
}
promise = promise.catch(this.onError.bind(this, request, response));
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q13225
|
postDecode
|
train
|
function postDecode(request) {
return new Promise(function promisePostDecode(resolve) {
var postData = '';
if (request.method === 'POST') {
request.on('data', function (chunk) {
// append the current chunk of data to the fullBody variable
postData += chunk.toString();
});
request.on('end', function () {
request.body = qs.parse(postData);
resolve();
});
} else {
resolve();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q13226
|
runHooks
|
train
|
function runHooks(request, response, hooks) {
var promise = Promise.resolve();
for (var i = 0; i < hooks.length; i++) {
promise = promise.then(hooks[i].bind(this, request, response));
}
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q13227
|
pad
|
train
|
function pad(text, width) {
var space = (width - text.length) + 5;
return text + Array(space).join(" ");
}
|
javascript
|
{
"resource": ""
}
|
q13228
|
generate
|
train
|
function generate() {
var rnum = Math.floor(Math.random() * 10);
var mood = rnum <= 8 ? "good" : "bad";
var sentences = [_sentence_mgr2.default.feeling(mood), _word_library2.default.warning(), nu.chooseFrom([_sentence_mgr2.default.relationship(mood), _sentence_mgr2.default.encounter(mood)])];
// randomize (shuffle) the array
sentences = nu.shuffle(sentences);
// Select 2 or 3 sentences, to add to the random feel
var num_s = Math.floor(Math.random() * 2) + 2;
sentences = sentences.slice(0, num_s);
sentences = sentences.join(" ");
sentences += " " + _sentence_mgr2.default.datePredict();
debug(sentences);
return sentences;
}
|
javascript
|
{
"resource": ""
}
|
q13229
|
FileListController
|
train
|
function FileListController($scope, mediator, $stateParams, $window, userClient, fileMediatorService, $timeout, mobileCamera, desktopCamera, FILE_CONFIG) {
var self = this;
self.files = null;
var _files;
self.uploadEnabled = FILE_CONFIG.uploadEnabled;
userClient.getProfile().then(function(profileData){
var userFilter;
if(FILE_CONFIG.userMode){
userFilter = profileData.id;
}
function refreshFiles(){
fileMediatorService.listFiles(userFilter).then(function(files){
$timeout(function(){
_files = files;
self.files = files;
});
});
}
refreshFiles();
fileMediatorService.subscribeToFileCRUDDoneTopics($scope, refreshFiles);
self.selectFile = function(event, file){
self.selectedFileId = file.id;
mediator.publish(fileMediatorService.fileUITopics.getTopic(CONSTANTS.TOPICS.SELECTED), file);
};
//TODO: Move to service
self.applyFilter = function(term){
term = term.toLowerCase();
self.files = _files.filter(function(file){
return String(file.name).toLowerCase().indexOf(term) !== -1
|| String(file.id).indexOf(term) !== -1;
});
};
$scope.$parent.selected = {id: null};
var captureThenUpload = function(){
if($window.cordova){
return mobileCamera.capture()
.then(function(capture){
var fileData = {
userId: profileData.id,
fileURI: capture.fileURI,
options: {fileName: capture.fileName}
};
fileMediatorService.createFile(fileData);
});
}else{
return desktopCamera.capture()
.then(function(dataUrl){
return fileMediatorService.createFile({userId: profileData.id, dataUrl: dataUrl});
});
}
};
self.capturePhoto = function(){
captureThenUpload().then(function(){
}, function(error){
console.error(error);
});
};
});
}
|
javascript
|
{
"resource": ""
}
|
q13230
|
optionResult
|
train
|
function optionResult(options, option){
var result = options[option];
// If the returned value is a function, call it with the dest option parameter
if(_.isFunction(result)){
result = result(options.dest);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q13231
|
build_shell
|
train
|
function build_shell(fields) {
var $fields = Array.isArray(fields) ? normalizeFields(fields) : ['ProcessId','Name','Path','ParentProcessId','Priority'];
var args = command.shell_arg.split(' ');
args.push(`${command.ps} | ${command.select} ${ $fields.join(',') } | ${command.convert}`);
return shell(command.shell, args);
}
|
javascript
|
{
"resource": ""
}
|
q13232
|
train
|
function(options) {
options = extend({
src: '',
output: '',
is3d: false,
failOnWarn: false,
overwrite: false,
reporter: 'default'
}, options);
if (!options.src || !options.output) {
throw new Error('Must specify source file and output directory');
}
var reporterConstructor;
if (options.reporter === 'default') {
reporterConstructor = require('./reporter.js').Reporter;
} else {
reporterConstructor = require('./reporters/' + options.reporter + '.js');
}
if (reporterConstructor === undefined) {
throw new Error('Invalid reporter given');
}
this.reporter = new reporterConstructor(options.failOnWarn);
this.sourceCode = fs.readFileSync(options.src, 'utf-8');
this.psykickVersion = (options.is3d) ? '3d' : '2d';
this.sourcePath = options.src;
this.outputPath = options.output;
this.overwrite = options.overwrite;
this.ast = null;
this.compiler = null;
this.writer = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q13233
|
handleRejects
|
train
|
function handleRejects(PromiseFunc, Obj, Err, Options){
var rejectOpts = Options.Reject || rejectConfig;
switch(rejectOpts.rejectBehaviour){
case "reject":
// Every time a promise finishes start the first one from the currentPromiseArrays[typeKey]Array that hasnt been started yet;
if(Obj.isRunning) return Obj.rejectResult(Err);
break;
case "resolve":
if(Obj.isRunning) return Obj.resolveResult(rejectOpts.returnOnReject);
break;
case "retry":
if(Obj.isRunning) return retryPromiseRejected(PromiseFunc, Obj, Options, Err);
break;
case "none":
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q13234
|
getHandler
|
train
|
function getHandler(method){
var taxonomy = {
create: store.set,
read: store.get,
update: store.set,
'delete': store.remove,
patch: store.set,
findAll: store.all,
findById: store.get
};
return store[method] || taxonomy[method];
}
|
javascript
|
{
"resource": ""
}
|
q13235
|
valid_leader
|
train
|
function valid_leader(durations) {
var on = durations[0];
var off = durations[1];
return (8900 < on && on < 9200) && (-4600 < off && off < -4350);
}
|
javascript
|
{
"resource": ""
}
|
q13236
|
command_id_from_buffer
|
train
|
function command_id_from_buffer(data) {
var durations = command_durations_from_hex_buffer(data);
if (!valid_leader(durations)) return;
var binary = binary_from_durations(durations);
if (!valid_binary(binary)) return;
var bytes = bytes_from_binary(binary);
if (!valid_bytes(bytes)) return;
if (!valid_codes(bytes)) return;
return command_id_from_bytes(bytes);
}
|
javascript
|
{
"resource": ""
}
|
q13237
|
continue_from_buffer
|
train
|
function continue_from_buffer(data) {
var durations = continue_durations_from_hex_buffer(data);
var on = durations[0];
var off = durations[1];
var stop = durations[2];
return (8900 < on && on < 9200) &&
(-2350 < off && off < -2100) &&
(500 < stop && stop < 650);
}
|
javascript
|
{
"resource": ""
}
|
q13238
|
versions
|
train
|
function versions(a, b) {
if (!a || !b) return false;
a = Array.isArray(a) ? a : Object.keys(a);
b = Array.isArray(a) ? a : Object.keys(a);
return a.length === b.length && a.reduce(function has(memo, item) {
return memo && ~b.indexOf(item);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q13239
|
dereference
|
train
|
function dereference(file, opts, cb) {
parser.dereference(file.path, opts, (err, schema) => {
if (err) {
this.emit('error', new gutil.PluginError('gulp-jsonschema-deref', err, {fileName: file.path}));
} else {
file.contents = Buffer.from(JSON.stringify(schema));
this.push(file);
}
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
q13240
|
breadcrumbs
|
train
|
function breadcrumbs(target, path) {
path = pathToArray(path);
const result = [target];
let part;
let value = target;
if (! isObject(value)) {
return result;
}
for (let i = 0, l = path.length; i < l; i++) {
part = path[i];
if (! value.hasOwnProperty(part)) {
break;
}
result.push(value[part]);
value = value[part];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q13241
|
hasPath
|
train
|
function hasPath(target, path) {
path = pathToArray(path);
const result = breadcrumbs(target, path);
return result.length === path.length + 1;
}
|
javascript
|
{
"resource": ""
}
|
q13242
|
setByPath
|
train
|
function setByPath(target, path, value) {
path = pathToArray(path);
if (! path.length) {
return value;
}
const key = path[0];
if (isNumber(key)) {
if (! Array.isArray(target)) {
target = [];
}
}
else if (! isObject(target)) {
target = {};
}
if (path.length > 1) {
target[key] = setByPath(target[key], path.slice(1), value);
}
else {
target[key] = value;
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
q13243
|
pushByPath
|
train
|
function pushByPath(target, path, value) {
path = pathToArray(path);
if (! path.length) {
if (! Array.isArray(target)) {
return [value];
}
else {
target.push(value);
return target;
}
}
if (! isObject(target)) {
target = {};
}
return at(target, path, function(finalTarget, key) {
if (Array.isArray(finalTarget[key])) {
finalTarget[key].push(value);
}
else {
finalTarget[key] = [value];
}
return finalTarget;
});
}
|
javascript
|
{
"resource": ""
}
|
q13244
|
getByPath
|
train
|
function getByPath(target, path) {
path = pathToArray(path);
const values = breadcrumbs(target, path);
return values[values.length - 1];
}
|
javascript
|
{
"resource": ""
}
|
q13245
|
methodByPath
|
train
|
function methodByPath(target, path) {
path = pathToArray(path);
const values = breadcrumbs(target, path);
if (values.length < path.length) {
return noop;
}
if (typeof values[values.length - 1] !== 'function') {
return noop;
}
if (values.length > 1) {
return values[values.length - 1].bind(values[values.length - 2]);
}
else {
return values[0].bind(target);
}
}
|
javascript
|
{
"resource": ""
}
|
q13246
|
callByPath
|
train
|
function callByPath(target, path, args) {
var fn = methodByPath(target, path);
if (! fn) {
return;
}
return fn.apply(null, args);
}
|
javascript
|
{
"resource": ""
}
|
q13247
|
train
|
function(point) {
var d2r = Math.PI / 180.0;
var lat1rad = this.latitude * d2r;
var long1rad = this.longitude * d2r;
var lat2rad = point.latitude * d2r;
var long2rad = point.longitude * d2r;
var deltaLat = lat1rad - lat2rad;
var deltaLong = long1rad - long2rad;
var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);
var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);
// Square of half the straight line chord distance between both points.
var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) +
(Math.cos(lat1rad) * Math.cos(lat2rad) *
sinDeltaLongDiv2 * sinDeltaLongDiv2));
a = Math.min(1.0, a);
return 2 * Math.asin(Math.sqrt(a));
}
|
javascript
|
{
"resource": ""
}
|
|
q13248
|
throwError
|
train
|
function throwError(name, message) {
var error = new Error(message);
error.name = name;
error.stack = formaterrors.stackFilter(error.stack, ["exceptions.js"], false);
throw error;
}
|
javascript
|
{
"resource": ""
}
|
q13249
|
regret
|
train
|
function regret(name, input){
var matchers, res = null, re, matches, matcher;
if(typeof name.exec === 'function'){
matchers = Object.keys(regret.matchers).filter(function(m){
return name.test(m);
}).map(function(m){
return regret.matchers[m];
});
}
else {
matchers = regret.matchers[name] ? [regret.matchers[name]] : [];
}
if(matchers.length === 0){
return undefined;
}
while(matchers.length > 0){
matcher = matchers.shift();
matches = matcher.pattern.exec(input);
if(!matches){
continue;
}
res = {};
// pop off the input string
matches.shift();
matches.map(function(p, i){
res[matcher.captures[i]] = p;
});
break;
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q13250
|
seqActions
|
train
|
function seqActions(actions, seed, onCompleted) {
var index = 0;
function invokeNext(v) {
var action = actions[index];
action(v, function (res) {
index = index + 1;
if (index < actions.length) {
invokeNext(res);
} else {
onCompleted(res);
}
});
}
invokeNext(seed);
}
|
javascript
|
{
"resource": ""
}
|
q13251
|
RestApi
|
train
|
function RestApi(config, cb) {
var self = this;
self.routes = {};
self.bindTo = (config && config.bindTo) ? config.bindTo : undefined;
self.port = (config && config.port) ? config.port : DEFAULT_PORT;
// create the HTTP server object and on every request, try to match the
// request with a known route. If there is no match, return a 404 error.
self.HttpServer = http.createServer(function(req, res) {
var uriPath;
var queryStr;
var urlParts = url.parse(req.url, true);
if (is.obj(urlParts)) {
uriPath = urlParts.pathname || undefined;
queryStr = urlParts.query || undefined;
debug('queryStr: '+inspect(queryStr));
} else {
// no match was found, return a 404 error.
res.writeHead(400, {'Content-Type': 'application/json; charset=utf-8'});
res.end('{status:400, message:"Bad URI path."}', 'utf8');
return;
}
// try to match the request & method with a handler
for (var path in self.routes[req.method]) {
if (path === uriPath) {
self.routes[req.method][path](req, res, queryStr);
return;
}
}
// no match was found, return a 404 error.
res.writeHead(404, {'Content-Type': 'application/json; charset=utf-8'});
res.end('{status:404, message:"Content not found."}', 'utf8');
});
if (cb) self.listen(cb);
}
|
javascript
|
{
"resource": ""
}
|
q13252
|
Rule
|
train
|
function Rule (subrules, type, handler, props, groupProps, encoding) {
var self = this
var n = subrules.length
this.props = props
this.debug = false
// Used for cloning
this.subrules = subrules
// Required by Atok#_resolveRules
for (var p in groupProps)
this[p] = groupProps[p]
// Runtime values for continue props
this.continue = this.props.continue[0]
this.continueOnFail = this.props.continue[1]
this.type = type
this.handler = handler
// For debug
this.prevHandler = null
this.id = this.type !== null ? this.type : handler
// Id for debug
this._id = (handler !== null ? (handler.name || '#emit()') : this.type)
// Subrule pattern index that matched (-1 if only 1 pattern)
this.idx = -1
// Single subrule: special case for trimRight
this.single = (n === 1)
// First subrule
var subrule = this.first = n > 0
? SubRule.firstSubRule( subrules[0], this.props, encoding, this.single )
// Special case: no rule given -> passthrough
: SubRule.emptySubRule
// Special case: one empty rule -> tokenize whole buffer
if (n === 1 && subrule.length === 0) {
subrule = this.first = SubRule.allSubRule
// Make infinite loop detection ignore this
this.length = -1
} else {
// First subrule pattern length (max of all patterns if many)
// - used in infinite loop detection
this.length = this.first.length
}
// Instantiate and link the subrules
// { test: {Function}
// , next: {SubRule|undefined}
// }
var prev = subrule
// Many subrules or none
for (var i = 1; i < n; i++) {
subrule = SubRule.SubRule( subrules[i], this.props, encoding )
prev.next = subrule
subrule.prev = prev // Useful in some edge cases
prev = subrule
if (this.length < subrule.length) this.length = subrule.length
}
// Last subrule (used for trimRight and matched idx)
this.last = subrule
// Set the first and last subrules length based on trim properties
if (!this.props.trimLeft) this.first.length = 0
if (!this.single && !this.props.trimRight) this.last.length = 0
this.next = null
this.nextFail = null
this.currentRule = null
}
|
javascript
|
{
"resource": ""
}
|
q13253
|
initializeItemSerializer
|
train
|
function initializeItemSerializer(hasItems) {
// Is there is a itemSerializer specified, we MUST use it.
// If existing data and no itemSerializer specified, this is an old JSON database,
// so "fake" the compatible JSON serializer
var providerInfo = storageProvider.getMetadata(namespace); // TODO I hate this!
var itemSerializerName = providerInfo ? providerInfo.itemSerializer :
hasItems ? "JSONSerializer" : null;
storageProvider.itemSerializer = itemSerializerName;
}
|
javascript
|
{
"resource": ""
}
|
q13254
|
_yield
|
train
|
function _yield(name, context) {
var prop = this.props[name || 'children'];
if (typeof prop !== 'function') return prop;
var args = Array.prototype.slice.call(arguments, 2);
return prop.apply(context, args);
}
|
javascript
|
{
"resource": ""
}
|
q13255
|
getJsonResource
|
train
|
function getJsonResource(url) {
var protocol = url.match(/^(.*?):/)
protocol = (protocol && protocol[1]) || 'file'
const defaultLoader = defaultOptions.loaders[protocol]
const loader = options.loaders[protocol]
return Promise.resolve(cache[url])
.then(cached => {
if(cached) {
return cached
} else {
return loader(url, defaultOptions.loaders)
.then(json => cache[url] = {raw: json, parsed: Array.isArray(json) ? [] : {} })
}
})
}
|
javascript
|
{
"resource": ""
}
|
q13256
|
processNode
|
train
|
function processNode({rawNode, parsedNode, parentId = resourceId, cursor, refChain, prop}) {
logger.info(`processNode ${cursor}${prop ? '(' + prop + ')' : ''} with refChain ${refChain}`)
const currentId = options.urlBaseKey && rawNode[options.urlBaseKey]
? parseRef(rawNode[options.urlBaseKey], parentId).fullUrl
: parentId
const props = !!prop ? [prop] : Object.getOwnPropertyNames(rawNode)
let propIndex = -1, nodeChanged = 0
return new Promise((accept, reject) => {
nextProp()
function nextProp() {
propIndex++
if(propIndex >= props.length) {
if (!!prop) {
accept(parsedNode[prop])
} else {
accept(nodeChanged ? parsedNode : rawNode)
}
} else {
const prop = props[propIndex]
const sourceValue = rawNode[prop]
const propCursor = `${cursor}/${prop}`
// If prop is already defined in parsedNode assume complete and skip it
if(parsedNode.hasOwnProperty(prop)){
nodeChanged |= parsedNode[prop] !== sourceValue
nextProp()
}
// Is scalar, just set same and continue
else if (typeof sourceValue !== 'object' || sourceValue === null) {
parsedNode[prop] = sourceValue
nextProp()
}
// prop is a reference
else if(!!sourceValue.$ref) {
const {$ref, ...params} = sourceValue
const branchRefChain = [...refChain, propCursor]
const {url, pointer, isLocalRef, isCircular} = parseRef($ref, currentId, branchRefChain) //, options.vars)
if(!url) throw new Error(`Invalid $ref ${$ref}`)
if(isCircular && options.skipCircular || isLocalRef && externalOnly) {
// if(isLocalRef && externalOnly) {
parsedNode[prop] = sourceValue
nextProp()
} else {
Promise.resolve(isLocalRef
? solvePointer(pointer, branchRefChain, currentId)
: externalOnly && pointer
? processResource(url, pointer, branchRefChain, false)
: processResource(url, pointer, branchRefChain)
)
.then(newValue => {
nodeChanged = 1
parsedNode[prop] = newValue
nextProp()
})
.catch(err => {
const log = `Error derefing ${cursor}/${prop}`
if (options.failOnMissing) {
reject(log)
} else {
logger.info(log)
parsedNode[prop] = sourceValue
nextProp()
}
})
}
} else {
const placeholder = parsedNode[prop] = Array.isArray(sourceValue) ? [] : {}
processNode({
rawNode: sourceValue,
parsedNode: placeholder,
parentId: currentId,
cursor: propCursor,
refChain
})
.then(newValue => {
nodeChanged |= newValue !== sourceValue
nextProp()
})
.catch(reject)
}
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q13257
|
getAll
|
train
|
function getAll(name, deploy, fn, single) {
getTree(name, deploy, function(err, tree) {
if (err) return fn(err);
var acc = [];
flatten(tree, acc);
if (acc.length === 0) return fn(null);
if (single && acc.length === 1) return fn(null, acc[0]);
fn(err, acc);
});
}
|
javascript
|
{
"resource": ""
}
|
q13258
|
train
|
function(portKey) {
var result = this.isValidPort(portKey) ? tessel.port[this.validLEDNames.indexOf(portKey)] : null;
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13259
|
train
|
function(ledName) {
var result = this.isValidLEDName(ledName) ? tessel.port[this.validLEDNames.indexOf(ledName)] : null;
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13260
|
train
|
function(startState) {
let dfa = new DFA();
let stateMap = {};
let epsilonNFASetCache = {}; // NFA-set -> NFA-set
let startOrigin = {
[startState]: 1
};
let start = this.epsilonClosure(startOrigin);
epsilonNFASetCache[hashNFAStates(startOrigin)] = start;
let dfaStates = {},
newAdded = [];
let last = 0,
offset = 0; // distance between last state and current state
dfaStates[hashNFAStates(start)] = 0; // default, the start state for DFA is 0
stateMap[0] = start;
newAdded.push(start);
while (newAdded.length) {
let newAddedTmp = [];
for (let i = 0, n = newAdded.length; i < n; i++) {
let stateSet = newAdded[i];
let newMap = this._getNFASetTransitionMap(stateSet);
let currentDFAState = i + offset;
for (let letter in newMap) {
let toSet = newMap[letter];
let hashKey = hashNFAStates(toSet);
// find new state
let newItem = null;
if (epsilonNFASetCache[hashKey]) {
newItem = epsilonNFASetCache[hashKey];
} else {
newItem = this.epsilonClosure(newMap[letter]);
}
let newItemHashKey = hashNFAStates(newItem);
//
if (dfaStates[newItemHashKey] !== undefined) {
dfa.addTransition(currentDFAState, letter, dfaStates[newItemHashKey]);
} else {
// find new item
last++; // last + 1 as new DFA state
dfaStates[newItemHashKey] = last;
stateMap[last] = newItem;
newAddedTmp.push(newItem);
// build the connection from (index + offset) -> last
dfa.addTransition(currentDFAState, letter, last);
}
}
}
offset += newAdded.length;
newAdded = newAddedTmp;
}
return {
dfa,
stateMap
};
}
|
javascript
|
{
"resource": ""
}
|
|
q13261
|
virtualForm
|
train
|
function virtualForm (h, opts, arr) {
if (!arr) {
arr = opts
opts = {}
}
assert.equal(typeof h, 'function')
assert.equal(typeof opts, 'object')
assert.ok(Array.isArray(arr), 'is array')
return arr.map(function createInput (val) {
if (typeof val === 'string') {
val = { type: 'text', name: val }
}
if (!val.value) val.value = ''
assert.equal(typeof val, 'object')
if (opts.label) {
if (val.type === 'submit') return h('input', val)
return h('fieldset', [
h('label', [ val.name ]),
h('input', val)
])
}
if (val.type !== 'submit' && !val.placeholder) {
val.placeholder = val.name
}
return h('input', val)
})
}
|
javascript
|
{
"resource": ""
}
|
q13262
|
cleanRedundantCode
|
train
|
function cleanRedundantCode(str, opts){
opts = opts || {};
var minimize = def(opts.minimize, true);
var comments = opts.comments || {};
var htmlComments = comments.html,
rglComments = comments.rgl;
if(minimize && typeof str === 'string'){
var SINGLE_SPACE = ' ';
var EMPTY = '';
// remove html-comments <!-- xxx -->
str = !htmlComments ? str.replace(/<!-[\s\S]*?-->/g, EMPTY) : str;
// remove regular-comments {! xxx !}
str = !rglComments ? str.replace(/{![\s\S]*?!}/g, EMPTY) : str;
// 暴力全局替换\s,副作用:内容里面有带空格或回车的字符串会被替换截掉
// str = str.replace(/[\s]{2,}/g, SINGLE_SPACE);
str = str.replace(/[\f\t\v]{2,}/g, SINGLE_SPACE);
// // <abc>,<abc/> 左边
// str = str.replace(/[\s]{2,}(?=<\w+(\s[\s\S]*?)*?\/?>)/g, SINGLE_SPACE);
// // </abc> 左边
// str = str.replace(/[\s]{2,}(?=<\/\w+>)/g, SINGLE_SPACE);
//
// // js并不支持'后行断言'(?<=condition)这种写法,这里只能采用callback函数来弥补
//
// // <abc>,</abc>,<abc/>,/> 右边
// str = str.replace(/((?:<\/?\w+>)|(?:<\w+\/>)|(?:\/>))[\s]{2,}/g, function($0, $1){
// return ($1 ? ($ + SINGLE_SPACE) : $0);
// });
// // 花括号左右
// str = str.replace(/[\s]+(?=(}|\{))/g, SINGLE_SPACE); // 左空格
// str = str.replace(/(}|\{)(\s+)/g, function($0, $1){ // 右空格
// return $1 + SINGLE_SPACE;
// });
// // 大小于等号左右
// str = str.replace(/[\s]+(?=(>|<))/g, SINGLE_SPACE); // 左空格
// str = str.replace(/(>|<)(\s+)/g, function($0, $1){ // 右空格
// return $1 + SINGLE_SPACE;
// });
// Last, trim
str = str.trim();
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q13263
|
getCache
|
train
|
function getCache (pkg, config) {
pkg = toPkg(pkg)
if(config && config.cacheHash)
return path.join(config.cache, pkg.shasum, 'package.tgz')
return path.join(
config.cache || path.join(process.env.HOME, '.npm'),
pkg.name, pkg.version, 'package.tgz'
)
}
|
javascript
|
{
"resource": ""
}
|
q13264
|
get
|
train
|
function get (url, cb) {
var urls = [], end
_get(url, cb)
function _get (url) {
urls.push(url)
if(end) return
if(urls.length > 5)
cb(end = new Error('too many redirects\n'+JSON.stringify(urls)))
console.error('GET', url)
;(/^https/.test(url) ? https : http).get(url, function next (res) {
if(res.statusCode >= 300 && res.statusCode < 400)
_get(res.headers.location)
else {
end = true,
cb(null, res)
}
})
.on('error', function (err) {
if(!end)
cb(end = err)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q13265
|
getTarballStream
|
train
|
function getTarballStream (pkg, config, cb) {
if(config.casDb && pkg.shasum) {
var db = config.casDb
db.has(pkg.shasum, function (err, stat) {
if(!err)
cb(null, db.getStream(pkg.shasum))
else //fallback to the old way...
tryCache()
})
}
else
tryCache()
function tryCache () {
var cache = getCache(pkg, config)
fs.stat(cache, function (err) {
if(!err)
cb(null, fs.createReadStream(cache))
else
getDownload(pkg, config, cb)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q13266
|
getTmp
|
train
|
function getTmp (config) {
return path.join(config.tmpdir || '/tmp', ''+Date.now() + Math.random())
}
|
javascript
|
{
"resource": ""
}
|
q13267
|
mixin
|
train
|
function mixin(source) {
var keys = [];
if (arguments.length > 1) {
for (var i = 1, len = arguments.length; i < len; i++) {
var key = arguments[i];
if (!source.hasOwnProperty(key)) {
throw new Error(util.format('Property not found: %s', key));
}
keys.push(key);
}
} else {
keys = Object.keys(source);
}
// Copy.
for (var i = 0, len = keys.length; i < len; i++) {
key = keys[i];
defineProp(this, key, descriptor(source, key));
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q13268
|
subst
|
train
|
function subst(str, file, dst) {
if (dst !== undefined) {
str = str.replace(/\{\{DST\}\}/g, dst);
}
var dir = path.dirname(file);
str = str.replace(/\{\{SRC\}\}/g, file);
var name = path.basename(file);
str = str.replace(/\{\{NAME\}\}/g, name);
name = name.replace(/\.\w+$/, '');
str = str.replace(/\{\{BASENAME\}\}/g, name);
str = str.replace(/\{\{DIR\}\}/g, dir);
var parts = dir.split(path.sep);
parts.splice(0, 1);
str = str.replace(/\{\{SUBDIR\}\}/g, path.join.apply(null, parts));
parts.splice(0, 1);
str = str.replace(/\{\{SUBSUBDIR\}\}/g, path.join.apply(null, parts));
return str;
}
|
javascript
|
{
"resource": ""
}
|
q13269
|
train
|
function(request, response, next){
if (utils.Misc.isEmptyObject(request.query)) {
var errApp = new Error(errors['130']);
response.end(utils.Misc.createResponse(null, errApp, 130));
}
else {
next();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13270
|
train
|
function(request, response, next){
if (!utils.Misc.isNullOrUndefined(request.user)) {
next();
}
else {
var error = new Error(errors['213']);
response.end(utils.Misc.createResponse(null, error, 213));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13271
|
train
|
function(request, response, next){
if (!utils.Misc.isNullOrUndefined(request.user) || request.originalUrl == '/error' || request.originalUrl.indexOf('/error?') == 0) {
next();
}
else {
var success = encodeURIComponent(request.protocol + '://' + request.get('host') + request.originalUrl);
response.redirect('/login?success=' + success + '&no_query=true'); //we don't want it to add any query string
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13272
|
train
|
function(request, response, next){
var apptkn;
if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) {
apptkn = request.get(X_BOLT_APP_TOKEN);
}
else {
var error = new Error(errors['110']);
response.end(utils.Misc.createResponse(null, error, 110));
return;
}
var name = __getAppFromAppToken(apptkn, request);
if (utils.Misc.isNullOrUndefined(name)) {
var error = new Error(errors['113']);
response.end(utils.Misc.createResponse(null, error, 113));
return;
}
var appnm = utils.String.trim(name.toLowerCase());
if (appnm == 'bolt') {
//native views
next();
}
else {
models.app.findOne({
name: appnm, system: true
}, function(appError, app){
if (!utils.Misc.isNullOrUndefined(appError)) {
response.end(utils.Misc.createResponse(null, appError));
}
else if(utils.Misc.isNullOrUndefined(app)){
var error = new Error(errors['504']);
response.end(utils.Misc.createResponse(null, error, 504));
}
else{
next();
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13273
|
train
|
function(request, response, next){
var apptkn;
if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) {
apptkn = request.get(X_BOLT_APP_TOKEN);
}
else {
var error = new Error(errors['110']);
response.end(utils.Misc.createResponse(null, error, 110));
return;
}
var name = __getAppFromAppToken(apptkn, request);
if (utils.Misc.isNullOrUndefined(name)) {
var error = new Error(errors['113']);
response.end(utils.Misc.createResponse(null, error, 113));
return;
}
var appnm = utils.String.trim(name.toLowerCase());
request.appName = appnm;
next();
}
|
javascript
|
{
"resource": ""
}
|
|
q13274
|
train
|
function(request, response, next){
if (!utils.Misc.isNullOrUndefined(request.body.db)) {
request.db = request.body.db;
}
else if (!utils.Misc.isNullOrUndefined(request.body.app)) {
request.db = request.body.app;
}
else {
var apptkn;
if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) {
apptkn = request.get(X_BOLT_APP_TOKEN);
}
else {
var error = new Error(errors['110']);
response.end(utils.Misc.createResponse(null, error, 110));
return;
}
var name = __getAppFromAppToken(apptkn, request);
if (utils.Misc.isNullOrUndefined(name)) {
var error = new Error(errors['113']);
response.end(utils.Misc.createResponse(null, error, 113));
return;
}
var appnm = utils.String.trim(name.toLowerCase());
request.db = appnm;
}
if (request.db.indexOf('/') > -1 || request.db.indexOf('\\') > -1 || request.db.indexOf('?') > -1 || request.db.indexOf('&') > -1) {
//invalid characters in app name
var error = new Error(errors['405']);
response.end(utils.Misc.createResponse(null, error, 405));
return;
}
next();
}
|
javascript
|
{
"resource": ""
}
|
|
q13275
|
train
|
function(request, response, next) {
var apptkn;
if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) {
apptkn = request.get(X_BOLT_APP_TOKEN);
}
else {
var error = new Error(errors['110']);
response.end(utils.Misc.createResponse(null, error, 110));
return;
}
var name = __getAppFromAppToken(apptkn, request);
if (utils.Misc.isNullOrUndefined(name)) {
var error = new Error(errors['113']);
response.end(utils.Misc.createResponse(null, error, 113));
return;
}
var appnm = utils.String.trim(name.toLowerCase());
var dbOwner = request.body.db || request.body.app || appnm;
models.collection.findOne({ name: request.params.collection, app: dbOwner }, function(collError, collection){
if (!utils.Misc.isNullOrUndefined(collError)){
response.end(utils.Misc.createResponse(null, collError));
}
else if(utils.Misc.isNullOrUndefined(collection)){
var errColl = new Error(errors['703']);
response.end(utils.Misc.createResponse(null, errColl, 703));
}
else {
//allow the owner to pass
if (appnm == collection.app.toLowerCase()) {
next();
return;
}
if (!utils.Misc.isNullOrUndefined(collection.tenants)) { //tenants allowed
if ("*" == collection.tenants) { //every body is allowed
next();
return;
}
//there is a tenant list; are u listed?
else if (collection.tenants.map(function(value){ return value.toLowerCase(); }).indexOf(appnm) > -1) {
next();
return;
}
}
//no guests allowed
var error = new Error(errors['704']);
response.end(utils.Misc.createResponse(null, error, 704));
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13276
|
toBitMask
|
train
|
function toBitMask(event) {
if (!_.has(eventMap, event)) {
throw new Error('Unkown event: ' + event);
}
return eventMap[event];
}
|
javascript
|
{
"resource": ""
}
|
q13277
|
addFlags
|
train
|
function addFlags(mask, flags) {
if (flags.onlydir) mask = mask | Inotify.IN_ONLYDIR;
if (flags.dont_follow) mask = mask | Inotify.IN_DONT_FOLLOW;
if (flags.oneshot) mask = mask | Inotify.IN_ONESHOT;
return mask;
}
|
javascript
|
{
"resource": ""
}
|
q13278
|
FABridge__bridgeInitialized
|
train
|
function FABridge__bridgeInitialized(bridgeName) {
var objects = document.getElementsByTagName("object");
var ol = objects.length;
var activeObjects = [];
if (ol > 0) {
for (var i = 0; i < ol; i++) {
if (typeof objects[i].SetVariable != "undefined") {
activeObjects[activeObjects.length] = objects[i];
}
}
}
var embeds = document.getElementsByTagName("embed");
var el = embeds.length;
var activeEmbeds = [];
if (el > 0) {
for (var j = 0; j < el; j++) {
if (typeof embeds[j].SetVariable != "undefined") {
activeEmbeds[activeEmbeds.length] = embeds[j];
}
}
}
var aol = activeObjects.length;
var ael = activeEmbeds.length;
var searchStr = "bridgeName="+ bridgeName;
if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) {
FABridge.attachBridge(activeObjects[0], bridgeName);
}
else if (ael == 1 && !aol) {
FABridge.attachBridge(activeEmbeds[0], bridgeName);
}
else {
var flash_found = false;
if (aol > 1) {
for (var k = 0; k < aol; k++) {
var params = activeObjects[k].childNodes;
for (var l = 0; l < params.length; l++) {
var param = params[l];
if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) {
FABridge.attachBridge(activeObjects[k], bridgeName);
flash_found = true;
break;
}
}
if (flash_found) {
break;
}
}
}
if (!flash_found && ael > 1) {
for (var m = 0; m < ael; m++) {
var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue;
if (flashVars.indexOf(searchStr) >= 0) {
FABridge.attachBridge(activeEmbeds[m], bridgeName);
break;
}
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q13279
|
train
|
function(objRef, propName)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
retVal = this.target.getPropFromAS(objRef, propName);
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13280
|
train
|
function(objRef,propName, value)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
retVal = this.target.setPropInAS(objRef,propName, this.serialize(value));
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13281
|
train
|
function(funcID, args)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
retVal = this.target.invokeASFunction(funcID, this.serialize(args));
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13282
|
train
|
function(objID, funcName, args)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
args = this.serialize(args);
retVal = this.target.invokeASMethod(objID, funcName, args);
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13283
|
train
|
function(funcID, args)
{
var result;
var func = this.localFunctionCache[funcID];
if(func != undefined)
{
result = this.serialize(func.apply(null, this.deserialize(args)));
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13284
|
train
|
function(objID, typeName)
{
var objType = this.getTypeFromName(typeName);
instanceFactory.prototype = objType;
var instance = new instanceFactory(objID);
this.remoteInstanceCache[objID] = instance;
return instance;
}
|
javascript
|
{
"resource": ""
}
|
|
q13285
|
train
|
function(typeData)
{
var newType = new ASProxy(this, typeData.name);
var accessors = typeData.accessors;
for (var i = 0; i < accessors.length; i++)
{
this.addPropertyToType(newType, accessors[i]);
}
var methods = typeData.methods;
for (var i = 0; i < methods.length; i++)
{
if (FABridge.blockedMethods[methods[i]] == undefined)
{
this.addMethodToType(newType, methods[i]);
}
}
this.remoteTypeCache[newType.typeName] = newType;
return newType;
}
|
javascript
|
{
"resource": ""
}
|
|
q13286
|
train
|
function(ty, propName)
{
var c = propName.charAt(0);
var setterName;
var getterName;
if(c >= "a" && c <= "z")
{
getterName = "get" + c.toUpperCase() + propName.substr(1);
setterName = "set" + c.toUpperCase() + propName.substr(1);
}
else
{
getterName = "get" + propName;
setterName = "set" + propName;
}
ty[setterName] = function(val)
{
this.bridge.setPropertyInAS(this.fb_instance_id, propName, val);
}
ty[getterName] = function()
{
return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13287
|
train
|
function(ty, methodName)
{
ty[methodName] = function()
{
return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id, methodName, FABridge.argsToArray(arguments)));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13288
|
train
|
function(funcID)
{
var bridge = this;
if (this.remoteFunctionCache[funcID] == null)
{
this.remoteFunctionCache[funcID] = function()
{
bridge.callASFunction(funcID, FABridge.argsToArray(arguments));
}
}
return this.remoteFunctionCache[funcID];
}
|
javascript
|
{
"resource": ""
}
|
|
q13289
|
train
|
function(func)
{
if (func.__bridge_id__ == undefined)
{
func.__bridge_id__ = this.makeID(this.nextLocalFuncID++);
this.localFunctionCache[func.__bridge_id__] = func;
}
return func.__bridge_id__;
}
|
javascript
|
{
"resource": ""
}
|
|
q13290
|
shadowClose
|
train
|
function shadowClose(connection) {
debug('shadowClose', 'start');
let close = connection.close;
connection.close = function() {
debug('connection.close','start');
//remove references
delete promises[connection._mssqlngKey];
delete connections[connection._mssqlngKey];
//close original connection
setImmediate(()=>{
try {
debug('connection.close','apply');
close.apply(connection);
debug('connection.close','applied');
//clear local references - allow GC
close = null;
connection - null;
}catch(err){}
});
debug('connection.close','end');
}
}
|
javascript
|
{
"resource": ""
}
|
q13291
|
train
|
function (infos, name) {
name = name || 'jsdoc.json';
var firstFile = null;
var readme = null;
var wp = new Parser(infos);
var bufferFiles = function(file, enc, next){
if (file.isNull()) return; // ignore
if (file.isStream()) return this.emit('error', new PluginError('gulp-jsdoc', 'Streaming not supported'));
// Store firstFile to get a base and cwd later on
if (!firstFile)
firstFile = file;
if (/[.]js$/i.test(file.path))
wp.parse(file);
else if(/readme(?:[.]md)?$/i.test(file.path))
readme = marked(file.contents.toString('utf8'));
next();
};
var endStream = function(conclude){
// Nothing? Exit right away
if (!firstFile){
conclude();
return;
}
var data;
try{
data = JSON.stringify(wp.complete(), null, 2);
// data = parser(options, filemap));
}catch(e){
return this.emit('error', new PluginError('gulp-jsdoc',
'Oooooh! Failed parsing with jsdoc. What did you do?! ' + e));
}
// Pump-up the generated output
var vinyl = new File({
cwd: firstFile.cwd,
base: firstFile.base,
path: path.join(firstFile.base, name),
contents: new Buffer(data)
});
// Possibly stack-up the readme, if there was any in the first place
vinyl.readme = readme;
// Add that to the stream...
this.push(vinyl);
conclude();
};
// That's it for the parser
return through2.obj(bufferFiles, endStream);
}
|
javascript
|
{
"resource": ""
}
|
|
q13292
|
train
|
function(model, options) {
if (!(model instanceof Parse.Object)) {
var attrs = model;
options.collection = this;
model = new this.model(attrs, options);
if (!model._validate(model.attributes, options)) {
model = false;
}
} else if (!model.collection) {
model.collection = this;
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q13293
|
_configGetExtLang
|
train
|
function _configGetExtLang(filext) {
var fileext1 = filext.indexOf('.') == 0 ? fileext.substring(1, filext.length) : fileext;
if (!config.extlangs.hasOwnProperty(fileext1))
return null;
return config.extlangs[fileext1];
}
|
javascript
|
{
"resource": ""
}
|
q13294
|
extractCommentTagFromLine
|
train
|
function extractCommentTagFromLine(fileext, line) {
line = line.trim();
// CHECK FORMAT [
var b;
function chkfmt(b) {
if (line.indexOf(b) == 0 && line.indexOf('[') == line.length-1) // begin
return [line.substr(b.length, line.length-b.length-1).trim(), 0];
if (line.indexOf(b) == 0 && line.indexOf(']') == line.length-1 && line.indexOf('[') == -1) // end
return [line.substr(b.length, line.length-b.length-1).trim(), 1];
return null;
};
// CHECK FORMAT ]
// SUPPORT FORMATS [
switch (fileext) {
case '.js':
case '.java':
case '.c':
case '.h':
case '.cpp':
case '.hpp':
case '.less':
case '.m':
case '.mm':
return chkfmt('//') || false;
case '.css':
return chkfmt('/*') || false;
case '.acpul':
case '.sh':
case '.py':
case '.pro':
return chkfmt('#') || false;
case '.ejs':
case '.jade':
case '.sass':
case '.styl':
case '.coffee':
break;
default:
return null;
}
// SUPPORT FORMATS ]
return false;
}
|
javascript
|
{
"resource": ""
}
|
q13295
|
train
|
function(name, dimensions) {
name = name || '';
name = name.replace(/^\s*/, '');
name = name.replace(/\s*$/, '');
if (name.length === 0) {
throw 'A name for the custom event must be provided';
}
_.each(dimensions, function(val, key) {
if (!_.isString(key) || !_.isString(val)) {
throw 'track() dimensions expects keys and values of type "string".';
}
});
return Parse._request({
route: 'events',
className: name,
method: 'POST',
data: { dimensions: dimensions }
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13296
|
retryPromiseTimeout
|
train
|
function retryPromiseTimeout(PromiseFunc, Obj, Options){
let timeoutOpts = Options.Timeout;
limitpromises = limitpromises || require('../limitpromises');
setTimeout( () => {
if(Obj.isRunning && Obj.attempt <= timeoutOpts.retryAttempts){
// Put a new promise on the same stack as the current one is, so you dont call more promises of one
// group as specified. Input Value is just true as we dont need it and only make one promise
let newPromise = limitpromises( () =>{
return new Promise((resolve, reject) => {
PromiseFunc(Obj.inputValue).then(data => {
resolve(data);
}, err => {
reject(err);
});
});
},[true], Obj.maxAtOnce, Obj.TypeKey);
// Wait for the PromiseArray and either resolve the current promise or handle the rejects
Promise.all(newPromise.map(r => {return r.result})).then(data => {
if(Obj.isRunning){
Obj.resolveResult(data);
}
}, err => {
if(Obj.isRunning){
handleRejects(PromiseFunc, Obj, err, Options);
}
});
// Call the function again to check again after a given time
retryPromiseTimeout(PromiseFunc, Obj, Options);
// Count that an attempt has been made for that object
Obj.attempt++;
// If more retry attempts have been made than specified by the user, reject the result
} else if (Obj.isRunning && Obj.attempt > timeoutOpts.retryAttempts){
Obj.rejectResult(new Error.TimeoutError(Obj));
}
}, timeoutOpts.timeoutMillis);
}
|
javascript
|
{
"resource": ""
}
|
q13297
|
queue
|
train
|
function queue(task, done) {
var storage = this,
key = this.keygen(task);
// store task as JSON serialized string
task = JSON.stringify(task);
// first add the key to the queue
this.redis().rpush(this.queueKey(), key, function(err) {
if (err) done(err);
// now store task data
else storage.redis().set(key, task, function(err) {
if (err) done(err);
else done(null, key);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q13298
|
unqueue
|
train
|
function unqueue(done) {
var storage = this;
this.redis().lpop(this.queueKey(), function(err, key) {
if (err) return done(err);
storage.redis().get(key, function(err, task) {
if (err) return done(err);
if (!task) return done();
storage.redis().del(key);
done(null, JSON.parse(task), key);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q13299
|
log
|
train
|
function log(key, result, done) {
var storage = this;
// store result as JSON serialized string
result = JSON.stringify(result);
// generate result key from task key
key = key + "-result";
// first add the key to the log
this.redis().rpush(this.logKey(), key, function(err) {
if (err) done(err);
// now store result data
else storage.redis().set(key, result, done);
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.