_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6000
|
inferSettings
|
train
|
function inferSettings(graph) {
var order = graph.order;
return {
barnesHutOptimize: order > 2000,
strongGravityMode: true,
gravity: 0.05,
scalingRatio: 10,
slowDown: 1 + Math.log(order)
};
}
|
javascript
|
{
"resource": ""
}
|
q6001
|
Page
|
train
|
function Page(path, ctx) {
events.EventEmitter.call(this);
this.path = path;
this.context = ctx;
this._isOpen = false;
}
|
javascript
|
{
"resource": ""
}
|
q6002
|
dispatch
|
train
|
function dispatch(req, done) {
var site = req.site
, path = upath.join(site.path || '', req.path)
, parent = site.parent;
while (parent) {
path = upath.join(parent.path || '', path);
parent = parent.parent;
}
console.log('# ' + path);
var page = new Page(path, req.context);
pages.push(page);
page.once('close', done);
//page.site = self;
//page.pages = pages;
self.handle(page);
}
|
javascript
|
{
"resource": ""
}
|
q6003
|
rewrite_code
|
train
|
function rewrite_code(code, node, replacement_string) {
return code.substr(0, node.start.pos) + replacement_string + code.substr(node.end.endpos);
}
|
javascript
|
{
"resource": ""
}
|
q6004
|
generateData
|
train
|
function generateData( filepath )
{
var dataObj = new datauri( filepath );
return {
data: dataObj.content,
path: filepath
};
}
|
javascript
|
{
"resource": ""
}
|
q6005
|
generateCss
|
train
|
function generateCss( filepath, data )
{
var filetype = filepath.split( '.' ).pop().toLowerCase();
var className;
var template;
className = options.classPrefix + path.basename( data.path ).split( '.' )[0] + options.classSuffix;
filetype = options.usePlaceholder ? filetype : filetype + '_no';
if (options.variables)
{
template = cssTemplates.variables;
}
else
{
template = cssTemplates[ filetype ] || cssTemplates.default;
}
return template.replace( '{{class}}', className ).replace( '{{data}}', data.data );
}
|
javascript
|
{
"resource": ""
}
|
q6006
|
getHistory
|
train
|
function getHistory(callback) {
if (_.isUndefined(callback)) {
} else {
var u = config.baseUrl + ((api_version == "v1") ? "v1.1" : api_version) + "/history",
tokenData = this.getAuthToken();
if (tokenData.type != "bearer") {
throw new Error("Invalid token type. Must use a token of type bearer.");
}
return helper.get(tokenData, u, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q6007
|
getUserProfile
|
train
|
function getUserProfile(callback) {
if (_.isUndefined(callback)) {
} else {
var u = baseUrl + "/me";
var tokenData = this.getAuthToken();
if (tokenData.type != "bearer") {
throw new Error("Invalid token type. Must use a token of type bearer.");
}
return helper.get(tokenData, u, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q6008
|
train
|
function() {
return new Promise(function(resolve, reject) {
exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", {
timeout: 3000,
cwd: process.cwd()
}, function(err, stdout, stdin) {
var results = stdout.trim().split('\n');
for (var i = 0; i < results.length; i++) {
eval(fs.readFileSync(results[i]) + '');
}
resolve(Object.keys(CRUD.entities));
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6009
|
train
|
function() {
return new Promise(function(resolve, reject) {
exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", {
timeout: 3000,
cwd: process.cwd()
}, function(err, stdout, stdin) {
var results = stdout.trim().split('\n');
var entities = {};
// iterate all found js files and search for CRUD.define calls
results.map(function(filename) {
if (filename.trim() == '') return;
var code = fs.readFileSync(filename) + '';
var ast = UglifyJS.parse(code);
ast.walk(new UglifyJS.TreeWalker(function(node) {
if (node instanceof UglifyJS.AST_Call && node.start.value == 'CRUD' && node.expression.property == 'define') {
entities[node.args[0].start.value] = filename;
}
}));
});
resolve(entities);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6010
|
Group
|
train
|
function Group(props) {
var children = React.Children.toArray(props.children).filter(Boolean);
if (children.length === 1) {
return children;
}
// Insert separators
var separator = props.separator;
var separatorIsElement = React.isValidElement(separator);
var items = [children.shift()];
children.forEach(function(item, index) {
if (separatorIsElement) {
var key = 'separator-' + (item.key || index);
separator = React.cloneElement(separator, { key: key });
}
items.push(separator, item);
});
return items;
}
|
javascript
|
{
"resource": ""
}
|
q6011
|
createSite
|
train
|
function createSite() {
function app(page) { app.handle(page); }
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
app.init();
return app;
}
|
javascript
|
{
"resource": ""
}
|
q6012
|
invalidResponseError
|
train
|
function invalidResponseError(result, host) {
const message = !!result && !!result.error && !!result.error.message ? `[ethjs-provider-http] ${result.error.message}` : `[ethjs-provider-http] Invalid JSON RPC response from host provider ${host}: ${JSON.stringify(result, null, 2)}`;
return new Error(message);
}
|
javascript
|
{
"resource": ""
}
|
q6013
|
HttpProvider
|
train
|
function HttpProvider(host, timeout) {
if (!(this instanceof HttpProvider)) { throw new Error('[ethjs-provider-http] the HttpProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new HttpProvider());`).'); }
if (typeof host !== 'string') { throw new Error('[ethjs-provider-http] the HttpProvider instance requires that the host be specified (e.g. `new HttpProvider("http://localhost:8545")` or via service like infura `new HttpProvider("http://ropsten.infura.io")`)'); }
const self = this;
self.host = host;
self.timeout = timeout || 0;
}
|
javascript
|
{
"resource": ""
}
|
q6014
|
train
|
function(ip) {
this.connectionparams = {
host: ip,
port: 23,
timeout: 1000, // The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay)
sendTimeout: 1200,
negotiationMandatory: false,
ors: '\r', // Set outbound record separator
irs: '\r'
};
this.cmdCue = [];
this.connection = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q6015
|
sendKeys
|
train
|
function sendKeys(element, str) {
return str.split('').reduce(function (promise, char) {
return promise.then(function () {
return element.sendKeys(char);
});
}, element.getAttribute('value'));
// better to create a resolved promise here but ... don't know how with protractor;
}
|
javascript
|
{
"resource": ""
}
|
q6016
|
insertQuerySuccess
|
train
|
function insertQuerySuccess(resultSet) {
resultSet.Action = 'inserted';
resultSet.ID = resultSet.rs.insertId;
CRUD.stats.writesExecuted++;
return resultSet;
}
|
javascript
|
{
"resource": ""
}
|
q6017
|
insertQueryError
|
train
|
function insertQueryError(err, tx) {
CRUD.stats.writesExecuted++;
console.error("Insert query error: ", err);
return err;
}
|
javascript
|
{
"resource": ""
}
|
q6018
|
parseSchemaInfo
|
train
|
function parseSchemaInfo(resultset) {
for (var i = 0; i < resultset.rs.rows.length; i++) {
var row = resultset.rs.rows.item(i);
if (row.name.indexOf('sqlite_autoindex') > -1 || row.name == '__WebKitDatabaseInfoTable__') continue;
if (row.type == 'table') {
tables.push(row.tbl_name);
} else if (row.type == 'index') {
if (!(row.tbl_name in indexes)) {
indexes[row.tbl_name] = [];
}
indexes[row.tbl_name].push(row.name);
}
}
return;
}
|
javascript
|
{
"resource": ""
}
|
q6019
|
createTables
|
train
|
function createTables() {
return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) {
var entity = CRUD.EntityManager.entities[entityName];
if (tables.indexOf(entity.table) == -1) {
if (!entity.createStatement) {
throw "No create statement found for " + entity.getType() + ". Don't know how to create table.";
}
return db.execute(entity.createStatement).then(function() {
tables.push(entity.table);
localStorage.setItem('database.version.' + entity.table, ('migrations' in entity) ? Math.max.apply(Math, Object.keys(entity.migrations)) : 1);
CRUD.log(entity.table + " table created.");
return entity;
}, function(err) {
CRUD.log("Error creating " + entity.table, err, entity.createStatement);
throw "Error creating table: " + entity.table;
}).then(createFixtures).then(function() {
CRUD.log("Table created and fixtures inserted for ", entityName);
return;
});
}
return;
}));
}
|
javascript
|
{
"resource": ""
}
|
q6020
|
createIndexes
|
train
|
function createIndexes() {
// create listed indexes if they don't already exist.
return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) {
var entity = CRUD.EntityManager.entities[entityName];
if (('indexes' in entity)) {
return Promise.all(entity.indexes.map(function(index) {
var indexName = index.replace(/\W/g, '') + '_idx';
if (!(entity.table in indexes) || indexes[entity.table].indexOf(indexName) == -1) {
return db.execute("create index if not exists " + indexName + " on " + entity.table + " (" + index + ")").then(function(result) {
CRUD.log("index created: ", entity.table, index, indexName);
if (!(entity.table in indexes)) {
indexes[entity.table] = [];
}
indexes[entity.table].push(indexName);
return;
});
}
return;
}));
}
}));
}
|
javascript
|
{
"resource": ""
}
|
q6021
|
createFixtures
|
train
|
function createFixtures(entity) {
return new Promise(function(resolve, reject) {
if (!entity.fixtures) return resolve();
return Promise.all(entity.fixtures.map(function(fixture) {
CRUD.fromCache(entity.getType(), fixture).Persist(true);
})).then(resolve, reject);
});
}
|
javascript
|
{
"resource": ""
}
|
q6022
|
train
|
function(field, def) {
var ret;
if (field in this.__dirtyValues__) {
ret = this.__dirtyValues__[field];
} else if (field in this.__values__) {
ret = this.__values__[field];
} else if (CRUD.EntityManager.entities[this.getType()].fields.indexOf(field) > -1) {
ret = (field in CRUD.EntityManager.entities[this.getType()].defaultValues) ? CRUD.EntityManager.entities[this.getType()].defaultValues[field] : null;
} else {
CRUD.log('Could not find field \'' + field + '\' in \'' + this.getType() + '\' (for get)');
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q6023
|
Route
|
train
|
function Route(path, fns, options) {
options = options || {};
this.path = path;
this.fns = fns;
this.regexp = pathRegexp(path, this.keys = [], options);
}
|
javascript
|
{
"resource": ""
}
|
q6024
|
buildFile
|
train
|
function buildFile() {
var reader = readline.createInterface({
input: fs.createReadStream(path.resolve("./src/assets/template.html"))
});
var lines = [];
reader.on("line", line => lines.push(line));
return new Promise(resolve => {
reader.on("close", () => resolve(buildJsFileContents(lines)));
});
}
|
javascript
|
{
"resource": ""
}
|
q6025
|
train
|
function(moveBack) {
return new Promise(function(resolve, reject) {
exec(resolve, reject, APP_PLUGIN_NAME, "minimizeApp", [moveBack || false]);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6026
|
train
|
function(packageName, componentName) {
return new Promise(function(resolve, reject) {
exec(resolve, reject, APP_PLUGIN_NAME, "startApp", [packageName, componentName]);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6027
|
promisePrompt
|
train
|
function promisePrompt(questions) {
return new Promise(function(resolve, reject) {
inquirer.prompt(questions, function(results) {
resolve(results);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q6028
|
buildJsFileContent
|
train
|
function buildJsFileContent(lines) {
var ls = lines
.map(l => l
// remove space at beginning of line
.replace(/^\s*/g, "")
// remove space at end of line
.replace(/\s*$/g, "")
// convert \ to \\
.replace(/\\/g, "\\\\")
// convert " to \"
.replace(/"/g, "\\\"")
// convert " { " to "{"
.replace(/\s*\{\s*/g, "{")
// convert " : " to ":"
.replace(/\s*:\s*/g, ":"))
.join("")
// remove comments
.replace(/\/\*.+?\*\//g, "");
return [
// add css string
`var css = "${ls}";`,
"var enabled = false;",
"",
// add function which injects css into page
"function enable () {",
"\tif (enabled) return;",
"\tenabled = true;",
"",
"\tvar el = document.createElement('style');",
"\tel.innerHTML = css;",
"",
"\tvar parent = document.head || document.body;",
"\tparent.firstChild ?",
"\t\tparent.insertBefore(el, parent.firstChild) :",
"\t\tparent.appendChild(el);",
"}",
"",
"export {",
"\tenable",
"}"
].join("\n");
}
|
javascript
|
{
"resource": ""
}
|
q6029
|
train
|
function(done, promise, expectedState, expectedData, isNegative) {
function verify(promiseState) {
return function(data) {
var test = verifyState(promiseState, expectedState);
if (test.pass) {
test = verifyData(data, expectedData);
}
if (!test.pass && !isNegative) {
done.fail(new Error(test.message));
return;
}
done();
}
}
promise.then(
verify(PROMISE_STATE.RESOLVED),
verify(PROMISE_STATE.REJECTED)
);
return { pass: true };
}
|
javascript
|
{
"resource": ""
}
|
|
q6030
|
train
|
function(class_data, path) {
var implements_source = this._sources[path],
name,
references_offset;
if (Lava.schema.DEBUG) {
if (!implements_source) Lava.t('Implements: class not found - "' + path + '"');
for (name in implements_source.shared) Lava.t("Implements: unable to use a class with Shared as mixin.");
if (class_data.implements.indexOf(path) != -1) Lava.t("Implements: class " + class_data.path + " already implements " + path);
}
class_data.implements.push(path);
references_offset = class_data.references.length;
// array copy is inexpensive, cause it contains only reference types
class_data.references = class_data.references.concat(implements_source.references);
this._extend(class_data, class_data.skeleton, implements_source, implements_source.skeleton, true, references_offset);
}
|
javascript
|
{
"resource": ""
}
|
|
q6031
|
train
|
function(class_data, source_object, is_root) {
var name,
skeleton = {},
value,
type,
skeleton_value;
for (name in source_object) {
if (is_root && (this._reserved_members.indexOf(name) != -1 || (name in class_data.shared))) {
continue;
}
value = source_object[name];
type = Firestorm.getType(value);
switch (type) {
case 'null':
case 'boolean':
case 'number':
skeleton_value = {type: this.MEMBER_TYPES.PRIMITIVE, value: value};
break;
case 'string':
skeleton_value = {type: this.MEMBER_TYPES.STRING, value: value};
break;
case 'function':
skeleton_value = {type: this.MEMBER_TYPES.FUNCTION, index: class_data.references.length};
class_data.references.push(value);
break;
case 'regexp':
skeleton_value = {type: this.MEMBER_TYPES.REGEXP, index: class_data.references.length};
class_data.references.push(value);
break;
case 'object':
skeleton_value = {
type: this.MEMBER_TYPES.OBJECT,
skeleton: this._disassemble(class_data, value, false)
};
break;
case 'array':
if (value.length == 0) {
skeleton_value = {type: this.MEMBER_TYPES.EMPTY_ARRAY};
} else if (this.inline_simple_arrays && this.isInlineArray(value)) {
skeleton_value = {type: this.MEMBER_TYPES.INLINE_ARRAY, value: value};
} else {
skeleton_value = {type: this.MEMBER_TYPES.SLICE_ARRAY, index: class_data.references.length};
class_data.references.push(value);
}
break;
case 'undefined':
Lava.t("[ClassManager] Forced code style restriction: please, replace undefined member values with null. Member name: " + name);
break;
default:
Lava.t("[ClassManager] Unsupported property type in source object: " + type);
break;
}
skeleton[name] = skeleton_value;
}
return skeleton;
}
|
javascript
|
{
"resource": ""
}
|
|
q6032
|
train
|
function(skeleton, class_data, padding, serialized_properties) {
var name,
serialized_value,
uses_references = false,
object_properties;
for (name in skeleton) {
switch (skeleton[name].type) {
case this.MEMBER_TYPES.STRING:
serialized_value = Firestorm.String.quote(skeleton[name].value);
break;
case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number
serialized_value = skeleton[name].value + '';
break;
case this.MEMBER_TYPES.REGEXP:
case this.MEMBER_TYPES.FUNCTION:
serialized_value = 'r[' + skeleton[name].index + ']';
uses_references = true;
break;
case this.MEMBER_TYPES.EMPTY_ARRAY:
serialized_value = "[]";
break;
case this.MEMBER_TYPES.INLINE_ARRAY:
serialized_value = this._serializeInlineArray(skeleton[name].value);
break;
case this.MEMBER_TYPES.SLICE_ARRAY:
serialized_value = 'r[' + skeleton[name].index + '].slice()';
uses_references = true;
break;
case this.MEMBER_TYPES.OBJECT:
object_properties = [];
if (this._serializeSkeleton(skeleton[name].skeleton, class_data, padding + "\t", object_properties)) {
uses_references = true;
}
serialized_value = object_properties.length
? "{\n\t" + padding + object_properties.join(",\n\t" + padding) + "\n" + padding + "}" : "{}";
break;
default:
Lava.t("[_serializeSkeleton] unknown property descriptor type: " + skeleton[name].type);
}
if (Lava.VALID_PROPERTY_NAME_REGEX.test(name) && Lava.JS_KEYWORDS.indexOf(name) == -1) {
serialized_properties.push(name + ': ' + serialized_value);
} else {
serialized_properties.push(Firestorm.String.quote(name) + ': ' + serialized_value);
}
}
return uses_references;
}
|
javascript
|
{
"resource": ""
}
|
|
q6033
|
train
|
function(path_segments) {
var namespace,
segment_name,
count = path_segments.length,
i = 1;
if (!count) Lava.t("ClassManager: class names must include a namespace, even for global classes.");
if (!(path_segments[0] in this._root)) Lava.t("[ClassManager] namespace is not registered: " + path_segments[0]);
namespace = this._root[path_segments[0]];
for (; i < count; i++) {
segment_name = path_segments[i];
if (!(segment_name in namespace)) {
namespace[segment_name] = {};
}
namespace = namespace[segment_name];
}
return namespace;
}
|
javascript
|
{
"resource": ""
}
|
|
q6034
|
train
|
function(class_path, default_namespace) {
if (!(class_path in this.constructors) && default_namespace) {
class_path = default_namespace + '.' + class_path;
}
return this.constructors[class_path];
}
|
javascript
|
{
"resource": ""
}
|
|
q6035
|
train
|
function(data) {
var tempResult = [],
i = 0,
count = data.length,
type,
value;
for (; i < count; i++) {
type = Firestorm.getType(data[i]);
switch (type) {
case 'string':
value = Firestorm.String.quote(data[i]);
break;
case 'null':
case 'undefined':
case 'boolean':
case 'number':
value = data[i] + '';
break;
default:
Lava.t();
}
tempResult.push(value);
}
return '[' + tempResult.join(", ") + ']';
}
|
javascript
|
{
"resource": ""
}
|
|
q6036
|
train
|
function(class_data) {
var skeleton = class_data.skeleton,
name,
serialized_value,
serialized_actions = [],
is_polymorphic = !class_data.is_monomorphic;
for (name in skeleton) {
switch (skeleton[name].type) {
case this.MEMBER_TYPES.REGEXP:
case this.MEMBER_TYPES.FUNCTION:
serialized_value = 'r[' + skeleton[name].index + ']';
break;
//case 'undefined':
case this.MEMBER_TYPES.STRING:
if (is_polymorphic) {
serialized_value = '"' + skeleton[name].value.replace(/\"/g, "\\\"") + '"';
}
break;
case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number
if (is_polymorphic) {
serialized_value = skeleton[name].value + '';
}
break;
}
if (serialized_value) {
if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) {
serialized_actions.push('p.' + name + ' = ' + serialized_value + ';');
} else {
serialized_actions.push('p[' + Firestorm.String.quote(name) + '] = ' + serialized_value + ';');
}
serialized_value = null;
}
}
for (name in class_data.shared) {
serialized_actions.push('p.' + name + ' = s.' + name + ';');
}
return serialized_actions.length
? new Function('cd,p', "\tvar r=cd.references,\n\t\ts=cd.shared;\n\n\t" + serialized_actions.join('\n\t') + "\n")
: null;
}
|
javascript
|
{
"resource": ""
}
|
|
q6037
|
train
|
function(class_datas) {
for (var i = 0, count = class_datas.length; i <count; i++) {
this.loadClass(class_datas[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6038
|
train
|
function(class_data) {
var class_path = class_data.path,
namespace_path,
class_name,
namespace;
if ((class_path in this._sources) || (class_path in this.constructors)) Lava.t("Class is already defined: " + class_path);
this._sources[class_path] = class_data;
if (class_data.constructor) {
namespace_path = class_path.split('.');
class_name = namespace_path.pop();
namespace = this._getNamespace(namespace_path);
if ((class_name in namespace) && namespace[class_name] != null) Lava.t("Class name conflict: '" + class_path + "' property is already defined in namespace path");
this.constructors[class_path] = class_data.constructor;
namespace[class_name] = class_data.constructor;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6039
|
train
|
function(base_path, suffix) {
if (Lava.schema.DEBUG && !(base_path in this._sources)) Lava.t("[getPackageConstructor] Class not found: " + base_path);
var path,
current_class = this._sources[base_path],
result = null;
do {
path = current_class.path + suffix;
if (path in this.constructors) {
result = this.constructors[path];
break;
}
current_class = current_class.parent_class_data;
} while (current_class);
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q6040
|
$$core$$ResolveLocale
|
train
|
function /* 9.2.5 */$$core$$ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) {
if (availableLocales.length === 0) {
throw new ReferenceError('No locale data has been provided for this object yet.');
}
// The following steps are taken:
var
// 1. Let matcher be the value of options.[[localeMatcher]].
matcher = options['[[localeMatcher]]'];
// 2. If matcher is "lookup", then
if (matcher === 'lookup')
var
// a. Let r be the result of calling the LookupMatcher abstract operation
// (defined in 9.2.3) with arguments availableLocales and
// requestedLocales.
r = $$core$$LookupMatcher(availableLocales, requestedLocales);
// 3. Else
else
var
// a. Let r be the result of calling the BestFitMatcher abstract
// operation (defined in 9.2.4) with arguments availableLocales and
// requestedLocales.
r = $$core$$BestFitMatcher(availableLocales, requestedLocales);
var
// 4. Let foundLocale be the value of r.[[locale]].
foundLocale = r['[[locale]]'];
// 5. If r has an [[extension]] field, then
if ($$core$$hop.call(r, '[[extension]]'))
var
// a. Let extension be the value of r.[[extension]].
extension = r['[[extension]]'],
// b. Let extensionIndex be the value of r.[[extensionIndex]].
extensionIndex = r['[[extensionIndex]]'],
// c. Let split be the standard built-in function object defined in ES5,
// 15.5.4.14.
split = String.prototype.split,
// d. Let extensionSubtags be the result of calling the [[Call]] internal
// method of split with extension as the this value and an argument
// list containing the single item "-".
extensionSubtags = split.call(extension, '-'),
// e. Let extensionSubtagsLength be the result of calling the [[Get]]
// internal method of extensionSubtags with argument "length".
extensionSubtagsLength = extensionSubtags.length;
var
// 6. Let result be a new Record.
result = new $$core$$Record();
// 7. Set result.[[dataLocale]] to foundLocale.
result['[[dataLocale]]'] = foundLocale;
var
// 8. Let supportedExtension be "-u".
supportedExtension = '-u',
// 9. Let i be 0.
i = 0,
// 10. Let len be the result of calling the [[Get]] internal method of
// relevantExtensionKeys with argument "length".
len = relevantExtensionKeys.length;
// 11 Repeat while i < len:
while (i < len) {
var
// a. Let key be the result of calling the [[Get]] internal method of
// relevantExtensionKeys with argument ToString(i).
key = relevantExtensionKeys[i],
// b. Let foundLocaleData be the result of calling the [[Get]] internal
// method of localeData with the argument foundLocale.
foundLocaleData = localeData[foundLocale],
// c. Let keyLocaleData be the result of calling the [[Get]] internal
// method of foundLocaleData with the argument key.
keyLocaleData = foundLocaleData[key],
// d. Let value be the result of calling the [[Get]] internal method of
// keyLocaleData with argument "0".
value = keyLocaleData['0'],
// e. Let supportedExtensionAddition be "".
supportedExtensionAddition = '',
// f. Let indexOf be the standard built-in function object defined in
// ES5, 15.4.4.14.
indexOf = $$core$$arrIndexOf;
// g. If extensionSubtags is not undefined, then
if (extensionSubtags !== undefined) {
var
// i. Let keyPos be the result of calling the [[Call]] internal
// method of indexOf with extensionSubtags as the this value and
// an argument list containing the single item key.
keyPos = indexOf.call(extensionSubtags, key);
// ii. If keyPos ≠ -1, then
if (keyPos !== -1) {
// 1. If keyPos + 1 < extensionSubtagsLength and the length of the
// result of calling the [[Get]] internal method of
// extensionSubtags with argument ToString(keyPos +1) is greater
// than 2, then
if (keyPos + 1 < extensionSubtagsLength
&& extensionSubtags[keyPos + 1].length > 2) {
var
// a. Let requestedValue be the result of calling the [[Get]]
// internal method of extensionSubtags with argument
// ToString(keyPos + 1).
requestedValue = extensionSubtags[keyPos + 1],
// b. Let valuePos be the result of calling the [[Call]]
// internal method of indexOf with keyLocaleData as the
// this value and an argument list containing the single
// item requestedValue.
valuePos = indexOf.call(keyLocaleData, requestedValue);
// c. If valuePos ≠ -1, then
if (valuePos !== -1)
var
// i. Let value be requestedValue.
value = requestedValue,
// ii. Let supportedExtensionAddition be the
// concatenation of "-", key, "-", and value.
supportedExtensionAddition = '-' + key + '-' + value;
}
// 2. Else
else {
var
// a. Let valuePos be the result of calling the [[Call]]
// internal method of indexOf with keyLocaleData as the this
// value and an argument list containing the single item
// "true".
valuePos = indexOf(keyLocaleData, 'true');
// b. If valuePos ≠ -1, then
if (valuePos !== -1)
var
// i. Let value be "true".
value = 'true';
}
}
}
// h. If options has a field [[<key>]], then
if ($$core$$hop.call(options, '[[' + key + ']]')) {
var
// i. Let optionsValue be the value of options.[[<key>]].
optionsValue = options['[[' + key + ']]'];
// ii. If the result of calling the [[Call]] internal method of indexOf
// with keyLocaleData as the this value and an argument list
// containing the single item optionsValue is not -1, then
if (indexOf.call(keyLocaleData, optionsValue) !== -1) {
// 1. If optionsValue is not equal to value, then
if (optionsValue !== value) {
// a. Let value be optionsValue.
value = optionsValue;
// b. Let supportedExtensionAddition be "".
supportedExtensionAddition = '';
}
}
}
// i. Set result.[[<key>]] to value.
result['[[' + key + ']]'] = value;
// j. Append supportedExtensionAddition to supportedExtension.
supportedExtension += supportedExtensionAddition;
// k. Increase i by 1.
i++;
}
// 12. If the length of supportedExtension is greater than 2, then
if (supportedExtension.length > 2) {
var
// a. Let preExtension be the substring of foundLocale from position 0,
// inclusive, to position extensionIndex, exclusive.
preExtension = foundLocale.substring(0, extensionIndex),
// b. Let postExtension be the substring of foundLocale from position
// extensionIndex to the end of the string.
postExtension = foundLocale.substring(extensionIndex),
// c. Let foundLocale be the concatenation of preExtension,
// supportedExtension, and postExtension.
foundLocale = preExtension + supportedExtension + postExtension;
}
// 13. Set result.[[locale]] to foundLocale.
result['[[locale]]'] = foundLocale;
// 14. Return result.
return result;
}
|
javascript
|
{
"resource": ""
}
|
q6041
|
$$core$$GetOption
|
train
|
function /*9.2.9 */$$core$$GetOption (options, property, type, values, fallback) {
var
// 1. Let value be the result of calling the [[Get]] internal method of
// options with argument property.
value = options[property];
// 2. If value is not undefined, then
if (value !== undefined) {
// a. Assert: type is "boolean" or "string".
// b. If type is "boolean", then let value be ToBoolean(value).
// c. If type is "string", then let value be ToString(value).
value = type === 'boolean' ? Boolean(value)
: (type === 'string' ? String(value) : value);
// d. If values is not undefined, then
if (values !== undefined) {
// i. If values does not contain an element equal to value, then throw a
// RangeError exception.
if ($$core$$arrIndexOf.call(values, value) === -1)
throw new RangeError("'" + value + "' is not an allowed value for `" + property +'`');
}
// e. Return value.
return value;
}
// Else return fallback.
return fallback;
}
|
javascript
|
{
"resource": ""
}
|
q6042
|
$$core$$GetNumberOption
|
train
|
function /* 9.2.10 */$$core$$GetNumberOption (options, property, minimum, maximum, fallback) {
var
// 1. Let value be the result of calling the [[Get]] internal method of
// options with argument property.
value = options[property];
// 2. If value is not undefined, then
if (value !== undefined) {
// a. Let value be ToNumber(value).
value = Number(value);
// b. If value is NaN or less than minimum or greater than maximum, throw a
// RangeError exception.
if (isNaN(value) || value < minimum || value > maximum)
throw new RangeError('Value is not a number or outside accepted range');
// c. Return floor(value).
return Math.floor(value);
}
// 3. Else return fallback.
return fallback;
}
|
javascript
|
{
"resource": ""
}
|
q6043
|
$$core$$calculateScore
|
train
|
function $$core$$calculateScore (options, formats, bestFit) {
var
// Additional penalty type when bestFit === true
diffDataTypePenalty = 8,
// 1. Let removalPenalty be 120.
removalPenalty = 120,
// 2. Let additionPenalty be 20.
additionPenalty = 20,
// 3. Let longLessPenalty be 8.
longLessPenalty = 8,
// 4. Let longMorePenalty be 6.
longMorePenalty = 6,
// 5. Let shortLessPenalty be 6.
shortLessPenalty = 6,
// 6. Let shortMorePenalty be 3.
shortMorePenalty = 3,
// 7. Let bestScore be -Infinity.
bestScore = -Infinity,
// 8. Let bestFormat be undefined.
bestFormat,
// 9. Let i be 0.
i = 0,
// 10. Let len be the result of calling the [[Get]] internal method of formats with argument "length".
len = formats.length;
// 11. Repeat while i < len:
while (i < len) {
var
// a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i).
format = formats[i],
// b. Let score be 0.
score = 0;
// c. For each property shown in Table 3:
for (var property in $$core$$dateTimeComponents) {
if (!$$core$$hop.call($$core$$dateTimeComponents, property))
continue;
var
// i. Let optionsProp be options.[[<property>]].
optionsProp = options['[['+ property +']]'],
// ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format
// with argument property.
// iii. If formatPropDesc is not undefined, then
// 1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property.
formatProp = $$core$$hop.call(format, property) ? format[property] : undefined;
// iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by
// additionPenalty.
if (optionsProp === undefined && formatProp !== undefined)
score -= additionPenalty;
// v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by
// removalPenalty.
else if (optionsProp !== undefined && formatProp === undefined)
score -= removalPenalty;
// vi. Else
else {
var
// 1. Let values be the array ["2-digit", "numeric", "narrow", "short",
// "long"].
values = [ '2-digit', 'numeric', 'narrow', 'short', 'long' ],
// 2. Let optionsPropIndex be the index of optionsProp within values.
optionsPropIndex = $$core$$arrIndexOf.call(values, optionsProp),
// 3. Let formatPropIndex be the index of formatProp within values.
formatPropIndex = $$core$$arrIndexOf.call(values, formatProp),
// 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2).
delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2);
// When the bestFit argument is true, subtract additional penalty where data types are not the same
if (bestFit && (
((optionsProp === 'numeric' || optionsProp === '2-digit') && (formatProp !== 'numeric' && formatProp !== '2-digit') || (optionsProp !== 'numeric' && optionsProp !== '2-digit') && (formatProp === '2-digit' || formatProp === 'numeric'))
))
score -= diffDataTypePenalty;
// 5. If delta = 2, decrease score by longMorePenalty.
if (delta === 2)
score -= longMorePenalty;
// 6. Else if delta = 1, decrease score by shortMorePenalty.
else if (delta === 1)
score -= shortMorePenalty;
// 7. Else if delta = -1, decrease score by shortLessPenalty.
else if (delta === -1)
score -= shortLessPenalty;
// 8. Else if delta = -2, decrease score by longLessPenalty.
else if (delta === -2)
score -= longLessPenalty;
}
}
// d. If score > bestScore, then
if (score > bestScore) {
// i. Let bestScore be score.
bestScore = score;
// ii. Let bestFormat be format.
bestFormat = format;
}
// e. Increase i by 1.
i++;
}
// 12. Return bestFormat.
return bestFormat;
}
|
javascript
|
{
"resource": ""
}
|
q6044
|
$$core$$resolveDateString
|
train
|
function $$core$$resolveDateString(data, ca, component, width, key) {
// From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance:
// 'In clearly specified instances, resources may inherit from within the same locale.
// For example, ... the Buddhist calendar inherits from the Gregorian calendar.'
var obj = data[ca] && data[ca][component]
? data[ca][component]
: data.gregory[component],
// "sideways" inheritance resolves strings when a key doesn't exist
alts = {
narrow: ['short', 'long'],
short: ['long', 'narrow'],
long: ['short', 'narrow']
},
//
resolved = $$core$$hop.call(obj, width)
? obj[width]
: $$core$$hop.call(obj, alts[width][0])
? obj[alts[width][0]]
: obj[alts[width][1]];
// `key` wouldn't be specified for components 'dayPeriods'
return key != null ? resolved[key] : resolved;
}
|
javascript
|
{
"resource": ""
}
|
q6045
|
$$core$$createRegExpRestore
|
train
|
function $$core$$createRegExpRestore () {
var esc = /[.?*+^$[\]\\(){}|-]/g,
lm = RegExp.lastMatch || '',
ml = RegExp.multiline ? 'm' : '',
ret = { input: RegExp.input },
reg = new $$core$$List(),
has = false,
cap = {};
// Create a snapshot of all the 'captured' properties
for (var i = 1; i <= 9; i++)
has = (cap['$'+i] = RegExp['$'+i]) || has;
// Now we've snapshotted some properties, escape the lastMatch string
lm = lm.replace(esc, '\\$&');
// If any of the captured strings were non-empty, iterate over them all
if (has) {
for (var i = 1; i <= 9; i++) {
var m = cap['$'+i];
// If it's empty, add an empty capturing group
if (!m)
lm = '()' + lm;
// Else find the string in lm and escape & wrap it to capture it
else {
m = m.replace(esc, '\\$&');
lm = lm.replace(m, '(' + m + ')');
}
// Push it to the reg and chop lm to make sure further groups come after
$$core$$arrPush.call(reg, lm.slice(0, lm.indexOf('(') + 1));
lm = lm.slice(lm.indexOf('(') + 1);
}
}
// Create the regular expression that will reconstruct the RegExp properties
ret.exp = new RegExp($$core$$arrJoin.call(reg, '') + lm, ml);
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q6046
|
$$core$$toLatinUpperCase
|
train
|
function $$core$$toLatinUpperCase (str) {
var i = str.length;
while (i--) {
var ch = str.charAt(i);
if (ch >= "a" && ch <= "z")
str = str.slice(0, i) + ch.toUpperCase() + str.slice(i+1);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q6047
|
PersistInNode
|
train
|
function PersistInNode(n) {
RED.nodes.createNode(this,n);
var node = this;
node.name = n.name;
node.storageNode = RED.nodes.getNode(n.storageNode);
node.on("input", function(msg) {
node.storageNode.store(node.name, msg);
});
}
|
javascript
|
{
"resource": ""
}
|
q6048
|
PersistOutNode
|
train
|
function PersistOutNode(n) {
RED.nodes.createNode(this,n);
var node = this;
node.name = n.name;
node.storageNode = RED.nodes.getNode(n.storageNode);
node.restore = function() {
var msg = node.storageNode.getMessage(node.name);
node.send(msg);
};
RED.events.on("nodes-started", node.restore);
node.on("input", function(msg) {
node.restore();
});
node.on('close', function(removed, done) {
RED.events.removeListener("nodes-started", node.restore);
done();
});
}
|
javascript
|
{
"resource": ""
}
|
q6049
|
isMethodCall
|
train
|
function isMethodCall(node) {
var nodeParentType = node.parent.type,
nodeParentParentParentType = node.parent.parent.parent.type;
if (nodeParentType === "CallExpression" && nodeParentParentParentType === "BlockStatement" && !variable) {
return true;
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q6050
|
broadcast
|
train
|
function broadcast (subscriptions, type) {
return value => {
subscriptions.forEach(s => {
if (typeof s.emit[type] === 'function') {
s.emit[type](value)
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
q6051
|
train
|
function (){
var outputPropertyName,
callback,
inputPropertyNames,
inputs,
output;
if(arguments.length === 0){
return configurationProperty();
} else if(arguments.length === 1){
if(typeof arguments[0] === "object"){
// The invocation is of the form model(configuration)
return setConfiguration(arguments[0]);
} else {
// The invocation is of the form model(propertyName)
return addProperty(arguments[0]);
}
} else if(arguments.length === 2){
if(typeof arguments[0] === "function"){
// The invocation is of the form model(callback, inputPropertyNames)
inputPropertyNames = arguments[1];
callback = arguments[0];
outputPropertyName = undefined;
} else {
// The invocation is of the form model(propertyName, defaultValue)
return addProperty(arguments[0], arguments[1]);
}
} else if(arguments.length === 3){
outputPropertyName = arguments[0];
callback = arguments[1];
inputPropertyNames = arguments[2];
}
// inputPropertyNames may be a string of comma-separated property names,
// or an array of property names.
if(typeof inputPropertyNames === "string"){
inputPropertyNames = inputPropertyNames.split(",").map(invoke("trim"));
}
inputs = inputPropertyNames.map(function (propertyName){
var property = getProperty(propertyName);
if(typeof property === "undefined"){
throw new Error([
"The property \"",
propertyName,
"\" was referenced as a dependency for a reactive function before it was defined. ",
"Please define each property first before referencing them in reactive functions."
].join(""));
}
return property;
});
// Create a new reactive property for the output and assign it to the model.
if(outputPropertyName){
addProperty(outputPropertyName);
output = model[outputPropertyName];
}
// If the number of arguments expected by the callback is one greater than the
// number of inputs, then the last argument is the "done" callback, and this
// reactive function will be set up to be asynchronous. The "done" callback should
// be called with the new value of the output property asynchronously.
var isAsynchronous = (callback.length === inputs.length + 1);
if(isAsynchronous){
reactiveFunctions.push(ReactiveFunction({
inputs: inputs,
callback: function (){
// Convert the arguments passed into this function into an array.
var args = Array.prototype.slice.call(arguments);
// Push the "done" callback onto the args array.
// We are actally passing the output reactive property here, invoking it
// as the "done" callback will set the value of the output property.
args.push(output);
// Wrap in setTimeout to guarantee that the output property is set
// asynchronously, outside of the current digest. This is necessary
// to ensure that if developers inadvertently invoke the "done" callback
// synchronously, their code will still have the expected behavior.
setTimeout(function (){
// Invoke the original callback with the args array as arguments.
callback.apply(null, args);
});
}
}));
} else {
reactiveFunctions.push(ReactiveFunction({
inputs: inputs,
output: output, // This may be undefined.
callback: callback
}));
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q6052
|
addProperty
|
train
|
function addProperty(propertyName, defaultValue){
if(model[propertyName]){
throw new Error("The property \"" + propertyName + "\" is already defined.");
}
var property = ReactiveProperty(defaultValue);
property.propertyName = propertyName;
model[propertyName] = property;
lastPropertyAdded = propertyName;
return model;
}
|
javascript
|
{
"resource": ""
}
|
q6053
|
expose
|
train
|
function expose(){
// TODO test this
// if(!isDefined(defaultValue)){
// throw new Error("model.addPublicProperty() is being " +
// "invoked with an undefined default value. Default values for exposed properties " +
// "must be defined, to guarantee predictable behavior. For exposed properties that " +
// "are optional and should have the semantics of an undefined value, " +
// "use null as the default value.");
//}
// TODO test this
if(!lastPropertyAdded){
throw Error("Expose() was called without first adding a property.");
}
var propertyName = lastPropertyAdded;
if(!exposedProperties){
exposedProperties = [];
}
exposedProperties.push(propertyName);
// Destroy the previous reactive function that was listening for changes
// in all exposed properties except the newly added one.
// TODO think about how this might be done only once, at the same time isFinalized is set.
if(configurationReactiveFunction){
configurationReactiveFunction.destroy();
}
// Set up the new reactive function that will listen for changes
// in all exposed properties including the newly added one.
var inputPropertyNames = exposedProperties;
//console.log(inputPropertyNames);
configurationReactiveFunction = ReactiveFunction({
inputs: inputPropertyNames.map(getProperty),
output: configurationProperty,
callback: function (){
var configuration = {};
inputPropertyNames.forEach(function (propertyName){
var property = getProperty(propertyName);
// Omit default values from the returned configuration object.
if(property() !== property.default()){
configuration[propertyName] = property();
}
});
return configuration;
}
});
// Support method chaining.
return model;
}
|
javascript
|
{
"resource": ""
}
|
q6054
|
destroy
|
train
|
function destroy(){
// Destroy reactive functions.
reactiveFunctions.forEach(invoke("destroy"));
if(configurationReactiveFunction){
configurationReactiveFunction.destroy();
}
// Destroy properties (removes listeners).
Object.keys(model).forEach(function (propertyName){
var property = model[propertyName];
if(property.destroy){
property.destroy();
}
});
// Release references.
reactiveFunctions = undefined;
configurationReactiveFunction = undefined;
}
|
javascript
|
{
"resource": ""
}
|
q6055
|
tiler
|
train
|
function tiler(root, options) {
this.root = root;
options = options || {};
options.packSize = options.packSize || 128;
if (!options.storageFormat) {
options.storageFormat = guessStorageFormat(root);
}
this.options = options;
}
|
javascript
|
{
"resource": ""
}
|
q6056
|
train
|
function (id, type) {
if (this.state.sourcePageID !== id) {
var selectedPage;
this.state.pages.forEach(function (page) {
if (parseInt(page.id, 10) === parseInt(id, 10)) {
selectedPage = page;
}
});
if (!selectedPage) {
console.warn('Page not found.');
return;
}
var currentZoom = this.state.matrix[0];
var {x, y} = this.cartesian.getFocusTransform(selectedPage.coords, this.state.matrix[0]);
var newState = {
matrix: [currentZoom, 0, 0, currentZoom, x, y]
};
if (type === 'selected') {
newState.selectedEl = id;
} else if (type === 'source') {
newState.sourcePageID = id;
}
this.setState(newState);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6057
|
appendDirEnd
|
train
|
function appendDirEnd(str, struct) {
if (!struct.block) {
return str;
}
const [rightSpace] = rightWSRgxp.exec(str);
str = str.replace(rightPartRgxp, '');
const
s = alb + lb,
e = rb;
let tmp;
if (needSpace) {
tmp = `${struct.trim.right ? '' : eol}${endDirInit ? '' : `${s}__&+__${e}`}${struct.trim.right ? eol : ''}`;
} else {
tmp = eol + struct.space.slice(1);
}
endDirInit = true;
str += `${tmp}${struct.adv + lb}__end__${e}${s}__cutLine__${e}`;
if (rightSpace && needSpace) {
str += `${s}__&-__${rb}`;
}
return str + rightSpace;
}
|
javascript
|
{
"resource": ""
}
|
q6058
|
train
|
function() {
var fonts = ["Roboto", "Bitter", "Pacifico"];
var options = fonts.map(name => {
// setting style on an <option> does not work in WebView...
return <option key={name} value={name}>{name}</option>;
});
return <select className="select" valueLink={this.linkState('fontFamily')}>{ options }</select>;
}
|
javascript
|
{
"resource": ""
}
|
|
q6059
|
callback
|
train
|
function callback(fn, context, event) {
//window.setTimeout(function(){
event.target = context;
(typeof context[fn] === "function") && context[fn].apply(context, [event]);
//}, 1);
}
|
javascript
|
{
"resource": ""
}
|
q6060
|
polyfill
|
train
|
function polyfill() {
if (navigator.userAgent.match(/MSIE/) ||
navigator.userAgent.match(/Trident/) ||
navigator.userAgent.match(/Edge/)) {
// Internet Explorer's native IndexedDB does not support compound keys
compoundKeyPolyfill();
}
}
|
javascript
|
{
"resource": ""
}
|
q6061
|
readBlobAsDataURL
|
train
|
function readBlobAsDataURL(blob, path) {
var reader = new FileReader();
reader.onloadend = function(loadedEvent) {
var dataURL = loadedEvent.target.result;
var blobtype = 'Blob';
if (blob instanceof File) {
//blobtype = 'File';
}
updateEncodedBlob(dataURL, path, blobtype);
};
reader.readAsDataURL(blob);
}
|
javascript
|
{
"resource": ""
}
|
q6062
|
updateEncodedBlob
|
train
|
function updateEncodedBlob(dataURL, path, blobtype) {
var encoded = queuedObjects.indexOf(path);
path = path.replace('$','derezObj');
eval(path+'.$enc="'+dataURL+'"');
eval(path+'.$type="'+blobtype+'"');
queuedObjects.splice(encoded, 1);
checkForCompletion();
}
|
javascript
|
{
"resource": ""
}
|
q6063
|
dataURLToBlob
|
train
|
function dataURLToBlob(dataURL) {
var BASE64_MARKER = ';base64,',
contentType,
parts,
raw;
if (dataURL.indexOf(BASE64_MARKER) === -1) {
parts = dataURL.split(',');
contentType = parts[0].split(':')[1];
raw = parts[1];
return new Blob([raw], {type: contentType});
}
parts = dataURL.split(BASE64_MARKER);
contentType = parts[0].split(':')[1];
raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array.buffer], {type: contentType});
}
|
javascript
|
{
"resource": ""
}
|
q6064
|
train
|
function(key) {
var key32 = Math.abs(key).toString(32);
// Get the index of the decimal.
var decimalIndex = key32.indexOf(".");
// Remove the decimal.
key32 = (decimalIndex !== -1) ? key32.replace(".", "") : key32;
// Get the index of the first significant digit.
var significantDigitIndex = key32.search(/[^0]/);
// Truncate leading zeros.
key32 = key32.slice(significantDigitIndex);
var sign, exponent = zeros(2), mantissa = zeros(11);
// Finite cases:
if (isFinite(key)) {
// Negative cases:
if (key < 0) {
// Negative exponent case:
if (key > -1) {
sign = signValues.indexOf("smallNegative");
exponent = padBase32Exponent(significantDigitIndex);
mantissa = flipBase32(padBase32Mantissa(key32));
}
// Non-negative exponent case:
else {
sign = signValues.indexOf("bigNegative");
exponent = flipBase32(padBase32Exponent(
(decimalIndex !== -1) ? decimalIndex : key32.length
));
mantissa = flipBase32(padBase32Mantissa(key32));
}
}
// Non-negative cases:
else {
// Negative exponent case:
if (key < 1) {
sign = signValues.indexOf("smallPositive");
exponent = flipBase32(padBase32Exponent(significantDigitIndex));
mantissa = padBase32Mantissa(key32);
}
// Non-negative exponent case:
else {
sign = signValues.indexOf("bigPositive");
exponent = padBase32Exponent(
(decimalIndex !== -1) ? decimalIndex : key32.length
);
mantissa = padBase32Mantissa(key32);
}
}
}
// Infinite cases:
else {
sign = signValues.indexOf(
key > 0 ? "positiveInfinity" : "negativeInfinity"
);
}
return collations.indexOf("number") + "-" + sign + exponent + mantissa;
}
|
javascript
|
{
"resource": ""
}
|
|
q6065
|
train
|
function(key) {
var sign = +key.substr(2, 1);
var exponent = key.substr(3, 2);
var mantissa = key.substr(5, 11);
switch (signValues[sign]) {
case "negativeInfinity":
return -Infinity;
case "positiveInfinity":
return Infinity;
case "bigPositive":
return pow32(mantissa, exponent);
case "smallPositive":
exponent = negate(flipBase32(exponent));
return pow32(mantissa, exponent);
case "smallNegative":
exponent = negate(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
case "bigNegative":
exponent = flipBase32(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
default:
throw new Error("Invalid number.");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6066
|
flipBase32
|
train
|
function flipBase32(encoded) {
var flipped = "";
for (var i = 0; i < encoded.length; i++) {
flipped += (31 - parseInt(encoded[i], 32)).toString(32);
}
return flipped;
}
|
javascript
|
{
"resource": ""
}
|
q6067
|
validate
|
train
|
function validate(key) {
var type = getType(key);
if (type === "array") {
for (var i = 0; i < key.length; i++) {
validate(key[i]);
}
}
else if (!types[type] || (type !== "string" && isNaN(key))) {
throw idbModules.util.createDOMException("DataError", "Not a valid key");
}
}
|
javascript
|
{
"resource": ""
}
|
q6068
|
getValue
|
train
|
function getValue(source, keyPath) {
try {
if (keyPath instanceof Array) {
var arrayValue = [];
for (var i = 0; i < keyPath.length; i++) {
arrayValue.push(eval("source." + keyPath[i]));
}
return arrayValue;
} else {
return eval("source." + keyPath);
}
}
catch (e) {
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q6069
|
setValue
|
train
|
function setValue(source, keyPath, value) {
var props = keyPath.split('.');
for (var i = 0; i < props.length - 1; i++) {
var prop = props[i];
source = source[prop] = source[prop] || {};
}
source[props[props.length - 1]] = value;
}
|
javascript
|
{
"resource": ""
}
|
q6070
|
isMultiEntryMatch
|
train
|
function isMultiEntryMatch(encodedEntry, encodedKey) {
var keyType = collations[encodedKey.substring(0, 1)];
if (keyType === "array") {
return encodedKey.indexOf(encodedEntry) > 1;
}
else {
return encodedKey === encodedEntry;
}
}
|
javascript
|
{
"resource": ""
}
|
q6071
|
createNativeEvent
|
train
|
function createNativeEvent(type, debug) {
var event = new Event(type);
event.debug = debug;
// Make the "target" writable
Object.defineProperty(event, 'target', {
writable: true
});
return event;
}
|
javascript
|
{
"resource": ""
}
|
q6072
|
ShimEvent
|
train
|
function ShimEvent(type, debug) {
this.type = type;
this.debug = debug;
this.bubbles = false;
this.cancelable = false;
this.eventPhase = 0;
this.timeStamp = new Date().valueOf();
}
|
javascript
|
{
"resource": ""
}
|
q6073
|
createNativeDOMException
|
train
|
function createNativeDOMException(name, message) {
var e = new DOMException.prototype.constructor(0, message);
e.name = name || 'DOMException';
e.message = message;
return e;
}
|
javascript
|
{
"resource": ""
}
|
q6074
|
createNativeDOMError
|
train
|
function createNativeDOMError(name, message) {
name = name || 'DOMError';
var e = new DOMError(name, message);
e.name === name || (e.name = name);
e.message === message || (e.message = message);
return e;
}
|
javascript
|
{
"resource": ""
}
|
q6075
|
createError
|
train
|
function createError(name, message) {
var e = new Error(message);
e.name = name || 'DOMException';
e.message = message;
return e;
}
|
javascript
|
{
"resource": ""
}
|
q6076
|
createSysDB
|
train
|
function createSysDB(success, failure) {
function sysDbCreateError(tx, err) {
err = idbModules.util.findError(arguments);
idbModules.DEBUG && console.log("Error in sysdb transaction - when creating dbVersions", err);
failure(err);
}
if (sysdb) {
success();
}
else {
sysdb = window.openDatabase("__sysdb__", 1, "System Database", DEFAULT_DB_SIZE);
sysdb.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);", [], success, sysDbCreateError);
}, sysDbCreateError);
}
}
|
javascript
|
{
"resource": ""
}
|
q6077
|
train
|
function(args) {
if (!args.src) {
ret = new Error('metalsmith-convert: "src" arg is required');
return;
}
if (!args.target) { // use source-format for target in convertFile
args.target = '__source__';
}
var ext = args.extension || '.' + args.target;
if (!args.nameFormat) {
if (args.resize) {
args.nameFormat = '%b_%x_%y%e';
} else {
args.nameFormat = '%b%e';
}
}
if (!!args.remove // don't remove source-files from build if
&& args.nameFormat === '%b%e' // the converted target has the
&& args.target === '__source__') { // same name
args.remove = false;
}
Object.keys(files).forEach(function (file) {
convertFile(file, ext, args, files, results);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6078
|
timedLog
|
train
|
function timedLog(msg) {
console.log(Date.now() + ":" + window.performance.now() + ": " + msg);
}
|
javascript
|
{
"resource": ""
}
|
q6079
|
train
|
function(evt) {
evt.preventDefault();
evt.stopPropagation();
// Calculate actual height of element so we can calculate bounds properly
positionable.rect = positionable.refs.styleWrapper.getBoundingClientRect();
if (debug) { timedLog("startmark"); }
if(!evt.touches || evt.touches.length === 1) {
if (debug) { timedLog("startmark - continued"); }
mark = copy(positionable.state);
transform.x1 = evt.clientX || evt.touches[0].pageX;
transform.y1 = evt.clientY || evt.touches[0].pageY;
positionable.setState({ touchactive: true });
} else { handlers.secondFinger(evt); }
var timeStart = new Date();
//For detecting taps
tapStart = {
x1: evt.touches[0].pageX,
y1: evt.touches[0].pageY,
timeStart: timeStart
};
}
|
javascript
|
{
"resource": ""
}
|
|
q6080
|
train
|
function(evt) {
if (debug) { timedLog("endmark"); }
if(evt.touches && evt.touches.length > 0) {
if (handlers.endSecondFinger(evt)) {
return;
}
}
if (debug) { timedLog("endmark - continued"); }
mark = copy(positionable.state);
var modified = transform.modified;
transform = resetTransform();
// Only fire a tap if it's under the threshold
if (tapDiff < MAX_TAP_THRESHOLD && (new Date() - tapStart.timeStart <= tapDuration) && positionable.onTap) {
positionable.setState({touchactive: false}, function() {
if(positionable.onTap){
positionable.onTap();
}
});
return;
}
// Reset
tapDiff = 0;
positionable.setState({ touchactive: false }, function() {
if (positionable.onTouchEnd) {
positionable.onTouchEnd(modified);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6081
|
train
|
function(evt) {
evt.preventDefault();
evt.stopPropagation();
if (debug) { timedLog("secondFinger"); }
if (evt.touches.length < 2) {
return;
}
// we need to rebind finger 1, because it may have moved!
transform.x1 = evt.touches[0].pageX;
transform.y1 = evt.touches[0].pageY;
transform.x2 = evt.touches[1].pageX;
transform.y2 = evt.touches[1].pageY;
var x1 = transform.x1,
y1 = transform.y1,
x2 = transform.x2,
y2 = transform.y2,
dx = x2 - x1,
dy = y2 - y1,
d = Math.sqrt(dx*dx + dy*dy),
a = Math.atan2(dy,dx);
transform.distance = d;
transform.angle = a;
}
|
javascript
|
{
"resource": ""
}
|
|
q6082
|
train
|
function(evt) {
evt.preventDefault();
evt.stopPropagation();
if (debug) { timedLog("endSecondFinger"); }
if (evt.touches.length > 1) {
if (debug) { timedLog("endSecondFinger - capped"); }
return true;
}
if (debug) { timedLog("endSecondFinger - continued"); }
handlers.startmark(evt);
// If there are no fingers left on the screen,
// we have not finished the handling
return evt.touches.length !== 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q6083
|
tryFormat
|
train
|
function tryFormat(body) {
try {
const parsed = typeof body === 'string' ? JSON.parse(body) : body
return JSON.stringify(parsed, null, 2)
} catch (err) {
return body
}
}
|
javascript
|
{
"resource": ""
}
|
q6084
|
formatReport
|
train
|
function formatReport() { // eslint-disable-line no-unused-vars
const lineCoverage = new LineCoverage(2, 2, [
new LineData(6, 2, 'PF4Rz2r7RTliO9u6bZ7h6g'),
new LineData(7, 2, 'yGMB6FhEEAd8OyASe3Ni1w')
]);
const record = new Record('/home/cedx/lcov.js/fixture.js', {
functions: new FunctionCoverage(1, 1),
lines: lineCoverage
});
const report = new Report('Example', [record]);
console.log(report.toString());
}
|
javascript
|
{
"resource": ""
}
|
q6085
|
parseReport
|
train
|
async function parseReport() { // eslint-disable-line no-unused-vars
try {
const coverage = await promises.readFile('lcov.info', 'utf8');
const report = Report.fromCoverage(coverage);
console.log(`The coverage report contains ${report.records.length} records:`);
console.log(report.toJSON());
}
catch (error) {
console.log(`An error occurred: ${error.message}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q6086
|
range
|
train
|
function range(from, to) {
// TODO: make this inlined.
const list = new Array(to - from + 1);
for (let i = 0; i < list.length; i += 1) {
list[i] = from + i;
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
q6087
|
setupBrowserStorage
|
train
|
function setupBrowserStorage(){
if(browser || storageMock){
if(storageMock){
store = storageMock;
storageKey = 'cache-module-storage-mock';
}
else{
var storageType = (config.storage === 'local' || config.storage === 'session') ? config.storage : null;
store = (storageType && typeof Storage !== void(0)) ? window[storageType + 'Storage'] : false;
storageKey = (storageType) ? self.type + '-' + storageType + '-storage' : null;
}
if(store){
var db = store.getItem(storageKey);
try {
cache = JSON.parse(db) || cache;
} catch (err) { /* Do nothing */ }
}
// If storageType is set but store is not, the desired storage mechanism was not available
else if(storageType){
log(true, 'Browser storage is not supported by this browser. Defaulting to an in-memory cache.');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6088
|
overwriteBrowserStorage
|
train
|
function overwriteBrowserStorage(){
if((browser && store) || storageMock){
var db = cache;
try {
db = JSON.stringify(db);
store.setItem(storageKey, db);
} catch (err) { /* Do nothing */ }
}
}
|
javascript
|
{
"resource": ""
}
|
q6089
|
handleRefreshResponse
|
train
|
function handleRefreshResponse (key, data, err, response) {
if(!err) {
this.set(key, response, (data.lifeSpan / 1000), data.refresh, function(){});
}
}
|
javascript
|
{
"resource": ""
}
|
q6090
|
log
|
train
|
function log(isError, message, data){
if(self.verbose || isError){
if(data) console.log(self.type + ': ' + message, data);
else console.log(self.type + message);
}
}
|
javascript
|
{
"resource": ""
}
|
q6091
|
WebRequest
|
train
|
function WebRequest (options, callback) {
request(options, function (err, response, body) {
if (err) {
return callback(err);
}
callback(null, body);
});
}
|
javascript
|
{
"resource": ""
}
|
q6092
|
train
|
function(options) {
var out = this.formatEmpty(),
data = [],
rels;
this.init();
options = (options)? options : {};
this.mergeOptions(options);
this.getDOMContext( options );
// if we do not have any context create error
if(!this.rootNode || !this.document){
this.errors.push(this.noContentErr);
}else{
// only parse h-* microformats if we need to
// this is added to speed up parsing
if(this.hasMicroformats(this.rootNode, options)){
this.prepareDOM( options );
if(this.options.filters.length > 0){
// parse flat list of items
var newRootNode = this.findFilterNodes(this.rootNode, this.options.filters);
data = this.walkRoot(newRootNode);
}else{
// parse whole document from root
data = this.walkRoot(this.rootNode);
}
out.items = data;
// don't clear-up DOM if it was cloned
if(modules.domUtils.canCloneDocument(this.document) === false){
this.clearUpDom(this.rootNode);
}
}
// find any rels
if(this.findRels){
rels = this.findRels(this.rootNode);
out.rels = rels.rels;
out['rel-urls'] = rels['rel-urls'];
}
}
if(this.errors.length > 0){
return this.formatError();
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q6093
|
train
|
function(node, options) {
this.init();
options = (options)? options : {};
if(node){
return this.getParentTreeWalk(node, options);
}else{
this.errors.push(this.noContentErr);
return this.formatError();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6094
|
train
|
function( options ) {
var out = {},
items,
classItems,
x,
i;
this.init();
options = (options)? options : {};
this.getDOMContext( options );
// if we do not have any context create error
if(!this.rootNode || !this.document){
return {'errors': [this.noContentErr]};
}else{
items = this.findRootNodes( this.rootNode, true );
i = items.length;
while(i--) {
classItems = modules.domUtils.getAttributeList(items[i], 'class');
x = classItems.length;
while(x--) {
// find v2 names
if(modules.utils.startWith( classItems[x], 'h-' )){
this.appendCount(classItems[x], 1, out);
}
// find v1 names
for(var key in modules.maps) {
// dont double count if v1 and v2 roots are present
if(modules.maps[key].root === classItems[x] && classItems.indexOf(key) === -1) {
this.appendCount(key, 1, out);
}
}
}
}
var relCount = this.countRels( this.rootNode );
if(relCount > 0){
out.rels = relCount;
}
return out;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6095
|
train
|
function( node, options ) {
var classes,
i;
if(!node){
return false;
}
// if documemt gets topmost node
node = modules.domUtils.getTopMostNode( node );
// look for h-* microformats
classes = this.getUfClassNames(node);
if(options && options.filters && modules.utils.isArray(options.filters)){
i = options.filters.length;
while(i--) {
if(classes.root.indexOf(options.filters[i]) > -1){
return true;
}
}
return false;
}else{
return (classes.root.length > 0);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6096
|
train
|
function( node, options ) {
var items,
i;
if(!node){
return false;
}
// if browser based documemt get topmost node
node = modules.domUtils.getTopMostNode( node );
// returns all microformat roots
items = this.findRootNodes( node, true );
if(options && options.filters && modules.utils.isArray(options.filters)){
i = items.length;
while(i--) {
if( this.isMicroformat( items[i], options ) ){
return true;
}
}
return false;
}else{
return (items.length > 0);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6097
|
train
|
function( maps ){
maps.forEach(function(map){
if(map && map.root && map.name && map.properties){
modules.maps[map.name] = JSON.parse(JSON.stringify(map));
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6098
|
train
|
function (node, options, recursive) {
options = (options)? options : {};
// recursive calls
if (recursive === undefined) {
if (node.parentNode && node.nodeName !== 'HTML'){
return this.getParentTreeWalk(node.parentNode, options, true);
}else{
return this.formatEmpty();
}
}
if (node !== null && node !== undefined && node.parentNode) {
if (this.isMicroformat( node, options )) {
// if we have a match return microformat
options.node = node;
return this.get( options );
}else{
return this.getParentTreeWalk(node.parentNode, options, true);
}
}else{
return this.formatEmpty();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6099
|
train
|
function( options ){
var baseTag,
href;
// use current document to define baseUrl, try/catch needed for IE10+ error
try {
if (!options.baseUrl && this.document && this.document.location) {
this.options.baseUrl = this.document.location.href;
}
} catch (e) {
// there is no alt action
}
// find base tag to set baseUrl
baseTag = modules.domUtils.querySelector(this.document,'base');
if(baseTag) {
href = modules.domUtils.getAttribute(baseTag, 'href');
if(href){
this.options.baseUrl = href;
}
}
// get path to rootNode
// then clone document
// then reset the rootNode to its cloned version in a new document
var path,
newDocument,
newRootNode;
path = modules.domUtils.getNodePath(this.rootNode);
newDocument = modules.domUtils.cloneDocument(this.document);
newRootNode = modules.domUtils.getNodeByPath(newDocument, path);
// check results as early IE fails
if(newDocument && newRootNode){
this.document = newDocument;
this.rootNode = newRootNode;
}
// add includes
if(this.addIncludes){
this.addIncludes( this.document );
}
return (this.rootNode && this.document);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.