_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q62600
|
byteCount
|
test
|
function byteCount(testName, len, baseLen) {
console.log(testName + " Byte Count: " + len + (baseLen ? ', ' + Math.round(len / baseLen * 100) + '%' : ''));
}
|
javascript
|
{
"resource": ""
}
|
q62601
|
test
|
function() {
var colors = []
var trs = _$sortableDataList.find("li");
for (var i=0; i<trs.length; i++) {
colors.push(utils.rgb2hex($(trs[i]).find(".segmentColor").css("background-color")));
}
colors = utils.shuffleArray(colors);
_setColors(colors);
}
|
javascript
|
{
"resource": ""
}
|
|
q62602
|
test
|
function(moduleID, message, data) {
if (C.DEBUG) {
console.log("[" + moduleID + "] publish(): ", message, data);
}
for (var i in _modules) {
var subscriptions = _modules[i].subscriptions;
// if this module has subscribed to this event, call the callback function
if (subscriptions.hasOwnProperty(message)) {
subscriptions[message]({
sender: moduleID,
data: data
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62603
|
test
|
function() {
$(document).on("click", ".selectPage", function(e) {
e.preventDefault();
_selectPage(this.hash);
});
$(window).on("resize", function() {
var width = $(window).width();
var height = $(window).height();
var breakPoint = _updateBodySizeClass(width);
mediator.publish(_MODULE_ID, C.EVENT.PAGE.RESIZE, {
width: width,
height: height,
breakPoint: breakPoint
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62604
|
test
|
function(width) {
var breakPointIndex = null;
for (var i=0; i< C.OTHER.BREAKPOINTS.length; i++) {
if (width >= C.OTHER.BREAKPOINTS[i]) {
breakPointIndex = i;
}
}
$("body").removeClass("size768 size992 size1200");
var breakPoint = null;
if (breakPointIndex !== null) {
breakPoint = C.OTHER.BREAKPOINTS[breakPointIndex];
$("body").addClass("size" + breakPoint);
}
return breakPoint;
}
|
javascript
|
{
"resource": ""
}
|
|
q62605
|
test
|
function() {
var hb = new base.HandlebarsEnvironment();
Utils.extend(hb, base);
hb.SafeString = SafeString;
hb.Exception = Exception;
hb.Utils = Utils;
hb.VM = runtime;
hb.template = function(spec) {
return runtime.template(spec, hb);
};
return hb;
}
|
javascript
|
{
"resource": ""
}
|
|
q62606
|
test
|
function(paramSize, params, useRegister) {
var options = '{' + this.setupOptions(paramSize, params).join(',') + '}';
if (useRegister) {
this.useRegister('options');
params.push('options');
return 'options=' + options;
} else {
params.push(options);
return '';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62607
|
test
|
function(msg) {
_canvasWidth = msg.data.config.size.canvasWidth;
_canvasHeight = msg.data.config.size.canvasHeight;
}
|
javascript
|
{
"resource": ""
}
|
|
q62608
|
test
|
function(number) {
switch (number) {
case 1:
_demoPie2.redraw();
_demoPie3.redraw();
break;
case 2:
_demoPie1.redraw();
_demoPie3.redraw();
break;
case 3:
_demoPie1.redraw();
_demoPie2.redraw();
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62609
|
test
|
function() {
config.template.indexFile.options.data.C = _CONSTANTS.DEV;
config.template.indexFile.options.data.D3PIE_VERSION = packageFile.version;
config.template.devRequireConfig.options.data.handlebarsLib = _CONSTANTS.DEV.HANDLEBARS_LIB;
config.template.devRequireConfig.options.data.baseUrl = _CONSTANTS.DEV.BASE_URL;
var lines = [];
for (var i in _requireJSModulePaths) {
var file = _requireJSModulePaths[i].replace(/\.js$/, "");
lines.push('\t\t"' + i + '": "' + file + '"');
}
config.template.devRequireConfig.options.data.moduleStr = lines.join(",\n");
config.template.constants.options.data.VERSION = packageFile.version;
config.template.constants.options.data.MINIMIZED = _CONSTANTS.DEV.MINIMIZED;
config.template.constants.options.data.DEBUG = _CONSTANTS.DEV.DEBUG;
}
|
javascript
|
{
"resource": ""
}
|
|
q62610
|
test
|
function() {
return {
header: titleTab.getTabData(),
footer: footerTab.getTabData(),
size: sizeTab.getTabData(),
data: dataTab.getTabData(),
labels: labelsTab.getTabData(),
tooltips: tooltipsTab.getTabData(),
effects: effectsTab.getTabData(),
callbacks: eventsTab.getTabData(),
misc: miscTab.getTabData()
};
}
|
javascript
|
{
"resource": ""
}
|
|
q62611
|
getOrDef
|
test
|
function getOrDef(obj, prop) {
return obj[prop] === undefined ? options[prop] : obj[prop];
}
|
javascript
|
{
"resource": ""
}
|
q62612
|
calcViewport
|
test
|
function calcViewport() {
var scrollTop = $window.scrollTop(),
scrollLeft = window.pageXOffset || 0,
edgeX = options.edgeX,
edgeY = options.edgeY;
viewportTop = scrollTop - edgeY;
viewportBottom = scrollTop + (window.innerHeight || $window.height()) + edgeY;
viewportLeft = scrollLeft - edgeX;
viewportRight = scrollLeft + (window.innerWidth || $window.width()) + edgeX;
}
|
javascript
|
{
"resource": ""
}
|
q62613
|
checkVersion
|
test
|
function checkVersion() {
var nextVersionCheckTimestamp = parseInt(Cookies.get('nextVersionCheckTimestamp')) || 0;
if (!nextVersionCheckTimestamp || (Date.now() >= nextVersionCheckTimestamp)) {
$http.get('/api/build-info')
.then(function success(res) {
var currentVersion = parseVersion(res.data && res.data.version);
$http.get('https://api.github.com/repos/mcdcorp/opentest/releases')
.then(
function success(res) {
var eightDaysLater = Date.now() + (8 * 24 * 60 * 60 * 1000);
Cookies.set('nextVersionCheckTimestamp', eightDaysLater);
var latestVersionStr = res.data && res.data[0] && res.data[0].tag_name;
var latestVersionUrl = res.data && res.data[0] && res.data[0].html_url;
var latestVersion = parseVersion(latestVersionStr);
if (latestVersion && (compareVersions(latestVersion, currentVersion) === 1)) {
$.notify(
{
message:
'A new OpenTest version is now available: <a href="' + latestVersionUrl + '" target="_blank">' + latestVersionStr + '</a>. ' +
'You should always stay on the latest version to benefit from new features and security updates.'
}, {
type: 'info',
delay: 0,
placement: { from: 'bottom' }
})
}
},
function error(res) {
var oneHourLater = Date.now() + (60 * 60 * 1000);
Cookies.set('nextVersionCheckTimestamp', oneHourLater);
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q62614
|
parseVersion
|
test
|
function parseVersion(versionString) {
if (typeof versionString !== 'string') {
return null;
}
var versionRegexMatch = versionString.match(/v?(\d+)\.(\d+)\.(\d+)/i);
if (versionRegexMatch) {
return [parseInt(versionRegexMatch[1]), parseInt(versionRegexMatch[2]), parseInt(versionRegexMatch[3])];
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q62615
|
cellAccessor
|
test
|
function cellAccessor(row1, col1, row2, col2, isMerged) {
let theseCells = new cellBlock();
theseCells.ws = this;
row2 = row2 ? row2 : row1;
col2 = col2 ? col2 : col1;
if (row2 > this.lastUsedRow) {
this.lastUsedRow = row2;
}
if (col2 > this.lastUsedCol) {
this.lastUsedCol = col2;
}
for (let r = row1; r <= row2; r++) {
for (let c = col1; c <= col2; c++) {
let ref = `${utils.getExcelAlpha(c)}${r}`;
if (!this.cells[ref]) {
this.cells[ref] = new Cell(r, c);
}
if (!this.rows[r]) {
this.rows[r] = new Row(r, this);
}
if (this.rows[r].cellRefs.indexOf(ref) < 0) {
this.rows[r].cellRefs.push(ref);
}
theseCells.cells.push(this.cells[ref]);
theseCells.excelRefs.push(ref);
}
}
if (isMerged) {
theseCells.merged = true;
mergeCells(theseCells);
}
return theseCells;
}
|
javascript
|
{
"resource": ""
}
|
q62616
|
allProjects
|
test
|
function allProjects(done) {
User.find({}, function (err, users) {
if (err) return done(err);
Project.find()
.sort({_id: -1})
.exec(function (err, projects) {
if (err) return done(err);
done(null, projects.map(function (project) {
project = utils.sanitizeProject(project);
project.created_date = utils.timeFromId(project._id);
project.users = [];
for (var i = 0; i < users.length; i++) {
if ('undefined' !== typeof users[i].projects[project.name]) {
project.users.push({
email: users[i].email,
access: users[i].projects[project.name]
});
}
}
return project;
}));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q62617
|
getConfig
|
test
|
function getConfig() {
process.env = filterEnv(deprecated(process.env), envDefaults);
var rc = require('rc')('strider', defaults);
if (!rc.smtp) rc.smtp = smtp(rc);
if (!rc.smtp) rc.stubSmtp = true;
rc.ldap = getConfigByName('ldap');
addPlugins(rc, process.env);
// BACK COMPAT until we get strider config into plugins...
if (hasGithub) {
rc.plugins.github = rc.plugins.github || {};
rc.plugins.github.hostname = rc.server_name;
}
debug(rc);
return rc;
}
|
javascript
|
{
"resource": ""
}
|
q62618
|
filterEnv
|
test
|
function filterEnv(env, defaults) {
var res = {};
for (var k in env) {
if (defaults[k.toLowerCase()] !== undefined) {
res[`strider_${k.toLowerCase()}`] = env[k];
} else {
res[k] = env[k];
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q62619
|
mergePlugins
|
test
|
function mergePlugins(branch, sjson) {
if (!branch) return sjson;
if (!sjson) return branch;
// if strict_plugins is not turned on, we merge each plugin config instead of overwriting.
var plugins = [];
var pluginMap = {};
for (var pluginIndex = 0; pluginIndex < sjson.length; pluginIndex++) {
plugins.push(sjson[pluginIndex]);
pluginMap[sjson[pluginIndex].id] = true;
}
for (var branchIndex = 0; branchIndex < branch.length; branchIndex++) {
if (!pluginMap[branch[branchIndex].id]) plugins.push(branch[branchIndex]);
}
return plugins;
}
|
javascript
|
{
"resource": ""
}
|
q62620
|
registerTemplate
|
test
|
function registerTemplate(name, template, dir) {
cache[name] = function (context, cb) {
if (/\.html$/.test(template)){
dir = dir || '.';
template = fs.readFileSync(path.join(dir, template), 'utf8');
}
cb(null, template);
};
}
|
javascript
|
{
"resource": ""
}
|
q62621
|
getPluginTemplate
|
test
|
function getPluginTemplate(name, context) {
return function (cb) {
if (cache[name]){
cache[name](context, function (err, res) {
if (err) return cb(err);
cb(null, [name, res]);
});
} else {
cb(null, null);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q62622
|
engine
|
test
|
function engine(path, options, fn) {
options.filename = path;
fs.readFile(path, 'utf8', function (err, str) {
if (err) return fn(err);
engine.render(str, options, fn);
});
}
|
javascript
|
{
"resource": ""
}
|
q62623
|
test
|
function (uid, socket) {
var socks = this.sockets[uid];
if (!socks) return false;
return socks.remove(socket);
}
|
javascript
|
{
"resource": ""
}
|
|
q62624
|
test
|
function (socket) {
var session = socket.handshake.session;
if (session && session.passport) {
this.addSocket(session.passport.user, socket);
} else {
console.debug('Websocket connection does not have authorization - nothing to do.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62625
|
status
|
test
|
function status(job) {
if (job.errored) return 'errored';
if (!job.started) return 'submitted';
if (!job.finished) return 'running';
if (job.test_exitcode !== 0) return 'failed';
if (job.type !== TEST_ONLY && job.deploy_exitcode !== 0) return 'failed';
return 'passed';
}
|
javascript
|
{
"resource": ""
}
|
q62626
|
prepareJob
|
test
|
function prepareJob(emitter, job) {
Project.findOne({ name: job.project }).populate('creator').exec(function (err, project) {
if (err || !project) return debug('job.prepare - failed to get project', job.project, err);
// ok so the project is real, we can go ahead and save this job
var provider = common.extensions.provider[project.provider.id];
if (!provider) {
return debug('job.prepare - provider not found for project', job.project, project.provider.id);
}
Job.create(job, function (err, mjob) {
if (err) return debug('job.prepare - failed to save job', job, err);
var jjob = mjob.toJSON();
jjob.project = project;
jjob.providerConfig = project.provider.config;
jjob.fromStriderJson = true;
striderJson(provider, project, job.ref, function (err, config) {
if (err) {
if (err.status === 403 || err.statusCode === 403) {
debug('job.prepare - access to strider.json is forbidden, skipping config merge');
config = {};
jjob.fromStriderJson = false;
} else if (err.status === 404 || err.statusCode === 404) {
debug('job.prepare - strider.json not found, skipping config merge');
config = {};
jjob.fromStriderJson = false;
} else {
debug('job.prepare - error opening/processing project\'s `strider.json` file: ', err);
config = {};
jjob.fromStriderJson = false;
}
} else {
debug('Using configuration from "strider.json".');
}
var branch = project.branch(job.ref.branch || 'master');
if (!branch) {
return debug('job.prepare - branch not found', job.ref.branch || 'master', project.name);
}
branch = branch.mirror_master ? project.branch('master') : branch;
jjob.providerConfig = _.extend({}, project.provider.config, config.provider || {});
config.runner = config.runner || branch.runner;
if (!common.extensions.runner[config.runner.id]) {
debug(`Error: A job was registered for a runner that doesn't exist, i.e. "${config.runner.id}". This job will never run!`);
}
if (config) {
delete config.provider;
config = utils.mergeConfigs(branch, config);
}
emitter.emit('job.new', jjob, config);
if (!mjob.runner) mjob.runner = {};
mjob.runner.id = config.runner.id;
mjob.save()
.then(() => debug('job saved'))
.catch(e => debug(e));
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q62627
|
killAttrs
|
test
|
function killAttrs(model, attrs) {
for (var i = 0; i < attrs.length; i++) {
delete model[attrs[i]];
}
}
|
javascript
|
{
"resource": ""
}
|
q62628
|
bodySetter
|
test
|
function bodySetter(req, res, next) {
if (req._post_body) {
return next();
}
req.post_body = req.post_body || '';
if ('POST' !== req.method) {
return next();
}
req._post_body = true;
req.on('data', function (chunk) {
req.post_body += chunk;
});
next();
}
|
javascript
|
{
"resource": ""
}
|
q62629
|
requireBody
|
test
|
function requireBody(paramsList) {
return function (req, res, next) {
var errors = [];
var status = 'ok';
for (var i = 0; i < paramsList.length; i++) {
var val = req.body[paramsList[i]];
if (!val) {
errors.push(`required parameter \`${paramsList[i]}\` not found.`);
status = 'error';
}
}
if (errors.length === 0) {
next();
} else {
return res.status(400).json({
errors: errors,
status: status
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
q62630
|
anonProject
|
test
|
function anonProject(req, res, next) {
var name = `${req.params.org}/${req.params.repo}`;
name = name.toLowerCase();
Project.findOne({name: name})
.populate('creator')
.exec(function (err, project) {
if (err) {
return res.status(500).send({
error: 'Failed to find project',
info: err
});
}
if (!project) {
return res.status(404).send('Project not found');
}
if (!project.creator) {
return res.status(400).send('Project malformed; project creator user is missing.');
}
req.project = project;
req.accessLevel = User.projectAccessLevel(req.user, project);
if (req.user && project.creator) {
req.user.isProjectCreator = project.creator._id.toString() === req.user._id.toString();
}
next();
});
}
|
javascript
|
{
"resource": ""
}
|
q62631
|
requireUser
|
test
|
function requireUser(req, res, next) {
if (req.user) {
next();
} else {
req.session.return_to = req.url;
res.redirect('/login');
}
}
|
javascript
|
{
"resource": ""
}
|
q62632
|
requireAdminOr401
|
test
|
function requireAdminOr401(req, res, next) {
if (!req.user || !req.user['account_level'] || req.user.account_level < 1) {
res.status(401).send('not authorized');
} else {
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q62633
|
pluginBlock
|
test
|
function pluginBlock(indent, parser) {
var template = this.args[0];
var output = '';
// Register that the template is needed, for 1st pass;
output += `_context._striderRegister.push('${template}');\n`;
// Generate code to see if pluginTemplates has block
output += `var _pg = _context._striderBlocks['${template}'];\n`;
output += 'if (_pg){ ';
output += '_output += _pg;';
output += '} else {\n';
output += parser.compile.call(this, `${indent} `);
output += '}\n';
return output;
}
|
javascript
|
{
"resource": ""
}
|
q62634
|
_findNested
|
test
|
function _findNested (d) {
let nested = [];
walk.walkSync(d, (basedir, filename, stat) => {
const file = path.join(basedir, filename);
if (file.indexOf('.app/Info.plist') !== -1) {
const nest = file.lastIndexOf('.app/');
nested.push(file.substring(0, nest + 4));
}
});
return nested;
}
|
javascript
|
{
"resource": ""
}
|
q62635
|
binAbsLibs
|
test
|
function binAbsLibs (file, o) {
try {
return bin.enumerateLibraries(file)
.filter((l) => {
return !(l.startsWith('/'));
})
.map((l) => {
if (l[0] === '@') {
const ll = depSolver.resolvePath(o.exe, file, l, o.libs);
if (ll) {
l = ll;
} else {
console.error('Warning: Cannot resolve dependency library: ' + file);
}
}
return l;
});
} catch (e) {
console.error('Warning: missing file:', file);
return [];
}
}
|
javascript
|
{
"resource": ""
}
|
q62636
|
_findLibraries
|
test
|
function _findLibraries (appdir, appbin, disklibs) {
const exe = path.join(appdir, appbin);
const o = {
exe: exe,
lib: exe,
libs: disklibs
};
const libraries = [];
const pending = [exe];
while (pending.length > 0) {
const target = pending.pop();
if (libraries.indexOf(target) === -1) {
libraries.push(target);
}
let res = binAbsLibs(target, o);
const unexplored = res.filter(l => libraries.indexOf(l) === -1);
pending.push(...unexplored.filter(l => pending.indexOf(l) === -1));
libraries.push(...unexplored);
}
return libraries;
}
|
javascript
|
{
"resource": ""
}
|
q62637
|
fix
|
test
|
function fix (file, options, emit) {
const { appdir, bundleid, forceFamily, allowHttp } = options;
if (!file || !appdir) {
throw new Error('Invalid parameters for fixPlist');
}
let changed = false;
const data = plist.readFileSync(file);
delete data[''];
if (allowHttp) {
emit('message', 'Adding NSAllowArbitraryLoads');
if (!Object.isObject(data['NSAppTransportSecurity'])) {
data['NSAppTransportSecurity'] = {};
}
data['NSAppTransportSecurity']['NSAllowsArbitraryLoads'] = true;
changed = true;
}
if (forceFamily) {
if (performForceFamily(data, emit)) {
changed = true;
}
}
if (bundleid) {
setBundleId(data, bundleid);
changed = true;
}
if (changed) {
plist.writeFileSync(file, data);
}
}
|
javascript
|
{
"resource": ""
}
|
q62638
|
generateAccessor
|
test
|
function generateAccessor (accessor) {
return function () {
let value = container[varName]
if (typeof value === 'undefined') {
if (typeof defValue === 'undefined') {
// Need to return since no value is available. If a value needed to
// be available required() should be called, or a default passed
return
}
// Assign the default as the value since process.env does not contain
// the desired variable
value = defValue
}
if (isBase64) {
if (!value.match(base64Regex)) {
generateRaiseError(value)('should be a valid base64 string if using convertFromBase64')
}
value = Buffer.from(value, 'base64').toString()
}
const args = [
generateRaiseError(value),
value
].concat(Array.prototype.slice.call(arguments))
return accessor.apply(
accessor,
args
)
}
}
|
javascript
|
{
"resource": ""
}
|
q62639
|
test
|
function (isRequired) {
if (isRequired === false) {
return accessors
}
if (typeof container[varName] === 'undefined' && typeof defValue === 'undefined') {
throw new EnvVarError(`"${varName}" is a required variable, but it was not set`)
}
return accessors
}
|
javascript
|
{
"resource": ""
}
|
|
q62640
|
test
|
function(ast, bodyContent) {
var macro = this.macros[ast.id];
var ret = '';
if (!macro) {
var jsmacros = this.jsmacros;
macro = jsmacros[ast.id];
var jsArgs = [];
if (macro && macro.apply) {
utils.forEach(ast.args, function(a) {
jsArgs.push(this.getLiteral(a));
}, this);
var self = this;
// bug修复:此处由于闭包特性,导致eval函数执行时的this对象是上一次函数执行时的this对象,渲染时上下文发生错误。
jsmacros.eval = function() {
return self.eval.apply(self, arguments);
};
try {
ret = macro.apply(jsmacros, jsArgs);
} catch (e) {
var pos = ast.pos;
var text = Velocity.Helper.getRefText(ast);
// throws error tree
var err = '\n at ' + text + ' L/N ' + pos.first_line + ':' + pos.first_column;
e.name = '';
e.message += err;
throw new Error(e);
}
}
} else {
var asts = macro.asts;
var args = macro.args;
var callArgs = ast.args;
var local = { bodyContent: bodyContent };
var guid = utils.guid();
var contextId = 'macro:' + ast.id + ':' + guid;
utils.forEach(args, function(ref, i) {
if (callArgs[i]) {
local[ref.id] = this.getLiteral(callArgs[i]);
} else {
local[ref.id] = undefined;
}
}, this);
ret = this.eval(asts, local, contextId);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q62641
|
checkBinReferences_
|
test
|
function checkBinReferences_ (file, data, warn, cb) {
if (!(data.bin instanceof Object)) return cb()
var keys = Object.keys(data.bin)
var keysLeft = keys.length
if (!keysLeft) return cb()
function handleExists (relName, result) {
keysLeft--
if (!result) warn('No bin file found at ' + relName)
if (!keysLeft) cb()
}
keys.forEach(function (key) {
var dirName = path.dirname(file)
var relName = data.bin[key]
try {
var binPath = path.resolve(dirName, relName)
fs.stat(binPath, (err) => handleExists(relName, !err))
} catch (error) {
if (error.message === 'Arguments to path.resolve must be strings' || error.message.indexOf('Path must be a string') === 0) {
warn('Bin filename for ' + key + ' is not a string: ' + util.inspect(relName))
handleExists(relName, true)
} else {
cb(error)
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q62642
|
test
|
function() {
var self = this;
self.bind('RuntimeInit', function(e, runtime) {
self.ruid = runtime.uid;
self.shimid = runtime.shimid;
self.bind("Ready", function() {
self.trigger("Refresh");
}, 999);
// re-position and resize shim container
self.bind('Refresh', function() {
var pos, size, browseButton, shimContainer, zIndex;
browseButton = Dom.get(options.browse_button);
shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist
if (browseButton) {
pos = Dom.getPos(browseButton, Dom.get(options.container));
size = Dom.getSize(browseButton);
zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 0;
if (shimContainer) {
Basic.extend(shimContainer.style, {
top: pos.y + 'px',
left: pos.x + 'px',
width: size.w + 'px',
height: size.h + 'px',
zIndex: zIndex + 1
});
}
}
shimContainer = browseButton = null;
});
runtime.exec.call(self, 'FileInput', 'init', options);
});
// runtime needs: options.required_features, options.runtime_order and options.container
self.connectRuntime(Basic.extend({}, options, {
required_caps: {
select_file: true
}
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q62643
|
test
|
function(name, value) {
if (!options.hasOwnProperty(name)) {
return;
}
var oldValue = options[name];
switch (name) {
case 'accept':
if (typeof(value) === 'string') {
value = Mime.mimes2extList(value);
}
break;
case 'container':
case 'required_caps':
throw new x.FileException(x.FileException.NO_MODIFICATION_ALLOWED_ERR);
}
options[name] = value;
this.exec('FileInput', 'setOption', name, value);
this.trigger('OptionChanged', name, value, oldValue);
}
|
javascript
|
{
"resource": ""
}
|
|
q62644
|
test
|
function(e, runtime) {
self.unbind("RuntimeInit", cb);
_run.call(self, type, runtime);
}
|
javascript
|
{
"resource": ""
}
|
|
q62645
|
test
|
function() {
this.result = null;
if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) {
return;
} else if (this.readyState === FileReader.LOADING) {
this.readyState = FileReader.DONE;
}
this.exec('FileReader', 'abort');
this.trigger('abort');
this.trigger('loadend');
}
|
javascript
|
{
"resource": ""
}
|
|
q62646
|
test
|
function(type) {
var list;
if (type) {
type = type.toLowerCase();
list = eventpool[this.uid] && eventpool[this.uid][type];
} else {
list = eventpool[this.uid];
}
return list ? list : false;
}
|
javascript
|
{
"resource": ""
}
|
|
q62647
|
test
|
function(type, fn) {
var self = this, list, i;
type = type.toLowerCase();
if (/\s/.test(type)) {
// multiple event types were passed for one handler
Basic.each(type.split(/\s+/), function(type) {
self.removeEventListener(type, fn);
});
return;
}
list = eventpool[this.uid] && eventpool[this.uid][type];
if (list) {
if (fn) {
for (i = list.length - 1; i >= 0; i--) {
if (list[i].fn === fn) {
list.splice(i, 1);
break;
}
}
} else {
list = [];
}
// delete event list if it has become empty
if (!list.length) {
delete eventpool[this.uid][type];
// and object specific entry in a hash if it has no more listeners attached
if (Basic.isEmptyObj(eventpool[this.uid])) {
delete eventpool[this.uid];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62648
|
test
|
function(type, fn, priority, scope) {
var self = this;
self.bind.call(this, type, function cb() {
self.unbind(type, cb);
return fn.apply(this, arguments);
}, priority, scope);
}
|
javascript
|
{
"resource": ""
}
|
|
q62649
|
test
|
function(cap, value) {
var refCaps = arguments[2] || caps;
// if cap var is a comma-separated list of caps, convert it to object (key/value)
if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') {
cap = Runtime.parseCaps(cap);
}
if (Basic.typeOf(cap) === 'object') {
for (var key in cap) {
if (!this.can(key, cap[key], refCaps)) {
return false;
}
}
return true;
}
// check the individual cap
if (Basic.typeOf(refCaps[cap]) === 'function') {
return refCaps[cap].call(this, value);
} else {
return (value === refCaps[cap]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62650
|
getShimVersion
|
test
|
function getShimVersion() {
var version;
try {
version = navigator.plugins['Shockwave Flash'];
version = version.description;
} catch (e1) {
try {
version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
} catch (e2) {
version = '0.0';
}
}
version = version.match(/\d+/g);
return parseFloat(version[0] + '.' + version[1]);
}
|
javascript
|
{
"resource": ""
}
|
q62651
|
removeSWF
|
test
|
function removeSWF(id) {
var obj = Dom.get(id);
if (obj && obj.nodeName == "OBJECT") {
if (Env.browser === 'IE') {
obj.style.display = "none";
(function onInit(){
// http://msdn.microsoft.com/en-us/library/ie/ms534360(v=vs.85).aspx
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(onInit, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62652
|
test
|
function(url) {
function origin(url) {
return [url.scheme, url.host, url.port].join('/');
}
if (typeof url === 'string') {
url = parseUrl(url);
}
return origin(parseUrl()) === origin(url);
}
|
javascript
|
{
"resource": ""
}
|
|
q62653
|
ctor
|
test
|
function ctor() {
this.constructor = child;
if (MXI_DEBUG) {
var getCtorName = function(fn) {
var m = fn.toString().match(/^function\s([^\(\s]+)/);
return m ? m[1] : false;
};
this.ctorName = getCtorName(child);
}
}
|
javascript
|
{
"resource": ""
}
|
q62654
|
inArray
|
test
|
function inArray(needle, array) {
if (array) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(array, needle);
}
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === needle) {
return i;
}
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q62655
|
arrayDiff
|
test
|
function arrayDiff(needles, array) {
var diff = [];
if (typeOf(needles) !== 'array') {
needles = [needles];
}
if (typeOf(array) !== 'array') {
array = [array];
}
for (var i in needles) {
if (inArray(needles[i], array) === -1) {
diff.push(needles[i]);
}
}
return diff.length ? diff : false;
}
|
javascript
|
{
"resource": ""
}
|
q62656
|
arrayIntersect
|
test
|
function arrayIntersect(array1, array2) {
var result = [];
each(array1, function(item) {
if (inArray(item, array2) !== -1) {
result.push(item);
}
});
return result.length ? result : null;
}
|
javascript
|
{
"resource": ""
}
|
q62657
|
parseSizeStr
|
test
|
function parseSizeStr(size) {
if (typeof(size) !== 'string') {
return size;
}
var muls = {
t: 1099511627776,
g: 1073741824,
m: 1048576,
k: 1024
},
mul;
size = /^([0-9\.]+)([tmgk]?)$/.exec(size.toLowerCase().replace(/[^0-9\.tmkg]/g, ''));
mul = size[2];
size = +size[1];
if (muls.hasOwnProperty(mul)) {
size *= muls[mul];
}
return Math.floor(size);
}
|
javascript
|
{
"resource": ""
}
|
q62658
|
test
|
function(name, value) {
var self = this, valueType = Basic.typeOf(value);
// according to specs value might be either Blob or String
if (value instanceof Blob) {
_blob = {
name: name,
value: value // unfortunately we can only send single Blob in one FormData
};
} else if ('array' === valueType) {
name += '[]';
Basic.each(value, function(value) {
self.append(name, value);
});
} else if ('object' === valueType) {
Basic.each(value, function(value, key) {
self.append(name + '[' + key + ']', value);
});
} else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) {
self.append(name, "false");
} else {
_fields.push({
name: name,
value: value.toString()
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62659
|
test
|
function(cb) {
Basic.each(_fields, function(field) {
cb(field.value, field.name);
});
if (_blob) {
cb(_blob.value, _blob.name);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62660
|
test
|
function(obj, name) {
if (!obj.className) {
return false;
}
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
return regExp.test(obj.className);
}
|
javascript
|
{
"resource": ""
}
|
|
q62661
|
test
|
function(obj, name) {
if (!hasClass(obj, name)) {
obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62662
|
test
|
function(obj, name) {
if (obj.className) {
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
obj.className = obj.className.replace(regExp, function($0, $1, $2) {
return $1 === ' ' && $2 === ' ' ? ' ' : '';
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62663
|
test
|
function(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
} else if (window.getComputedStyle) {
return window.getComputedStyle(obj, null)[name];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62664
|
test
|
function(node, root) {
var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;
node = node;
root = root || doc.body;
// Returns the x, y cordinate for an element on IE 6 and IE 7
function getIEPos(node) {
var bodyElm, rect, x = 0, y = 0;
if (node) {
rect = node.getBoundingClientRect();
bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
x = rect.left + bodyElm.scrollLeft;
y = rect.top + bodyElm.scrollTop;
}
return {
x : x,
y : y
};
}
// Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) {
nodeRect = getIEPos(node);
rootRect = getIEPos(root);
return {
x : nodeRect.x - rootRect.x,
y : nodeRect.y - rootRect.y
};
}
parent = node;
while (parent && parent != root && parent.nodeType) {
x += parent.offsetLeft || 0;
y += parent.offsetTop || 0;
parent = parent.offsetParent;
}
parent = node.parentNode;
while (parent && parent != root && parent.nodeType) {
x -= parent.scrollLeft || 0;
y -= parent.scrollTop || 0;
parent = parent.parentNode;
}
return {
x : x,
y : y
};
}
|
javascript
|
{
"resource": ""
}
|
|
q62665
|
getIEPos
|
test
|
function getIEPos(node) {
var bodyElm, rect, x = 0, y = 0;
if (node) {
rect = node.getBoundingClientRect();
bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
x = rect.left + bodyElm.scrollLeft;
y = rect.top + bodyElm.scrollTop;
}
return {
x : x,
y : y
};
}
|
javascript
|
{
"resource": ""
}
|
q62666
|
test
|
function(node) {
return {
w : node.offsetWidth || node.clientWidth,
h : node.offsetHeight || node.clientHeight
};
}
|
javascript
|
{
"resource": ""
}
|
|
q62667
|
test
|
function(obj, key) {
if (!obj || !obj[uid]) {
return;
}
Basic.each(eventhash[obj[uid]], function(events, name) {
removeEvent(obj, name, key);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62668
|
_preloadAndSend
|
test
|
function _preloadAndSend(meta, data) {
var target = this, blob, fr;
// get original blob
blob = data.getBlob().getSource();
// preload blob in memory to be sent as binary string
fr = new window.FileReader();
fr.onload = function() {
// overwrite original blob
data.append(data.getBlobName(), new Blob(null, {
type: blob.type,
data: fr.result
}));
// invoke send operation again
self.send.call(target, meta, data);
};
fr.readAsBinaryString(blob);
}
|
javascript
|
{
"resource": ""
}
|
q62669
|
_rotateToOrientaion
|
test
|
function _rotateToOrientaion(img, orientation) {
var RADIANS = Math.PI/180;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width = img.width;
var height = img.height;
if (Basic.inArray(orientation, [5,6,7,8]) > -1) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
/**
1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
*/
switch (orientation) {
case 2:
// horizontal flip
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
// 180 rotate left
ctx.translate(width, height);
ctx.rotate(180 * RADIANS);
break;
case 4:
// vertical flip
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
// vertical flip + 90 rotate right
ctx.rotate(90 * RADIANS);
ctx.scale(1, -1);
break;
case 6:
// 90 rotate right
ctx.rotate(90 * RADIANS);
ctx.translate(0, -height);
break;
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(90 * RADIANS);
ctx.translate(width, -height);
ctx.scale(-1, 1);
break;
case 8:
// 90 rotate left
ctx.rotate(-90 * RADIANS);
ctx.translate(-width, 0);
break;
}
ctx.drawImage(img, 0, 0, width, height);
return canvas;
}
|
javascript
|
{
"resource": ""
}
|
q62670
|
getEntries
|
test
|
function getEntries(cbcb) {
dirReader.readEntries(function(moreEntries) {
if (moreEntries.length) {
[].push.apply(entries, moreEntries);
getEntries(cbcb);
} else {
cbcb();
}
}, cbcb);
}
|
javascript
|
{
"resource": ""
}
|
q62671
|
test
|
function(method, url, async, user, password) {
var urlp;
// first two arguments are required
if (!method || !url) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method
if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3
if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) {
_method = method.toUpperCase();
}
// 4 - allowing these methods poses a security risk
if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) {
throw new x.DOMException(x.DOMException.SECURITY_ERR);
}
// 5
url = Encode.utf8_encode(url);
// 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError".
urlp = Url.parseUrl(url);
_same_origin_flag = Url.hasSameOrigin(urlp);
// 7 - manually build up absolute url
_url = Url.resolveUrl(url);
// 9-10, 12-13
if ((user || password) && !_same_origin_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
_user = user || urlp.user;
_password = password || urlp.pass;
// 11
_async = async || true;
if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 14 - terminate abort()
// 15 - terminate send()
// 18
_sync_flag = !_async;
_send_flag = false;
_headers = {};
_reset.call(this);
// 19
_p('readyState', XMLHttpRequest.OPENED);
// 20
this.dispatchEvent('readystatechange');
}
|
javascript
|
{
"resource": ""
}
|
|
q62672
|
test
|
function(header, value) {
var uaHeaders = [ // these headers are controlled by the user agent
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"cookie",
"cookie2",
"content-transfer-encoding",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
"via"
];
// 1-2
if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 4
/* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values
if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}*/
header = Basic.trim(header).toLowerCase();
// setting of proxy-* and sec-* headers is prohibited by spec
if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) {
return false;
}
// camelize
// browsers lowercase header names (at least for custom ones)
// header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); });
if (!_headers[header]) {
_headers[header] = value;
} else {
// http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph)
_headers[header] += ', ' + value;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q62673
|
test
|
function(header) {
header = header.toLowerCase();
if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) {
return null;
}
if (_responseHeaders && _responseHeaders !== '') {
// if we didn't parse response headers until now, do it and keep for later
if (!_responseHeadersBag) {
_responseHeadersBag = {};
Basic.each(_responseHeaders.split(/\r\n/), function(line) {
var pair = line.split(/:\s+/);
if (pair.length === 2) { // last line might be empty, omit
pair[0] = Basic.trim(pair[0]); // just in case
_responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form
header: pair[0],
value: Basic.trim(pair[1])
};
}
});
}
if (_responseHeadersBag.hasOwnProperty(header)) {
return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q62674
|
test
|
function(mime) {
var matches, charset;
// 1
if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2
mime = Basic.trim(mime.toLowerCase());
if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) {
mime = matches[1];
if (matches[2]) {
charset = matches[2];
}
}
if (!Mime.mimes[mime]) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3-4
_finalMime = mime;
_finalCharset = charset;
}
|
javascript
|
{
"resource": ""
}
|
|
q62675
|
test
|
function(data, options) {
if (Basic.typeOf(options) === 'string') {
_options = { ruid: options };
} else if (!options) {
_options = {};
} else {
_options = options;
}
// 1-2
if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
// sending Blob
if (data instanceof Blob) {
_options.ruid = data.ruid;
_mimeType = data.type || 'application/octet-stream';
}
// FormData
else if (data instanceof FormData) {
if (data.hasBlob()) {
var blob = data.getBlob();
_options.ruid = blob.ruid;
_mimeType = blob.type || 'application/octet-stream';
}
}
// DOMString
else if (typeof data === 'string') {
_encoding = 'UTF-8';
_mimeType = 'text/plain;charset=UTF-8';
// data should be converted to Unicode and encoded as UTF-8
data = Encode.utf8_encode(data);
}
// if withCredentials not set, but requested, set it automatically
if (!this.withCredentials) {
this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag;
}
// 4 - storage mutex
// 5
_upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP
// 6
_error_flag = false;
// 7
_upload_complete_flag = !data;
// 8 - Asynchronous steps
if (!_sync_flag) {
// 8.1
_send_flag = true;
// 8.2
// this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
// 8.3
//if (!_upload_complete_flag) {
// this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
//}
}
// 8.5 - Return the send() method call, but continue running the steps in this algorithm.
_doXHR.call(this, data);
}
|
javascript
|
{
"resource": ""
}
|
|
q62676
|
test
|
function() {
_error_flag = true;
_sync_flag = false;
if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) {
_p('readyState', XMLHttpRequest.DONE);
_send_flag = false;
if (_xhr) {
_xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag);
} else {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
_upload_complete_flag = true;
} else {
_p('readyState', XMLHttpRequest.UNSENT);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62677
|
test
|
function(target) {
var undef;
each(arguments, function(arg, i) {
if (i > 0) {
each(arg, function(value, key) {
if (value !== undef) {
if (typeof(target[key]) === typeof(value) && (typeof(value) === 'object' || util.isArray(value))) {
extend(target[key], value);
} else {
target[key] = value;
}
}
});
}
});
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q62678
|
test
|
function() {
if (this.ruid) {
this.getRuntime().exec.call(this, 'Image', 'destroy');
this.disconnectRuntime();
}
if (this.meta && this.meta.thumb) {
// thumb is blob, make sure we destroy it first
this.meta.thumb.data.destroy();
}
this.unbindAll();
}
|
javascript
|
{
"resource": ""
}
|
|
q62679
|
test
|
function(obj, prop, desc)
{
if (o.typeOf(desc) === 'object') {
defineGSetter.call(obj, prop, desc, 'get');
if (!Object.defineProperty) {
// additionally call it for setter
defineGSetter.call(obj, prop, desc, 'set');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62680
|
test
|
function(prop, desc, type) {
var defaults = {
enumerable: true,
configurable: true
}
, fn
, camelType
, self = this
;
type = type.toLowerCase();
camelType = type.replace(/^[gs]/, function($1) { return $1.toUpperCase(); });
// define function object for fallback
if (o.typeOf(desc) === 'function') {
fn = desc;
desc = {};
desc[type] = fn;
} else if (o.typeOf(desc[type]) === 'function') {
fn = desc[type];
} else {
return;
}
if (Env.can('define_property')) {
if (Object.defineProperty) {
return Object.defineProperty(this, prop, o.extend({}, defaults, desc));
} else {
return self['__define' + camelType + 'ter__'](prop, fn);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62681
|
SyntaxError
|
test
|
function SyntaxError (message/*: string */, expected/*: ?string */, found/*: ?string */, offset/*: number */, line/*: number */, column/*: number */) {
Error.call(this, message)
this.name = 'SyntaxError'
this.message = message
this.expected = expected
this.found = found
this.offset = offset
this.line = line
this.column = column
}
|
javascript
|
{
"resource": ""
}
|
q62682
|
test
|
function(twist) {
var i, m, o, ori, parity, v;
if (twist != null) {
parity = 0;
for (i = m = 6; m >= 0; i = --m) {
ori = twist % 3;
twist = (twist / 3) | 0;
this.co[i] = ori;
parity += ori;
}
this.co[7] = (3 - parity % 3) % 3;
return this;
} else {
v = 0;
for (i = o = 0; o <= 6; i = ++o) {
v = 3 * v + this.co[i];
}
return v;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62683
|
test
|
function(flip) {
var i, m, o, ori, parity, v;
if (flip != null) {
parity = 0;
for (i = m = 10; m >= 0; i = --m) {
ori = flip % 2;
flip = flip / 2 | 0;
this.eo[i] = ori;
parity += ori;
}
this.eo[11] = (2 - parity % 2) % 2;
return this;
} else {
v = 0;
for (i = o = 0; o <= 10; i = ++o) {
v = 2 * v + this.eo[i];
}
return v;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62684
|
test
|
function() {
var i, j, m, o, ref, ref1, ref2, ref3, s;
s = 0;
for (i = m = ref = DRB, ref1 = URF + 1; (ref <= ref1 ? m <= ref1 : m >= ref1); i = ref <= ref1 ? ++m : --m) {
for (j = o = ref2 = i - 1, ref3 = URF; (ref2 <= ref3 ? o <= ref3 : o >= ref3); j = ref2 <= ref3 ? ++o : --o) {
if (this.cp[j] > this.cp[i]) {
s++;
}
}
}
return s % 2;
}
|
javascript
|
{
"resource": ""
}
|
|
q62685
|
test
|
function() {
var i, j, m, o, ref, ref1, ref2, ref3, s;
s = 0;
for (i = m = ref = BR, ref1 = UR + 1; (ref <= ref1 ? m <= ref1 : m >= ref1); i = ref <= ref1 ? ++m : --m) {
for (j = o = ref2 = i - 1, ref3 = UR; (ref2 <= ref3 ? o <= ref3 : o >= ref3); j = ref2 <= ref3 ? ++o : --o) {
if (this.ep[j] > this.ep[i]) {
s++;
}
}
}
return s % 2;
}
|
javascript
|
{
"resource": ""
}
|
|
q62686
|
all_modulo
|
test
|
function all_modulo(tickValues, interval) {
// we can't modulo-check decimals so we need to multiply by 10^Ndecimals
var maxDecimals = reduce(tickValues, function(prevMax, tick) {
if ((tick % 1) !== 0) {
return Math.max(prevMax, tick.toString().split(".")[1].length);
} else {
return prevMax;
}
}, 0);
var decimalOffset = Math.pow(10, maxDecimals);
interval = interval * decimalOffset;
return reduce(tickValues, function(prev, curr) {
return prev && ((curr * decimalOffset) % interval === 0);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q62687
|
autoDateFormatAndFrequency
|
test
|
function autoDateFormatAndFrequency(minDate, maxDate, dateFormat, availableWidth) {
var timespan = Math.abs(maxDate - minDate);
var years = timespan / 31536000000;
var months = timespan / 2628000000;
var days = timespan / 86400000;
var yearGap;
var hourGap;
var interval;
var targetPixelGap = 64;
var maximum_ticks = Math.max(Math.floor(availableWidth / targetPixelGap), 1);
var time_gap = timespan / maximum_ticks;
if (dateFormat == "auto") {
//lets go small to large
if (days <= 2) {
dateFormat = "h";
}
else if (days <= 91) {
dateFormat = "M1d";
}
else if (months < 36) {
dateFormat = "M";
}
else {
dateFormat = "yy";
}
}
var gapInYears = humanReadableNumber(Math.floor(time_gap / 31536000000));
var gapInMonths = Math.ceil(time_gap / 2628000000);
var gapInDays = humanReadableNumber(time_gap / 86400000);
var gapInHours = humanReadableNumber(time_gap / 3600000);
//make sure that the interval include the maxDate in the interval list
maxDate.addMilliseconds(0.1);
switch (dateFormat) {
case "yy":
// Add a day to the max date for years to make inclusive of max date
// irrespective of time zone / DST
maxDate = d3.time.day.offset(maxDate, 1);
interval = d3.time.year.range(minDate, maxDate, gapInYears);
break;
case "yyyy":
// See above
maxDate = d3.time.day.offset(maxDate, 1);
interval = d3.time.year.range(minDate, maxDate, gapInYears);
break;
case "MM":
interval = d3.time.month.range(minDate, maxDate, gapInMonths);
break;
case "M":
interval = d3.time.month.range(minDate, maxDate, gapInMonths);
break;
case "Mdd":
interval = d3.time.day.range(minDate, maxDate, gapInDays);
break;
case "M1d":
interval = d3.time.day.range(minDate, maxDate, gapInDays);
break;
case "YY":
interval = d3.time.year.range(minDate, maxDate, gapInYears);
break;
case "QJan":
interval = d3.time.month.range(minDate, maxDate, 4);
break;
case "QJul":
interval = d3.time.month.range(minDate, maxDate, 4);
break;
case "h":
interval = d3.time.hour.range(minDate, maxDate, gapInHours);
break;
default:
interval = d3.time.year.range(minDate, maxDate, 1);
}
interval = cleanInterval(interval);
return {"format": dateFormat, "frequency": interval};
}
|
javascript
|
{
"resource": ""
}
|
q62688
|
validate_chart_model
|
test
|
function validate_chart_model(modelStr) {
var parsed;
try {
parsed = JSON.parse(modelStr);
} catch (e) {
throw new TypeError("Chart model is not valid JSON");
}
var isValidChartModel = (parsed.hasOwnProperty("chartProps") && parsed.hasOwnProperty("metadata"));
if (isValidChartModel) {
return parsed;
} else {
throw new TypeError("Not a valid Chartbuilder model");
}
}
|
javascript
|
{
"resource": ""
}
|
q62689
|
exact_ticks
|
test
|
function exact_ticks(domain, numticks) {
numticks -= 1;
var ticks = [];
var delta = domain[1] - domain[0];
var i;
for (i = 0; i < numticks; i++) {
ticks.push(domain[0] + (delta / numticks) * i);
}
ticks.push(domain[1]);
if (domain[1] * domain[0] < 0) {
//if the domain crosses zero, make sure there is a zero line
var hasZero = false;
for (i = ticks.length - 1; i >= 0; i--) {
//check if there is already a zero line
if (ticks[i] === 0) {
hasZero = true;
}
}
if (!hasZero) {
ticks.push(0);
}
}
return ticks;
}
|
javascript
|
{
"resource": ""
}
|
q62690
|
round_to_precision
|
test
|
function round_to_precision(num, precision, supress_thou_sep) {
//zero should always be "0"
if (num === 0) return "0";
var s = Math.round(num * Math.pow(10,precision)) / Math.pow(10,precision);
s = s + "";
s = s.split(".");
if (s.length == 1) {
s[1] = "";
}
if (s[1].length < precision) {
s[1] += Array(precision-s[1].length + 1).join("0");
}
if (!supress_thou_sep) {
s[0] = d3.format(",")(parseInt(s[0]));
}
if (precision === 0) {
return s[0];
}
return s.join(".");
}
|
javascript
|
{
"resource": ""
}
|
q62691
|
merge_or_apply
|
test
|
function merge_or_apply(defaults, source) {
var defaultKeys = keys(defaults);
var sourceKeys = keys(source);
return reduce(defaultKeys, function(result, key) {
if (sourceKeys.indexOf(key) > -1) {
result[key] = source[key];
return result;
} else {
result[key] = defaults[key];
return result;
}
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q62692
|
suggest_tick_num
|
test
|
function suggest_tick_num(domain) {
var MAX_TICKS = 10;
var INTERVAL_BASE_VALS = [1, 2, 2.5, 5, 10, 25];
var range = Math.abs(domain[0] - domain[1])
var minimum = range / MAX_TICKS;
var digits = Math.floor(range).toString().length;
var multiplier = Math.pow(10, (digits - 2));
var acceptable_intervals = reduce(INTERVAL_BASE_VALS, function(prev, curr) {
var mult = curr * multiplier;
if (mult >= minimum) {
prev = prev.concat([mult]);
}
return prev;
}, []);
for (var i = 0; i < acceptable_intervals.length; i++) {
var interval = acceptable_intervals[i]
if(range % interval == 0) {
return (range / interval) + 1
}
};
return 11;
}
|
javascript
|
{
"resource": ""
}
|
q62693
|
detectNumberSeparators
|
test
|
function detectNumberSeparators() {
var n = 1000.50;
var l = n.toLocaleString();
var s = n.toString();
var o = {
decimal: l.substring(5,6),
thousands: l.substring(1,2)
};
if (l.substring(5,6) == s.substring(5,6)) {
o.decimal = ".";
}
if (l.substring(1,2) == s.substring(1,2)) {
o.thousands = ",";
}
return o;
}
|
javascript
|
{
"resource": ""
}
|
q62694
|
transformerFactory
|
test
|
function transformerFactory(fileSet, info) {
return transformer
// Transformer. Adds references files to the set.
function transformer(ast, file) {
var filePath = file.path
var space = file.data
var links = []
var landmarks = {}
var references
var current
var link
var pathname
/* istanbul ignore if - stdin */
if (!filePath) {
return
}
references = gatherReferences(file, ast, info, fileSet)
current = getPathname(filePath)
for (link in references) {
pathname = getPathname(link)
if (
fileSet &&
pathname !== current &&
getHash(link) &&
links.indexOf(pathname) === -1
) {
links.push(pathname)
fileSet.add(pathname)
}
}
landmarks[filePath] = true
slugs.reset()
visit(ast, mark)
space[referenceId] = references
space[landmarkId] = landmarks
function mark(node) {
var data = node.data || {}
var props = data.hProperties || {}
var id = props.name || props.id || data.id
if (!id && node.type === 'heading') {
id = slugs.slug(toString(node))
}
if (id) {
landmarks[filePath + '#' + id] = true
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62695
|
validate
|
test
|
function validate(exposed, file) {
var references = file.data[referenceId]
var filePath = file.path
var reference
var nodes
var real
var hash
var pathname
var warning
var suggestion
var ruleId
for (reference in references) {
nodes = references[reference]
real = exposed[reference]
hash = getHash(reference)
// Check if files without `hash` can be linked to. Because there’s no need
// to inspect those files for headings they are not added to remark. This
// is especially useful because they might be non-markdown files. Here we
// check if they exist.
if ((real === undefined || real === null) && !hash && fs) {
real = fs.existsSync(path.join(file.cwd, decodeURI(reference)))
references[reference] = real
}
if (!real) {
if (hash) {
pathname = getPathname(reference)
warning = 'Link to unknown heading'
ruleId = headingRuleId
if (pathname !== filePath) {
warning += ' in `' + pathname + '`'
ruleId = headingInFileRuleId
}
warning += ': `' + hash + '`'
} else {
warning = 'Link to unknown file: `' + decodeURI(reference) + '`'
ruleId = fileRuleId
}
suggestion = getClosest(reference, exposed)
if (suggestion) {
warning += '. Did you mean `' + suggestion + '`'
}
warnAll(file, nodes, warning, ruleId)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62696
|
onresource
|
test
|
function onresource(node) {
var link = node.url
var definition
var index
var uri
var pathname
var hash
// Handle references.
if (node.identifier) {
definition = getDefinition(node.identifier)
link = definition && definition.url
}
// Ignore definitions without url.
if (!link) {
return
}
uri = parse(link)
// Drop `?search`
uri.search = ''
link = format(uri)
if (!fileSet && (uri.hostname || uri.pathname)) {
return
}
if (!uri.hostname) {
if (lines && lineExpression.test(uri.hash)) {
uri.hash = ''
}
// Handle hashes, or relative files.
if (!uri.pathname && uri.hash) {
link = file.path + uri.hash
uri = parse(link)
} else {
link = urljoin(file.dirname, link)
if (uri.hash) {
link += uri.hash
}
uri = parse(link)
}
}
// Handle full links.
if (uri.hostname) {
if (!prefix || !fileSet) {
return
}
if (
uri.hostname !== info.domain ||
uri.pathname.slice(0, prefix.length) !== prefix
) {
return
}
link = uri.pathname.slice(prefix.length) + (uri.hash || '')
// Things get interesting here: branches: `foo/bar/baz` could be `baz` on
// the `foo/bar` branch, or, `baz` in the `bar` directory on the `foo`
// branch.
// Currently, we’re ignoring this and just not supporting branches.
link = link.slice(link.indexOf('/') + 1)
}
// Handle file links, or combinations of files and hashes.
index = link.indexOf(headingPrefix)
if (index === -1) {
pathname = link
hash = null
} else {
pathname = link.slice(0, index)
hash = link.slice(index + headingPrefix.length)
if (lines && lineExpression.test(hash)) {
hash = null
}
}
if (!cache[pathname]) {
cache[pathname] = []
}
cache[pathname].push(node)
if (hash) {
link = pathname + '#' + hash
if (!cache[link]) {
cache[link] = []
}
cache[link].push(node)
}
}
|
javascript
|
{
"resource": ""
}
|
q62697
|
warnAll
|
test
|
function warnAll(file, nodes, reason, ruleId) {
nodes.forEach(one)
function one(node) {
file.message(reason, node, [sourceId, ruleId].join(':'))
}
}
|
javascript
|
{
"resource": ""
}
|
q62698
|
getClosest
|
test
|
function getClosest(pathname, references) {
var hash = getHash(pathname)
var base = getPathname(pathname)
var dictionary = []
var reference
var subhash
var subbase
for (reference in references) {
subbase = getPathname(reference)
subhash = getHash(reference)
if (getPathname(reference) === base) {
if (subhash && hash) {
dictionary.push(subhash)
}
} else if (!subhash && !hash) {
dictionary.push(subbase)
}
}
return propose(hash ? hash : base, dictionary, {threshold: 0.7})
}
|
javascript
|
{
"resource": ""
}
|
q62699
|
getHash
|
test
|
function getHash(uri) {
var hash = parse(uri).hash
return hash ? hash.slice(1) : null
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.