_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q9000
|
isBuf
|
train
|
function isBuf(obj) {
return (
(withNativeBuffer && commonjsGlobal.Buffer.isBuffer(obj)) ||
(withNativeArrayBuffer && (obj instanceof commonjsGlobal.ArrayBuffer || isView(obj)))
);
}
|
javascript
|
{
"resource": ""
}
|
q9001
|
hasBinary
|
train
|
function hasBinary(obj) {
if (!obj || typeof obj !== "object") {
return false;
}
if (isarray(obj)) {
for (var i = 0, l = obj.length; i < l; i++) {
if (hasBinary(obj[i])) {
return true;
}
}
return false;
}
if (
(typeof Buffer === "function" && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
(typeof ArrayBuffer === "function" && obj instanceof ArrayBuffer) ||
(withNativeBlob$1 && obj instanceof Blob) ||
(withNativeFile$1 && obj instanceof File)
) {
return true;
}
// see: https://github.com/Automattic/has-binary/pull/4
if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
return hasBinary(obj.toJSON(), true);
}
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q9002
|
train
|
function(obj) {
var str = "";
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length) str += "&";
str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
}
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
|
q9003
|
Polling
|
train
|
function Polling(opts) {
var forceBase64 = opts && opts.forceBase64;
if (!hasXHR2 || forceBase64) {
this.supportsBinary = false;
}
transport.call(this, opts);
}
|
javascript
|
{
"resource": ""
}
|
q9004
|
onerror
|
train
|
function onerror(err) {
var error = new Error("probe error: " + err);
error.transport = transport$$1.name;
freezeTransport();
debug$5('probe transport "%s" failed because of error: %s', name, err);
self.emit("upgradeError", error);
}
|
javascript
|
{
"resource": ""
}
|
q9005
|
convertRuleToCondition
|
train
|
function convertRuleToCondition(rule) {
if (!rule || typeof rule !== 'object' || !Object.keys(rule).length) {
return rule;
}
if (Array.isArray(rule)) {
return rule.map(convertRuleToCondition);
}
const condition = {};
// We allow certain properties...
ALLOWED_PROPERTIES.forEach((prop) => {
if (rule[prop]) {
condition[prop] = convertRuleToCondition(rule[prop]);
}
});
// We prohibit certain properties...
PROHIBITIED_PROPERTIES.forEach((prop) => {
if (rule[prop]) {
throw new Error(`Webpack rules added in a Twist library cannot contain the property "${prop}". `
+ `Try to reformulate your rule with ${ALLOWED_PROPERTIES.join('/')}.`);
}
});
// And the rest we ignore, because they're needed for a Rule but not a Condition.
return condition;
}
|
javascript
|
{
"resource": ""
}
|
q9006
|
processRoutes
|
train
|
function processRoutes(handler, uriContext, routes) {
return routes.map(setupRoute);
/**
* @param {(PreReq|pageAdapter)[]} adapters - Array of adapters and Hapi route prerequisites for processing
* an incoming request
* @param {pageFilter} pageFilter - Function for performing post-processing on page object before
* templating begins
* @param {string} method - HTTP method for the route
* @param {string} path - Path for the route
* @param {module:processRoutes.Context} context
* - Data that should be made available to the adapters and route handler
*
* @returns {object} Hapi route options object
*/
function setupRoute({adapters, pageFilter, method, path, context}) {
const allAdaptersAndPreHandlers = flattenDeep(adapters);
const preHandlers = allAdaptersAndPreHandlers.filter(x => isPreHandler(x));
const pageAdapters = allAdaptersAndPreHandlers.filter(x => !isPreHandler(x));
const app = {
context,
adapters: pageAdapters
};
if (pageFilter) {
app.pageFilter = pageFilter;
}
const pre = preHandlers.map(mapToWrappedHandler);
return {
method,
path: uriContext + path,
handler,
config: {
state: {
failAction: 'log'
},
app,
pre
}
};
}
}
|
javascript
|
{
"resource": ""
}
|
q9007
|
train
|
function (object) {
var sortedObj = {},
keys = _.keys(object);
keys = _.sortBy(keys, function(key){
return key;
});
_.each(keys, function(key) {
if(_.isArray(object[key])) {
sortedObj[key] = _.map(object[key], function(val) {
return _.isObject(val) ? _.alphabetize(val) : val;
});
} else if(_.isObject(object[key])){
sortedObj[key] = _.alphabetize(object[key]);
} else {
sortedObj[key] = object[key];
}
});
return sortedObj;
}
|
javascript
|
{
"resource": ""
}
|
|
q9008
|
train
|
function(str) {
// allow browser implementation if it exists
// https://developer.mozilla.org/en-US/docs/Web/API/window.btoa
if (typeof atob!=='undefined') {
// utf8 decode after the fact to make sure we convert > 0xFF to ascii
return _.utf8_decode(atob(str));
}
// allow node.js Buffer implementation if it exists
if (Buffer) {
return new Buffer(str, 'base64').toString('binary');
}
// now roll our own
// decoder
// [https://gist.github.com/1020396] by [https://github.com/atk]
str = str.replace(/=+$/, '');
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~ buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
|
q9009
|
train
|
function(originalFn, moreFn, scope) {
return scope ?
function() {
originalFn.apply(scope, arguments);
moreFn.apply(scope, arguments);
} : function() {
originalFn();
moreFn();
};
}
|
javascript
|
{
"resource": ""
}
|
|
q9010
|
train
|
function (target, name, meta){
var _ctor = __define.fixTargetCtor(target),
_key = __define.fixTargetKey(name),
_exist = _key in _ctor,
_descriptor = {};
if(!_exist){
_descriptor = Object.defineProperty(target, 'on' + name.toLowerCase(), {
get: function () {
var _listeners = this.__handlers__[name];
if (_listeners) {
return _listeners[0].handler;
}
else {
return null;
}
},
set: function (value) {
var _handlers = this.__handlers__;
var _listeners = _handlers[name] = _handlers[name] || [];
_listeners[0] = {
owner: this,
handler: value,
context: null
};
}
});
}
_ctor[_key] = {
name: name,
type: 'event',
meta: meta,
descriptor: _descriptor
};
return _exist;
}
|
javascript
|
{
"resource": ""
}
|
|
q9011
|
train
|
function (target, name, meta){
var _ctor = __define.fixTargetCtor(target),
_key = __define.fixTargetKey(name),
_exist = _key in _ctor,
_descriptor = {};
var _getter, _setter;
if ('value' in meta) {
var _value = meta.value,
_field = '_' + name,
_get = meta.get,
_set = meta.set;
_getter = _get || function () {
if (_field in this) {
return this[_field];
}
else {
return zn.is(_value, 'function') ? _value.call(this) : _value;
}
};
_setter = meta.readonly ?
function (value, options) {
if (options && options.force) {
this[_field] = value;
}
else {
return false;
}
} :
(_set ||function (value) {
this[_field] = value;
});
} else {
_getter = meta.get || function () {
return undefined;
};
_setter = meta.set || function () {
return false;
};
}
if (_exist) {
_getter.__super__ = _ctor[_key].getter;
_setter.__super__ = _ctor[_key].setter;
}
/*
if(!_exist){
_descriptor = Object.defineProperty(target, name, {
get: _getter,
set: _setter,
configurable : true
});
}*/
_descriptor = Object.defineProperty(target, name, {
get: _getter,
set: _setter,
configurable : true
});
_ctor[_key] = {
name: name,
type: 'property',
meta: meta,
getter: _getter,
setter: _setter,
descriptor: _descriptor
};
return _exist;
}
|
javascript
|
{
"resource": ""
}
|
|
q9012
|
train
|
function (target, name, meta){
var _ctor = __define.fixTargetCtor(target),
_key = __define.fixTargetKey(name),
_exist = _key in _ctor;
_ctor[_key] = {
name: name,
type: 'method',
meta: meta
};
if (name in target) {
if(!meta.value){
meta.value = function (){
};
}
meta.value.__super__ = target[name];
}
target[name] = meta.value;
return _exist;
}
|
javascript
|
{
"resource": ""
}
|
|
q9013
|
train
|
function (name, target) {
var _ctor = __define.fixTargetCtor(target||this),
_member = _ctor[__define.fixTargetKey(name)];
if(!_member&&_ctor!==ZNObject){
return this.member(name, _ctor._super_);
}
return _member;
}
|
javascript
|
{
"resource": ""
}
|
|
q9014
|
train
|
function (name, options) {
var _member = this.member(name);
if(_member && _member.getter){
return _member.getter.call(this, options);
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q9015
|
train
|
function (name, value, options) {
var _member = this.member(name);
if (_member && _member.setter) {
_member.setter.call(this, value, options);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9016
|
train
|
function (options) {
var _values = {},
_properties = __define.fixTargetCtor(this)._properties_;
zn.each(_properties, function (name) {
_values[name] = this.get(name, options);
}, this);
return _values;
}
|
javascript
|
{
"resource": ""
}
|
|
q9017
|
train
|
function (values, options, callback) {
if (values) {
var _value = null;
for (var _name in values) {
if (values.hasOwnProperty(_name)) {
_value = values[_name];
if((callback && callback(_value, _name, options))!==false){
this.set(_name, _value, options);
}
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9018
|
train
|
function (name, meta, target) {
if (!__define.defineEvent(target || this.prototype, name, meta)) {
this._events_.push(name);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9019
|
train
|
function (name, meta, target) {
if (!__define.defineProperty(target || this.prototype, name, meta)) {
this._properties_.push(name);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9020
|
train
|
function (name, meta, target) {
if (!__define.defineMethod(target || this.prototype, name, meta)) {
this._methods_.push(name);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9021
|
train
|
function (){
var _info = {
ClassName: (this.__name__ || 'Anonymous'),
InstanceID: this.__id__,
Meta: this.constructor._meta_
};
return JSON.stringify(_info);
}
|
javascript
|
{
"resource": ""
}
|
|
q9022
|
train
|
function (){
var _json = {};
zn.each(this.constructor.getProperties(), function (field, key){
_json[key] = this.get(key);
}, this);
return _json;
}
|
javascript
|
{
"resource": ""
}
|
|
q9023
|
train
|
function (name, handler, options) {
if (handler) {
var _handlers = this.__handlers__;
var _listeners = _handlers[name] = _handlers[name] || [];
_listeners[0] = zn.extend({
owner: this,
handler: handler
}, options);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9024
|
train
|
function (name, handler, options) {
if (handler) {
var _handlers = this.__handlers__;
var _listeners = _handlers[name] = _handlers[name] || [
{
owner: null,
handler: null,
context: null
}
];
_listeners.push(zn.extend({
owner: this,
handler: handler
}, options));
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9025
|
train
|
function (name, handler, options) {
var _listeners = this.__handlers__[name]||[], _listener;
var _context = options && options.context;
if (handler) {
for (var i = _listeners.length - 1; i >= 0; i--) {
_listener = _listeners[i];
if (_listener.handler === handler && (!_context || _listener.context === _context )) {
this.__handlers__[name].splice(i, 1);
}
}
}
else {
this.__handlers__[name] = [
{
owner: null,
handler: null,
context: null
}
];
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9026
|
train
|
function (name, data, options) {
var _listeners = this.__handlers__[name],
_listener,
_result = null;
if (_listeners) {
for (var i = 0, length = _listeners.length; i < length; i++) {
_listener = _listeners[i];
if (_listener && _listener.handler) {
if(options && options.method=='apply'){
_result = _listener.handler.apply(_listener.context || _listener.owner, data);
} else {
_result = _listener.handler.call(_listener.context || _listener.owner, _listener.owner, data, options);
}
if (false === _result) {
return false;
}
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9027
|
train
|
function (type) {
if (typeof type === 'string') {
type = zn.path(GLOBAL, type);
}
if (type) {
if (this instanceof type) {
return true;
} else {
var _mixins = this.constructor._mixins_;
for (var i = 0, _len = _mixins.length; i < _len; i++) {
var _mixin = _mixins[i];
if (type === _mixin) {
return true;
}
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q9028
|
train
|
function(into, data) {
var existingDataLen = into.length == 0 ? 0 : into[0].length - 1;
var i = 0;
var j = 0;
for (; i<into.length && j<data.length; ) {
if (into[i][0] == data[j][0]) {
into[i].push(data[j][1]);
i++;
j++;
}
else if (into[i][0] < data[j][0]) {
into[i].push(null);
i++;
}
else {
var arr = [data[j][0]];
for (var k=1; k<into[i].length; k++) {
arr.push(null);
}
arr.push(data[j][1]);
into.splice(i,0,arr);
i++;
j++;
}
}
while (j<data.length) {
var arr = [data[j][0]];
for (var k=0; k<existingDataLen; k++) {
arr.push(null);
}
arr.push(data[j][1]);
into.push(arr);
j++;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9029
|
composeVersion
|
train
|
function composeVersion (str, regex) {
var r = regex.exec(str)
return {
number: r[ 1 ],
stage: r[ 2 ] || null,
stageName: r[ 3 ] || null,
stageNumber: r[ 4 ] || null
}
}
|
javascript
|
{
"resource": ""
}
|
q9030
|
createEvent
|
train
|
function createEvent(name) {
var event = void 0;
if (typeof document !== 'undefined') {
event = document.createEvent('HTMLEvents') || document.createEvent('event');
event.initEvent(name, false, true);
}
return event;
}
|
javascript
|
{
"resource": ""
}
|
q9031
|
train
|
function(target, skeleton) {
// console.log("Applying change: "+JSON.stringify(skeleton));
if (skeleton == null) {
return false;
}
if (typeof skeleton != typeof target) {
return false;
}
switch (typeof skeleton)
{
case 'string':
case 'number':
case 'boolean':
// gone too far
return false;
case 'object':
if (skeleton instanceof Array)
{
// for now only support direct replacement/mutation of elements, skeleton is insufficient to describe splicing
if (target.length != skeleton.length) {
return false;
}
var changed = false;
for (var i=0; i<skeleton.length; i++) {
if (skeleton[i] == null) {
continue;
}
switch (typeof skeleton[i]) {
case 'string':
case 'number':
case 'boolean':
changed = (target[i] != skeleton[i]) || changed;
target[i] = skeleton[i];
break;
case 'object':
changed = deepApply(target[i], skeleton[i]) || changed;
break;
default:
throw 'Unrecognized type: '+(typeof skeleton[i]);
}
}
return changed;
}
else {
var changed = false;
for (var k in skeleton) {
if (skeleton.hasOwnProperty(k)) {
if (target.hasOwnProperty(k)) {
if (skeleton[k] == null) {
continue;
}
switch (typeof skeleton[k]) {
case 'string':
case 'number':
case 'boolean':
changed = target[k] != skeleton[k] || changed;
target[k] = skeleton[k];
break;
case 'object':
changed = deepApply(target[k], skeleton[k]) || changed;
break;
default:
throw 'Unrecognized type: '+(typeof skeleton[k]);
}
}
else {
target[k] = skeleton[k];
}
}
}
return changed;
}
break;
default:
throw 'Unrecognized type: '+(typeof incoming);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9032
|
train
|
function (newPaneOptions) {
var newInstance = newPaneOptions.newInstance
if (!newInstance) {
let uri = newPaneOptions.newBase
if (uri.endsWith('/')) {
uri = uri.slice(0, -1)
newPaneOptions.newBase = uri
}
newInstance = kb.sym(uri)
newPaneOptions.newInstance = newInstance
}
var contentType = mime.lookup(newInstance.uri)
if (!contentType || !(contentType.startsWith('text') || contentType.includes('xml'))) {
let msg = 'A new text file has to have an file extension like .txt .ttl etc.'
alert(msg)
throw new Error(msg)
}
return new Promise(function (resolve, reject) {
kb.fetcher.webOperation('PUT', newInstance.uri, {data: '\n', contentType: contentType})
.then(function (response) {
console.log('New text file created: ' + newInstance.uri)
newPaneOptions.newInstance = newInstance
resolve(newPaneOptions)
}, err => {
alert('Cant make new file: ' + err)
reject(err)
})
})
}
|
javascript
|
{
"resource": ""
}
|
|
q9033
|
visit
|
train
|
function visit(item, cycle) {
let visitedDeps = visited.get(item);
// Create an object for the item to mark visited deps.
if (!visitedDeps) {
visitedDeps = [];
visited.set(item, visitedDeps);
}
// Get the current deps for the item.
let deps = currDepsMap.get(item);
if (typeof deps === 'undefined') return;
// For each dep,
for (let dep of deps) {
// Check if this dep creates a cycle. We know it's a cycle if the first
// item is the same as our dep.
if (cycle[0] === dep) {
cycles.push(cycle);
}
// If an item hasn't been visited, visit it (and pass an updated
// potential cycle)
if (!arrayIncludes(visitedDeps, dep)) {
visitedDeps.push(dep);
visit(dep, cycle.concat(dep));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9034
|
setupBotStatus
|
train
|
function setupBotStatus(bot, node) {
var updates = 0;
var replies = 0;
var updateText = function updateText() {
return updates !== 1 ? updates + ' updates' : updates + ' update';
};
var replyText= function replyText() {
return replies !== 1 ? replies + ' replies': replies + ' reply';
};
var updateStatus = function updateStatus() {
node.status({fill: 'green', shape: 'dot',
text: updateText() + '; ' + replyText()
});
};
node.status({fill: 'grey', shape: 'ring', text: 'inactive'});
bot.on('update', function updateCallback() {
updates += 1;
updateStatus();
});
bot.on('error', function errorCallback(error) {
node.error(error);
node.status({fill: 'red', shape: 'dot', text: 'error'});
});
bot.use('outgoing', function outgoingCallback(bot, update, message, next) {
replies += 1;
updateStatus();
next();
});
}
|
javascript
|
{
"resource": ""
}
|
q9035
|
processGraph
|
train
|
function processGraph(data) {
let dataset = {
'@default': []
};
let subjects = data.subjects,
htmlMapper = n => {
let div = n.ownerDocument.createElement('div');
div.appendChild(n.cloneNode(true));
return div.innerHTML;
};
Object.keys(subjects).forEach(subject => {
let predicates = subjects[subject].predicates;
Object.keys(predicates).forEach(predicate => {
// iterate over objects
let objects = predicates[predicate].objects;
for (let oi = 0; oi < objects.length; ++oi) {
let object = objects[oi];
// create RDF triple
let triple = {};
// add subject & predicate
triple.subject = {
type: subject.indexOf('_:') === 0 ? 'blank node' : 'IRI',
value: subject
};
triple.predicate = {
type: predicate.indexOf('_:') === 0 ? 'blank node' : 'IRI',
value: predicate
};
triple.object = {};
// serialize XML literal
let value = object.value;
// !!! TODO: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// The below actually most likely does NOT work.
// In most usage contexts this will be an HTML DOM, passing it to xmldom's XMLSerializer
// will cause it to call .toString() on all the nodes it finds — this only works inside
// xmldom.
if (object.type === RDF_XML_LITERAL) {
// initialize XMLSerializer
let serializer = new XMLSerializer();
value = Array.from(object.value)
.map(n => serializer.serializeToString(n))
.join('');
triple.object.datatype = RDF_XML_LITERAL;
}
// serialise HTML literal
else if (object.type === RDF_HTML_LITERAL) {
value = Array.from(object.value)
.map(htmlMapper)
.join('');
triple.object.datatype = RDF_HTML_LITERAL;
}
// object is an IRI
else if (object.type === RDF_OBJECT) {
if (object.value.indexOf('_:') === 0)
triple.object.type = 'blank node';
else triple.object.type = 'IRI';
} else {
// object is a literal
triple.object.type = 'literal';
if (object.type === RDF_PLAIN_LITERAL) {
if (object.language) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = object.language;
} else {
triple.object.datatype = XSD_STRING;
}
} else {
triple.object.datatype = object.type;
}
}
triple.object.value = value;
// add triple to dataset in default graph
dataset['@default'].push(triple);
}
});
});
return dataset;
}
|
javascript
|
{
"resource": ""
}
|
q9036
|
customBase64Hash
|
train
|
function customBase64Hash(str, hashFunction) {
const result = hashFunction(str).toString(encBase64);
return customBase64(result);
}
|
javascript
|
{
"resource": ""
}
|
q9037
|
hash
|
train
|
function hash(method) {
// Is user supplies a function, use it and assume they will take of any
// encoding (Base-64 or otherwise).
if (typeof method === 'function') {
return method;
}
if (hashFunctions.hasOwnProperty(method)) {
return hashFunctions[method];
}
throw new Error(`Could not resolve hash function, received ${typeof method}.`);
}
|
javascript
|
{
"resource": ""
}
|
q9038
|
normalize
|
train
|
function normalize(options, templates) {
// Options override defaults and toc methods.
var result = _.defaults({}, options, toc, toc.defaults);
// Remove "core" methods from result object.
['defaults', 'process', 'anchorize', 'toc'].forEach(function(prop) {
delete result[prop];
});
// Compile Lodash string templates into functions.
(templates || []).forEach(function(tmpl) {
if (typeof result[tmpl] === 'string') {
result[tmpl] = _.template(result[tmpl]);
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q9039
|
_parseShellConfigOptions
|
train
|
function _parseShellConfigOptions(argv) {
var out = {};
//`parse-pos-args` value is `true` by default, it must be
//explicitly set to falsy value thus undefined & null values does not count
if (argv['parse-pos-args'] === false || argv['parse-pos-args'] === 0) {
setConfigPathOption(out);
return out;
}
var options = argv.options.reduce(function(out, option, index) {
if (index % 2 === 0) {
out.names.push(option);
} else {
out.values.push(option);
}
return out;
}, {
names: [],
values: []
});
if (argv.options.length % 2 !== 0) {
throw new Error(
`Invalid number of shell positional arguments received.
Possitional arguments are expected to be in "[key] [value]" pairs`
);
}
options.names.forEach(function(propPath, index) {
_.set(
out,
propPath,
json5.parse(options.values[index])
);
});
setConfigPathOption(out);
return out;
function setConfigPathOption(obj) {
//for overwriting expected config filepath we can use --config option only
if (argv.config) {
obj.fileConfigPath = argv.config;
obj.fileConfigPath = path.normalize(obj.fileConfigPath);
} else {
delete obj.fileConfigPath;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9040
|
train
|
function (loggerName, level, message) {
this.time = new Date();
this.loggerName = loggerName;
this.level = level;
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
|
q9041
|
writeReport
|
train
|
function writeReport(fileResult, formatter, formattedSourceLines, baseDir) {
var fileName = fileResult.fileName,
stats = StatUtils.decorateStatPercentages(fileResult.stats),
parentDir = path.normalize(baseDir + '/..'),
mutations = formatter.formatMutations(fileResult.mutationResults),
breadcrumb = new IndexHtmlBuilder(baseDir).linkPathItems({
currentDir: parentDir,
fileName: baseDir + '/' + fileName + '.html',
separator: ' >> ',
relativePath: getRelativeDistance(baseDir + '/' + fileName, baseDir ),
linkDirectoryOnly: true
});
var file = Templates.fileTemplate({
sourceLines: formattedSourceLines,
mutations: mutations
});
fs.writeFileSync(
path.join(baseDir, fileName + ".html"),
Templates.baseTemplate({
style: Templates.baseStyleTemplate({ additionalStyle: Templates.fileStyleCode }),
script: Templates.baseScriptTemplate({ additionalScript: Templates.fileScriptCode }),
fileName: path.basename(fileName),
stats: stats,
status: stats.successRate > this._config.successThreshold ? 'killed' : stats.all > 0 ? 'survived' : 'neutral',
breadcrumb: breadcrumb,
generatedAt: new Date().toLocaleString(),
content: file
})
);
}
|
javascript
|
{
"resource": ""
}
|
q9042
|
train
|
function(obj, keys, caseSensitive /* default: false */) {
var key, keyLower, newObj = {};
if (!$.isArray(keys) || !keys.length) {
return newObj;
}
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
if(caseSensitive === true) {
continue;
}
//when getting data-* attributes via $.data() it's converted to lowercase.
//details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery
//workaround is code below.
keyLower = key.toLowerCase();
if (obj.hasOwnProperty(keyLower)) {
newObj[key] = obj[keyLower];
}
}
return newObj;
}
|
javascript
|
{
"resource": ""
}
|
|
q9043
|
train
|
function(element, options) {
this.$element = $(element);
//since 1.4.1 container do not use data-* directly as they already merged into options.
this.options = $.extend({}, $.fn.editableContainer.defaults, options);
this.splitOptions();
//set scope of form callbacks to element
this.formOptions.scope = this.$element[0];
this.initContainer();
//flag to hide container, when saving value will finish
this.delayedHide = false;
//bind 'destroyed' listener to destroy container when element is removed from dom
this.$element.on('destroyed', $.proxy(function(){
this.destroy();
}, this));
//attach document handler to close containers on click / escape
if(!$(document).data('editable-handlers-attached')) {
//close all on escape
$(document).on('keyup.editable', function (e) {
if (e.which === 27) {
$('.editable-open').editableContainer('hide');
//todo: return focus on element
}
});
//close containers when click outside
//(mousedown could be better than click, it closes everything also on drag drop)
$(document).on('click.editable', function(e) {
var $target = $(e.target), i,
exclude_classes = ['.editable-container',
'.ui-datepicker-header',
'.datepicker', //in inline mode datepicker is rendered into body
'.modal-backdrop',
'.bootstrap-wysihtml5-insert-image-modal',
'.bootstrap-wysihtml5-insert-link-modal'
];
//check if element is detached. It occurs when clicking in bootstrap datepicker
if (!$.contains(document.documentElement, e.target)) {
return;
}
//for some reason FF 20 generates extra event (click) in select2 widget with e.target = document
//we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199
//Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec
if($target.is(document)) {
return;
}
//if click inside one of exclude classes --> no nothing
for(i=0; i<exclude_classes.length; i++) {
if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) {
return;
}
}
//close all open containers (except one - target)
Popup.prototype.closeOthers(e.target);
});
$(document).data('editable-handlers-attached', true);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9044
|
train
|
function() {
this.containerOptions = {};
this.formOptions = {};
if(!$.fn[this.containerName]) {
throw new Error(this.containerName + ' not found. Have you included corresponding js file?');
}
var cDef = $.fn[this.containerName].defaults;
//keys defined in container defaults go to container, others go to form
for(var k in this.options) {
if(k in cDef) {
this.containerOptions[k] = this.options[k];
} else {
this.formOptions[k] = this.options[k];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9045
|
train
|
function(reason) {
if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) {
return;
}
//if form is saving value, schedule hide
if(this.$form.data('editableform').isSaving) {
this.delayedHide = {reason: reason};
return;
} else {
this.delayedHide = false;
}
this.$element.removeClass('editable-open');
this.innerHide();
/**
Fired when container was hidden. It occurs on both save or cancel.
**Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one.
The workaround is to check `arguments.length` that is always `2` for x-editable.
@event hidden
@param {object} event event object
@param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code>
@example
$('#username').on('hidden', function(e, reason) {
if(reason === 'save' || reason === 'cancel') {
//auto-open next editable
$(this).closest('tr').next().find('.editable').editable('show');
}
});
**/
this.$element.triggerHandler('hidden', reason || 'manual');
}
|
javascript
|
{
"resource": ""
}
|
|
q9046
|
train
|
function(value, convertStr, response) {
if(convertStr) {
this.value = this.input.str2value(value);
} else {
this.value = value;
}
if(this.container) {
this.container.option('value', this.value);
}
$.when(this.render(response))
.then($.proxy(function() {
this.handleEmpty();
}, this));
}
|
javascript
|
{
"resource": ""
}
|
|
q9047
|
train
|
function() {
if (this.options.clear) {
this.$clear = $('<span class="editable-clear-x"></span>');
this.$input.after(this.$clear)
.css('padding-right', 24)
.keyup($.proxy(function(e) {
//arrows, enter, tab, etc
if(~$.inArray(e.keyCode, [40,38,9,13,27])) {
return;
}
clearTimeout(this.t);
var that = this;
this.t = setTimeout(function() {
that.toggleClear(e);
}, 100);
}, this))
.parent().css('position', 'relative');
this.$clear.click($.proxy(this.clear, this));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9048
|
train
|
function(str) {
var reg, value = null;
if(typeof str === 'string' && str.length) {
reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*');
value = str.split(reg);
} else if($.isArray(str)) {
value = str;
} else {
value = [str];
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q9049
|
train
|
function(value) {
this.$input.prop('checked', false);
if($.isArray(value) && value.length) {
this.$input.each(function(i, el) {
var $el = $(el);
// cannot use $.inArray as it performs strict comparison
$.each(value, function(j, val){
/*jslint eqeq: true*/
if($el.val() == val) {
/*jslint eqeq: false*/
$el.prop('checked', true);
}
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9050
|
train
|
function(value, element) {
var html = [],
checked = $.fn.editableutils.itemsByValue(value, this.sourceData);
if(checked.length) {
$.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
$(element).html(html.join('<br>'));
} else {
$(element).empty();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9051
|
train
|
function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
var $extraEventClass = $(this).attr('data-class');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
if($extraEventClass) copiedEventObject['className'] = [$extraEventClass];
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9052
|
applyCatchList
|
train
|
function applyCatchList(promise, req, res, catchList, index) {
index = index || 0;
if ( !Array.isArray(catchList)
|| index > catchList.length - 1
|| !Array.isArray(catchList[index])
|| !(catchList[index][1] instanceof Function)
) {
return promise;
}
var args = _.clone(catchList[index]);
var cb = args[1];
args[1] = function(err) {
return cb(err, req, res);
};
promise = promise.catch.apply(promise, args);
return applyCatchList(promise, req, res, catchList, ++index);
}
|
javascript
|
{
"resource": ""
}
|
q9053
|
performMove
|
train
|
function performMove(fields, direction) {
const oldSpaceshipPosition = findSpaceshipPosition(fields);
const dx = { left: -1, ahead: 0, right: 1 }[direction];
const newSpaceshipPosition = [oldSpaceshipPosition[0] - 1, oldSpaceshipPosition[1] + dx];
const newFields = fields.map((row, i) => row.map((field, j) => {
const [background, oldObjects] = field;
let newObjects = oldObjects;
if (i === oldSpaceshipPosition[0] && j === oldSpaceshipPosition[1]) {
if (outsideWorld(fields, newSpaceshipPosition)) {
let border = null;
if (i === 0) {
border = 'top';
} else if (j === 0) {
border = 'left';
} else {
border = 'right';
}
newObjects = [`spaceship-out-${border}`];
} else {
newObjects = removeSpaceship(oldObjects);
}
}
if (i === newSpaceshipPosition[0] && j === newSpaceshipPosition[1]) {
if (onRock(fields, newSpaceshipPosition)) {
newObjects = [...newObjects, 'spaceship-broken'];
} else {
newObjects = [...newObjects, 'S'];
}
}
return [background, newObjects];
}));
return newFields;
}
|
javascript
|
{
"resource": ""
}
|
q9054
|
KarmaServerPool
|
train
|
function KarmaServerPool(config) {
this._config = _.merge({ port: 12111, maxActiveServers: 5, startInterval: 100 }, config);
this._instances = [];
}
|
javascript
|
{
"resource": ""
}
|
q9055
|
LoggerContext
|
train
|
function LoggerContext() {
LifeCycle.call(this);
/**
* Context start time
*/
this.startTime = new Date();
/**
* The list of trace levels that the logger context knows about
*/
this.logLevel = new LogLevel();
/**
* Root logger, final ancestor of all loggers
*/
this.rootLogger = new Logger('[root]', this);
/**
* List of loggers that have been created, indexed by name.
*/
this.loggers = {};
/**
* List of appenders that have been registered through a call to
* "registerAppender", indexed by name.
*/
this.appenders = {};
/**
* List of filters that have been registered through a call to
* "registerFilter", indexed by name.
*/
this.filters = {};
/**
* List of layouts that have been registered through a call to
* "registerLayout", indexed by name.
*/
this.layouts = {};
/**
* List of appenders that have been instantiated.
*
* The list is constructed when the configuration is applied. It is used
* to start/stop appenders when corresponding functions are called on this
* context.
*/
this.createdAppenders = [];
/**
* The context-wide filter.
*
* The filter is constructed when the configuration is applied. If the
* configuration specifies more than one context-wide filter, a
* CompositeFilter filter is created.
*/
this.filter = null;
/**
* Flag set when the context is up and running
*/
this.started = false;
/**
* Log events received by the context before it got a chance to start and
* that need to be processed as soon as the context is operational
*
* The context keeps a maximum of 1000 events in memory. If more events are
* received before the context becomes operational, the context starts to
* drop events, replacing the first event with a warning that events had to
* be droppes. That warning is sent to the root logger.
*/
this.pendingEvents = [];
/**
* Maximum number of log events that can be stored in the pending list.
*
* TODO: adjust this setting based on configuration settings.
*/
this.maxPendingEvents = 1000;
/**
* Number of log events that had to be discarded so far
*/
this.discardedPendingEvents = 0;
}
|
javascript
|
{
"resource": ""
}
|
q9056
|
link
|
train
|
function link(href, title, text) {
var reLabelFirst = /^(.*?)\s*\?([^?\s]*)\?(\*?)(X?)(H?)$/;
var reLabelAfter = /^\?([^?\s]*)\?(\*?)(X?)(H?)\s*(.*)$/;
var m = text.match(reLabelFirst);
if (m) return renderInput(m[1], m[2], m[3], m[4], m[5], href, title, true);
m = text.match(reLabelAfter);
if (m) return renderInput(m[5], m[1], m[2], m[3], m[4], href, title, false);
return fallback.link.call(this, href, title, text);
}
|
javascript
|
{
"resource": ""
}
|
q9057
|
listitem
|
train
|
function listitem(text) {
if (inList()) {
// capture value in trailing "text" - unescape makes regexp work
var m = unescapeQuotes(text).match(/^(.*)\s+"([^"]*)"\s*$/);
var txt = m ? escapeQuotes(m[1]) : text;
var val = m ? escapeQuotes(m[2]) : text;
return renderOption(txt, val);
}
return fallback.listitem.call(this, text);
}
|
javascript
|
{
"resource": ""
}
|
q9058
|
list
|
train
|
function list(body, ordered) {
if (inList()) return body + endList();
return fallback.list.call(this, body, ordered);
}
|
javascript
|
{
"resource": ""
}
|
q9059
|
train
|
function () {
this.update = {
velocity: function (entity, dt) {
entity.c.position.x += hitagi.utils.delta(entity.c.velocity.xspeed, dt);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q9060
|
train
|
function (params) {
this.$id = 'dragBoxUI';
this.width = 0;
this.height = 0;
this.origin = {
x: params.x,
y: params.y
};
}
|
javascript
|
{
"resource": ""
}
|
|
q9061
|
train
|
function (params) {
params = _.extend({
anchor: {
x: 0.5,
y: 0.5
}
}, params);
this.$id = 'collision';
this.$deps = ['position'];
this.width = params.width;
this.height = params.height;
this.anchor = params.anchor;
}
|
javascript
|
{
"resource": ""
}
|
|
q9062
|
getRequest
|
train
|
function getRequest(at, api_url, config, callback) {
if (!config.responseCode)
config.responseCode = 200;
request(
{
uri: getURL(at, api_url, config.opts),
method: 'GET',
headers: {'Content-Type': 'application/json'}
},
function(err,res,body) {
if (!err && res.statusCode == config.responseCode) {
if (config.doParse) {
callback(null,JSON.parse(body).response);
} else {
callback(null,res.statusCode);
}
} else {
callback(res)
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9063
|
postRequest
|
train
|
function postRequest(at, api_url, config, callback) {
var r_opts = {
uri: getURL(at, api_url),
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
if (config.body && !config.form) {
r_opts.body = JSON.stringify(config.body);
} else {
r_opts.form = config.form;
}
if (!config.responseCode)
config.responseCode = 200;
request(
r_opts,
function(err,res,body) {
if (!err && res.statusCode == config.responseCode) {
if (config.doParse) {
callback(null,JSON.parse(body).response);
} else {
callback(null,res.statusCode);
}
} else {
callback(res)
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9064
|
clones
|
train
|
function clones (source, bind, target) {
let opts = {
bind: bind,
visited: [],
cloned: []
}
return _clone(opts, source, target)
}
|
javascript
|
{
"resource": ""
}
|
q9065
|
_clone
|
train
|
function _clone (opts, source, target) {
let type = toType(source)
switch (type) {
case 'String':
case 'Number':
case 'Boolean':
case 'Null':
case 'Undefined':
case 'Symbol':
case 'DOMPrototype': // (browser)
case 'process': // (node) cloning this is not a good idea
target = source
break
case 'Function':
if (!target) {
let _bind = (opts.bind === null ? null : opts.bind || source)
if (opts.wrapFn) {
target = function () {
return source.apply(_bind, arguments)
}
} else {
target = source.bind(_bind)
}
}
target = _props(opts, source, target)
break
case 'Int8Array':
case 'Uint8Array':
case 'Uint8ClampedArray':
case 'Int16Array':
case 'Uint16Array':
case 'Int32Array':
case 'Uint32Array':
case 'Float32Array':
case 'Float64Array':
target = new source.constructor(source)
break
case 'Array':
target = source.map(function (item) {
return _clone(opts, item)
})
target = _props(opts, source, target)
break
case 'Date':
target = new Date(source)
break
case 'Error':
case 'EvalError':
case 'InternalError':
case 'RangeError':
case 'ReferenceError':
case 'SyntaxError':
case 'TypeError':
case 'URIError':
target = new source.constructor(source.message)
target = _props(opts, source, target)
target.stack = source.stack
break
case 'RegExp':
let flags = source.flags ||
(source.global ? 'g' : '') +
(source.ignoreCase ? 'i' : '') +
(source.multiline ? 'm' : '')
target = new RegExp(source.source, flags)
break
case 'Buffer':
target = new source.constructor(source)
break
case 'Window': // clone of global object
case 'global':
opts.wrapFn = true
target = _props(opts, source, target || {})
break
case 'Math':
case 'JSON':
case 'Console':
case 'Navigator':
case 'Screen':
case 'Object':
target = _props(opts, source, target || {})
break
default:
if (/^HTML/.test(type)) { // handle HTMLElements
if (source.cloneNode) {
target = source.cloneNode(true)
} else {
target = source
}
} else if (typeof source === 'object') { // handle other object based types
target = _props(opts, source, target || {})
} else { // anything else should be a primitive
target = source
}
}
return target
}
|
javascript
|
{
"resource": ""
}
|
q9066
|
_props
|
train
|
function _props (opts, source, target) {
let idx = opts.visited.indexOf(source) // check for circularities
if (idx === -1) {
opts.visited.push(source)
opts.cloned.push(target)
Object.getOwnPropertyNames(source).forEach(function (key) {
if (key === 'prototype') {
target[key] = Object.create(source[key])
Object.getOwnPropertyNames(source[key]).forEach(function (p) {
if (p !== 'constructor') {
_descriptor(opts, source[key], target[key], p)
// } else {
// target[key][p] = target
// Safari may throw here with TypeError: Attempted to assign to readonly property.
}
})
} else {
_descriptor(opts, source, target, key)
}
})
opts.visited.pop()
opts.cloned.pop()
} else {
target = opts.cloned[idx] // add reference of circularity
}
return target
}
|
javascript
|
{
"resource": ""
}
|
q9067
|
_descriptor
|
train
|
function _descriptor (opts, source, target, key) {
let desc = Object.getOwnPropertyDescriptor(source, key)
if (desc) {
if (desc.writable) {
desc.value = _clone(opts, desc.value)
}
try {
Object.defineProperty(target, key, desc)
} catch (e) {
// Safari throws with TypeError:
// Attempting to change access mechanism for an unconfigurable property.
// Attempting to change value of a readonly property.
if (!'Attempting to change'.indexOf(e.message)) {
throw e
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9068
|
cleanContent
|
train
|
function cleanContent() {
function transform(file, cb) {
file.contents = new Buffer((function (src) {
var lines = src.replace('_.mixin({\n','').split('\n'),
last = lines.pop();
// handle empty lines at the end of the file
while(last===''){
last = lines.pop();
}
return lines.join('\n');
})(String(file.contents)));
cb(null, file);
}
return require('event-stream').map(transform);
}
|
javascript
|
{
"resource": ""
}
|
q9069
|
recursiveCall
|
train
|
function recursiveCall(i, callback) {
if(i >= _modules.length) {
callback();
} else {
_modules[i].check(req, res, function () {
recursiveCall(++i, callback);
})
}
}
|
javascript
|
{
"resource": ""
}
|
q9070
|
train
|
function (params) {
this.formatString = '';
this.params = [];
if (!params) {
return;
}
params = utils.isArray(params) ? params : [params];
if ((params.length > 0) &&
utils.isString(params[0]) &&
(params[0].indexOf('{}') !== -1)) {
this.formatString = params[0];
this.params = params.slice(1);
}
else {
this.params = params;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9071
|
setSize
|
train
|
function setSize(size, dimension) {
return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : winheight()) / 100) : 1) * parseInt(size, 10));
}
|
javascript
|
{
"resource": ""
}
|
q9072
|
appendHTML
|
train
|
function appendHTML() {
if (!$box && document.body) {
init = false;
$window = $(window);
$box = $tag(div).attr({
id: colorbox,
'class': $.support.opacity === false ? prefix + 'IE' : '', // class for optional IE8 & lower targeted CSS.
role: 'dialog',
tabindex: '-1'
}).hide();
$overlay = $tag(div, "Overlay").hide();
$loadingOverlay = $([$tag(div, "LoadingOverlay")[0],$tag(div, "LoadingGraphic")[0]]);
$wrap = $tag(div, "Wrapper");
$content = $tag(div, "Content").append(
$title = $tag(div, "Title"),
$current = $tag(div, "Current"),
$prev = $('<button type="button"/>').attr({id:prefix+'Previous'}),
$next = $('<button type="button"/>').attr({id:prefix+'Next'}),
$slideshow = $tag('button', "Slideshow"),
$loadingOverlay
);
$close = $('<button type="button"/>').attr({id:prefix+'Close'});
$wrap.append( // The 3x3 Grid that makes up Colorbox
$tag(div).append(
$tag(div, "TopLeft"),
$topBorder = $tag(div, "TopCenter"),
$tag(div, "TopRight")
),
$tag(div, false, 'clear:left').append(
$leftBorder = $tag(div, "MiddleLeft"),
$content,
$rightBorder = $tag(div, "MiddleRight")
),
$tag(div, false, 'clear:left').append(
$tag(div, "BottomLeft"),
$bottomBorder = $tag(div, "BottomCenter"),
$tag(div, "BottomRight")
)
).find('div div').css({'float': 'left'});
$loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none');
$groupControls = $next.add($prev).add($current).add($slideshow);
$(document.body).append($overlay, $box.append($wrap, $loadingBay));
}
}
|
javascript
|
{
"resource": ""
}
|
q9073
|
addBindings
|
train
|
function addBindings() {
function clickHandler(e) {
// ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt.
// See: http://jacklmoore.com/notes/click-events/
if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey)) {
e.preventDefault();
launch(this);
}
}
if ($box) {
if (!init) {
init = true;
// Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly.
$next.click(function () {
publicMethod.next();
});
$prev.click(function () {
publicMethod.prev();
});
$close.click(function () {
publicMethod.close();
});
$overlay.click(function () {
if (settings.overlayClose) {
publicMethod.close();
}
});
// Key Bindings
$(document).bind('keydown.' + prefix, function (e) {
var key = e.keyCode;
if (open && settings.escKey && key === 27) {
e.preventDefault();
publicMethod.close();
}
if (open && settings.arrowKey && $related[1] && !e.altKey) {
if (key === 37) {
e.preventDefault();
$prev.click();
} else if (key === 39) {
e.preventDefault();
$next.click();
}
}
});
if ($.isFunction($.fn.on)) {
// For jQuery 1.7+
$(document).on('click.'+prefix, '.'+boxElement, clickHandler);
} else {
// For jQuery 1.3.x -> 1.6.x
// This code is never reached in jQuery 1.9, so do not contact me about 'live' being removed.
// This is not here for jQuery 1.9, it's here for legacy users.
$('.'+boxElement).live('click.'+prefix, clickHandler);
}
}
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q9074
|
Blocker
|
train
|
function Blocker(config, logger) {
//DB must define an add, remove and contains function!
if(!(config.db && config.db.add && config.db.remove && config.db.contains)){
throw "db must define an add, remove and contains function";
};
_config = config;
_logger = logger;
}
|
javascript
|
{
"resource": ""
}
|
q9075
|
replaceHtml
|
train
|
function replaceHtml(ele, html) {
var _this = this;
if (ele.classList.contains('raw-text')) {
return;
}
ele.innerHTML = withEscape( // eslint-disable-line no-undef
function (html) {
return function (reg, rep) {
return _this.htmlSugars.reduce(function (html, _ref) {
var _ref2 = _slicedToArray(_ref, 2),
regExp = _ref2[0],
replace = _ref2[1];
return html.replace(regExp, replace);
}, html).replace(reg, rep);
};
})(html);
}
|
javascript
|
{
"resource": ""
}
|
q9076
|
train
|
function() {
try {
return navigator.cookieEnabled ||
("cookie" in $document && ($document.cookie.length > 0 ||
($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9077
|
updatePagerIcons
|
train
|
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first' : 'icon-double-angle-left bigger-140',
'ui-icon-seek-prev' : 'icon-angle-left bigger-140',
'ui-icon-seek-next' : 'icon-angle-right bigger-140',
'ui-icon-seek-end' : 'icon-double-angle-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
})
}
|
javascript
|
{
"resource": ""
}
|
q9078
|
KarmaServerManager
|
train
|
function KarmaServerManager(config, port, runnerTimeUnlimited) {
this._status = null;
this._serverProcess = null;
this._runnerTimeUnlimited = runnerTimeUnlimited;
this._config = _.merge({ waitForServerTime: 10, waitForRunnerTime: 2 }, config, { port: port });
var notIncluded = this._config.notIncluded || [];
this._config.files = _.map(this._config.files, function(filename) {
return { pattern: filename, included: _.indexOf(notIncluded, filename) < 0 };
});
}
|
javascript
|
{
"resource": ""
}
|
q9079
|
startServer
|
train
|
function startServer(serverPromise) {
var self = this,
startTime = Date.now(),
browsersStarting,
serverTimeout,
serverProcess = fork(__dirname + '/KarmaWorker.js', { silent: true });
// Limit the time it can take for a server to start to config.waitForServerTime seconds
serverTimeout = setTimeout(function() {
self._setStatus(KarmaServerStatus.DEFUNCT);
serverPromise.reject(
'Could not connect to a Karma server on port ' + self._config.port + ' within ' +
self._config.waitForServerTime + ' seconds'
);
}, self._config.waitForServerTime * 1000);
serverProcess.send({ command: 'start', config: self._config });
serverProcess.stdout.on('data', function(data) {
var message = data.toString('utf-8'),
messageParts = message.split(/\s/g);
logger.debug(message);
//this is a hack: because Karma exposes no method of determining when the server is started up we'll dissect the log messages
if(message.indexOf('Starting browser') > -1) {
browsersStarting = browsersStarting ? browsersStarting.concat([messageParts[4]]) : [messageParts[4]];
}
if(message.indexOf('Connected on socket') > -1) {
browsersStarting.pop();
if(browsersStarting && browsersStarting.length === 0) {
clearTimeout(serverTimeout);
self._setStatus(KarmaServerStatus.READY);
logger.info(
'Karma server started after %dms and is listening on port %d',
(Date.now() - startTime), self._config.port
);
serverPromise.resolve(self);
}
}
});
return serverProcess;
}
|
javascript
|
{
"resource": ""
}
|
q9080
|
parseASTComments
|
train
|
function parseASTComments(astNode) {
var comments = [];
if(astNode && astNode.leadingComments) {
_.forEach(astNode.leadingComments, function(comment) {
if(comment.type === 'Block') {
comments = comments.concat(comment.value.split('\n').map(function(commentLine) {
// Remove asterisks at the start of the line
return commentLine.replace(/^\s*\*\s*/g, '').trim();
}));
} else {
comments.push(comment.value);
}
});
}
return comments;
}
|
javascript
|
{
"resource": ""
}
|
q9081
|
train
|
function (node, nodeType) {
var parentNode = node;
var levelNode = 0; // Security in while loop
while ((parentNode.type !== nodeType) &&
(parentNode.parent !== undefined) &&
(levelNode <= 20)) {
levelNode++;
parentNode = parentNode.parent;
}
parentNode.levelNode = levelNode;
return parentNode;
}
|
javascript
|
{
"resource": ""
}
|
|
q9082
|
runValidation
|
train
|
function runValidation(validators, field, context, callback) {
var fieldErrors = [];
var pending = 0;
function saveResult(result) {
if (result !== true) {
fieldErrors.push(result);
}
}
function doCallback() {
callback(fieldErrors);
}
function asyncValidationDone(result) {
saveResult(result);
pending--;
pending === 0 && doCallback();
}
validators.forEach(function (validator) {
if (validator.length === 2) {
pending++;
validator.call(context, field, asyncValidationDone);
} else {
saveResult(validator.call(context, field));
}
});
if (pending === 0) {
// synchronous callback
doCallback();
}
return fieldErrors;
}
|
javascript
|
{
"resource": ""
}
|
q9083
|
matchesValidator
|
train
|
function matchesValidator(match) {
return function matchValue(value) {
var result;
if (typeof match.test === "function") {
match.lastIndex = 0; // reset the lastIndex just in case the regexp is accidentally global
result = match.test(value);
} else {
result = match === value;
}
return result || "matches";
};
}
|
javascript
|
{
"resource": ""
}
|
q9084
|
_setImmediate
|
train
|
function _setImmediate(fn) {
let args = Array.prototype.slice.call(arguments, 1);
return new Promise(function(resolve, reject) {
setImmediate(function() {
try {
fn.apply(this, args);
} catch(e) {
return reject(e);
}
resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9085
|
_onBuildApp
|
train
|
function _onBuildApp(app) {
let proto = Object.getPrototypeOf(app);
if (proto.constructor && proto.constructor.name === 'ShellApp') {
app.once('post-init', function() {
this.build();
this.listen();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q9086
|
random
|
train
|
function random( width, set ) {
width = parseInt( width ) || 4
set = set || RANDOM_SET
ass.isString( set, "Random character set must be string" )
var
i = 0,
r = ''
for ( ; i < width; i ++ )
r += RANDOM_SET[ Math.floor( Math.random() * RANDOM_SET.length ) ]
return r
}
|
javascript
|
{
"resource": ""
}
|
q9087
|
expandFiles
|
train
|
function expandFiles(files, basePath) {
var expandedFiles = [];
files = files ? _.isArray(files) ? files : [files] : [];
_.forEach(files, function(fileName) {
expandedFiles = _.union(
expandedFiles,
glob.sync(path.join(basePath, fileName), { dot: true, nodir: true })
);
});
return expandedFiles;
}
|
javascript
|
{
"resource": ""
}
|
q9088
|
getOptions
|
train
|
function getOptions(grunt, task) {
var globalOpts = grunt.config(task.name).options;
var localOpts = grunt.config([task.name, task.target]).options;
var opts = _.merge({}, DEFAULT_OPTIONS, globalOpts, localOpts);
// Set logging options
log4js.setGlobalLogLevel(log4js.levels[opts.logLevel]);
log4js.configure(LOG_OPTIONS);
opts.code = expandFiles(opts.code, opts.basePath);
opts.specs = expandFiles(opts.specs, opts.basePath);
opts.mutate = expandFiles(opts.mutate, opts.basePath);
if (opts.karma) {
opts.karma.notIncluded = expandFiles(opts.karma.notIncluded, opts.basePath);
}
var requiredOptionsSetErr = areRequiredOptionsSet(opts);
if(requiredOptionsSetErr !== null) {
grunt.warn('Not all required options have been set properly. ' + requiredOptionsSetErr);
return null;
}
ensureReportersConfig(opts);
ensureIgnoreConfig(opts);
return opts;
}
|
javascript
|
{
"resource": ""
}
|
q9089
|
Buffering
|
train
|
function Buffering(options) {
events.EventEmitter.call(this);
options = options || {};
if (options.useUnique) {
var newOptions = {};
Object.keys(options).forEach(function(key) {
if (key != 'useUnique') newOptions[key] = options[key];
});
return new UniqueBuffering(newOptions);
}
this._timeThreshold = (typeof options.timeThreshold === 'undefined') ? -1 : options.timeThreshold;
this._sizeThreshold = (typeof options.sizeThreshold === 'undefined') ? -1 : options.sizeThreshold;
this._data = [];
this._flushTimer = null;
this._paused = false;
this._resumeTimer = null;
this._flushingBySize = false;
}
|
javascript
|
{
"resource": ""
}
|
q9090
|
reducer
|
train
|
function reducer(individualSeries, initialFunction, reductionFunction) {
if (individualSeries.length == 0) {
return NaN;
}
var initial = initialFunction(individualSeries[0][1]);
var i=1;
for (; initial==null && i<individualSeries.length; i++) {
initial = initialFunction(individualSeries[i][1]);
}
for (; i<individualSeries.length; i++) {
if (individualSeries[i][1] != null) {
initial = reductionFunction(initial, individualSeries[i][1]);
}
}
return initial;
}
|
javascript
|
{
"resource": ""
}
|
q9091
|
train
|
function(baseDir, config) {
this._baseDir = baseDir;
this._config = _.merge({}, DEFAULT_CONFIG, config);
this._folderPercentages = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q9092
|
createUser
|
train
|
function createUser(req, res, next){
// the HTML form names are conveniently named the same as
// the UserApp fields...
var user = req.body;
// Create the user in UserApp
UserApp.User.save(user, function(err, user){
// We can just pass through messages like "Password must be at least 5 characters." etc.
if (err) return res.render('signup', {user: false, message: err.message});
// UserApp passport needs a username parameter
req.body.username = req.body.login;
//on to authentication
next();
});
// authenticate the user using passport
}
|
javascript
|
{
"resource": ""
}
|
q9093
|
Block
|
train
|
function Block() {
if( !(this instanceof Block) )
return new Block()
/** @type {Number} Entry / compression type */
this.type = 0x00000000
/** @type {String} Entry type name */
this.description = 'UNKNOWN'
/** @type {String} Comment ('+beg'|'+end' if type == COMMENT) */
this.comment = ''
/** @type {Number} Start sector of this chunk */
this.sectorNumber = 0x0000000000000000
/** @type {Number} Number of sectors in this chunk */
this.sectorCount = 0x0000000000000000
/** @type {Number} Start of chunk in data fork */
this.compressedOffset = 0x0000000000000000
/** @type {Number} Chunk's bytelength in data fork */
this.compressedLength = 0x0000000000000000
}
|
javascript
|
{
"resource": ""
}
|
q9094
|
train
|
function( buffer, offset ) {
offset = offset || 0
this.type = buffer.readUInt32BE( offset + 0 )
this.description = Block.getDescription( this.type )
this.comment = buffer.toString( 'ascii', offset + 4, offset + 8 ).replace( /\u0000/g, '' )
this.sectorNumber = uint64.readBE( buffer, offset + 8, 8 )
this.sectorCount = uint64.readBE( buffer, offset + 16, 8 )
this.compressedOffset = uint64.readBE( buffer, offset + 24, 8 )
this.compressedLength = uint64.readBE( buffer, offset + 32, 8 )
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q9095
|
print
|
train
|
function print(object) {
console.log(util.inspect(object, null, null, true));
}
|
javascript
|
{
"resource": ""
}
|
q9096
|
callsites
|
train
|
function callsites() {
var _ = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) {
return stack;
};
var stack = new Error().stack.slice(1);
Error.prepareStackTrace = _;
return stack;
}
|
javascript
|
{
"resource": ""
}
|
q9097
|
existsCached
|
train
|
function existsCached(testPath) {
if (existsCache[testPath] == 1) {
return true;
}
if (existsCache[testPath] == 0) {
return false;
}
if (exists(testPath)) {
existsCache[testPath] = 1;
return true;
}
else {
existsCache[testPath] = 0;
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q9098
|
applyCase
|
train
|
function applyCase(wordA, wordB) {
// Exception to avoid words like "I" being converted to "ME"
if (wordA.length === 1 && wordB.length !== 1) return wordB;
// Uppercase
if (wordA === wordA.toUpperCase()) return wordB.toUpperCase();
// Lowercase
if (wordA === wordA.toLowerCase()) return wordB.toLowerCase();
// Capitialized
var firstChar = wordA.slice(0, 1);
var otherChars = wordA.slice(1);
if (firstChar === firstChar.toUpperCase() && otherChars === otherChars.toLowerCase()) {
return wordB.slice(0, 1).toUpperCase() + wordB.slice(1).toLowerCase();
}
// Other cases
return wordB;
}
|
javascript
|
{
"resource": ""
}
|
q9099
|
train
|
function(options){
EventEmitter.call(this);
// Data Structures
// Persistence
this.data = {};
this.triggers = {};
this.queue = [];
this.nextTick = false;
// Dynamic
this.needs = {};
this.events = {};
this.options = options || {};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.