_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q4700
|
bcscale
|
train
|
function bcscale(scale) {
scale = parseInt(scale, 10);
if (isNaN(scale)) {
return false;
}
if (scale < 0) {
return false;
}
libbcmath.scale = scale;
return true;
}
|
javascript
|
{
"resource": ""
}
|
q4701
|
bcdiv
|
train
|
function bcdiv(left_operand, right_operand, scale) {
var first, second, result;
if (typeof(scale) == 'undefined') {
scale = libbcmath.scale;
}
scale = ((scale < 0) ? 0 : scale);
// create objects
first = libbcmath.bc_init_num();
second = libbcmath.bc_init_num();
result = libbcmath.bc_init_num();
first = libbcmath.php_str2num(left_operand.toString());
second = libbcmath.php_str2num(right_operand.toString());
// normalize arguments to same scale.
if (first.n_scale > second.n_scale) second.setScale(first.n_scale);
if (second.n_scale > first.n_scale) first.setScale(second.n_scale);
result = libbcmath.bc_divide(first, second, scale);
if (result === -1) {
// error
throw new Error(11, "(BC) Division by zero");
}
if (result.n_scale > scale) {
result.n_scale = scale;
}
return result.toString();
}
|
javascript
|
{
"resource": ""
}
|
q4702
|
bcmul
|
train
|
function bcmul(left_operand, right_operand, scale) {
var first, second, result;
if (typeof(scale) == 'undefined') {
scale = libbcmath.scale;
}
scale = ((scale < 0) ? 0 : scale);
// create objects
first = libbcmath.bc_init_num();
second = libbcmath.bc_init_num();
result = libbcmath.bc_init_num();
first = libbcmath.php_str2num(left_operand.toString());
second = libbcmath.php_str2num(right_operand.toString());
// normalize arguments to same scale.
if (first.n_scale > second.n_scale) second.setScale(first.n_scale);
if (second.n_scale > first.n_scale) first.setScale(second.n_scale);
result = libbcmath.bc_multiply(first, second, scale);
if (result.n_scale > scale) {
result.n_scale = scale;
}
return result.toString();
}
|
javascript
|
{
"resource": ""
}
|
q4703
|
ensureAnArray
|
train
|
function ensureAnArray (arr) {
if (Object.prototype.toString.call(arr) === '[object Array]') {
return arr;
} else if (arr === null || arr === void 0) {
return [];
} else {
return [arr];
}
}
|
javascript
|
{
"resource": ""
}
|
q4704
|
renderTouches
|
train
|
function renderTouches(touches, element) {
touches.forEach(function(touch) {
var el = document.createElement('div');
el.style.width = '20px';
el.style.height = '20px';
el.style.background = 'red';
el.style.position = 'fixed';
el.style.top = touch.y +'px';
el.style.left = touch.x +'px';
el.style.borderRadius = '100%';
el.style.border = 'solid 2px #000';
el.style.zIndex = 6000;
element.appendChild(el);
setTimeout(function() {
el && el.parentNode && el.parentNode.removeChild(el);
el = null;
}, 100);
});
}
|
javascript
|
{
"resource": ""
}
|
q4705
|
trigger
|
train
|
function trigger(touches, element, type) {
return Simulator.events[Simulator.type].trigger(touches, element, type);
}
|
javascript
|
{
"resource": ""
}
|
q4706
|
train
|
function(msg, errno) {
if (output && config.file) {
output.close()
}
if (msg) {
stderr.writeLine(msg)
}
return phantom.exit(errno || 1)
}
|
javascript
|
{
"resource": ""
}
|
|
q4707
|
train
|
function() {
this.n_sign = null; // sign
this.n_len = null; /* (int) The number of digits before the decimal point. */
this.n_scale = null; /* (int) The number of digits after the decimal point. */
//this.n_refs = null; /* (int) The number of pointers to this number. */
//this.n_text = null; /* ?? Linked list for available list. */
this.n_value = null; /* array as value, where 1.23 = [1,2,3] */
this.toString = function() {
var r, tmp;
tmp=this.n_value.join('');
// add minus sign (if applicable) then add the integer part
r = ((this.n_sign == libbcmath.PLUS) ? '' : this.n_sign) + tmp.substr(0, this.n_len);
// if decimal places, add a . and the decimal part
if (this.n_scale > 0) {
r += '.' + tmp.substr(this.n_len, this.n_scale);
}
return r;
};
this.setScale = function(newScale) {
while (this.n_scale < newScale) {
this.n_value.push(0);
this.n_scale++;
}
while (this.n_scale > newScale) {
this.n_value.pop();
this.n_scale--;
}
return this;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4708
|
train
|
function(str) {
var p;
p = str.indexOf('.');
if (p==-1) {
return libbcmath.bc_str2num(str, 0);
} else {
return libbcmath.bc_str2num(str, (str.length-p));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4709
|
train
|
function(r, ptr, chr, len) {
var i;
for (i=0;i<len;i++) {
r[ptr+i] = chr;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4710
|
train
|
function(num) {
var count; // int
var nptr; // int
/* Quick check. */
//if (num == BCG(_zero_)) return TRUE;
/* Initialize */
count = num.n_len + num.n_scale;
nptr = 0; //num->n_value;
/* The check */
while ((count > 0) && (num.n_value[nptr++] === 0)) {
count--;
}
if (count !== 0) {
return false;
} else {
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4711
|
Conf
|
train
|
function Conf(config, _pg) {
if (typeof config === 'string') config = {connectionString: config};
this._config = config;
this._pg = _pg || pg;
this._pool = this._pg.Pool(config);
}
|
javascript
|
{
"resource": ""
}
|
q4712
|
train
|
function (tweets, search, includeHighlighted) {
var updated = [], tmp, i = 0;
if (typeof search == 'string') {
search = this.format(search);
}
for (i = 0; i < tweets.length; i++) {
if (this.match(tweets[i], search, includeHighlighted)) {
updated.push(tweets[i]);
}
}
return updated;
}
|
javascript
|
{
"resource": ""
}
|
|
q4713
|
train
|
function(){
angular.element(document.querySelector('body')).removeClass('jr_active jr_overlay_show');
removeJoyride();
scope.joyride.current = 0;
scope.joyride.transitionStep = true;
if (typeof scope.joyride.config.onFinish === "function") {
scope.joyride.config.onFinish();
}
if (document.querySelector(".jr_target")) {
angular.element(document.querySelector(".jr_target")).removeClass('jr_target');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4714
|
train
|
function (connection, collections, cb) {
if (!connection.identity) return cb(Errors.IdentityMissing);
if (connections[connection.identity]) return cb(Errors.IdentityDuplicate);
// Store the connection
connections[connection.identity] = {
config: connection,
collections: collections,
client: null
};
// connect to database
new Connection(connection, function (err, client) {
if (err) return cb(err);
connections[connection.identity].client = client;
// Build up a registry of collections
Object.keys(collections).forEach(function (key) {
connections[connection.identity].collections[key] = new Collection(collections[key], client);
});
// execute callback
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q4715
|
train
|
function(cb) {
var collection = connectionObject.collections[collectionName];
if (!collection) return cb(Errors.CollectionNotRegistered);
collection.dropTable(function(err) {
// ignore "table does not exist" error
if (err && err.code === 8704) return cb();
if (err) return cb(err);
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q4716
|
addDropdownToMenu
|
train
|
function addDropdownToMenu(dropdownName, routerName, glyphiconName, enableTranslation, clientFramework) {
let navbarPath;
try {
if (clientFramework === 'angular1') {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [ `<li ng-class="{active: vm.$state.includes('${dropdownName}')}" ng-switch-when="true" uib-dropdown class="dropdown pointer">
<a class="dropdown-toggle" uib-dropdown-toggle href="" id="${dropdownName}-menu">
<span>
<span class="glyphicon glyphicon-${glyphiconName}"></span>
<span class="hidden-sm" data-translate="global.menu.${dropdownName}.main">
${dropdownName}
</span>
<b class="caret"></b>
</span>
</a>
<ul class="dropdown-menu" uib-dropdown-menu>
<li ui-sref-active="active">
<a ui-sref="${routerName}" ng-click="vm.collapseNavbar()">
<span class="glyphicon glyphicon-${glyphiconName}"></span>
<span${enableTranslation ? ` data-translate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>
<!-- jhipster-needle-add-element-to-${dropdownName} - JHipster will add elements to the ${dropdownName} here -->
</ul>
</li>`
]
}, this);
} else {
navbarPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
jhipsterUtils.rewriteFile({
file: navbarPath,
needle: 'jhipster-needle-add-element-to-menu',
splicable: [`<li *ngSwitchCase="true" ngbDropdown class="nav-item dropdown pointer">
<a class="nav-link dropdown-toggle" routerLinkActive="active" ngbDropdownToggle href="javascript:void(0);" id="${dropdownName}-menu">
<span>
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span>${dropdownName}</span>
</span>
</a>
<ul class="dropdown-menu" ngbDropdownMenu>
<li>
<a class="dropdown-item" routerLink="${routerName}" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" (click)="collapseNavbar()">
<i class="fa fa-${glyphiconName}" aria-hidden="true"></i>
<span${enableTranslation ? ` jhiTranslate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}</span>
</a>
</li>
<!-- jhipster-needle-add-element-to-${dropdownName} - JHipster will add elements to the ${dropdownName} here -->
</ul>
</li>`
]
}, this);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + navbarPath + chalk.yellow(' or missing required jhipster-needle. Reference to ') + dropdownName} ${chalk.yellow('not added to menu.\n')}`);
this.debug('Error:', e);
this.log('Error:', e);
}
}
|
javascript
|
{
"resource": ""
}
|
q4717
|
addPageSetsModule
|
train
|
function addPageSetsModule(clientFramework) {
let appModulePath;
try {
if (clientFramework !== 'angular1') {
appModulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
const fullPath = path.join(process.cwd(), appModulePath);
let args = {
file: appModulePath
};
args.haystack = this.fs.read(fullPath);
args.needle = `import { ${this.angularXAppName}EntityModule } from './entities/entity.module';`;
args.splicable = [`import { ${this.angularXAppName}PageSetsModule } from './pages/page-sets.module';`]
args.haystack = jhipsterUtils.rewrite(args);
args.needle = `${this.angularXAppName}AccountModule,`;
args.splicable = [`${this.angularXAppName}PageSetsModule,`]
args.haystack = jhipsterUtils.rewrite(args);
this.fs.write(fullPath, args.haystack);
}
} catch (e) {
this.log(`${chalk.yellow('\nUnable to find ') + appModulePath + chalk.yellow('. Reference to PageSets module not added to App module.\n')}`);
this.log('Error:', e);
}
}
|
javascript
|
{
"resource": ""
}
|
q4718
|
trigger_service_login
|
train
|
function trigger_service_login (msg, respond) {
var seneca = this
if (!msg.user) {
return respond(null, {ok: false, why: 'no-user'})
}
var user_data = msg.user
var q = {}
if (user_data.identifier) {
q[msg.service + '_id'] = user_data.identifier
user_data[msg.service + '_id'] = user_data.identifier
}
else {
return respond(null, {ok: false, why: 'no-identifier'})
}
seneca.act("role: 'user', get: 'user'", q, function (err, data) {
if (err) return respond(null, {ok: false, why: 'no-identifier'})
if (!data.ok) return respond(null, {ok: false, why: data.why})
var user = data.user
if (!user) {
seneca.act("role:'user',cmd:'register'", user_data, function (err, out) {
if (err) {
return respond(null, {ok: false, why: err})
}
respond(null, out.user)
})
}
else {
seneca.act("role:'user',cmd:'update'", user_data, function (err, out) {
if (err) {
return respond(null, {ok: false, why: err})
}
respond(null, out.user)
})
}
})
}
|
javascript
|
{
"resource": ""
}
|
q4719
|
readPackageJSON
|
train
|
function readPackageJSON () {
var pkg = JSON.parse(require('fs').readFileSync('./package.json'));
var dependencies = pkg.dependencies ? Object.keys(pkg.dependencies) : [];
var peerDependencies = pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : [];
return {
name: pkg.name,
deps: dependencies.concat(peerDependencies),
aliasify: pkg.aliasify
};
}
|
javascript
|
{
"resource": ""
}
|
q4720
|
initTasks
|
train
|
function initTasks (gulp, config) {
var pkg = readPackageJSON();
var name = capitalize(camelCase(config.component.pkgName || pkg.name));
config = defaults(config, { aliasify: pkg.aliasify });
config.component = defaults(config.component, {
pkgName: pkg.name,
dependencies: pkg.deps,
name: name,
src: 'src',
lib: 'lib',
dist: 'dist',
file: (config.component.name || name) + '.js'
});
if (config.example) {
if (config.example === true) config.example = {};
defaults(config.example, {
src: 'example/src',
dist: 'example/dist',
files: ['index.html'],
scripts: ['example.js'],
less: ['example.less']
});
}
require('./tasks/bump')(gulp, config);
require('./tasks/dev')(gulp, config);
require('./tasks/dist')(gulp, config);
require('./tasks/release')(gulp, config);
var buildTasks = ['build:dist'];
var cleanTasks = ['clean:dist'];
if (config.component.lib) {
require('./tasks/lib')(gulp, config);
buildTasks.push('build:lib');
cleanTasks.push('clean:lib');
}
if (config.example) {
require('./tasks/examples')(gulp, config);
buildTasks.push('build:examples');
cleanTasks.push('clean:examples');
}
gulp.task('build', buildTasks);
gulp.task('clean', cleanTasks);
}
|
javascript
|
{
"resource": ""
}
|
q4721
|
makeOptionsObj
|
train
|
function makeOptionsObj(port, host, inUse, retryTimeMs, timeOutMs) {
var opts = {};
opts.port = port;
opts.host = host;
opts.inUse = inUse;
opts.retryTimeMs = retryTimeMs;
opts.timeOutMs = timeOutMs;
return opts;
}
|
javascript
|
{
"resource": ""
}
|
q4722
|
cmd_logout
|
train
|
function cmd_logout (msg, respond) {
var req = msg.req$
// get token from request
req.seneca.act("role: 'auth', get: 'token'", {tokenkey: options.tokenkey}, function (err, clienttoken) {
if (err) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
if (!clienttoken) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
clienttoken = clienttoken.token
// delete token
req.seneca.act("role: 'auth', set: 'token'", {tokenkey: options.tokenkey}, function (err) {
if (err) {
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
}
req.seneca.act("role:'user',cmd:'logout'", {token: clienttoken}, function (err) {
if (err) {
req.seneca.log('error ', err)
}
req.cookieAuth.clear()
delete req.seneca.user
delete req.seneca.login
return req.seneca.act('role: auth, do: respond', {err: err, action: 'logout', req: req}, respond)
})
})
})
}
|
javascript
|
{
"resource": ""
}
|
q4723
|
extract
|
train
|
function extract(str, options, tranformFn) {
let extractor = new Extractor(options, tranformFn);
return extractor.extract(str);
}
|
javascript
|
{
"resource": ""
}
|
q4724
|
train
|
function( grunt, options, callback ) {
this.callback = callback;
this.diffCount = 0;
this.grunt = grunt;
this.options = options;
this.options.indexPath = this.getIndexPath();
this.pictureCount = 0;
if ( typeof options.template === 'string' ) {
this.template = options.template;
} else if ( typeof options.template === 'object' ) {
this.template = options.template.name;
}
this.movePictures();
this.pictures = this.getPreparedPictures();
}
|
javascript
|
{
"resource": ""
}
|
|
q4725
|
train
|
function(treeType) {
if (treeType === 'vendor') {
// The treeForVendor returns a different value based on whether or not
// this addon is a nested dependency
return caclculateCacheKeyForTree(treeType, this, [!this.parent.parent]);
} else {
return this._super.cacheKeyForTree.call(this, treeType);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4726
|
train
|
function(elem) {
this.getOffset._offset = $(elem).offset();
if (Garnish.$scrollContainer[0] !== Garnish.$win[0]) {
this.getOffset._offset.top += Garnish.$scrollContainer.scrollTop();
this.getOffset._offset.left += Garnish.$scrollContainer.scrollLeft();
}
return this.getOffset._offset;
}
|
javascript
|
{
"resource": ""
}
|
|
q4727
|
train
|
function(source, target) {
var $source = $(source),
$target = $(target);
$target.css({
fontFamily: $source.css('fontFamily'),
fontSize: $source.css('fontSize'),
fontWeight: $source.css('fontWeight'),
letterSpacing: $source.css('letterSpacing'),
lineHeight: $source.css('lineHeight'),
textAlign: $source.css('textAlign'),
textIndent: $source.css('textIndent'),
whiteSpace: $source.css('whiteSpace'),
wordSpacing: $source.css('wordSpacing'),
wordWrap: $source.css('wordWrap')
});
}
|
javascript
|
{
"resource": ""
}
|
|
q4728
|
train
|
function() {
Garnish.getBodyScrollTop._scrollTop = document.body.scrollTop;
if (Garnish.getBodyScrollTop._scrollTop < 0) {
Garnish.getBodyScrollTop._scrollTop = 0;
}
else {
Garnish.getBodyScrollTop._maxScrollTop = Garnish.$bod.outerHeight() - Garnish.$win.height();
if (Garnish.getBodyScrollTop._scrollTop > Garnish.getBodyScrollTop._maxScrollTop) {
Garnish.getBodyScrollTop._scrollTop = Garnish.getBodyScrollTop._maxScrollTop;
}
}
return Garnish.getBodyScrollTop._scrollTop;
}
|
javascript
|
{
"resource": ""
}
|
|
q4729
|
train
|
function(container, elem) {
var $elem;
if (typeof elem === 'undefined') {
$elem = $(container);
$container = $elem.scrollParent();
}
else {
var $container = $(container);
$elem = $(elem);
}
if ($container.prop('nodeName') === 'HTML' || $container[0] === Garnish.$doc[0]) {
$container = Garnish.$win;
}
var scrollTop = $container.scrollTop(),
elemOffset = $elem.offset().top;
var elemScrollOffset;
if ($container[0] === window) {
elemScrollOffset = elemOffset - scrollTop;
}
else {
elemScrollOffset = elemOffset - $container.offset().top;
}
var targetScrollTop = false;
// Is the element above the fold?
if (elemScrollOffset < 0) {
targetScrollTop = scrollTop + elemScrollOffset - 10;
}
else {
var elemHeight = $elem.outerHeight(),
containerHeight = ($container[0] === window ? window.innerHeight : $container[0].clientHeight);
// Is it below the fold?
if (elemScrollOffset + elemHeight > containerHeight) {
targetScrollTop = scrollTop + (elemScrollOffset - (containerHeight - elemHeight)) + 10;
}
}
if (targetScrollTop !== false) {
// Velocity only allows you to scroll to an arbitrary position if you're scrolling the main window
if ($container[0] === window) {
$('html').velocity('scroll', {
offset: targetScrollTop + 'px',
mobileHA: false
});
}
else {
$container.scrollTop(targetScrollTop);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4730
|
train
|
function(elem, prop) {
var $elem = $(elem);
if (!prop) {
prop = 'margin-left';
}
var startingPoint = parseInt($elem.css(prop));
if (isNaN(startingPoint)) {
startingPoint = 0;
}
for (var i = 0; i <= Garnish.SHAKE_STEPS; i++) {
(function(i) {
setTimeout(function() {
Garnish.shake._properties = {};
Garnish.shake._properties[prop] = startingPoint + (i % 2 ? -1 : 1) * (10 - i);
$elem.velocity(Garnish.shake._properties, Garnish.SHAKE_STEP_DURATION);
}, (Garnish.SHAKE_STEP_DURATION * i));
})(i);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4731
|
train
|
function(container) {
var postData = {},
arrayInputCounters = {},
$inputs = Garnish.findInputs(container);
var inputName;
for (var i = 0; i < $inputs.length; i++) {
var $input = $inputs.eq(i);
if ($input.prop('disabled')) {
continue;
}
inputName = $input.attr('name');
if (!inputName) {
continue;
}
var inputVal = Garnish.getInputPostVal($input);
if (inputVal === null) {
continue;
}
var isArrayInput = (inputName.substr(-2) === '[]');
if (isArrayInput) {
// Get the cropped input name
var croppedName = inputName.substring(0, inputName.length - 2);
// Prep the input counter
if (typeof arrayInputCounters[croppedName] === 'undefined') {
arrayInputCounters[croppedName] = 0;
}
}
if (!Garnish.isArray(inputVal)) {
inputVal = [inputVal];
}
for (var j = 0; j < inputVal.length; j++) {
if (isArrayInput) {
inputName = croppedName + '[' + arrayInputCounters[croppedName] + ']';
arrayInputCounters[croppedName]++;
}
postData[inputName] = inputVal[j];
}
}
return postData;
}
|
javascript
|
{
"resource": ""
}
|
|
q4732
|
train
|
function(ev) {
ev.preventDefault();
this.realMouseX = ev.pageX;
this.realMouseY = ev.pageY;
if (this.settings.axis !== Garnish.Y_AXIS) {
this.mouseX = ev.pageX;
}
if (this.settings.axis !== Garnish.X_AXIS) {
this.mouseY = ev.pageY;
}
this.mouseDistX = this.mouseX - this.mousedownX;
this.mouseDistY = this.mouseY - this.mousedownY;
if (!this.dragging) {
// Has the mouse moved far enough to initiate dragging yet?
this._handleMouseMove._mouseDist = Garnish.getDist(this.mousedownX, this.mousedownY, this.realMouseX, this.realMouseY);
if (this._handleMouseMove._mouseDist >= Garnish.BaseDrag.minMouseDist) {
this.startDragging();
}
}
if (this.dragging) {
this.drag(true);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4733
|
train
|
function($newDraggee) {
if (!$newDraggee.length) {
return;
}
if (!this.settings.collapseDraggees) {
var oldLength = this.$draggee.length;
}
this.$draggee = $(this.$draggee.toArray().concat($newDraggee.toArray()));
// Create new helpers?
if (!this.settings.collapseDraggees) {
var newLength = this.$draggee.length;
for (var i = oldLength; i < newLength; i++) {
this._createHelper(i);
}
}
if (this.settings.removeDraggee || this.settings.collapseDraggees) {
$newDraggee.hide();
}
else {
$newDraggee.css('visibility', 'hidden');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4734
|
train
|
function() {
this._returningHelpersToDraggees = true;
for (var i = 0; i < this.helpers.length; i++) {
var $draggee = this.$draggee.eq(i),
$helper = this.helpers[i];
$draggee.css({
display: this.draggeeDisplay,
visibility: 'hidden'
});
var draggeeOffset = $draggee.offset();
var callback;
if (i === 0) {
callback = $.proxy(this, '_showDraggee');
}
else {
callback = null;
}
$helper.velocity({left: draggeeOffset.left, top: draggeeOffset.top}, Garnish.FX_DURATION, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4735
|
train
|
function() {
// Has the mouse moved?
if (this.mouseX !== this.lastMouseX || this.mouseY !== this.lastMouseY) {
// Get the new target helper positions
for (this._updateHelperPos._i = 0; this._updateHelperPos._i < this.helpers.length; this._updateHelperPos._i++) {
this.helperTargets[this._updateHelperPos._i] = this._getHelperTarget(this._updateHelperPos._i);
}
this.lastMouseX = this.mouseX;
this.lastMouseY = this.mouseY;
}
// Gravitate helpers toward their target positions
for (this._updateHelperPos._j = 0; this._updateHelperPos._j < this.helpers.length; this._updateHelperPos._j++) {
this._updateHelperPos._lag = this.settings.helperLagBase + (this.helperLagIncrement * this._updateHelperPos._j);
this.helperPositions[this._updateHelperPos._j] = {
left: this.helperPositions[this._updateHelperPos._j].left + ((this.helperTargets[this._updateHelperPos._j].left - this.helperPositions[this._updateHelperPos._j].left) / this._updateHelperPos._lag),
top: this.helperPositions[this._updateHelperPos._j].top + ((this.helperTargets[this._updateHelperPos._j].top - this.helperPositions[this._updateHelperPos._j].top) / this._updateHelperPos._lag)
};
this.helpers[this._updateHelperPos._j].css(this.helperPositions[this._updateHelperPos._j]);
}
// Let's do this again on the next frame!
this.updateHelperPosFrame = Garnish.requestAnimationFrame(this.updateHelperPosProxy);
}
|
javascript
|
{
"resource": ""
}
|
|
q4736
|
train
|
function(i) {
return {
left: this.getHelperTargetX() + (this.settings.helperSpacingX * i),
top: this.getHelperTargetY() + (this.settings.helperSpacingY * i)
};
}
|
javascript
|
{
"resource": ""
}
|
|
q4737
|
train
|
function() {
for (var i = 0; i < this.helpers.length; i++) {
(function($draggeeHelper) {
$draggeeHelper.velocity('fadeOut', {
duration: Garnish.FX_DURATION,
complete: function() {
$draggeeHelper.remove();
}
});
})(this.helpers[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4738
|
train
|
function(bodyContents) {
// Cleanup
this.$main.html('');
if (this.$header) {
this.$hud.removeClass('has-header');
this.$header.remove();
this.$header = null;
}
if (this.$footer) {
this.$hud.removeClass('has-footer');
this.$footer.remove();
this.$footer = null;
}
// Append the new body contents
this.$main.append(bodyContents);
// Look for a header and footer
var $header = this.$main.find('.' + this.settings.headerClass + ':first'),
$footer = this.$main.find('.' + this.settings.footerClass + ':first');
if ($header.length) {
this.$header = $header.insertBefore(this.$mainContainer);
this.$hud.addClass('has-header');
}
if ($footer.length) {
this.$footer = $footer.insertAfter(this.$mainContainer);
this.$hud.addClass('has-footer');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4739
|
train
|
function($item, preventScroll) {
if (preventScroll) {
var scrollLeft = Garnish.$doc.scrollLeft(),
scrollTop = Garnish.$doc.scrollTop();
$item.focus();
window.scrollTo(scrollLeft, scrollTop);
}
else {
$item.focus();
}
this.$focusedItem = $item;
this.trigger('focusItem', {item: $item});
}
|
javascript
|
{
"resource": ""
}
|
|
q4740
|
train
|
function(ev) {
// ignore right clicks
if (ev.which !== Garnish.PRIMARY_CLICK) {
return;
}
// Enfore the filter
if (this.settings.filter && !$(ev.target).is(this.settings.filter)) {
return;
}
var $item = $($.data(ev.currentTarget, 'select-item'));
// was this a click?
if (
!this._actAsCheckbox(ev) && !ev.shiftKey &&
ev.currentTarget === this.mousedownTarget
) {
// If this is already selected, wait a moment to see if this is a double click before making any rash decisions
if (this.isSelected($item)) {
this.clearMouseUpTimeout();
this.mouseUpTimeout = setTimeout($.proxy(function() {
this.deselectOthers($item);
}, this), 300);
}
else {
this.deselectAll();
this.selectItem($item, true, true);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4741
|
train
|
function(item) {
var $handle = $.data(item, 'select-handle');
if ($handle) {
$handle.removeData('select-item');
this.removeAllListeners($handle);
}
$.removeData(item, 'select');
$.removeData(item, 'select-handle');
if (this.$focusedItem && this.$focusedItem[0] === item) {
this.$focusedItem = null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4742
|
loadCurrentVersion
|
train
|
function loadCurrentVersion (options, context) {
return new Extension(options, context).read()
.then(function (response) {
let version = response.sys.version;
options.version = version;
return options;
});
}
|
javascript
|
{
"resource": ""
}
|
q4743
|
train
|
function(err) {
notify.onError({
title: "Garnish",
message: "Error: <%= error.message %>",
sound: "Beep"
})(err);
console.log( 'plumber error!' );
this.emit('end');
}
|
javascript
|
{
"resource": ""
}
|
|
q4744
|
all
|
train
|
function all(subreddit) {
const eventEmitter = new EventEmitter();
function emitRandomImage(subreddit) {
randomPuppy(subreddit).then(imageUrl => {
eventEmitter.emit('data', imageUrl + '#' + subreddit);
if (eventEmitter.listeners('data').length) {
setTimeout(() => emitRandomImage(subreddit), 200);
}
});
}
emitRandomImage(subreddit);
return eventEmitter;
}
|
javascript
|
{
"resource": ""
}
|
q4745
|
train
|
function(dbOrUri, stream, callback) {
if (arguments.length === 2) {
callback = stream;
stream = undefined;
}
if (!stream) {
stream = process.stdout;
}
var db;
var out = stream;
var endOfCollection = crypto.pseudoRandomBytes(8).toString('base64');
write({
type: 'mongo-dump-stream',
version: '2',
endOfCollection: endOfCollection
});
return async.series({
connect: function(callback) {
if (typeof(dbOrUri) !== 'string') {
// Already a mongodb connection
db = dbOrUri;
return setImmediate(callback);
}
return mongodb.MongoClient.connect(dbOrUri, function(err, _db) {
if (err) {
return callback(err);
}
db = _db;
return callback(null);
});
},
getCollections: function(callback) {
return db.collections(function(err, _collections) {
if (err) {
return callback(err);
}
collections = _collections;
return callback(null);
});
},
dumpCollections: function(callback) {
return async.eachSeries(collections, function(collection, callback) {
if (collection.collectionName.match(/^system\./)) {
return setImmediate(callback);
}
return async.series({
getIndexes: function(callback) {
return collection.indexInformation({ full: true }, function(err, info) {
if (err) {
return callback(err);
}
write({
type: 'collection',
name: collection.collectionName,
indexes: info
});
return callback(null);
});
},
getDocuments: function(callback) {
var cursor = collection.find({}, { raw: true });
iterate();
function iterate() {
return cursor.nextObject(function(err, item) {
if (err) {
return callback(err);
}
if (!item) {
write({
// Ensures we don't confuse this with
// a legitimate database object
endOfCollection: endOfCollection
});
return callback(null);
}
// v2: just a series of actual data documents
out.write(item);
// If we didn't have the raw BSON document,
// we could do this instead, but it would be very slow
// write({
// type: 'document',
// document: item
// });
return setImmediate(iterate);
});
}
},
}, callback);
}, callback);
},
endDatabase: function(callback) {
write({
type: 'endDatabase'
}, callback);
}
}, function(err) {
if (err) {
return callback(err);
}
return callback(null);
});
function write(o, callback) {
out.write(BSON.serialize(o, false, true, false), callback);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4746
|
escapes
|
train
|
function escapes(options) {
var settings = options || {}
if (settings.commonmark) {
return commonmark
}
return settings.gfm ? gfm : defaults
}
|
javascript
|
{
"resource": ""
}
|
q4747
|
parseModifiers
|
train
|
function parseModifiers(packet, bits) {
/* eslint-disable no-bitwise */
/* eslint-disable no-param-reassign */
packet.modifiers.l_control = ((bits & 1) !== 0);
packet.modifiers.l_shift = ((bits & 2) !== 0);
packet.modifiers.l_alt = ((bits & 4) !== 0);
packet.modifiers.l_meta = ((bits & 8) !== 0);
packet.modifiers.r_control = ((bits & 16) !== 0);
packet.modifiers.r_shift = ((bits & 32) !== 0);
packet.modifiers.r_alt = ((bits & 64) !== 0);
packet.modifiers.r_meta = ((bits & 128) !== 0);
/* eslint-enable no-bitwise */
/* eslint-enable no-param-reassign */
}
|
javascript
|
{
"resource": ""
}
|
q4748
|
parseKeyCodes
|
train
|
function parseKeyCodes(arr, keys) {
if (typeof keys !== 'object') { return false; }
keys.forEach((key) => {
if (key > 3) { arr.keyCodes.push(key); }
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
q4749
|
parseErrorState
|
train
|
function parseErrorState(packet, state) {
let states = 0;
state.forEach((s) => {
if (s === 1) {
states += 1;
}
});
if (states >= 6) {
packet.errorStatus = true; // eslint-disable-line no-param-reassign
}
}
|
javascript
|
{
"resource": ""
}
|
q4750
|
stack
|
train
|
function stack(e) {
return {
toString: function() {
// first line is err.message, which we already show, so start from
// second line
return e.stack.substr(e.stack.indexOf('\n'));
},
toJSON: function() {
return stacktrace.parse(e);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q4751
|
getFirstHeader
|
train
|
function getFirstHeader (req, header) {
const value = req.headers[header]
return (Array.isArray(value) ? value[0] : value).split(', ')[0]
}
|
javascript
|
{
"resource": ""
}
|
q4752
|
Application
|
train
|
function Application(ctx, config) {
// validate params
if (!ctx && !config) {
// both empty
ctx = document;
config = {};
}
else if (Utils.isNode(config)) {
// reverse order of arguments
var tmpConfig = config;
config = ctx;
ctx = tmpConfig;
}
else if (!Utils.isNode(ctx) && !config) {
// only config is given
config = ctx;
ctx = document;
}
else if (Utils.isNode(ctx) && !config) {
// only ctx is given
config = {};
}
var defaults = {
namespace: Module
};
config = Utils.extend(defaults, config);
/**
* The context node.
*
* @property _ctx
* @type Node
*/
this._ctx = Utils.getElement(ctx);
/**
* The configuration.
*
* @property config
* @type Object
*/
this._config = config;
/**
* The sandbox to get the resources from.
* The singleton is shared between all modules.
*
* @property _sandbox
* @type Sandbox
*/
this._sandbox = new Sandbox(this);
/**
* Contains references to all modules on the page.
*
* @property _modules
* @type Object
*/
this._modules = {};
/**
* The next unique module id to use.
*
* @property id
* @type Number
*/
this._id = 1;
}
|
javascript
|
{
"resource": ""
}
|
q4753
|
train
|
function (options, callback) {
LOG.debug('preauth#createPreauth called');
LOG.debug('Validating options');
try {
options = new preauthOptions.CreatePreauth().validate(options);
} catch (err) {
if (err.name === 'InvalidOption') {
LOG.error('Invalid options specified: %s', err.message);
callback(
commonErrors.InvalidOption(
undefined,
{
message: err.message
}
)
);
} else {
LOG.error('System error: %s', err.message);
callback(
commonErrors.SystemError(
undefined,
{
message: err.message
}
)
);
}
return;
}
var timestamp = options.timestamp;
if (!timestamp) {
timestamp = new Date().getTime();
}
LOG.debug('Generating preauth key');
var pakCreator = crypto.createHmac('sha1', options.key)
.setEncoding('hex');
pakCreator.write(
util.format(
'%s|%s|%s|%s',
options.byValue,
options.by,
options.expires,
timestamp
)
);
pakCreator.end();
var pak = pakCreator.read();
LOG.debug('Returning preauth key %s', pak);
callback(null, pak);
}
|
javascript
|
{
"resource": ""
}
|
|
q4754
|
loadCss
|
train
|
function loadCss() {
var cssFileName = fs.path.join(fs.knownFolders.currentApp().path, application.cssFile);
var applicationCss;
if (FSA.fileExists(cssFileName)) {
FSA.readText(cssFileName, function (r) { applicationCss = r; });
//noinspection JSUnusedAssignment
application.cssSelectorsCache = styleScope.StyleScope.createSelectorsFromCss(applicationCss, cssFileName);
// Add New CSS to Current Page
var f = frameCommon.topmost();
if (f && f.currentPage) {
f.currentPage._resetCssValues();
f.currentPage._styleScope = new styleScope.StyleScope();
//noinspection JSUnusedAssignment
f.currentPage._addCssInternal(applicationCss, cssFileName);
f.currentPage._refreshCss();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4755
|
loadPageCss
|
train
|
function loadPageCss(cssFile) {
var cssFileName;
// Eliminate the ./ on the file if present so that we can add the full path
if (cssFile.startsWith("./")) {
cssFile = cssFile.substring(2);
}
if (cssFile.startsWith(UpdaterSingleton.currentAppPath())) {
cssFileName = cssFile;
} else {
cssFileName = fs.path.join(UpdaterSingleton.currentAppPath(), cssFile);
}
var applicationCss;
if (FSA.fileExists(cssFileName)) {
FSA.readText(cssFileName, function (r) { applicationCss = r; });
// Add New CSS to Current Page
var f = frameCommon.topmost();
if (f && f.currentPage) {
f.currentPage._resetCssValues();
f.currentPage._styleScope = new styleScope.StyleScope();
//noinspection JSUnusedAssignment
f.currentPage._addCssInternal(applicationCss, cssFileName);
f.currentPage._refreshCss();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4756
|
ResponseApi
|
train
|
function ResponseApi(constructorOptions) {
LOG.debug('Instantiating new response object');
LOG.debug('Validating options');
try {
this.options =
new responseOptions.Constructor().validate(constructorOptions);
} catch (err) {
LOG.error('Received error: %s', err);
throw(err);
}
this.response = {};
this.isBatch = false;
this._createResponseView();
}
|
javascript
|
{
"resource": ""
}
|
q4757
|
wrapFieldsWithMiddleware
|
train
|
function wrapFieldsWithMiddleware(type, deepWrap = true, typeMet = {}) {
if (!type) {
return;
}
let fields = type._fields;
typeMet[type.name] = true;
for (let label in fields) {
let field = fields[label];
if (field && !typeMet[field.type.name]) {
if (!!field && typeof field == 'object') {
field.resolve = resolveMiddlewareWrapper(
field.resolve,
field.directives,
);
if (field.type._fields && deepWrap) {
wrapFieldsWithMiddleware(field.type, deepWrap, typeMet);
} else if (field.type.ofType && field.type.ofType._fields && deepWrap) {
let child = field.type;
while (child.ofType) {
child = child.ofType;
}
if (child._fields) {
wrapFieldsWithMiddleware(child._fields);
}
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4758
|
reloadPage
|
train
|
function reloadPage(page, isModal) {
if (!LiveEditSingleton.enabled()) {
return;
}
var t = frameCommon.topmost();
if (!t) {
return;
}
if (!page) {
if (!t.currentEntry || !t.currentEntry.entry) {
return;
}
page = t.currentEntry.entry.moduleName;
if (!page) {
return;
}
}
if (LiveEditSingleton.isSuspended()) {
LiveEditSingleton._suspendedNavigate(page, isModal);
return;
}
if (isModal) {
reloadModal(page);
return;
}
var ext = "";
if (!page.endsWith(".js") && !page.endsWith(".xml")) {
ext = ".js";
}
var nextPage;
if (t._currentEntry && t._currentEntry.entry) {
nextPage = t._currentEntry.entry;
nextPage.animated = false;
} else {
nextPage = {moduleName: page, animated: false};
}
if (!nextPage.context) {
nextPage.context = {};
}
if (t._currentEntry && t._currentEntry.create) {
nextPage.create = t._currentEntry.create;
}
nextPage.context.liveSync = true;
nextPage.context.liveEdit = true;
// Disable it in the backstack
//nextPage.backstackVisible = false;
// Attempt to Go back, so that this is the one left in the queue
if (t.canGoBack()) {
//t._popFromFrameStack();
t.goBack();
} else {
nextPage.clearHistory = true;
}
// This should be before we navigate so that it is removed from the cache just before
// In case the goBack goes to the same page; we want it to return to the prior version in the cache; then
// we clear it so that we go to a new version.
__clearRequireCachedItem(LiveEditSingleton.currentAppPath() + page + ext);
__clearRequireCachedItem(LiveEditSingleton.currentAppPath() + "*" + LiveEditSingleton.currentAppPath() + page);
if (fileResolver.clearCache) {
fileResolver.clearCache();
}
// Navigate back to this page
try {
t.navigate(nextPage);
}
catch (err) {
console.log(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q4759
|
isWatching
|
train
|
function isWatching(fileName) {
for (var i=0;i<watching.length;i++) {
if (fileName.endsWith(watching[i])) {
return true;
}
}
//noinspection RedundantIfStatementJS
if (fileName.toLowerCase().lastIndexOf("restart.livesync") === (fileName.length - 16)) {
return true;
}
//noinspection RedundantIfStatementJS
if (fileName.toLowerCase().lastIndexOf("restart.liveedit") === (fileName.length - 16)) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q4760
|
normalPushADB
|
train
|
function normalPushADB(fileName, options, callback) {
if (typeof options === "function") {
callback = options;
options = null;
}
var srcFile = fileName;
if (options && typeof options.srcFile === "string") {
srcFile = options.srcFile;
}
var check = false;
if (options && options.check) {
check = true;
}
var quiet = false;
if (options && options.quiet) {
quiet = true;
}
var path = "/data/data/" + projectData.nativescript.id + "/files/" + fileName;
cp.exec('adb push "'+srcFile+'" "' + path + '"', {timeout: 10000}, function(err, sout, serr) {
if (err) {
if (sout.indexOf('Permission denied') > 0) { pushADB = backupPushADB; console.log("Using backup method for updates!"); }
if (serr.indexOf('Permission denied') > 0) { pushADB = backupPushADB; console.log("Using backup method for updates!"); }
if (check !== true) {
console.log("Failed to Push to Device: ", fileName);
console.log(err);
//console.log(sout);
//console.log(serr);
}
} else if (check !== true && quiet === false ) {
console.log("Pushed to Device: ", fileName);
}
if (callback) {
callback(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q4761
|
getWatcher
|
train
|
function getWatcher(dir) {
return function (event, fileName) {
if (event === "rename") {
verifyWatches();
if (fileName) {
if (!fs.existsSync(dir + fileName)) { return; }
var dirStat;
try {
dirStat = fs.statSync(dir + fileName);
} catch (err) {
// This means the File disappeared out from under me...
return;
}
if (dirStat.isDirectory()) {
if (!watchingFolders[dir + fileName]) {
console.log("Adding new directory to watch: ", dir + fileName);
setupWatchers(dir + fileName);
}
return;
}
} else {
checkForChangedFolders(dir);
}
return;
}
if (!fileName) {
fileName = checkForChangedFiles(dir);
if (fileName) {
checkCache(fileName);
}
}
else {
if (isWatching(fileName)) {
if (!fs.existsSync(dir + fileName)) {
return;
}
var stat;
try {
stat = fs.statSync(dir + fileName);
}
catch (e) {
// This means the file disappeared between exists and stat...
return;
}
if (stat.size === 0) { return; }
if (timeStamps[dir + fileName] === undefined || timeStamps[dir + fileName] !== stat.mtime.getTime()) {
//console.log("Found 2: ", event, dir+fileName, stat.mtime.getTime(), stat.mtime, stat.ctime.getTime(), stat.size);
timeStamps[dir + fileName] = stat.mtime.getTime();
checkCache(dir + fileName);
}
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q4762
|
setupWatchers
|
train
|
function setupWatchers(path) {
// We want to track the watchers now and return if we are already watching this folder
if (watchingFolders[path]) { return; }
watchingFolders[path] = fs.watch(path, getWatcher(path + "/"));
watchingFolders[path].on('error', function() { verifyWatches(); });
var fileList = fs.readdirSync(path);
var stats;
for (var i = 0; i < fileList.length; i++) {
try {
stats = fs.statSync(path + "/" + fileList[i]);
}
catch (e) {
continue;
}
if (isWatching(fileList[i])) {
timeStamps[path + "/" + fileList[i]] = stats.mtime.getTime();
} else {
if (stats.isDirectory()) {
if (fileList[i] === "node_modules") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
if (fileList[i] === "tns_modules") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
if (fileList[i] === "App_Resources") {
watchingFolders[path + "/" + fileList[i]] = true;
continue;
}
setupWatchers(path + "/" + fileList[i]);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4763
|
CommunicationApi
|
train
|
function CommunicationApi(constructorOptions) {
LOG.debug('Instantiating communication API');
LOG.debug('Validating constructor options');
// Sanitize option eventually throwing an InvalidOption
try {
this.options =
new communicationOptions.Constructor().validate(constructorOptions);
} catch (err) {
throw(
err
);
}
if (this.options.token !== '') {
LOG.debug('Setting predefined token');
this.token = this.options.token;
} else {
this.token = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q4764
|
RequestApi
|
train
|
function RequestApi(constructorOptions) {
LOG.debug('Instantiating new Request object');
LOG.debug('Validating options');
try {
this.options =
new requestOptions.Constructor().validate(constructorOptions);
} catch (err) {
LOG.error('Received error: %s', err);
throw(
err
);
}
this.requests = [];
this.batchId = 1;
}
|
javascript
|
{
"resource": ""
}
|
q4765
|
round
|
train
|
function round(num, dec) {
var pow = Math.pow(10, dec);
return Math.round(num * pow) / pow;
}
|
javascript
|
{
"resource": ""
}
|
q4766
|
jsonEncoder
|
train
|
function jsonEncoder(input, path) {
var output = new Stream();
output.readable = true;
var first = true;
input.on("data", function (entry) {
if (path) {
entry.href = path + entry.name;
var mime = entry.linkStat ? entry.linkStat.mime : entry.mime;
if (mime && mime.match(/(directory|folder)$/)) {
entry.href += "/";
}
}
if (first) {
output.emit("data", "[\n " + JSON.stringify(entry));
first = false;
} else {
output.emit("data", ",\n " + JSON.stringify(entry));
}
});
input.on("end", function () {
if (first) output.emit("data", "[]");
else output.emit("data", "\n]");
output.emit("end");
});
if (input.pause) {
output.pause = function () {
input.pause();
};
}
if (input.resume) {
output.resume = function () {
input.resume();
};
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q4767
|
train
|
function (options) {
var result = {
type: options.actionType
};
if (options.channelName) {
result.channel = options.channelName
}
if (options.eventName) {
result.event = options.eventName
}
if (options.data) {
result.data = options.data
}
if (options.additionalParams) {
result.additionalParams = options.additionalParams
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q4768
|
_characterFromEvent
|
train
|
function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
var character = String.fromCharCode(e.which);
// if the shift key is not pressed then it is safe to assume
// that we want the character to be lowercase. this means if
// you accidentally have caps lock on then your key bindings
// will continue to work
//
// the only side effect that might not be desired is if you
// bind something like 'A' cause you want to trigger an
// event when capital A is pressed caps lock will no longer
// trigger the event. shift+a will though.
if (!e.shiftKey) {
character = character.toLowerCase();
}
return character;
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
// with keydown and keyup events the character seems to always
// come in as an uppercase character whether you are pressing shift
// or not. we should make sure it is always lowercase for comparisons
return String.fromCharCode(e.which).toLowerCase();
}
|
javascript
|
{
"resource": ""
}
|
q4769
|
_eventModifiers
|
train
|
function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
}
|
javascript
|
{
"resource": ""
}
|
q4770
|
_pickBestAction
|
train
|
function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
}
|
javascript
|
{
"resource": ""
}
|
q4771
|
_resetSequences
|
train
|
function _resetSequences(doNotReset) {
doNotReset = doNotReset || {};
var activeSequences = false,
key;
for (key in _sequenceLevels) {
if (doNotReset[key]) {
activeSequences = true;
continue;
}
_sequenceLevels[key] = 0;
}
if (!activeSequences) {
_nextExpectedAction = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q4772
|
_handleKeyEvent
|
train
|
function _handleKeyEvent(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
if (typeof e.which !== 'number') {
e.which = e.keyCode;
}
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
// need to use === for the character check because the character can be 0
if (e.type == 'keyup' && _ignoreNextKeyup === character) {
_ignoreNextKeyup = false;
return;
}
self.handleKey(character, _eventModifiers(e), e);
}
|
javascript
|
{
"resource": ""
}
|
q4773
|
_bindSingle
|
train
|
function _bindSingle(combination, callback, action, sequenceName, level) {
// store a direct mapped reference for use with Mousetrap.trigger
self._directMap[combination + ':' + action] = callback;
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' ');
var info;
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
_bindSequence(combination, sequence, callback, action);
return;
}
info = _getKeyInfo(combination, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
self._callbacks[info.key] = self._callbacks[info.key] || [];
// remove an existing match if there is one
_getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({
callback: callback,
modifiers: info.modifiers,
action: info.action,
seq: sequenceName,
level: level,
combo: combination
});
}
|
javascript
|
{
"resource": ""
}
|
q4774
|
train
|
function(remoteWindow, remoteOrigin) {
this.remoteWindow = remoteWindow;
this.remoteOrigin = remoteOrigin;
this.timeout = 3000;
this.handshaken = false;
this.handshake = pinkySwearPromise();
this._id = 0;
this._queue = [];
this._sent = {};
var _this = this;
window.addEventListener('message', function(messageEvent) { _this._receiveMessage(messageEvent) }, false);
this._sendHandshake();
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q4775
|
train
|
function () {
var args = arguments;
var len = names.length;
if (this instanceof ctr) {
if (args.length !== len) {
throw new Error(
'Unexpected number of arguments for ' + ctr.className + ': ' +
'got ' + args.length + ', but need ' + len + '.'
);
}
var i = 0, n;
for (; n = names[i]; i++) {
this[n] = constraints[n](args[i], n, ctr);
}
} else {
return args.length < len
? partial(ctr, toArray(args))
: ctrApply(ctr, args);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4776
|
train
|
function () {
var ctr = this.constructor;
var names = ctr.__names__;
var args = [], i = 0, n, val;
for (; n = names[i]; i++) {
val = this[n];
args[i] = val instanceof adt.__Base__
? val.clone()
: adt.nativeClone(val);
}
return ctr.apply(null, args);
}
|
javascript
|
{
"resource": ""
}
|
|
q4777
|
train
|
function (that) {
var ctr = this.constructor;
if (this === that) return true;
if (!(that instanceof ctr)) return false;
var names = ctr.__names__;
var i = 0, len = names.length;
var vala, valb, n;
for (; i < len; i++) {
n = names[i], vala = this[n], valb = that[n];
if (vala instanceof adt.__Base__) {
if (!vala.equals(valb)) return false;
} else if (!adt.nativeEquals(vala, valb)) return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q4778
|
train
|
function (field) {
var ctr = this.constructor;
var names = ctr.__names__;
var constraints = ctr.__constraints__;
if (typeof field === 'number') {
if (field < 0 || field > names.length - 1) {
throw new Error('Field index out of range: ' + field);
}
field = names[field];
} else {
if (!constraints.hasOwnProperty(field)) {
throw new Error('Field name does not exist: ' + field);
}
}
return this[field];
}
|
javascript
|
{
"resource": ""
}
|
|
q4779
|
addOrder
|
train
|
function addOrder (that) {
if (that.constructor) that = that.constructor;
that.__order__ = order++;
return that;
}
|
javascript
|
{
"resource": ""
}
|
q4780
|
makeRequire
|
train
|
function makeRequire(relModuleMap, enableBuildCallback, altRequire) {
var modRequire = makeContextModuleFunc(altRequire || context.require, relModuleMap, enableBuildCallback);
mixin(modRequire, {
nameToUrl: makeContextModuleFunc(context.nameToUrl, relModuleMap),
toUrl: makeContextModuleFunc(context.toUrl, relModuleMap),
defined: makeContextModuleFunc(context.requireDefined, relModuleMap),
specified: makeContextModuleFunc(context.requireSpecified, relModuleMap),
isBrowser: req.isBrowser
});
return modRequire;
}
|
javascript
|
{
"resource": ""
}
|
q4781
|
makeArgCallback
|
train
|
function makeArgCallback(manager, i) {
return function (value) {
//Only do the work if it has not been done
//already for a dependency. Cycle breaking
//logic in forceExec could mean this function
//is called more than once for a given dependency.
if (!manager.depDone[i]) {
manager.depDone[i] = true;
manager.deps[i] = value;
manager.depCount -= 1;
if (!manager.depCount) {
//All done, execute!
execManager(manager);
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q4782
|
addWait
|
train
|
function addWait(manager) {
if (!waiting[manager.id]) {
waiting[manager.id] = manager;
waitAry.push(manager);
context.waitCount += 1;
}
}
|
javascript
|
{
"resource": ""
}
|
q4783
|
toAstArray
|
train
|
function toAstArray(ary) {
var output = [
'array',
[]
],
i, item;
for (i = 0; (item = ary[i]); i++) {
output[1].push([
'string',
item
]);
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q4784
|
train
|
function (fileContents, fileName) {
//Uglify's ast generation removes comments, so just convert to ast,
//then back to source code to get rid of comments.
return uglify.uglify.gen_code(uglify.parser.parse(fileContents), true);
}
|
javascript
|
{
"resource": ""
}
|
|
q4785
|
makeWriteFile
|
train
|
function makeWriteFile(anonDefRegExp, namespaceWithDot, layer) {
function writeFile(name, contents) {
logger.trace('Saving plugin-optimized file: ' + name);
file.saveUtf8File(name, contents);
}
writeFile.asModule = function (moduleName, fileName, contents) {
writeFile(fileName,
build.toTransport(anonDefRegExp, namespaceWithDot, moduleName, fileName, contents, layer));
};
return writeFile;
}
|
javascript
|
{
"resource": ""
}
|
q4786
|
setBaseUrl
|
train
|
function setBaseUrl(fileName) {
//Use the file name's directory as the baseUrl if available.
dir = fileName.replace(/\\/g, '/');
if (dir.indexOf('/') !== -1) {
dir = dir.split('/');
dir.pop();
dir = dir.join('/');
exec("require({baseUrl: '" + dir + "'});");
}
}
|
javascript
|
{
"resource": ""
}
|
q4787
|
validateCompoundWithType
|
train
|
function validateCompoundWithType(attribute, values) {
for(var i in values) {
var value = values[i];
if(typeof(value) !== 'object') {
errors.push([attribute + '-' + i, "not-an-object"]);
} else if(! value.type) {
errors.push([attribute + '-' + i, "missing-type"]);
} else if(! value.value) { // empty values are not allowed.
errors.push([attribute + '-' + i, "missing-value"]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4788
|
train
|
function(key, value) {
console.log('add attribute', key, value);
if(! value) {
return;
}
if(VCard.multivaluedKeys[key]) {
if(this[key]) {
console.log('multivalued push');
this[key].push(value)
} else {
console.log('multivalued set');
this.setAttribute(key, [value]);
}
} else {
this.setAttribute(key, value);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4789
|
train
|
function(aDate, bDate, addSub) {
if(typeof(addSub) == 'undefined') { addSub = true };
if(! aDate) { return bDate; }
if(! bDate) { return aDate; }
var a = Number(aDate);
var b = Number(bDate);
var c = addSub ? a + b : a - b;
return new Date(c);
}
|
javascript
|
{
"resource": ""
}
|
|
q4790
|
train
|
function(str){
str = (str || "").toString();
str = str.replace(/\=(?:\r?\n|$)/g, "");
var str2 = "";
for(var i=0, len = str.length; i<len; i++){
chr = str.charAt(i);
if(chr == "=" && (hex = str.substr(i+1, 2)) && /[\da-fA-F]{2}/.test(hex)){
str2 += String.fromCharCode(parseInt(hex,16));
i+=2;
continue;
}
str2 += chr;
}
return str2;
}
|
javascript
|
{
"resource": ""
}
|
|
q4791
|
addParentNodeInterfaceToPrototype
|
train
|
function addParentNodeInterfaceToPrototype(p) {
Object.defineProperty(p, "firstElementChild", {
get: function firstElementChild() {
var el = this.firstChild;
while (el && el.nodeType !== 1) {
el = el.nextSibling;
}
return el;
},
});
Object.defineProperty(p, "lastElementChild", {
get: function lastElementChild() {
var el = this.lastChild;
while (el && el.nodeType !== 1) {
el = el.previousSibling;
}
return el;
},
});
Object.defineProperty(p, "childElementCount", {
get: function childElementCount() {
var el = this.firstElementChild;
var count = 0;
while (el) {
count++;
el = el.nextElementSibling;
}
return count;
},
});
}
|
javascript
|
{
"resource": ""
}
|
q4792
|
addChildrenToPrototype
|
train
|
function addChildrenToPrototype(p) {
// Unfortunately, it is not possible to emulate the liveness of the
// HTMLCollection this property *should* provide.
Object.defineProperty(p, "children", {
get: function children() {
var ret = [];
var el = this.firstElementChild;
while (el) {
ret.push(el);
el = el.nextElementSibling;
}
return ret;
},
});
}
|
javascript
|
{
"resource": ""
}
|
q4793
|
captureConfigObject
|
train
|
function captureConfigObject(config) {
let captured;
const require = {};
require.config = function _config(conf) {
captured = conf;
};
let wedConfig;
// eslint-disable-next-line no-unused-vars
function define(name, obj) {
if (wedConfig !== undefined) {
throw new Error("more than one define");
}
switch (arguments.length) {
case 0:
throw new Error("no arguments to the define!");
case 1:
if (typeof name !== "object") {
throw new Error("if define has only one argument, it must be an " +
"object");
}
wedConfig = name;
break;
default:
throw new Error("captureConfigObject is designed to capture a " +
"maximum of two arguments.");
}
}
eval(config); // eslint-disable-line no-eval
return {
requireConfig: captured,
wedConfig,
};
}
|
javascript
|
{
"resource": ""
}
|
q4794
|
_reset
|
train
|
function _reset() {
terminating = false;
if (termination_timeout) {
termination_window.clearTimeout(termination_timeout);
termination_timeout = undefined;
}
$modal.off();
$modal.modal("hide");
$modal.remove();
}
|
javascript
|
{
"resource": ""
}
|
q4795
|
showModal
|
train
|
function showModal(saveMessages, errorMessage) {
$(document.body).append($modal);
$modal.find(".save-messages")[0].innerHTML = saveMessages;
$modal.find(".error-message")[0].textContent = errorMessage;
$modal.on("hide.bs.modal.modal", function hidden() {
$modal.remove();
window.location.reload();
});
$modal.modal();
}
|
javascript
|
{
"resource": ""
}
|
q4796
|
lazyCache
|
train
|
function lazyCache(requireFn) {
var cache = {};
return function proxy(name, alias) {
var key = alias;
// camel-case the module `name` if `alias` is not defined
if (typeof key !== 'string') {
key = camelcase(name);
}
// create a getter to lazily invoke the module the first time it's called
function getter() {
return cache[key] || (cache[key] = requireFn(name));
}
// trip the getter if `process.env.UNLAZY` is defined
if (unlazy(process.env)) {
getter();
}
set(proxy, key, getter);
return getter;
};
}
|
javascript
|
{
"resource": ""
}
|
q4797
|
getDestinationDir
|
train
|
function getDestinationDir(vFile) {
if (vFile.data.destinationDir) {
return vFile.data.destinationDir;
}
return vFile.dirname;
}
|
javascript
|
{
"resource": ""
}
|
q4798
|
parseUrl
|
train
|
function parseUrl(url, normalize = false) {
if (typeof url !== "string" || !url.trim()) {
throw new Error("Invalid url.")
}
if (normalize) {
if (typeof normalize !== "object") {
normalize = {
stripFragment: false
}
}
url = normalizeUrl(url, normalize)
}
const parsed = parsePath(url)
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
q4799
|
train
|
function(query, data, successCallback, failureCallback) {
if(typeof successCallback != "function") successCallback = function(){};
if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); };
var i, l, remaining;
if(!Array.isArray(data[0])) data = [data];
remaining = data.length;
var innerSuccessCallback = function(tx, rs) {
var i, l, output = [];
remaining = remaining - 1;
if (!remaining) {
for (i = 0, l = rs.rows.length; i < l; i = i + 1){
var j = rs.rows.item(i).json;
//j = JSON.parse(j);
output.push(j);
}
successCallback(output);
}
};
self.db.transaction(function (tx) {
for (i = 0, l = data.length; i < l; i = i + 1) {
tx.executeSql(query, data[i], innerSuccessCallback, failureCallback);
}
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.