_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q4700
|
bcscale
|
train
|
function bcscale(scale) {
scale = parseInt(scale, 10);
if (isNaN(scale)) {
|
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)
|
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 >
|
javascript
|
{
"resource": ""
}
|
q4703
|
ensureAnArray
|
train
|
function ensureAnArray (arr) {
if (Object.prototype.toString.call(arr) === '[object Array]') {
|
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';
|
javascript
|
{
"resource": ""
}
|
q4705
|
trigger
|
train
|
function trigger(touches, element, type) {
return
|
javascript
|
{
"resource": ""
}
|
q4706
|
train
|
function(msg, errno) {
if (output && config.file) {
output.close()
}
if (msg) {
|
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;
|
javascript
|
{
"resource": ""
}
|
|
q4708
|
train
|
function(str) {
var p;
p = str.indexOf('.');
if (p==-1) {
return libbcmath.bc_str2num(str, 0);
} else {
|
javascript
|
{
"resource": ""
}
|
|
q4709
|
train
|
function(r, ptr, chr, len) {
var i;
|
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
|
javascript
|
{
"resource": ""
}
|
|
q4711
|
Conf
|
train
|
function Conf(config, _pg) {
if (typeof config === 'string') config = {connectionString: config};
this._config = 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++) {
|
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();
|
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;
|
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
|
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">
|
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';`;
|
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) {
|
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)
|
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);
|
javascript
|
{
"resource": ""
}
|
q4721
|
makeOptionsObj
|
train
|
function makeOptionsObj(port, host, inUse, retryTimeMs, timeOutMs) {
var opts = {};
opts.port = port;
opts.host = host;
opts.inUse = inUse;
|
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)
|
javascript
|
{
"resource": ""
}
|
q4723
|
extract
|
train
|
function extract(str, options, tranformFn) {
let extractor
|
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();
|
javascript
|
{
"resource": ""
}
|
|
q4725
|
train
|
function(treeType) {
if (treeType === 'vendor') {
// The treeForVendor returns a different value based on whether or not
|
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();
|
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'),
|
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
|
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
|
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 = {};
|
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;
|
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?
|
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++) {
|
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;
|
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)
|
javascript
|
{
"resource": ""
}
|
|
q4736
|
train
|
function(i) {
return {
left: this.getHelperTargetX() + (this.settings.helperSpacingX * 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() {
|
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'),
|
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 {
|
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
|
javascript
|
{
"resource": ""
}
|
|
q4741
|
train
|
function(item) {
var $handle = $.data(item, 'select-handle');
if ($handle) {
$handle.removeData('select-item');
this.removeAllListeners($handle);
}
$.removeData(item, 'select');
|
javascript
|
{
"resource": ""
}
|
|
q4742
|
loadCurrentVersion
|
train
|
function loadCurrentVersion (options, context) {
return new Extension(options, context).read()
|
javascript
|
{
"resource": ""
}
|
q4743
|
train
|
function(err) {
notify.onError({
title: "Garnish",
message: "Error: <%= error.message %>",
sound: "Beep"
|
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) {
|
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 });
|
javascript
|
{
"resource": ""
}
|
|
q4746
|
escapes
|
train
|
function escapes(options) {
var settings = options || {}
if
|
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
|
javascript
|
{
"resource": ""
}
|
q4748
|
parseKeyCodes
|
train
|
function parseKeyCodes(arr, keys) {
if (typeof keys !== 'object') { return false;
|
javascript
|
{
"resource": ""
}
|
q4749
|
parseErrorState
|
train
|
function parseErrorState(packet, state) {
let states = 0;
state.forEach((s) => {
if (s === 1)
|
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
|
javascript
|
{
"resource": ""
}
|
q4751
|
getFirstHeader
|
train
|
function getFirstHeader (req, header) {
const value = req.headers[header]
|
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;
|
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);
|
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();
|
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
|
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
|
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(
|
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();
|
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
|
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') >
|
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 {
|
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;
|
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 =
|
javascript
|
{
"resource": ""
}
|
q4764
|
RequestApi
|
train
|
function RequestApi(constructorOptions) {
LOG.debug('Instantiating new Request object');
LOG.debug('Validating options');
try {
this.options =
|
javascript
|
{
"resource": ""
}
|
q4765
|
round
|
train
|
function round(num, dec) {
var pow = Math.pow(10, dec);
|
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));
}
|
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) {
|
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
|
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) {
|
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';
}
//
|
javascript
|
{
"resource": ""
}
|
q4771
|
_resetSequences
|
train
|
function _resetSequences(doNotReset) {
doNotReset = doNotReset || {};
var activeSequences = false,
key;
for (key in _sequenceLevels) {
if (doNotReset[key]) {
activeSequences = true;
continue;
|
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;
}
|
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);
|
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;
|
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
|
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__
|
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 =
|
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);
}
|
javascript
|
{
"resource": ""
}
|
|
q4779
|
addOrder
|
train
|
function addOrder (that) {
if (that.constructor) that = that.constructor;
|
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),
|
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;
|
javascript
|
{
"resource": ""
}
|
q4782
|
addWait
|
train
|
function addWait(manager) {
if (!waiting[manager.id]) {
waiting[manager.id] = manager;
|
javascript
|
{
"resource": ""
}
|
q4783
|
toAstArray
|
train
|
function toAstArray(ary) {
var output = [
'array',
[]
],
i, item;
for (i = 0; (item = ary[i]); i++) {
output[1].push([
|
javascript
|
{
"resource": ""
}
|
q4784
|
train
|
function (fileContents, fileName) {
//Uglify's ast generation removes comments, so just convert to ast,
|
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) {
|
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('/');
|
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
|
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 {
|
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);
|
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)){
|
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;
|
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;
|
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 " +
|
javascript
|
{
"resource": ""
}
|
q4794
|
_reset
|
train
|
function _reset() {
terminating = false;
if (termination_timeout) {
termination_window.clearTimeout(termination_timeout);
termination_timeout = undefined;
|
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;
|
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() {
|
javascript
|
{
"resource": ""
}
|
q4797
|
getDestinationDir
|
train
|
function getDestinationDir(vFile) {
if (vFile.data.destinationDir) {
|
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 = {
|
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 =
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.