_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q61800
|
flip
|
validation
|
function flip(it) {
return __asyncGenerator(this, arguments, function* flip_1() {
yield __await(yield* __asyncDelegator(__asyncValues(yield __await(reduce((prev, next) => [next].concat(prev), [])(it)))));
});
}
|
javascript
|
{
"resource": ""
}
|
q61801
|
repeat
|
validation
|
function repeat(times) {
return function (it) {
return __asyncGenerator(this, arguments, function* () {
var e_26, _a;
const buffer = [];
try {
for (var it_6 = __asyncValues(it), it_6_1; it_6_1 = yield __await(it_6.next()), !it_6_1.done;) {
const item = it_6_1.value;
buffer.push(item);
yield yield __await(item);
}
}
catch (e_26_1) { e_26 = { error: e_26_1 }; }
finally {
try {
if (it_6_1 && !it_6_1.done && (_a = it_6.return)) yield __await(_a.call(it_6));
}
finally { if (e_26) throw e_26.error; }
}
for (let i = 0; i < times; ++i) {
yield __await(yield* __asyncDelegator(__asyncValues(buffer)));
}
});
};
}
|
javascript
|
{
"resource": ""
}
|
q61802
|
doppler
|
validation
|
function doppler(it) {
return __asyncGenerator(this, arguments, function* doppler_1() {
var e_27, _a;
const buffer = [];
try {
for (var it_7 = __asyncValues(it), it_7_1; it_7_1 = yield __await(it_7.next()), !it_7_1.done;) {
const item = it_7_1.value;
buffer.push(item);
yield yield __await(item);
}
}
catch (e_27_1) { e_27 = { error: e_27_1 }; }
finally {
try {
if (it_7_1 && !it_7_1.done && (_a = it_7.return)) yield __await(_a.call(it_7));
}
finally { if (e_27) throw e_27.error; }
}
buffer.reverse();
yield __await(yield* __asyncDelegator(__asyncValues(buffer)));
});
}
|
javascript
|
{
"resource": ""
}
|
q61803
|
count
|
validation
|
async function count(source) {
var e_33, _a;
let i = 0;
try {
for (var source_4 = __asyncValues(source), source_4_1; source_4_1 = await source_4.next(), !source_4_1.done;) {
const it = source_4_1.value;
++i;
}
}
catch (e_33_1) { e_33 = { error: e_33_1 }; }
finally {
try {
if (source_4_1 && !source_4_1.done && (_a = source_4.return)) await _a.call(source_4);
}
finally { if (e_33) throw e_33.error; }
}
return i;
}
|
javascript
|
{
"resource": ""
}
|
q61804
|
empty
|
validation
|
async function empty(source) {
var e_34, _a;
let i = 0;
try {
for (var source_5 = __asyncValues(source), source_5_1; source_5_1 = await source_5.next(), !source_5_1.done;) {
const it = source_5_1.value;
return false;
}
}
catch (e_34_1) { e_34 = { error: e_34_1 }; }
finally {
try {
if (source_5_1 && !source_5_1.done && (_a = source_5.return)) await _a.call(source_5);
}
finally { if (e_34) throw e_34.error; }
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q61805
|
CloseCommand
|
validation
|
function CloseCommand(args, define) {
var parsed = new statements.ExpressionStatement(args, define);
if (!(parsed.child instanceof statements.PointerStatement)) throw new SyntaxError('Expected pointer');
this.pointer = parsed;
}
|
javascript
|
{
"resource": ""
}
|
q61806
|
Block
|
validation
|
function Block(line, def, parent) {
this.startNames = [];
this.thenNames = [];
this.endNames = [];
for (var i = 0; i < def.start.length; i++) this.startNames.push(def.start[i].toLowerCase());
for (var x = 0; x < def.end.length; x++) this.endNames.push(def.end[x].toLowerCase());
for (var y = 0; y < def.then.length; y++) this.thenNames.push(def.then[y].toLowerCase());
this.line = line;
this.parent = parent;
this.searchIndex = line;
this.start = -1;
this.intermediateIndexes = {};
this.intermediateCursors = {};
this.end = -1;
}
|
javascript
|
{
"resource": ""
}
|
q61807
|
ReadCommand
|
validation
|
function ReadCommand(args) {
var parsed = new statements.ArgumentStatement(args);
for (var i = 0; i < parsed.args.length; i++) {
var placeVar = parsed.args[i];
if (!(placeVar.child instanceof statements.VariableStatement || placeVar.child instanceof statements.FunctionStatement))
throw new SyntaxError('Expected variable');
}
this.items = parsed.args;
}
|
javascript
|
{
"resource": ""
}
|
q61808
|
compileValue
|
validation
|
function compileValue(value) {
if (value.subtype === 'array') {
return compileArray(value)
} else if (value.subtype === 'object') {
return compileObject(value)
} else if (value.subtype === 'mixin') {
return compileMixin(value)
} else if (value.subtype === 'js') {
return compileJS(value)
} else if (value.subtype === 'function') {
return compileFunction(value)
}
throw new Error('Invalid subtype: ' + value.subtype)
}
|
javascript
|
{
"resource": ""
}
|
q61809
|
DrawspriteCommand
|
validation
|
function DrawspriteCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 3) throw new SyntaxError('DRAWSPRITE command requires 3 arguments');
this.id = parsed.args[0];
this.x = parsed.args[1];
this.y = parsed.args[2];
this.scale = parsed.args.length === 4 ? parsed.args[3] : false;
this.rotation = parsed.args.length === 5 ? parsed.args[4] : false;
}
|
javascript
|
{
"resource": ""
}
|
q61810
|
validation
|
function (string) { // string.check check sting type and size
return ((typeof string === 'string' || string instanceof String)
&& string.length >= this.min
&& string.length <= this.max
&& (!this.match || string.match(this.match))
);
}
|
javascript
|
{
"resource": ""
}
|
|
q61811
|
sprintf
|
validation
|
function sprintf (fstr, array) {
// check the formatted string is for JSON and confirm is a valid JSON
array.forEach(function (value) {
fstr = format(fstr, value);
});
return fstr;
}
|
javascript
|
{
"resource": ""
}
|
q61812
|
deepLook
|
validation
|
function deepLook(obj, types) {
if (typeof (obj) !== 'object') return obj;
for (var key in obj) {
if (!obj[key].type) {
obj[key] = deepLook(obj[key], types);
} else {
if (!types[obj[key].type]) {
throw new Error('No type ' + obj[key].type + ' in Types: key ' + key);
}
// check for range in new object
if (typeof obj[key].min !== 'undefined'
&& typeof types[obj[key].type].min !== 'undefined'
&& types[obj[key].type].min > obj[key].min) {
throw new Error('Key ' + key + ' minimal value (' + obj[key].min
+ ') is less than acceptable minimal in Types ('
+ types[obj[key].type].min + ')');
}
if (typeof obj[key].max !== 'undefined'
&& typeof types[obj[key].type].max !== 'undefined'
&& types[obj[key].type].max < obj[key].max) {
throw new Error('Key ' + key + ' maximal value (' + obj[key].max
+ ') is in excess of maximal acceptable value in Types ('
+ types[obj[key].type].max + ')');
}
}
// get properties and methods from Types
for (var keyParent in types[obj[key].type]) {
if (!obj[key][keyParent]) {
obj[key][keyParent] = types[obj[key].type][keyParent];
}
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q61813
|
validateObjectRequired
|
validation
|
function validateObjectRequired(options, modelObject, entity, parents, errors) {
for (var key in modelObject) {
if (!modelObject[key].type && entity) {
validateObjectRequired(
options,
modelObject[key],
entity[key],
parents + '.' + key,
errors);
} else if (!options.notRequired && modelObject[key].required && (!entity || !entity[key])) {
if (!errors.notFound) errors.notFound = [];
var fieldName = parents + '.' + key;
errors.notFound.push(fieldName);
errors.text.push('Field ' + fieldName + ' not found');
}
}
return errors;
}
|
javascript
|
{
"resource": ""
}
|
q61814
|
validateObjectEntity
|
validation
|
function validateObjectEntity(modelObject, entity, parents, errors) {
if (!errors) errors = {};
if (!errors.text) errors.text = [];
if (!parents) parents = [];
for (var key in entity) {
var fieldName = parents + '.' + key;
if (!modelObject || !modelObject[key]) {
if (!errors.notRequired) errors.notRequired = [];
errors.notRequired.push(fieldName);
errors.text.push('Field ' + fieldName + ' not required');
} else if (!modelObject[key].type) {
validateObjectEntity(modelObject[key], entity[key], [parents, key], errors);
} else if (!modelObject[key].check(entity[key])) {
if (!errors.notMatched) errors.notMatched = {};
errors.notMatched[fieldName] = modelObject[key].type;
errors.text.push('Field ' + fieldName + ' not matched with type ' + modelObject[key].type);
}
}
return errors;
}
|
javascript
|
{
"resource": ""
}
|
q61815
|
validation
|
function (params) {
var res = [];
if (typeof (params) === 'undefined') params = { displayEverything: false };
if (!this.registeredModels || Object.keys(this.registeredModels).length === 0) {
res.push('There is no registered models');
} else {
res.push('List of registered models');
for (var modelName in this.registeredModels) {
res.push(' - ' + modelName);
if (params.displayEverything) {
for (var key in this.registeredModels[modelName]) {
res.push(' ' + key + ' : ' + this.registeredModels[modelName][key].type);
}
}
}
}
return res.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
|
q61816
|
validation
|
function (modelName, entity, options, next) {
if (typeof options === 'function') next = options;
if (!options) options = {};
var modelObject = this.registeredModels[modelName];
if (typeof modelName === 'object') {
modelObject = deepLook(modelName, this.types);
} else if (this.types[modelName]) {
if (options.one) this.types[modelName].one = options.one;
var result = this.types[modelName].check(entity) ? null : { notMatched: modelName };
return typeof next === 'function' ? next(result) : result;
}
var errors = validateObjectRequired(
options, modelObject, entity, [],
validateObjectEntity(modelObject, entity)
);
if (!errors.text[0]) errors = {};
if (errors && errors.text) errors.text = errors.text.join('. ');
if (typeof next === 'function') {
next(Object.keys(errors).length ? errors : null);
} else {
return Object.keys(errors).length ? errors : {};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61817
|
validation
|
function (type) {
var examples = this.getExamples(type);
return examples[Math.floor(Math.random() * examples.length)];
}
|
javascript
|
{
"resource": ""
}
|
|
q61818
|
SleepCommand
|
validation
|
function SleepCommand(args, define) {
this.duration = new statements.ExpressionStatement(args, define);
if (this.duration.error) throw this.duration.error;
}
|
javascript
|
{
"resource": ""
}
|
q61819
|
validation
|
function(callback,compilationSource){
if( compilationSource && this.cache.compilationSource && this.cache.compilationSource === compilationSource ) return;
var callbackError=function(type,strOrErr){
/*if(strOrErr instanceof Array){
var i,finalStr='Errors :';
for(i in strOrErr){
console.error(strOrErr[i].stack);
finalStr+=+"\n"+strOrErr[i].toString().slice(7);
}
strOrErr=finalStr;
}*/
//var error=new Error(strOrErr instanceof Error ? strOrErr.toString().slice(7) : strOrErr);
var error=strOrErr instanceof Error ? strOrErr : new Error(strOrErr);
error._Type=type;
t.cache.error=error;
callback(error);
},t=this;
if(t.compiler){
(t.compiler.read||function(path,callback){
fs.readFile(t.srcPath,function(err,buffer){
if(err) return callback(err);
callback(null,buffer.toString());
});
})(t.srcPath,function(err,fileContent){
if(err) return callbackError('Reading',err);
t.lint(t,fileContent,function(err){
if(err) return callbackError('Linting',err);
t.parse(fileContent,function(err,data){
if(err) return callbackError('Parsing',err);
try{
t._compile(data,function(err,results,dependencies){
if(err) return callbackError('Compiling',err);
if(err===false) return callback();
t.optimize(t,results,function(err,optimizedResults){
if(err) return callbackError('Optimizing',err);
t.cache.error=null;
t.cache.compilationTime=Date.now();
t.cache.compilationSource=compilationSource;
if(err===false){
t.cache.dependencies=null;
return callback();
}
t.cache.dependencies=!dependencies || dependencies.app ? dependencies : {app:dependencies};
t.write(optimizedResults,callback);
});
});
}catch(err){
return callbackError('Compiling',err);
}
});
});
});
}else{
t.copy(callback);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61820
|
errorHandler
|
validation
|
function errorHandler(response, error) {
response
.status(500)
.send(error !== undefined && error !== null ? error.toString() : '')
}
|
javascript
|
{
"resource": ""
}
|
q61821
|
validation
|
function(cb) {
Person.find('Scott', function(err, person) {
if (err) { return cb(err); }
assert(person.uuid);
assert(person.name === 'Scott');
scott = person;
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q61822
|
validation
|
function(cb) {
var calli = Dog.new({ name: 'Calli' });
// saves and creates connection
scott.addDog(calli, function(err) {
if (err) { return cb(err); }
scott.fetchDogs(function(err) {
if (err) { return cb(err); }
assert(scott.dogs);
var dog = scott.dogs[0];
assert(dog.uuid);
assert(dog.name === 'Calli');
cb();
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q61823
|
CircleCommand
|
validation
|
function CircleCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 3) throw new SyntaxError('CIRCLE command requires 3 arguments');
this.x = parsed.args[0];
this.y = parsed.args[1];
this.radius = parsed.args[2];
this.stroke = parsed.args.length > 3 ? parsed.args[3] : false;
}
|
javascript
|
{
"resource": ""
}
|
q61824
|
Polling
|
validation
|
function Polling (objGoogleCheckout) {
var self = this;
//todo: check the constructor name
assert.ok(objGoogleCheckout, "A GoogleCheckout object is the only required argument");
self.gc = objGoogleCheckout;
self.settings = self.gc.settings;
self.continueToken = null;
}
|
javascript
|
{
"resource": ""
}
|
q61825
|
TriangleCommand
|
validation
|
function TriangleCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 6) throw new SyntaxError('TRIANGLE command requires 6 arguments');
this.x1 = parsed.args[0];
this.y1 = parsed.args[1];
this.x2 = parsed.args[2];
this.y2 = parsed.args[3];
this.x3 = parsed.args[4];
this.y3 = parsed.args[5];
this.stroke = parsed.args.length > 6 ? parsed.args[6] : false;
}
|
javascript
|
{
"resource": ""
}
|
q61826
|
processFile
|
validation
|
function processFile(file) {
var changed = true;
while(changed && !file.processed) {
changed = false;
changed = processWraps(file);
changed = processInserts(file);
}
file.processed = true;
}
|
javascript
|
{
"resource": ""
}
|
q61827
|
Service
|
validation
|
function Service(name) {
debug('new service: %s', name);
assert(name, "service not supplied with name");
this.name = name;
this.middleware = [];
this.uri = new Uri();
this.status = new Status();
this.initialize();
return this;
}
|
javascript
|
{
"resource": ""
}
|
q61828
|
Analyzer
|
validation
|
function Analyzer(config, state) {
config = config || {};
this.state = state;
this.config = extend(true, {
finders: {
styl : [
{
name: 'regex',
config: {
pattern: /^\s*(?:@import|@require)\s+['"](.+?)['"](?:$|;)/gm,
exclude: ['nib']
}
}
],
coffee: [
{
name: 'regex',
config: {
pattern: /^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*(?:\()?['"]([^'"]+)['"](?:\))?/gm
}
}
],
cjsx: [
{
name: 'regex',
config: {
pattern: /^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*(?:\()?['"]([^'"]+)['"](?:\))?/gm
}
}
],
js: [
{
name: 'regex',
config: {
pattern: [
/^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*\(?['"]([^'"]+)['"]\)?/gm,
/\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/gm
]
}
}
],
jsx: [
{
name: 'regex',
config: {
pattern: [
/^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*\(?['"]([^'"]+)['"]\)?/gm,
/\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/gm
]
}
}
]
},
resolvers: {
styl : [
{
name: 'basic',
config: {
extensions: [
'styl',
'css'
]
}
}
],
coffee: [
{
name: 'common-js',
config: {
extensions: [
'coffee',
'js',
'cjsx',
'jsx'
]
}
}
],
cjsx: [
{
name: 'common-js',
config: {
extensions: [
'coffee',
'js',
'cjsx',
'jsx'
]
}
}
],
js: [
{
name: 'common-js',
config: {
extensions: [
'coffee',
'js',
'cjsx',
'jsx'
]
}
}
],
jsx: [
{
name: 'common-js',
config: {
extensions: [
'coffee',
'js',
'cjsx',
'jsx'
]
}
}
]
}
}, config);
this.finders = {};
this.resolvers = {};
this.createFinders();
this.createResolvers();
}
|
javascript
|
{
"resource": ""
}
|
q61829
|
RrectCommand
|
validation
|
function RrectCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 5) throw new SyntaxError('RRECT command requires 5 arguments');
this.x1 = parsed.args[0];
this.y1 = parsed.args[1];
this.x2 = parsed.args[2];
this.y2 = parsed.args[3];
this.radius = parsed.args[4];
this.stroke = parsed.args.length > 5 ? parsed.args[5] : false;
}
|
javascript
|
{
"resource": ""
}
|
q61830
|
cons
|
validation
|
function cons (b, value, next) {
var free = readValue(b, 0) || 8
updateValue(b, free, value); updateNext(b, free, next)
updateValue(b, 0, free+8) //update free pointer
return free
}
|
javascript
|
{
"resource": ""
}
|
q61831
|
insert
|
validation
|
function insert (b, node, value) {
return updateNext(b, node, cons(b, value, readNext(b, node)))
}
|
javascript
|
{
"resource": ""
}
|
q61832
|
init
|
validation
|
function init(pathToModels, cb, addToSwagger) {
modelPath = pathToModels;
glob(modelPath + '/**/*.js', function(err, files) {
if (err) return cb && cb(err);
files.forEach(function(file) {
var Model = require(file)(),
modelSwagger = null;
if (Model.init) {
Model.init();
}
modelSwagger = Model.getSwagger();
if (modelSwagger && addToSwagger) {
modelSwagger.forEach(function(swaggerResource) {
swagger[swaggerMethodName[swaggerResource.spec.method.toLowerCase()]](swaggerResource);
});
}
models.push(Model);
});
return cb && cb(null, models);
});
}
|
javascript
|
{
"resource": ""
}
|
q61833
|
ArgumentStatement
|
validation
|
function ArgumentStatement(args, options, define) {
options = options || {};
this.value = args;
this.flags = {};
this.args = [];
this.options = options;
if (typeof options.parse === 'undefined') options.parse = true;
if (typeof options.separator === 'undefined') options.separator = ',';
if (typeof options.parseArgs === 'undefined') options.parseArgs = true;
if (options.parse) {
if (options.flags) {
var isFlag = true;
// Find all matching flags until no flag is found
while(isFlag) {
var firstFlagEnd = args.indexOf(' ');
if (firstFlagEnd === -1) firstFlagEnd = args.length;
var firstFlag = args.substring(0, firstFlagEnd).trim().toUpperCase();
if (options.flags.indexOf(firstFlag) !== -1) {
this.flags[firstFlag] = true;
args = args.substring(firstFlagEnd).trim();
}
else isFlag = false;
}
}
this.rawArgs = args;
args = args.trim();
var argList = [args];
if (options.separator) {
if (!args.length) argList = [];
else {
var positions = util.findPositions(args, [
{'start': '"', 'end': '"'},
{'start': '(', 'end': ')'}
]);
argList = util.splitOutside(args, options.separator, positions);
}
}
for (var i = 0; i < argList.length; i++) {
var arg = argList[i].trim();
if (options.parseArgs) arg = new statements.ExpressionStatement(arg, define);
this.args.push(arg);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61834
|
OpenCommand
|
validation
|
function OpenCommand(args, define) {
var lowerArgs = args.toLowerCase();
var forIndex = lowerArgs.indexOf(' for ');
if (forIndex === -1) throw new SyntaxError('OPEN without FOR');
var filename = new statements.ExpressionStatement(args.substring(0, forIndex).trim(), define);
var asIndex = lowerArgs.indexOf(' as ');
if (asIndex === -1) throw new SyntaxError('OPEN without AS');
var type = args.substring(forIndex + 5, asIndex).trim().toLowerCase();
if (type !== 'input' && type !== 'output' && type !== 'append') throw new SyntaxError('Invalid mode');
var pointer = new statements.ExpressionStatement(args.substring(asIndex + 4).trim(), define);
if (!(pointer.child instanceof statements.PointerStatement)) throw new SyntaxError('Expected pointer');
this.filename = filename;
this.type = type;
this.pointer = pointer;
}
|
javascript
|
{
"resource": ""
}
|
q61835
|
CommonJSResolverStrategy
|
validation
|
function CommonJSResolverStrategy(config) {
BasicResolverStrategy.call(this, config);
this.config = extend(true, this.config, {}, config);
}
|
javascript
|
{
"resource": ""
}
|
q61836
|
WhileCommand
|
validation
|
function WhileCommand(args, define) {
var parsed = new statements.ArgumentStatement(args, {
separator: false
});
this.condition = parsed.args[0];
this.block = define({
start: 'WHILE',
end: 'WEND'
});
}
|
javascript
|
{
"resource": ""
}
|
q61837
|
load
|
validation
|
function load(file, options) {
var stream = fs.createReadStream(file, options);
function onEnd() {
this.emit('load');
}
function onError(err) {
this.emit('error', err);
}
//stream.on('data', function onData(buf) {
//console.dir('got buffer length: ' + buf.length);
//})
stream.on('end', onEnd.bind(this));
stream.on('error', onError.bind(this));
stream.pipe(this);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q61838
|
validation
|
function(cb) {
// Callback is optional
cb = util.optional(cb);
// Grab policies config & policy modules and trigger callback
this.loadMiddleware(function (err) {
if (err) return cb(err);
sails.log.verbose('Finished loading policy middleware logic.');
cb();
}.bind(this));
// Before routing, curry controller functions with appropriate policy chains
sails.on('router:before', this.bindPolicies);
}
|
javascript
|
{
"resource": ""
}
|
|
q61839
|
validation
|
function() {
// Build / normalize policy config
this.mapping = this.buildPolicyMap();
_bindPolicies(this.mapping, sails.middleware.controllers);
// Emit event to let other hooks know we're ready to go
sails.log.verbose('Policy-controller bindings complete!');
sails.emit('hook:policies:bound');
}
|
javascript
|
{
"resource": ""
}
|
|
q61840
|
validation
|
function () {
var mapping = { };
_.each(sails.config.policies, function (_policy, controllerId) {
// Accept `FooController` or `foo`
// Case-insensitive
controllerId = util.normalizeControllerId(controllerId);
// Controller-level policy ::
// Just map the policy to the controller directly
if (!util.isDictionary(_policy)) {
mapping[controllerId] = policyHookDef.normalizePolicy(_policy);
return;
}
// Policy mapping contains a sub-object ::
// So we need to dive in and build/normalize the policy mapping from here
// Mapping each policy to each action for this controller
mapping[controllerId] = {};
_.each( _policy, function (__policy, actionId) {
// Case-insensitive
actionId = actionId.toLowerCase();
mapping[controllerId][actionId] = policyHookDef.normalizePolicy(__policy);
});
});
return mapping;
}
|
javascript
|
{
"resource": ""
}
|
|
q61841
|
validation
|
function (event) {
// Only pay attention to delegated route events
// if `policy` is declared in event.target
if ( !event.target || !event.target.policy ) {
return;
}
// Bind policy function to route
var fn = this.lookupFn(event.target.policy, 'config.routes');
sails.router.bind(event.path, fn, event.verb, _.merge(event.options, event.target));
}
|
javascript
|
{
"resource": ""
}
|
|
q61842
|
FunctionStatement
|
validation
|
function FunctionStatement(name, args) {
if (name[name.length - 1] === '$') {
this.type = 'string';
this.name = name.substring(0, name.length - 1);
} else {
this.type = 'number';
this.name = name;
}
var positions = util.findPositions(args, [
{ 'start': '"', 'end': '"' },
{ 'start': '(', 'end': ')' }
]);
var argList = util.splitOutside(args, ",", positions);
this.args = [];
for (var i = 0; i < argList.length; i++) {
this.args.push(new statements.ExpressionStatement(argList[i].trim()));
}
}
|
javascript
|
{
"resource": ""
}
|
q61843
|
LoadspriteCommand
|
validation
|
function LoadspriteCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 2) throw new SyntaxError('LOADSPRITE command requires 2 arguments');
else if (parsed.args.length > 2 && parsed.args.length < 5) throw new SyntaxError('LOADSPRITE command requires 5 arguments');
this.id = parsed.args[0];
if (parsed.args.length > 2) {
this.x1 = parsed.args[1];
this.y1 = parsed.args[2];
this.x2 = parsed.args[3];
this.y2 = parsed.args[4];
} else {
this.fileName = parsed.args[1];
}
}
|
javascript
|
{
"resource": ""
}
|
q61844
|
validation
|
function(verb, path, controller, method){
// Only add the route if we recognise the verb.
if (this.__verbs.indexOf(verb) >= 0){
// Create an actual object.
var entry = {
verb: verb,
path: path,
controller: controller,
method: method
};
this.routes.push(entry);
}
// Otherwise, they've made a mistake in their config, so throw an error.
else {
throw new Error('Unrecognised HTTP verb for route: ' + path);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61845
|
validation
|
function(url, val){
// Create a new object that we can manipulate safely.
var object = extend({}, val);
// Flag so we remember to append any attributes that can't be bound.
var append = false;
// If there are still parameters to bind, pull them out.
// Note: We use a different regex here because we need the global flag to ensure we pull all remaining bindings.
var remaining = url.match(/:\w+/ig);
if (remaining && remaining.length > 0){
// Iterate over the remaining potential bindings, looking for matches by name.
for (var j = 0; j < remaining.length; j++){
// Grab the key, stripping the : character.
var key = remaining[j].replace(':', '');
// Does our object contain that key?
if (object[key] !== undefined){
// Is it a type we can serialise?
if (this.canSerialise(object[key])){
// If it is, replace that value.
var keyRegex = new RegExp(':' + key);
url = url.replace(keyRegex, object[key]);
}
// Even if it wasn't, delete the value so we don't try again later.
delete object[key];
}
}
// If there are still fields left on our object, they need to become query parameters.
if (object !== {}){
append = true;
}
}
// Otherwise, we're going to append the object's values as key/value pairs.
else {
append = true;
}
// If we need to append key/values, do so.
if (append){
for (var attr in object){
// If the value is an object or a function, ignore it.
if (this.canSerialise(object[attr])){
// How are we appending?
var joiner = (url.indexOf('?') >= 0) ? "&" : "?";
// Append.
url += joiner + attr + "=" + object[attr];
}
}
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
|
q61846
|
validation
|
function(app, route){
var self = this;
var controller;
var controllerPath = self.options.controllersPath + route.controller;
// Load the controller.
try {
controller = require(self.options.rootPath + controllerPath);
}
catch (e) {
throw new Error('The specified controller (' + controllerPath + ') does not exist.');
}
if (controller) {
// If the specified method does not exist, throw an exception.
if (controller[route.method] === undefined) {
throw new Error('The specified method (' + route.method + ') does not exist on the controller (' + controllerPath + ').');
}
// Bind the route.
app[route.verb](route.path, controller[route.method]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61847
|
validation
|
function(app, route){
var self = this;
// Figure out the folder they want to bind.
var folderPath = route.controller.replace(/staticDir:/g, '');
var folder = self.options.rootPath + folderPath;
// Make sure that's actually a folder.
try {
var info = fs.lstatSync(folder);
if (info.isDirectory()) {
app.use(express.static(folder));
}
}
catch (e) {
throw new Error('The specified static path (' + folderPath + ') does not exist or is not a directory.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61848
|
validation
|
function(app){
// Cache the instance.
var self = this;
// Insert the instance into app.locals so it can be used in views.
app.locals[self.options.templateVar] = self;
// Grab the routes.
var routes = self.getRoutes();
// Bind them.
routes.forEach(function(route){
// If the controller begins with 'staticDir:', it's a static route.
if (route.controller.indexOf('staticDir:') === 0) {
self.bindStaticRoute(app, route);
}
else {
self.bindRegularRoute(app, route);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q61849
|
validation
|
function(){
// If we've already loaded the routes, skip.
if (this.routes.length === 0){
// Grab the entries.
var routes;
try {
routes = this.readFile(this.options.rootPath + this.options.routesFile);
}
catch (e) {
throw new Error('The specified routes file (' + this.options.routesFile + ') does not exist or could not be read.');
}
// Turn them into actual route entries.
for (var i = 0; i < routes.length; i++){
// Split it up into its component parts (VERB /path controller.method).
// TODO: An equivalent to PHP's list() would be really awesome too.
var bits = routes[i].split(/\s+/);
// Split the controller up further, so we can store the file and method separately.
var controller = bits[2].split('.');
// If the controller contains a wildcard, we handle it differently.
if (controller[1] == '{method}') {
this.getWildcardRoutes(bits[0].toLowerCase(), bits[1], controller[0]);
}
else {
this.addNewRouteEntry(bits[0].toLowerCase(), bits[1], controller[0], controller[1]);
}
}
}
return this.routes;
}
|
javascript
|
{
"resource": ""
}
|
|
q61850
|
validation
|
function(verb, path, controllerName){
// Load the referenced controller.
var controllerPath = this.options.controllersPath + controllerName;
try {
var controller = require(this.options.rootPath + controllerPath);
// Iterate over the controller, creating new route entries for each function.
for (var field in controller) {
if (typeof controller[field] == 'function') {
this.addNewRouteEntry(verb, path.replace(/{method}/, field), controllerName, field);
}
}
}
catch (e) {
throw new Error('The specified controller (' + controllerPath + ') does not exist.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61851
|
validation
|
function(path){
// Define the array we'll return.
var routes = [];
// Grab the FS library.
var fs = require('fs');
// Read the contents from disk.
var array = fs.readFileSync(path).toString().split("\n");
// We need to post-process since there might have been empty lines, or comments.
array.forEach(function(route){
// If it's not an empty line or a comment, add it.
if (route !== "" && route.match(/^#/) === null) {
routes.push(route);
}
});
return routes;
}
|
javascript
|
{
"resource": ""
}
|
|
q61852
|
validation
|
function(action){
var url;
var error;
// Iterate over the routes, looking for a match.
var routes = this.getRoutes();
for (var i = 0; url === undefined && i < routes.length; i++){
try {
// Simplify access.
var route = routes[i];
// Check the controller + method. If we find one, figure out the URL to return.
if (action == route.controller + '.' + route.method){
var params = [];
// If there are parameters, bind them.
if (arguments.length > 1) {
// Turn them into a proper array.
params = Array.prototype.slice.apply(arguments);
// And drop the first entry (which was the action itself).
params = params.slice(1);
}
// We always call bind, even with an empty array, to see if we generate an error.
url = this.bindUrl(route.path, params);
}
}
catch(e) {
// Store the error in case we need to rethrow it.
error = e;
}
}
// If we found a match, return it.
if (url !== undefined) {
return url;
}
// Otherwise, throw an exception.
else {
// If we captured an earlier error, reuse that (since it implies we found a match but couldn't bind it).
if (error !== undefined) {
throw error;
}
else {
throw new Error("No matching action was found.");
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61853
|
validation
|
function(value){
/*#if BROWSER*/ if(this._label) this._label.text(value); else /*#/if*/
this._label=$.create('label').attr('for',this.getAttr('id'))/*#if BROWSER*/.prependTo(this._container)/*#/if*/.text(value);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q61854
|
parse
|
validation
|
function parse(code) {
try {
var labels = {};
var root = [];
var manager = new BlockManager();
var lines = code.split('\n');
for (var i = 0; i < lines.length; i++) {
try {
var line = parseLine(lines[i].trim(), i, labels, false, manager);
if (line instanceof SyntaxError) throw createLineError(line, i);
if (line.error instanceof SyntaxError) throw createLineError(line.error, i);
root[i] = line;
} catch (ex) {
throw createLineError(ex, i);
}
}
return new AbstractSyntaxTree(root, labels, manager);
} catch (ex) {
return { "error": ex };
}
}
|
javascript
|
{
"resource": ""
}
|
q61855
|
CommandStatement
|
validation
|
function CommandStatement(name, args, manager, line) {
this.name = name;
this.args = args;
if (!commands[name]) throw new SyntaxError('Unknown command: ' + name);
this.command = new commands[name](args, manager.create(line));
}
|
javascript
|
{
"resource": ""
}
|
q61856
|
BasicResolverStrategy
|
validation
|
function BasicResolverStrategy(config) {
ResolverStrategy.call(this, config);
this.config = extend(true, this.config, {}, config);
}
|
javascript
|
{
"resource": ""
}
|
q61857
|
toArray
|
validation
|
function toArray() {
return Object
.keys(data)
.map(function(name) { return data[name]; })
.sort(function(a, b) {
return a.compareTo(b);
});
}
|
javascript
|
{
"resource": ""
}
|
q61858
|
add
|
validation
|
function add(snapshot) {
return Promise
.resolve(mapFn(snapshot))
.then(function(val) {
data[snapshot.key()] = val;
});
}
|
javascript
|
{
"resource": ""
}
|
q61859
|
emitValue
|
validation
|
function emitValue() {
var arr = toArray();
marker = arr[arr.length - 1];
setTimeout(function() {
emitter.emit('value', arr);
}, 0);
}
|
javascript
|
{
"resource": ""
}
|
q61860
|
onChildAdd
|
validation
|
function onChildAdd(newData) {
// ignore all events before first read
if (!started) return;
// ignore already added item
if (data[newData.key()]) return;
// ignore older items that are not loaded
if ( !ended
&& !data[newData.key()]
&& marker && newData.compareTo(marker) > 0) return;
return add(newData).then(emitValue);
}
|
javascript
|
{
"resource": ""
}
|
q61861
|
addChildren
|
validation
|
function addChildren(newData) {
var promises = [];
newData.forEach(function (child) {
promises.push(add(child));
});
return Promise.all(promises).then(emitValue);
}
|
javascript
|
{
"resource": ""
}
|
q61862
|
modalOpen
|
validation
|
function modalOpen (options) {
if (isString(options)) options = optionsFromTarget(options);
var modal = select('#d3-view-modal');
if (!modal.size())
select('body').append('modal').mount(options, vm => vm.model.$showModal());
else
modal.model().$update(options).$showModal();
}
|
javascript
|
{
"resource": ""
}
|
q61863
|
ColorCommand
|
validation
|
function ColorCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 3) throw new SyntaxError('COLOR command requires 3 arguments');
this.red = parsed.args[0];
this.green = parsed.args[1];
this.blue = parsed.args[2];
this.alpha = parsed.args.length > 3 ? parsed.args[3] : false;
}
|
javascript
|
{
"resource": ""
}
|
q61864
|
onChange
|
validation
|
function onChange () {
if (props.onChange) {
var changeHandlers = [...props.onChange]
var value = editor.getValue()
return changeHandlers.map((f) => f(value))
}
}
|
javascript
|
{
"resource": ""
}
|
q61865
|
PrintCommand
|
validation
|
function PrintCommand(args, define) {
if (args[args.length - 1] === ";") {
this.noLine = true;
args = args.substr(-1);
} else this.noLine = false;
var parsed = new statements.ArgumentStatement(args, {
flags: ['USING'],
parseArgs: false
});
if (parsed.flags.USING) {
if (parsed.args.length !== 1) throw new SyntaxError('PRINT USING command requires 1 argument');
if (parsed.args.length > 1) throw new SyntaxError('Unexpected comma');
var semicolonIndex = parsed.args[0].indexOf(';');
if (semicolonIndex === -1) throw new SyntaxError('Expected semicolon');
var formatExpression = new statements.ExpressionStatement(parsed.args[0].substring(0, semicolonIndex).trim(), define);
var numberExpression = new statements.ExpressionStatement(parsed.args[0].substring(semicolonIndex + 1).trim(), define);
if (formatExpression.error instanceof SyntaxError) throw formatExpression.error;
if (numberExpression.error instanceof SyntaxError) throw numberExpression.error;
this.formatExpr = formatExpression;
this.numberExpr = numberExpression;
} else {
var items = [];
for (var i = 0; i < parsed.args.length; i++) {
var expr = new statements.ExpressionStatement(parsed.args[i], define);
if (expr.error instanceof SyntaxError) throw expr.error;
items.push(expr);
}
this.items = items;
}
}
|
javascript
|
{
"resource": ""
}
|
q61866
|
intoExport
|
validation
|
function intoExport(obj) {
for (var k in obj) {
if (!obj.hasOwnProperty(k)) continue;
exports[k] = obj[k];
}
}
|
javascript
|
{
"resource": ""
}
|
q61867
|
charAt
|
validation
|
function charAt(index) {
return value => value.length <= index ? undefined : value.charAt(index);
}
|
javascript
|
{
"resource": ""
}
|
q61868
|
replace
|
validation
|
function replace(target, replaceWith) {
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
return target instanceof RegExp
? value => value.replace(target, replaceWith)
: replace(new RegExp(escapeRegExp(target), "g"), replaceWith);
}
|
javascript
|
{
"resource": ""
}
|
q61869
|
ExpressionStatement
|
validation
|
function ExpressionStatement(data, define) {
this.child = parseExpression(data, define ? define.line : 'unknown');
if (this.child instanceof SyntaxError) throw this.child;
else if (this.child.error) throw this.child.error;
}
|
javascript
|
{
"resource": ""
}
|
q61870
|
cleanLines
|
validation
|
function cleanLines(block, lines) {
var removeFirst = false
if (lines.length && emptyRegex.test(lines[0].str)) {
block.line += 1
block.size -= 1
removeFirst = true
}
return lines.filter(function (each, i) {
return !(!i && removeFirst) && !commentRegex.test(each.str)
})
}
|
javascript
|
{
"resource": ""
}
|
q61871
|
drawAllDataPoints
|
validation
|
function drawAllDataPoints(animationDecimal){
var rotationDegree = (2*Math.PI)/data.datasets[0].data.length;
ctx.save();
//translate to the centre of the canvas.
ctx.translate(width/2,height/2);
//We accept multiple data sets for radar charts, so show loop through each set
for (var i=0; i<data.datasets.length; i++){
ctx.beginPath();
ctx.moveTo(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[0],calculatedScale,scaleHop)));
for (var j=1; j<data.datasets[i].data.length; j++){
ctx.rotate(rotationDegree);
ctx.lineTo(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop)));
}
ctx.closePath();
ctx.fillStyle = data.datasets[i].fillColor;
ctx.strokeStyle = data.datasets[i].strokeColor;
ctx.lineWidth = config.datasetStrokeWidth;
ctx.fill();
ctx.stroke();
if (config.pointDot){
ctx.fillStyle = data.datasets[i].pointColor;
ctx.strokeStyle = data.datasets[i].pointStrokeColor;
ctx.lineWidth = config.pointDotStrokeWidth;
for (var k=0; k<data.datasets[i].data.length; k++){
ctx.rotate(rotationDegree);
ctx.beginPath();
ctx.arc(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[k],calculatedScale,scaleHop)),config.pointDotRadius,2*Math.PI,false);
ctx.fill();
ctx.stroke();
}
}
ctx.rotate(rotationDegree);
}
ctx.restore();
}
|
javascript
|
{
"resource": ""
}
|
q61872
|
populateLabels
|
validation
|
function populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue) {
if (labelTemplateString) {
//Fix floating point errors by setting to fixed the on the same decimal as the stepValue.
for (var i = 1; i < numberOfSteps + 1; i++) {
labels.push(tmpl(labelTemplateString, {value: (graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))}));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61873
|
validation
|
function(path){
var xhr=new XMLHttpRequest;
xhr.open('GET',baseUrl+'web/'+path+'.js', false);
xhr.send();
if(xhr.status !== 200) new FatalError(/*#if DEV*/'Unable to load: '+path+'.js'/*#/if*/);
var s = document.createElement('script');
s.type = "text/javascript";
s.text = xhr.responseText;
document.getElementsByTagName('head')[0].appendChild(s);
}
|
javascript
|
{
"resource": ""
}
|
|
q61874
|
TcolorCommand
|
validation
|
function TcolorCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 3) throw new SyntaxError('TCOLOR command requires 3 arguments');
this.red = parsed.args[0];
this.green = parsed.args[1];
this.blue = parsed.args[2];
}
|
javascript
|
{
"resource": ""
}
|
q61875
|
publish
|
validation
|
function publish(subject, op, target) {
try {
var type = (_.isString(target)) ? target : target.type;
var topic = getTopic(type);
// optimization: would be nice to tell if there are subscribers before I bother to create
var event = new Event(subject, op, target);
provider.publish(topic, event);
}
catch (err) {
logger.error('unable to publish event', err);
}
}
|
javascript
|
{
"resource": ""
}
|
q61876
|
ExecutionContext
|
validation
|
function ExecutionContext(options) {
EventEmitter.call(this);
this.stringVars = {};
this.numberVars = {};
this.pointers = {};
this.gosubs = [];
this.private = {
rnd_seed: Math.random(),
sprites: [],
data: []
};
this.constants = require('./constants');
this.running = false;
options = options || {};
this.options = options;
if (typeof options.delay === 'undefined') options.delay = false;
// Copy all functions as constants
for (var k in functions) {
if (!functions.hasOwnProperty(k)) continue;
this.constants[k] = functions[k];
}
// Stop multiple contexts conflicting with constants
this.constants = pUtil.shallowClone(this.constants);
}
|
javascript
|
{
"resource": ""
}
|
q61877
|
setArrayIndexAt
|
validation
|
function setArrayIndexAt(arr, dimensions, val, data) {
var currentDimension = dimensions[0].execute(data);
data.validate(currentDimension, 'number');
currentDimension -= 1;
if (currentDimension < 0) currentDimension = 0;
if (arr.length <= currentDimension) throw new Error('Invalid array bounds');
var item = arr[currentDimension];
if (dimensions.length > 1) {
if (!Array.isArray(item)) throw new Error('Invalid array dimensions');
return setArrayIndexAt(arr[currentDimension], dimensions.slice(1), val, data);
} else arr[currentDimension] = val;
}
|
javascript
|
{
"resource": ""
}
|
q61878
|
getArrayIndexAt
|
validation
|
function getArrayIndexAt(arr, dimensions, data) {
var currentDimension = dimensions[0];
data.validate(currentDimension, 'number');
currentDimension = Math.max(0, Math.floor(currentDimension - 1));
if (arr.length <= currentDimension) throw new Error('Invalid array bounds');
var item = arr[currentDimension];
if (dimensions.length > 1) {
if (!Array.isArray(item)) throw new Error('Invalid array dimensions');
return getArrayIndexAt(arr[currentDimension], dimensions.slice(1), data);
} else return item;
}
|
javascript
|
{
"resource": ""
}
|
q61879
|
createArrayDepth
|
validation
|
function createArrayDepth(dimensions, endpoint) {
var currentDimension = dimensions[0];
var newArr = new Array(currentDimension);
for (var i = 0; i < currentDimension; i++) {
var value = endpoint;
if (dimensions.length > 1) value = createArrayDepth(dimensions.slice(1), endpoint);
newArr[i] = value;
}
return newArr;
}
|
javascript
|
{
"resource": ""
}
|
q61880
|
validation
|
function (section) {
section.children.forEach(function (child) {
if (child.type === 'section') {
finalParse(child)
} else if (child.type === 'text' ||
child.type === 'value' ||
child.type === 'code') {
var sliceStart = child.line - 1,
sliceEnd = child.line + child.size - 1,
subLines = lines.slice(sliceStart, sliceEnd)
if (child.type === 'text') {
child.content = subLines.join('\n')
} else if (child.type === 'code') {
child.language = subLines[0].substr(3)
child.content = subLines.slice(1, -1).join('\n')
} else if (child.type === 'value') {
child.content = subLines.join('\n')
// Remove starting tab character
parseValue(child, subLines.map(function (e, i) {
return {
line: child.line + i,
str: e.substr(1)
}
}), throwSyntaxError)
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q61881
|
takeHeader
|
validation
|
function takeHeader(content, level, name) {
var currLevel = sectionStack.length
if (level > currLevel + 1) {
throwSyntaxError('Unexpected header level ' + level + ' on section level ' + currLevel)
} else if (level === 1) {
throwSyntaxError('There can be only one header level 1, the first line of the file')
}
// Walk out
sectionStack.length = level - 1
// Create section
section = {
type: 'section',
name: name || '',
line: line,
size: 1,
content: content,
level: level,
children: []
}
sectionStack[sectionStack.length - 1].children.push(section)
sectionStack.push(section)
}
|
javascript
|
{
"resource": ""
}
|
q61882
|
throwSyntaxError
|
validation
|
function throwSyntaxError(message, errorLine, size) {
errorLine = errorLine === undefined ? line : errorLine
size = size === undefined ? 1 : size
var snippet = getSnippet(source, errorLine, size),
err = new SyntaxError(message + '\n' + snippet)
err.line = errorLine
throw err
}
|
javascript
|
{
"resource": ""
}
|
q61883
|
appendLine
|
validation
|
function appendLine(type) {
var len = section.children.length
if (newBlock ||
!len ||
section.children[len - 1].type !== type) {
section.children.push({
type: type,
line: line,
size: 1
})
} else {
section.children[len - 1].size += 1
}
newBlock = false
}
|
javascript
|
{
"resource": ""
}
|
q61884
|
on
|
validation
|
function on(event, cb, context) {
var args = Array.prototype.slice.call(arguments, 0);
return dom.on.apply(false, [this].concat(args));
}
|
javascript
|
{
"resource": ""
}
|
q61885
|
detach
|
validation
|
function detach(node) {
if (node.placeholder instanceof HTMLElement === false) {
node.placeholder = createPlaceholder(node.data.tag || node.el.tagName);
}
if (node && node.el && node.el.parentNode) {
node.el.parentNode.replaceChild(node.placeholder, node.el);
}
}
|
javascript
|
{
"resource": ""
}
|
q61886
|
attach
|
validation
|
function attach(node) {
if (node && node.el && node.placeholder && node.placeholder.parentNode) {
node.placeholder.parentNode.replaceChild(node.el, node.placeholder);
}
}
|
javascript
|
{
"resource": ""
}
|
q61887
|
append
|
validation
|
function append(parent, child) {
if (parent.el !== undefined && child.el !== undefined) {
parent.el.appendChild(child.el);
}
}
|
javascript
|
{
"resource": ""
}
|
q61888
|
insertBefore
|
validation
|
function insertBefore(parent, child, index) {
var parentEl = parent.el,
childEl = child.el;
if (parentEl !== undefined && childEl !== undefined) {
if (parentEl.childNodes[index] !== undefined) {
parentEl.insertBefore(childEl, parentEl.childNodes[index]);
} else {
parentEl.appendChild(childEl);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61889
|
changePosition
|
validation
|
function changePosition(el, index) {
var HTMLElement = el.el;
if (HTMLElement && HTMLElement.parentNode) {
var parentNode = HTMLElement.parentNode,
elGroup = el.elGroup,
size = elGroup.size,
target = elGroup.getKeyByIndex(index) || elGroup.getLast();
if (target !== HTMLElement) {
if (size - 1 >= index) {
parentNode.insertBefore(HTMLElement, target);
} else if (target.nextSibling !== null) {
parentNode.insertBefore(HTMLElement, target.nextSibling);
} else {
parentNode.appendChild(HTMLElement);
}
el.elGroup.changeIndex(HTMLElement, index);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61890
|
text
|
validation
|
function text(node, _text2) {
if (node && node.el) {
node.el.innerHTML = _text2;
}
}
|
javascript
|
{
"resource": ""
}
|
q61891
|
setAttribute
|
validation
|
function setAttribute(node, prop, value) {
if (node && node.el) {
if (isObject(prop)) {
Object.keys(prop).forEach(function (key) {
node.el.setAttribute(key, prop[key]);
});
} else {
node.el.setAttribute(prop, value);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61892
|
getAttribute
|
validation
|
function getAttribute(node, prop) {
if (node && node.el) {
return node.el.getAttribute(prop);
} else {
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q61893
|
removeAttribute
|
validation
|
function removeAttribute(node, prop) {
if (node && node.el) {
node.el.removeAttribute(prop);
}
}
|
javascript
|
{
"resource": ""
}
|
q61894
|
setStyle
|
validation
|
function setStyle(node, prop, value) {
if (node && node.el) {
if (isObject(prop)) {
Object.keys(prop).forEach(function (key) {
node.el.style[key] = prop[key];
});
} else {
node.el.style[prop] = value;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61895
|
getStyle
|
validation
|
function getStyle(node, prop) {
if (node && node.el) {
if (node.el !== undefined && node.el.style !== undefined) {
return node.el.style[prop];
} else {
return undefined;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61896
|
removeStyle
|
validation
|
function removeStyle(node, prop) {
if (node && node.el) {
node.el.style[prop] = '';
}
}
|
javascript
|
{
"resource": ""
}
|
q61897
|
addClass
|
validation
|
function addClass(node, className) {
if (node && node.el) {
node.el.classList.add(className);
}
}
|
javascript
|
{
"resource": ""
}
|
q61898
|
hasClass
|
validation
|
function hasClass(node, className) {
if (node && node.el) {
return node.el.classList.contains(className);
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q61899
|
removeClass
|
validation
|
function removeClass(node, className) {
if (node && node.el) {
node.el.classList.remove(className);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.