_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q46600
|
train
|
function(callback, deferred) {
var root = this;
var manager = root.__manager__;
var rentManager = manager.parent && manager.parent.__manager__;
// Allow RAF processing to be shut off using `useRAF`:false.
if (this.useRAF === false) {
if (manager.queue) {
aPush.call(manager.queue, callback);
} else {
manager.queue = [];
callback();
}
return;
}
// Keep track of all deferreds so we can resolve them.
manager.deferreds = manager.deferreds || [];
manager.deferreds.push(deferred);
// Schedule resolving all deferreds that are waiting.
deferred.done(resolveDeferreds);
// Cancel any other renders on this view that are queued to execute.
this._cancelQueuedRAFRender();
// Trigger immediately if the parent was triggered by RAF.
// The flag propagates downward so this view's children are also
// rendered immediately.
if (rentManager && rentManager.triggeredByRAF) {
return finish();
}
// Register this request with requestAnimationFrame.
manager.rafID = root.requestAnimationFrame(finish);
function finish() {
// Remove this ID as it is no longer valid.
manager.rafID = null;
// Set flag (will propagate to children) so they render
// without waiting for RAF.
manager.triggeredByRAF = true;
// Call original cb.
callback();
}
// Resolve all deferreds that were cancelled previously, if any.
// This allows the user to bind callbacks to any render callback,
// even if it was cancelled above.
function resolveDeferreds() {
for (var i = 0; i < manager.deferreds.length; i++){
manager.deferreds[i].resolveWith(root, [root]);
}
manager.deferreds = [];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46601
|
resolveDeferreds
|
train
|
function resolveDeferreds() {
for (var i = 0; i < manager.deferreds.length; i++){
manager.deferreds[i].resolveWith(root, [root]);
}
manager.deferreds = [];
}
|
javascript
|
{
"resource": ""
}
|
q46602
|
train
|
function() {
var root = this;
var manager = root.__manager__;
if (manager.rafID != null) {
root.cancelAnimationFrame(manager.rafID);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46603
|
train
|
function(root, force) {
// Shift arguments around.
if (typeof root === "boolean") {
force = root;
root = this;
}
// Allow removeView to be called on instances.
root = root || this;
// Iterate over all of the nested View's and remove.
root.getViews().each(function(view) {
// Force doesn't care about if a View has rendered or not.
if (view.hasRendered || force) {
LayoutManager._removeView(view, force);
}
// call value() in case this chain is evaluated lazily
}).value();
}
|
javascript
|
{
"resource": ""
}
|
|
q46604
|
train
|
function(view, force) {
var parentViews;
// Shorthand the managers for easier access.
var manager = view.__manager__;
var rentManager = manager.parent && manager.parent.__manager__;
// Test for keep.
var keep = typeof view.keep === "boolean" ? view.keep : view.options.keep;
// In insert mode, remove views that do not have `keep` attribute set,
// unless the force flag is set.
if ((!keep && rentManager && rentManager.insert === true) || force) {
// Clean out the events.
LayoutManager.cleanViews(view);
// Since we are removing this view, force subviews to remove
view._removeViews(true);
// Remove the View completely.
view.$el.remove();
// Cancel any pending renders, if present.
view._cancelQueuedRAFRender();
// Bail out early if no parent exists.
if (!manager.parent) { return; }
// Assign (if they exist) the sibling Views to a property.
parentViews = manager.parent.views[manager.selector];
// If this is an array of items remove items that are not marked to
// keep.
if (_.isArray(parentViews)) {
// Remove duplicate Views.
_.each(_.clone(parentViews), function(view, i) {
// If the managers match, splice off this View.
if (view && view.__manager__ === manager) {
aSplice.call(parentViews, i, 1);
}
});
if (_.isEmpty(parentViews)) {
manager.parent.trigger("empty", manager.selector);
}
return;
}
// Otherwise delete the parent selector.
delete manager.parent.views[manager.selector];
manager.parent.trigger("empty", manager.selector);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46605
|
train
|
function(path, contents) {
// If template path is found in the cache, return the contents.
if (path in this._cache && contents == null) {
return this._cache[path];
// Ensure path and contents aren't undefined.
} else if (path != null && contents != null) {
return this._cache[path] = contents;
}
// If the template is not in the cache, return undefined.
}
|
javascript
|
{
"resource": ""
}
|
|
q46606
|
train
|
function(views) {
// Clear out all existing views.
_.each(aConcat.call([], views), function(view) {
// fire cleanup event to the attached handlers
view.trigger("cleanup", view);
// Remove all custom events attached to this View.
view.unbind();
// Automatically unbind `model`.
if (view.model instanceof Backbone.Model) {
view.model.off(null, null, view);
}
// Automatically unbind `collection`.
if (view.collection instanceof Backbone.Collection) {
view.collection.off(null, null, view);
}
// Automatically unbind events bound to this View.
view.stopListening();
// If a custom cleanup method was provided on the view, call it after
// the initial cleanup is done
if (_.isFunction(view.cleanup)) {
view.cleanup();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46607
|
train
|
function(options) {
_.extend(LayoutManager.prototype, options);
// Allow LayoutManager to manage Backbone.View.prototype.
if (options.manage) {
Backbone.View.prototype.manage = true;
}
// Disable the element globally.
if (options.el === false) {
Backbone.View.prototype.el = false;
}
// Allow global configuration of `suppressWarnings`.
if (options.suppressWarnings === true) {
Backbone.View.prototype.suppressWarnings = true;
}
// Allow global configuration of `useRAF`.
if (options.useRAF === false) {
Backbone.View.prototype.useRAF = false;
}
// Allow underscore to be swapped out
if (options._) {
_ = options._;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46608
|
train
|
function(views, options) {
// Ensure that options is always an object, and clone it so that
// changes to the original object don't screw up this view.
options = _.extend({}, options);
// Set up all Views passed.
_.each(aConcat.call([], views), function(view) {
// If the View has already been setup, no need to do it again.
if (view.__manager__) {
return;
}
var views, declaredViews;
var proto = LayoutManager.prototype;
// Ensure necessary properties are set.
_.defaults(view, {
// Ensure a view always has a views object.
views: {},
// Ensure a view always has a sections object.
sections: {},
// Internal state object used to store whether or not a View has been
// taken over by layout manager and if it has been rendered into the
// DOM.
__manager__: {},
// Add the ability to remove all Views.
_removeViews: LayoutManager._removeViews,
// Add the ability to remove itself.
_removeView: LayoutManager._removeView
// Mix in all LayoutManager prototype properties as well.
}, LayoutManager.prototype);
// Assign passed options.
view.options = options;
// Merge the View options into the View.
_.extend(view, options);
// By default the original Remove function is the Backbone.View one.
view._remove = Backbone.View.prototype.remove;
// Ensure the render is always set correctly.
view.render = LayoutManager.prototype.render;
// If the user provided their own remove override, use that instead of
// the default.
if (view.remove !== proto.remove) {
view._remove = view.remove;
view.remove = proto.remove;
}
// Normalize views to exist on either instance or options, default to
// options.
views = options.views || view.views;
// Set the internal views, only if selectors have been provided.
if (_.keys(views).length) {
// Keep original object declared containing Views.
declaredViews = views;
// Reset the property to avoid duplication or overwritting.
view.views = {};
// If any declared view is wrapped in a function, invoke it.
_.each(declaredViews, function(declaredView, key) {
if (typeof declaredView === "function") {
declaredViews[key] = declaredView.call(view, view);
}
});
// Set the declared Views.
view.setViews(declaredViews);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46609
|
train
|
function($root, $el, rentManager, manager) {
var $filtered;
// If selector is specified, attempt to find it.
if (manager.selector) {
if (rentManager.noel) {
$filtered = $root.filter(manager.selector);
$root = $filtered.length ? $filtered : $root.find(manager.selector);
} else {
$root = $root.find(manager.selector);
}
}
// Use the insert method if the parent's `insert` argument is true.
if (rentManager.insert) {
this.insert($root, $el);
} else {
this.html($root, $el);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46610
|
train
|
function(rootView, subViews, selector) {
// Shorthand the parent manager object.
var rentManager = rootView.__manager__;
// Create a simplified manager object that tells partial() where
// place the elements.
var manager = { selector: selector };
// Get the elements to be inserted into the root view.
var els = _.reduce(subViews, function(memo, sub) {
// Check if keep is present - do boolean check in case the user
// has created a `keep` function.
var keep = typeof sub.keep === "boolean" ? sub.keep : sub.options.keep;
// If a subView is present, don't push it. This can only happen if
// `keep: true`. We do the keep check for speed as $.contains is not
// cheap.
var exists = keep && $.contains(rootView.el, sub.el);
// If there is an element and it doesn't already exist in our structure
// attach it.
if (sub.el && !exists) {
memo.push(sub.el);
}
return memo;
}, []);
// Use partial to apply the elements. Wrap els in jQ obj for cheerio.
return this.partial(rootView.$el, $(els), rentManager, manager);
}
|
javascript
|
{
"resource": ""
}
|
|
q46611
|
train
|
function(e) {
el.off('mousemove');
elSlide.off('mouseleave');
elBlob.off('mouseup');
if (!diff && opts['click'] && e.type !== 'mouseleave') {
doToggle();
return;
}
var overBound = active ? diff < -slideLimit : diff > slideLimit;
if (overBound) {
// dragged far enough, toggle
doToggle();
} else {
// reset to previous state
elInner.stop().animate({
marginLeft: active ? 0 : -width + height
}, opts['animate'] / 2, opts['easing']);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46612
|
resolveSassPath
|
train
|
function resolveSassPath(sassPath, loadPaths, extensions) {
// trim sass file extensions
var re = new RegExp('(\.('+extensions.join('|')+'))$', 'i');
var sassPathName = sassPath.replace(re, '');
// check all load paths
var i, j, length = loadPaths.length, scssPath, partialPath;
for (i = 0; i < length; i++) {
for (j = 0; j < extensions.length; j++) {
scssPath = path.normalize(loadPaths[i] + '/' + sassPathName + '.' + extensions[j]);
try {
if (fs.lstatSync(scssPath).isFile()) {
return scssPath;
}
} catch (e) {}
}
// special case for _partials
for (j = 0; j < extensions.length; j++) {
scssPath = path.normalize(loadPaths[i] + '/' + sassPathName + '.' + extensions[j]);
partialPath = path.join(path.dirname(scssPath), '_' + path.basename(scssPath));
try {
if (fs.lstatSync(partialPath).isFile()) {
return partialPath;
}
} catch (e) {}
}
}
// File to import not found or unreadable so we assume this is a custom import
return false;
}
|
javascript
|
{
"resource": ""
}
|
q46613
|
getCookieAuthUrl
|
train
|
function getCookieAuthUrl(nextUri) {
nextUri = nextUri || config.OSF.redirectUri;
const loginUri = `${config.OSF.url}login/?next=${encodeURIComponent(nextUri)}`;
return `${config.OSF.cookieLoginUrl}?service=${encodeURIComponent(loginUri)}`;
}
|
javascript
|
{
"resource": ""
}
|
q46614
|
buildQueryBody
|
train
|
function buildQueryBody(queryParams, filters, queryParamsChanged) {
let query = {
query_string: {
query: queryParams.q || '*',
},
};
if (filters.length) {
query = {
bool: {
must: query,
filter: filters,
},
};
}
const queryBody = {
query,
from: (queryParams.page - 1) * queryParams.size,
aggregations: elasticAggregations,
};
let sortValue = queryParams.sort;
if (!queryParamsChanged) {
sortValue = '-date_modified';
}
if (sortValue) {
const sortBy = {};
sortBy[sortValue.replace(/^-/, '')] = sortValue[0] === '-' ? 'desc' : 'asc';
queryBody.sort = sortBy;
}
return JSON.stringify(queryBody);
}
|
javascript
|
{
"resource": ""
}
|
q46615
|
sortContributors
|
train
|
function sortContributors(contributors) {
return contributors
.sort((b, a) => (b.order_cited || -1) - (a.order_cited || -1))
.map(contributor => ({
users: Object.keys(contributor).reduce(
(acc, key) => Ember.assign(acc, { [Ember.String.camelize(key)]: contributor[key] }),
{ bibliographic: contributor.relation !== 'contributor' }
)
}));
}
|
javascript
|
{
"resource": ""
}
|
q46616
|
transformShareData
|
train
|
function transformShareData(result) {
const transformedResult = Ember.assign(result._source, {
id: result._id,
type: 'elastic-search-result',
workType: result._source['@type'],
abstract: result._source.description,
subjects: result._source.subjects.map(each => ({ text: each })),
subject_synonyms: result._source.subject_synonyms.map(each => ({ text: each })),
providers: result._source.sources.map(item => ({
name: item,
})),
hyperLinks: [ // Links that are hyperlinks from hit._source.lists.links
{
type: 'share',
url: `${config.OSF.shareBaseUrl}${result._source.type.replace(/ /g, '')}/${result._id}`,
},
],
infoLinks: [], // Links that are not hyperlinks hit._source.lists.links
registrationType: result._source.registration_type, // for registries
});
result._source.identifiers.forEach(function(identifier) {
if (identifier.startsWith('http://')) {
transformedResult.hyperLinks.push({ url: identifier });
} else {
const spl = identifier.split('://');
const [type, uri] = spl;
transformedResult.infoLinks.push({ type, uri });
}
});
transformedResult.contributors = transformedResult.lists.contributors ?
sortContributors(transformedResult.lists.contributors) :
[];
// Temporary fix to handle half way migrated SHARE ES
// Only false will result in a false here.
transformedResult.contributors.map((contributor) => {
const contrib = contributor;
contrib.users.bibliographic = !(contributor.users.bibliographic === false);
return contrib;
});
return transformedResult;
}
|
javascript
|
{
"resource": ""
}
|
q46617
|
train
|
function(options) {
// Verifying and validating the input object
if (!options) {
options = {};
}
// Creating the options object
this.options = {};
// Validating the options
this.options.text = options.text || "Hi there!"; // Display message
this.options.duration = options.duration || 3000; // Display duration
this.options.selector = options.selector; // Parent selector
this.options.callback = options.callback || function() {}; // Callback after display
this.options.destination = options.destination; // On-click destination
this.options.newWindow = options.newWindow || false; // Open destination in new window
this.options.close = options.close || false; // Show toast close icon
this.options.gravity = options.gravity == "bottom" ? "toastify-bottom" : "toastify-top"; // toast position - top or bottom
this.options.positionLeft = options.positionLeft || false; // toast position - left or right
this.options.backgroundColor = options.backgroundColor; // toast background color
this.options.avatar = options.avatar || ""; // toast position - left or right
this.options.className = options.className || ""; // additional class names for the toast
// Returning the current object for chaining functions
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q46618
|
train
|
function() {
// Validating if the options are defined
if (!this.options) {
throw "Toastify is not initialized";
}
// Creating the DOM object
var divElement = document.createElement("div");
divElement.className = "toastify on " + this.options.className;
// Positioning toast to left or right
if (this.options.positionLeft === true) {
divElement.className += " toastify-left";
} else {
divElement.className += " toastify-right";
}
// Assigning gravity of element
divElement.className += " " + this.options.gravity;
if (this.options.backgroundColor) {
divElement.style.background = this.options.backgroundColor;
}
// Adding the toast message
divElement.innerHTML = this.options.text;
if (this.options.avatar !== "") {
var avatarElement = document.createElement("img");
avatarElement.src = this.options.avatar;
avatarElement.className = "toastify-avatar";
if (this.options.positionLeft === true) {
// Adding close icon on the left of content
divElement.appendChild(avatarElement);
} else {
// Adding close icon on the right of content
divElement.insertAdjacentElement("beforeend", avatarElement);
}
}
// Adding a close icon to the toast
if (this.options.close === true) {
// Create a span for close element
var closeElement = document.createElement("span");
closeElement.innerHTML = "✖";
closeElement.className = "toast-close";
// Triggering the removal of toast from DOM on close click
closeElement.addEventListener(
"click",
function(event) {
event.stopPropagation();
this.removeElement(event.target.parentElement);
window.clearTimeout(event.target.parentElement.timeOutValue);
}.bind(this)
);
//Calculating screen width
var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
// Adding the close icon to the toast element
// Display on the right if screen width is less than or equal to 360px
if (this.options.positionLeft === true && width > 360) {
// Adding close icon on the left of content
divElement.insertAdjacentElement("afterbegin", closeElement);
} else {
// Adding close icon on the right of content
divElement.appendChild(closeElement);
}
}
// Adding an on-click destination path
if (typeof this.options.destination !== "undefined") {
divElement.addEventListener(
"click",
function(event) {
event.stopPropagation();
if (this.options.newWindow === true) {
window.open(this.options.destination, "_blank");
} else {
window.location = this.options.destination;
}
}.bind(this)
);
}
// Returning the generated element
return divElement;
}
|
javascript
|
{
"resource": ""
}
|
|
q46619
|
train
|
function() {
// Creating the DOM object for the toast
var toastElement = this.buildToast();
// Getting the root element to with the toast needs to be added
var rootElement;
if (typeof this.options.selector === "undefined") {
rootElement = document.body;
} else {
rootElement = document.getElementById(this.options.selector);
}
// Validating if root element is present in DOM
if (!rootElement) {
throw "Root element is not defined";
}
// Adding the DOM element
rootElement.insertBefore(toastElement, rootElement.firstChild);
// Repositioning the toasts in case multiple toasts are present
Toastify.reposition();
toastElement.timeOutValue = window.setTimeout(
function() {
// Remove the toast from DOM
this.removeElement(toastElement);
}.bind(this),
this.options.duration
); // Binding `this` for function invocation
// Supporting function chaining
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q46620
|
train
|
function(toastElement) {
// Hiding the element
// toastElement.classList.remove("on");
toastElement.className = toastElement.className.replace(" on", "");
// Removing the element from DOM after transition end
window.setTimeout(
function() {
// Remove the elemenf from the DOM
toastElement.parentNode.removeChild(toastElement);
// Calling the callback function
this.options.callback.call(toastElement);
// Repositioning the toasts again
Toastify.reposition();
}.bind(this),
400
); // Binding `this` for function invocation
}
|
javascript
|
{
"resource": ""
}
|
|
q46621
|
getSetting
|
train
|
function getSetting(value, key, defaultVal, transform) {
if (process.env[key] !== undefined) {
var envVal = process.env[key];
return (typeof transform === 'function') ? transform(envVal) : envVal;
}
if (value !== undefined) {
return value;
}
return defaultVal;
}
|
javascript
|
{
"resource": ""
}
|
q46622
|
MochaJUnitReporter
|
train
|
function MochaJUnitReporter(runner, options) {
this._options = configureDefaults(options);
this._runner = runner;
this._generateSuiteTitle = this._options.useFullSuiteTitle ? fullSuiteTitle : defaultSuiteTitle;
this._antId = 0;
var testsuites = [];
function lastSuite() {
return testsuites[testsuites.length - 1].testsuite;
}
// get functionality from the Base reporter
Base.call(this, runner);
// remove old results
this._runner.on('start', function() {
if (fs.existsSync(this._options.mochaFile)) {
debug('removing report file', this._options.mochaFile);
fs.unlinkSync(this._options.mochaFile);
}
}.bind(this));
this._runner.on('suite', function(suite) {
if (!isInvalidSuite(suite)) {
testsuites.push(this.getTestsuiteData(suite));
}
}.bind(this));
this._runner.on('pass', function(test) {
lastSuite().push(this.getTestcaseData(test));
}.bind(this));
this._runner.on('fail', function(test, err) {
lastSuite().push(this.getTestcaseData(test, err));
}.bind(this));
if (this._options.includePending) {
this._runner.on('pending', function(test) {
var testcase = this.getTestcaseData(test);
testcase.testcase.push({ skipped: null });
lastSuite().push(testcase);
}.bind(this));
}
this._runner.on('end', function(){
this.flush(testsuites);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q46623
|
mandatoryCheck
|
train
|
function mandatoryCheck (params = {}) {
assert.ok(params.host !== void 0, 'no host given');
assert.ok(params.path !== void 0, 'no path given');
assert.ok(params.wsdl !== void 0, 'no wsdl given');
}
|
javascript
|
{
"resource": ""
}
|
q46624
|
invoke
|
train
|
function invoke(actions, message, instance, deepHistory) {
if (deepHistory === void 0) { deepHistory = false; }
for (var _i = 0, actions_2 = actions; _i < actions_2.length; _i++) {
var action = actions_2[_i];
action(message, instance, deepHistory);
}
}
|
javascript
|
{
"resource": ""
}
|
q46625
|
getEnv
|
train
|
function getEnv (key, defaultValue) {
let value = process.env[key]
if (value === 'undefined') {
value = undefined
}
return (value === undefined) ? defaultValue : value
}
|
javascript
|
{
"resource": ""
}
|
q46626
|
processEnv
|
train
|
function processEnv (config) {
// Grab the CI stuff from env
config.computed.ci.buildNumber = getEnv(config.ci.env.buildNumber)
config.computed.ci.prNumber = getEnv(config.ci.env.pr, 'false')
config.computed.ci.isPr = config.computed.ci.prNumber !== 'false'
config.computed.ci.branch = getEnv(config.ci.env.branch, 'master')
logger.log(`pr-bumper::config: prNumber [${config.computed.ci.prNumber}], isPr [${config.computed.ci.isPr}]`)
// Fill in the owner/repo from the repo slug in env if necessary
const repoSlug = getEnv(config.ci.env.repoSlug)
if (repoSlug) {
const parts = repoSlug.split('/')
if (!config.vcs.repository.owner) {
config.vcs.repository.owner = parts[0]
}
if (!config.vcs.repository.name) {
config.vcs.repository.name = parts[1]
}
}
// Grab the VCS stuff from the env
config.computed.vcs.auth = {
password: getEnv(config.vcs.env.password),
readToken: getEnv(config.vcs.env.readToken),
username: getEnv(config.vcs.env.username),
writeToken: getEnv(config.vcs.env.writeToken)
}
}
|
javascript
|
{
"resource": ""
}
|
q46627
|
getFetchOpts
|
train
|
function getFetchOpts (config) {
const readToken = config.computed.vcs.auth.readToken
const headers = {}
logger.log(`RO_GH_TOKEN = [${readToken}]`)
if (readToken) {
headers['Authorization'] = `token ${readToken}`
}
return {headers}
}
|
javascript
|
{
"resource": ""
}
|
q46628
|
convertPr
|
train
|
function convertPr (ghPr) {
return {
number: ghPr.number,
description: ghPr.body,
url: ghPr.html_url,
headSha: ghPr.head.sha
}
}
|
javascript
|
{
"resource": ""
}
|
q46629
|
addModifiedFile
|
train
|
function addModifiedFile (info, filename) {
if (info.modifiedFiles.indexOf(filename) === -1) {
info.modifiedFiles.push(filename)
}
}
|
javascript
|
{
"resource": ""
}
|
q46630
|
handlePermissionResults
|
train
|
function handlePermissionResults(args) {
// get current promise set
//noinspection JSUnresolvedVariable
const promises = pendingPromises[args.requestCode];
// We have either gotten a promise from somewhere else or a bug has occurred and android has called us twice
// In either case we will ignore it...
if (!promises || typeof promises.granted !== 'function') {
return;
}
// Delete it, since we no longer need to track it
//noinspection JSUnresolvedVariable
delete pendingPromises[args.requestCode];
let trackingResults = promises.results;
//noinspection JSUnresolvedVariable
const length = args.permissions.length;
for (let i = 0; i < length; i++) {
// Convert back to JS String
//noinspection JSUnresolvedVariable
const name = args.permissions[i].toString();
//noinspection RedundantIfStatementJS,JSUnresolvedVariable,JSUnresolvedFunction
if (args.grantResults[i] === android.content.pm.PackageManager.PERMISSION_GRANTED) {
trackingResults[name] = true;
} else {
trackingResults[name] = false;
}
}
// Any Failures
let failureCount = 0;
for (let key in trackingResults) {
if (!trackingResults.hasOwnProperty(key)) continue;
if (trackingResults[key] === false) failureCount++;
}
if (Object.keys(pendingPromises).length === 0) {
removeEventListeners();
}
if (failureCount === 0) {
promises.granted(trackingResults);
} else {
promises.failed(trackingResults);
}
}
|
javascript
|
{
"resource": ""
}
|
q46631
|
hasSupportVersion4
|
train
|
function hasSupportVersion4() {
//noinspection JSUnresolvedVariable
if (!android.support || !android.support.v4 || !android.support.v4.content || !android.support.v4.content.ContextCompat || !android.support.v4.content.ContextCompat.checkSelfPermission) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q46632
|
hasAndroidX
|
train
|
function hasAndroidX() {
//noinspection JSUnresolvedVariable
if (!global.androidx || !global.androidx.core || !global.androidx.core.content || !global.androidx.core.content.ContextCompat || !global.androidx.core.content.ContextCompat.checkSelfPermission) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q46633
|
getContext
|
train
|
function getContext() {
if (application.android.context) {
return (application.android.context);
}
if (typeof application.getNativeApplication === 'function') {
let ctx = application.getNativeApplication();
if (ctx) {
return ctx;
}
}
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
let ctx = java.lang.Class.forName("android.app.AppGlobals").getMethod("getInitialApplication", null).invoke(null, null);
if (ctx) return ctx;
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
ctx = java.lang.Class.forName("android.app.ActivityThread").getMethod("currentApplication", null).invoke(null, null);
if (ctx) return ctx;
return ctx;
}
|
javascript
|
{
"resource": ""
}
|
q46634
|
proxyLogRewrite
|
train
|
function proxyLogRewrite(daArgs) {
const args = Array.prototype.slice.call(daArgs);
return args.map(arg => {
if (typeof arg === 'string') {
return arg.replace(/\[HPM\] /g, '').replace(/ {2}/g, ' ');
}
return arg;
});
}
|
javascript
|
{
"resource": ""
}
|
q46635
|
formatMessage
|
train
|
function formatMessage(message) {
let lines = message.split('\n');
// Remove webpack-specific loader notation from filename.
// Before:
// ./~/css-loader!./~/postcss-loader!./src/App.css
// After:
// ./src/App.css
if (lines[0].lastIndexOf('!') !== -1) {
lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
}
// line #0 is filename
// line #1 is the main error message
if (!lines[0] || !lines[1]) {
return lines.join('\n');
}
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1].indexOf('Module not found: ') === 0) {
lines = [
lines[0],
// Clean up message because "Module not found: " is descriptive enough.
lines[1]
.replace("Cannot resolve 'file' or 'directory' ", '')
.replace('Cannot resolve module ', '')
.replace('Error: ', ''),
// Skip all irrelevant lines.
// (For some reason they only appear on the client in browser.)
'',
lines[lines.length - 1] // error location is the last line
];
}
// Cleans up syntax error messages.
if (lines[1].indexOf('Module build failed: ') === 0) {
const cleanedLines = [];
lines.forEach(line => {
if (line !== '') {
cleanedLines.push(line);
}
});
// We are clean now!
lines = cleanedLines;
// Finally, brush up the error message a little.
lines[1] = lines[1].replace('Module build failed: SyntaxError:', friendlySyntaxErrorLabel);
}
// Reassemble the message.
message = lines.join('\n');
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by WebPack. For more information see
// https://github.com/facebookincubator/create-react-app/pull/1050
message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y
return message;
}
|
javascript
|
{
"resource": ""
}
|
q46636
|
validate
|
train
|
function validate(options) {
if (is.undef(options.validator)) {
throw new Error('validator option undefined')
}
if (!is.function(options.validator) && !is.string(options.validator)) {
throw new Error(
`validator must be of type function or string, received ${typeof options.validator}`
)
}
const validatorName = is.string(options.validator) ? options.validator : ''
const validatorFn = getValidatorFn(options.validator)
if (is.undef(validatorFn)) {
throw new Error(
`validator \`${validatorName}\` does not exist in validator.js or as a custom validator`
)
}
const passIfEmpty = !!options.passIfEmpty
const mongooseOpts = omit(
options,
'passIfEmpty',
'message',
'validator',
'arguments'
)
const args = toArray(options.arguments)
const messageStr = findFirstString(
options.message,
customErrorMessages[validatorName],
defaultErrorMessages[validatorName],
'Error'
)
const message = interpolateMessageWithArgs(messageStr, args)
const validator = createValidator(validatorFn, args, passIfEmpty)
return Object.assign(
{
validator,
message,
},
mongooseOpts
)
}
|
javascript
|
{
"resource": ""
}
|
q46637
|
addResourceToMap
|
train
|
function addResourceToMap(map, def, start) {
var sched = JSON.parse(JSON.stringify(def.available || defaultSched)),
nextFn = schedule.memoizedRangeFn(later.schedule(sched).nextRange);
map[def.id] = { schedule: sched, next: nextFn, nextAvail: nextFn(start) };
}
|
javascript
|
{
"resource": ""
}
|
q46638
|
getReservation
|
train
|
function getReservation(resources, start, min, max) {
var reservation, schedules = [], delays = {},
maxTries = 50;
initRanges(resources, start, schedules, delays);
while(!(reservation = tryReservation(schedules, min, max)).success && --maxTries) {
updateRanges(schedules, nextValidStart(schedules), delays);
}
reservation.delays = delays;
return reservation;
}
|
javascript
|
{
"resource": ""
}
|
q46639
|
initRanges
|
train
|
function initRanges(resources, start, ranges, delays) {
for(var i = 0, len = resources.length; i < len; i++) {
var resId = resources[i];
// handles nested resources (OR)
if(Array.isArray(resId)) {
var subRanges = [], subDelays = {};
initRanges(resId, start, subRanges, subDelays);
var longDelay = getLongestDelay(subDelays);
if(longDelay) {
delays[longDelay] = subDelays[longDelay];
}
var schedule = {subRanges: subRanges};
setEarliestSubRange(schedule);
ranges.push(schedule);
}
else {
var res = rMap[resId],
range = res.nextAvail[0] >= start ? res.nextAvail :
res.next(start);
if(range[0] > start && resId !== '_proj') {
delays[resId] = { needed: start, available: range[0] };
}
ranges.push({id: resId, range: range});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46640
|
tryReservation
|
train
|
function tryReservation(schedules, min,max) {
var reservation = {success: false},
resources = [], start, end;
for(var i = 0, len = schedules.length; i < len; i++) {
var schedule = schedules[i],
range = schedule.range;
if(!isInternal(schedule)) {
resources.push(schedule.id);
}
start = !start || range[0] > start ? range[0] : start;
end = !end || range[1] < end ? range[1] : end;
}
var duration = (end - start) / later.MIN;
if(duration >= min || duration >= max) {
duration = max && duration > max ? max : duration;
reservation = createReservation(resources, start, duration);
}
return reservation;
}
|
javascript
|
{
"resource": ""
}
|
q46641
|
createReservation
|
train
|
function createReservation(resources, start, duration) {
var end = start + (duration * later.MIN),
reservation = {
resources: resources,
start: start,
end: end,
duration: duration,
success: true
};
applyReservation(resources, start, end);
return reservation;
}
|
javascript
|
{
"resource": ""
}
|
q46642
|
updateRanges
|
train
|
function updateRanges(resources, start, delays) {
for(var i = 0, len = resources.length; i < len; i++) {
var res = resources[i];
if(res.range[1] > start) continue;
if(res.subRanges) {
updateRanges(res.subRanges, start, {});
setEarliestSubRange(res);
}
else {
res.range = rMap[res.id].next(start);
if(res.id !== '_proj' && !delays[res.id]) {
delays[res.id] = { needed: start, available: res.range[0] };
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46643
|
nextValidStart
|
train
|
function nextValidStart(schedules) {
var latest;
for(var i = 0, len = schedules.length; i < len; i++) {
var end = schedules[i].range[1];
latest = !latest || end < latest ? end : latest;
}
return latest;
}
|
javascript
|
{
"resource": ""
}
|
q46644
|
getLongestDelay
|
train
|
function getLongestDelay(delays) {
var latest, lid;
for(var id in delays) {
var available = delays[id].available;
if(!latest || available < latest) {
latest = available;
lid = id;
}
}
return lid;
}
|
javascript
|
{
"resource": ""
}
|
q46645
|
train
|
function(arr, prefix, start) {
for(var i = 0, len = arr.length; i < len; i++) {
var def = typeof arr[i] !== 'object' ?
{ id: prefix + arr[i] } :
{ id: prefix + arr[i].id, available: arr[i].available, isNotReservable: arr[i].isNotReservable };
if(!rMap[def.id]) {
addResourceToMap(rMap, def, start);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46646
|
train
|
function(resources, start, min, max) {
start = start ? new Date(start) : new Date();
return getReservation(resources, start.getTime(), min || 1, max);
}
|
javascript
|
{
"resource": ""
}
|
|
q46647
|
resources
|
train
|
function resources(data) {
var items = [],
fid = schedule.functor(id),
favailable = schedule.functor(available),
freserve = schedule.functor(isNotReservable);
for(var i = 0, len = data.length; i < len; i++) {
var resource = data[i],
rId = fid.call(this, resource, i),
rAvailable = favailable.call(this, resource, i),
rReserve = freserve.call(this, resource, i);
items.push({id: rId, available: rAvailable, isNotReservable: rReserve});
}
return items;
}
|
javascript
|
{
"resource": ""
}
|
q46648
|
forwardPassTask
|
train
|
function forwardPassTask(task, start) {
var resAll = ['_proj', '_task' + task.id],
resources = task.resources ? resAll.concat(task.resources) : resAll,
duration = task.duration,
next = start,
scheduledTask = {schedule: [], duration: task.duration};
while(duration) {
var r = resMgr.makeReservation(resources, next, task.minSchedule || 1, duration);
if(!r.success) return undefined;
scheduledTask.earlyStart = scheduledTask.earlyStart || r.start;
scheduledTask.schedule.push(r);
duration -= r.duration;
next = r.end;
}
scheduledTask.earlyFinish = next;
scheduledTasks[task.id] = scheduledTask;
return next;
}
|
javascript
|
{
"resource": ""
}
|
q46649
|
createDependencyGraph
|
train
|
function createDependencyGraph(tasks) {
var graph = {
tasks: {},
roots: [],
leaves: [],
resources: [],
depth: 0,
end : 0
};
for(var i = 0, len = tasks.length; i < len; i++) {
var t = tasks[i];
graph.tasks[t.id] = {
id: t.id,
duration: t.duration,
priority: t.priority,
schedule: t.schedule,
minSchedule: t.minSchedule,
dependsOn: t.dependsOn,
resources: t.resources
};
}
setResources(graph);
setRequiredBy(graph.tasks);
setRootsAndLeaves(graph);
setDepth(graph, graph.leaves, 0);
graph.depth += 1; // increment depth so it is 1 based
forwardPass(graph, {}, graph.roots, 0);
setEnd(graph, graph.leaves);
backwardPass(graph, {}, graph.leaves, graph.end);
return graph;
}
|
javascript
|
{
"resource": ""
}
|
q46650
|
counter
|
train
|
function counter(state = 0, action = {}) {
switch (action.type) {
case INCREMENT_COUNTER:
return state + 1;
case DECREMENT_COUNTER:
return state - 1;
default:
return state;
}
}
|
javascript
|
{
"resource": ""
}
|
q46651
|
routeMatcher
|
train
|
function routeMatcher(route) {
var segments = route.replace(/^\/+|\/+$/, '').split(/\/+/);
var names = [];
var rules = [];
segments.forEach(function(segment){
var rule;
if (segment.charAt(0) === ':') {
names.push(segment.slice(1));
rules.push('([^\/]+)');
} else if (segment === '**') {
names.push('tail');
rules.push('(.+)');
} else {
rules.push(escapeRegExp(segment));
}
});
var regex = new RegExp('^\/' + rules.join('\/') + '\/?$', 'i');
var matcher = function(url) {
var match = url.match(regex);
if (! match) {
return;
}
var result = {};
names.forEach(function(name, i) {
result[name] = match[i + 1];
});
return result;
};
return matcher;
}
|
javascript
|
{
"resource": ""
}
|
q46652
|
exampleBookFunction
|
train
|
function exampleBookFunction(element, uniqueId) {
expect(element).not.toBeUndefined();
expect(element.length).toBe(1);
expect($('.inline-edit-btn-' + uniqueId).length).toBe(2); // two because there are two buttons per section
expect($('.inline-edit-btn-' + uniqueId + '-fa-book').length).toBe(1);
buttonSetupRunCount += 1;
}
|
javascript
|
{
"resource": ""
}
|
q46653
|
onEdit
|
train
|
function onEdit() {
var editor;
if (o.wysiwyg && $('#' + uniqueId).find('.wk-container').length === 0) {
// insert rich editor
var editorOptions = o.editorOptions || {};
editorOptions.textarea = $('#' + uniqueId + ' textarea')[0];
editorOptions.tagsModule = (editorOptions.tagsModule === true); // disable this to not require Bloodhound, unless overridden
editor = new PL.Editor(editorOptions);
}
_form.find('.cancel').click(function inlineEditCancelClick(e) {
e.preventDefault();
_form.hide();
});
_form.find('button.submit').click(function(e) {
prepareAndSendSectionForm(e, _form, editor, originalSectionMarkdown);
});
}
|
javascript
|
{
"resource": ""
}
|
q46654
|
train
|
function () {
var target = this.dragTarget;
target.off( DRAG_START_EVENT, target._dragStartHandler );
target.getPaper().off( DRAG_END_EVENT, target._dragEndHandler );
delete target._dragStartHandler;
delete target._dragEndHandler;
this.dragEnabled = false;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q46655
|
typedValue
|
train
|
function typedValue(value) {
if (value[0] == '!') value = value.substr(1)
var regex = value.match(/^\/(.*)\/(i?)$/);
var quotedString = value.match(/(["'])(?:\\\1|.)*?\1/);
if (regex) {
return new RegExp(regex[1], regex[2]);
} else if (quotedString) {
return quotedString[0].substr(1, quotedString[0].length - 2);
} else if (value === 'true') {
return true;
} else if (value === 'false') {
return false;
} else if (iso8601.test(value) && value.length !== 4) {
return new Date(value);
} else if (!isNaN(Number(value))) {
return Number(value);
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q46656
|
typedValues
|
train
|
function typedValues(svalue) {
var commaSplit = /("[^"]*")|('[^']*')|([^,]+)/g
var values = []
svalue
.match(commaSplit)
.forEach(function(value) {
values.push(typedValue(value))
})
return values;
}
|
javascript
|
{
"resource": ""
}
|
q46657
|
downloadMap
|
train
|
function downloadMap(map) {
let data = map.exportAsJSON(),
json = JSON.stringify(data),
blob = new Blob([json], {type: "application/json"}),
a = document.createElement("a");
a.download = "example.json";
a.href = URL.createObjectURL(blob);
a.click();
}
|
javascript
|
{
"resource": ""
}
|
q46658
|
uploadMap
|
train
|
function uploadMap(map, e) {
let reader = new window.FileReader();
reader.readAsText(e.target.files[0]);
reader.onload = function () {
let data = JSON.parse(event.target.result);
map.new(data);
};
}
|
javascript
|
{
"resource": ""
}
|
q46659
|
downloadImage
|
train
|
function downloadImage(map) {
map.exportAsImage(function (url) {
let a = document.createElement("a");
a.download = "example";
a.href = url;
a.click();
}, "jpeg");
}
|
javascript
|
{
"resource": ""
}
|
q46660
|
insertImage
|
train
|
function insertImage(map) {
let src = map.selectNode().image.src;
if (src === "") {
let value = prompt("Please enter your name", "example/img/material-icons/add.svg");
if (value) {
map.updateNode("imageSrc", value);
}
} else {
map.updateNode("imageSrc", "");
}
}
|
javascript
|
{
"resource": ""
}
|
q46661
|
bold
|
train
|
function bold(map) {
let value = map.selectNode().font.weight !== "bold" ? "bold" : "normal";
map.updateNode("fontWeight", value);
}
|
javascript
|
{
"resource": ""
}
|
q46662
|
italic
|
train
|
function italic(map) {
let value = map.selectNode().font.style !== "italic" ? "italic" : "normal";
map.updateNode("fontStyle", value);
}
|
javascript
|
{
"resource": ""
}
|
q46663
|
updateValues
|
train
|
function updateValues(node, map) {
dom.fontSize[map].value = node.fontSize;
dom.imageSize[map].value = node.image.size;
dom.backgroundColor[map].value = node.colors.background;
dom.branchColor[map].value = node.colors.branch || "#ffffff";
dom.nameColor[map].value = node.colors.name;
}
|
javascript
|
{
"resource": ""
}
|
q46664
|
sorter
|
train
|
function sorter (a, b) {
const aDist = a.distance == null ? -1 : a.distance
const bDist = b.distance == null ? -1 : b.distance
if (aDist < bDist) {
return 1
}
if (bDist < aDist) {
return -1
}
return 0
}
|
javascript
|
{
"resource": ""
}
|
q46665
|
createConnectionObject
|
train
|
function createConnectionObject(context) {
const { req } = context.bindings;
const xForwardedFor = req.headers ? req.headers["x-forwarded-for"] : undefined;
return {
encrypted : req.originalUrl && req.originalUrl.toLowerCase().startsWith("https"),
remoteAddress : removePortFromAddress(xForwardedFor)
};
}
|
javascript
|
{
"resource": ""
}
|
q46666
|
sanitizeContext
|
train
|
function sanitizeContext(context) {
const sanitizedContext = {
...context,
log : context.log.bind(context)
};
// We don't want the developper to mess up express flow
// See https://github.com/yvele/azure-function-express/pull/12#issuecomment-336733540
delete sanitizedContext.done;
return sanitizedContext;
}
|
javascript
|
{
"resource": ""
}
|
q46667
|
getLengthAngle
|
train
|
function getLengthAngle(x1, x2, y1, y2) {
var xDiff = x2 - x1;
var yDiff = y2 - y1;
return {
length: Math.ceil(Math.sqrt(xDiff * xDiff + yDiff * yDiff)),
angle: Math.round(Math.atan2(yDiff, xDiff) * 180 / Math.PI)
};
}
|
javascript
|
{
"resource": ""
}
|
q46668
|
distEuclidean
|
train
|
function distEuclidean(rgb0, rgb1) {
var rd = rgb1[0]-rgb0[0],
gd = rgb1[1]-rgb0[1],
bd = rgb1[2]-rgb0[2];
return Math.sqrt(Pr*rd*rd + Pg*gd*gd + Pb*bd*bd) / euclMax;
}
|
javascript
|
{
"resource": ""
}
|
q46669
|
distManhattan
|
train
|
function distManhattan(rgb0, rgb1) {
var rd = Math.abs(rgb1[0]-rgb0[0]),
gd = Math.abs(rgb1[1]-rgb0[1]),
bd = Math.abs(rgb1[2]-rgb0[2]);
return (Pr*rd + Pg*gd + Pb*bd) / manhMax;
}
|
javascript
|
{
"resource": ""
}
|
q46670
|
sortedHashKeys
|
train
|
function sortedHashKeys(obj, desc) {
var keys = [];
for (var key in obj)
keys.push(key);
return sort.call(keys, function(a,b) {
return desc ? obj[b] - obj[a] : obj[a] - obj[b];
});
}
|
javascript
|
{
"resource": ""
}
|
q46671
|
mergeAliases
|
train
|
function mergeAliases(stackName, newTemplate, currentTemplate, aliasStackTemplates, currentAliasStackTemplate, removedResources) {
const allAliasTemplates = _.concat(aliasStackTemplates, currentAliasStackTemplate);
// Get all referenced function logical resource ids
const aliasedFunctions =
_.flatMap(
allAliasTemplates,
template => _.compact(_.map(
template.Resources,
(resource, name) => {
if (resource.Type === 'AWS::Lambda::Alias') {
return {
name: _.replace(name, /Alias$/, 'LambdaFunction'),
version: _.replace(_.get(resource, 'Properties.FunctionVersion.Fn::ImportValue'), `${stackName}-`, '')
};
}
return null;
}
))
);
// Get currently deployed function definitions and versions and retain them in the stack update
const usedFunctionElements = {
Resources: _.map(aliasedFunctions, aliasedFunction => _.assign(
{},
_.pick(currentTemplate.Resources, [ aliasedFunction.name, aliasedFunction.version ])
)),
Outputs: _.map(aliasedFunctions, aliasedFunction => _.assign(
{},
_.pick(currentTemplate.Outputs, [ `${aliasedFunction.name}Arn`, aliasedFunction.version ])
))
};
_.forEach(usedFunctionElements.Resources, resources => _.defaults(newTemplate.Resources, resources));
_.forEach(usedFunctionElements.Outputs, outputs => _.defaults(newTemplate.Outputs, outputs));
// Set references to obsoleted resources in fct env to "REMOVED" in case
// the alias that is removed was the last deployment of the stage.
// This will change the function definition, but that does not matter
// as is is neither aliased nor versioned
_.forEach(_.filter(newTemplate.Resources, [ 'Type', 'AWS::Lambda::Function' ]), func => {
const refs = utils.findReferences(func, removedResources);
_.forEach(refs, ref => _.set(func, ref, "REMOVED"));
});
}
|
javascript
|
{
"resource": ""
}
|
q46672
|
Cabal
|
train
|
function Cabal (storage, key, opts) {
if (!(this instanceof Cabal)) return new Cabal(storage, key, opts)
if (!opts) opts = {}
events.EventEmitter.call(this)
var json = {
encode: function (obj) {
return Buffer.from(JSON.stringify(obj))
},
decode: function (buf) {
var str = buf.toString('utf8')
try { var obj = JSON.parse(str) } catch (err) { return {} }
return obj
}
}
this.maxFeeds = opts.maxFeeds
this.key = key || null
this.db = kappa(storage, {
valueEncoding: json
})
// Create (if needed) and open local write feed
var self = this
this.feed = thunky(function (cb) {
self.db.ready(function () {
self.db.feed('local', function (err, feed) {
if (!self.key) self.key = feed.key.toString('hex')
cb(feed)
})
})
})
// views
this.db.use('channels', createChannelView(memdb({ valueEncoding: json })))
this.db.use('messages', createMessagesView(memdb({ valueEncoding: json })))
this.db.use('topics', createTopicsView(memdb({ valueEncoding: json })))
this.db.use('users', createUsersView(memdb({ valueEncoding: json })))
this.messages = this.db.api.messages
this.channels = this.db.api.channels
this.topics = this.db.api.topics
this.users = this.db.api.users
}
|
javascript
|
{
"resource": ""
}
|
q46673
|
sanitize
|
train
|
function sanitize (msg) {
if (typeof msg !== 'object') return null
if (typeof msg.value !== 'object') return null
if (typeof msg.value.content !== 'object') return null
if (typeof msg.value.timestamp !== 'number') return null
if (typeof msg.value.type !== 'string') return null
if (typeof msg.value.content.channel !== 'string') return null
if (typeof msg.value.content.text !== 'string') return null
return msg
}
|
javascript
|
{
"resource": ""
}
|
q46674
|
sanitize
|
train
|
function sanitize (msg) {
if (typeof msg !== 'object') return null
if (typeof msg.value !== 'object') return null
if (typeof msg.value.content !== 'object') return null
if (typeof msg.value.timestamp !== 'number') return null
if (typeof msg.value.type !== 'string') return null
return msg
}
|
javascript
|
{
"resource": ""
}
|
q46675
|
train
|
function (core, channel, opts) {
opts = opts || {}
var t = through.obj()
if (opts.gt) opts.gt = 'msg!' + channel + '!' + charwise.encode(opts.gt) + '!'
else opts.gt = 'msg!' + channel + '!'
if (opts.lt) opts.lt = 'msg!' + channel + '!' + charwise.encode(opts.lt) + '~'
else opts.lt = 'msg!' + channel + '~'
this.ready(function () {
var v = lvl.createValueStream(xtend({reverse: true}, opts))
v.pipe(t)
})
return readonly(t)
}
|
javascript
|
{
"resource": ""
}
|
|
q46676
|
Confluence
|
train
|
function Confluence(config) {
if (!(this instanceof Confluence)) return new Confluence(config);
if (!config) {
throw new Error("Confluence module expects a config object.");
}
else if (!config.username || ! config.password) {
throw new Error("Confluence module expects a config object with both a username and password.");
}
else if (!config.baseUrl) {
throw new Error("Confluence module expects a config object with a baseUrl.");
}
this.config = config;
this.config.apiPath = '/rest/api';
this.config.extension = ''; // no extension by default
if (this.config.version && this.config.version === 4) {
this.config.apiPath = '/rest/prototype/latest';
this.config.extension = '.json';
}
}
|
javascript
|
{
"resource": ""
}
|
q46677
|
xsltPassThrough
|
train
|
function xsltPassThrough(input, template, output, outputDocument) {
if (template.nodeType == DOM_TEXT_NODE) {
if (xsltPassText(template)) {
let node = domCreateTextNode(outputDocument, template.nodeValue);
domAppendChild(output, node);
}
} else if (template.nodeType == DOM_ELEMENT_NODE) {
let node = domCreateElement(outputDocument, template.nodeName);
for (const a of template.attributes) {
if (a) {
const name = a.nodeName;
const value = xsltAttributeValue(a.nodeValue, input);
domSetAttribute(node, name, value);
}
}
domAppendChild(output, node);
xsltChildNodes(input, template, node);
} else {
// This applies also to the DOCUMENT_NODE of the XSL stylesheet,
// so we don't have to treat it specially.
xsltChildNodes(input, template, output);
}
}
|
javascript
|
{
"resource": ""
}
|
q46678
|
find
|
train
|
function find (by, value, strict) {
return new Promise((resolve, reject) => {
if (!(by in findBy)) {
reject(new Error(`do not support find by "${by}"`))
} else {
findBy[by](value, strict).then(resolve, reject)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q46679
|
renderNavbar
|
train
|
function renderNavbar() {
var navbar = $('#navbar ul')[0];
if (typeof (navbar) === 'undefined') {
loadNavbar();
} else {
$('#navbar ul a.active').parents('li').addClass(active);
renderBreadcrumb();
}
function loadNavbar() {
var navbarPath = $("meta[property='docfx\\:navrel']").attr("content");
if (!navbarPath) {
return;
}
navbarPath = navbarPath.replace(/\\/g, '/');
var tocPath = $("meta[property='docfx\\:tocrel']").attr("content") || '';
if (tocPath) tocPath = tocPath.replace(/\\/g, '/');
$.get(navbarPath, function (data) {
$(data).find("#toc>ul").appendTo("#navbar");
if ($('#search-results').length !== 0) {
$('#search').show();
$('body').trigger("searchEvent");
}
var index = navbarPath.lastIndexOf('/');
var navrel = '';
if (index > -1) {
navrel = navbarPath.substr(0, index + 1);
}
$('#navbar>ul').addClass('navbar-nav');
var currentAbsPath = util.getAbsolutePath(window.location.pathname);
// set active item
$('#navbar').find('a[href]').each(function (i, e) {
var href = $(e).attr("href");
if (util.isRelativePath(href)) {
href = navrel + href;
$(e).attr("href", href);
// TODO: currently only support one level navbar
var isActive = false;
var originalHref = e.name;
if (originalHref) {
originalHref = navrel + originalHref;
if (util.getDirectory(util.getAbsolutePath(originalHref)) === util.getDirectory(util.getAbsolutePath(tocPath))) {
isActive = true;
}
} else {
if (util.getAbsolutePath(href) === currentAbsPath) {
var dropdown = $(e).attr('data-toggle') == "dropdown"
if (!dropdown) {
isActive = true;
}
}
}
if (isActive) {
$(e).addClass(active);
}
}
});
renderNavbar();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q46680
|
autocenter
|
train
|
function autocenter(options) {
options = options || {};
var needsCentering = false;
var globe = null;
var resize = function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
globe.canvas.width = width;
globe.canvas.height = height;
globe.projection.translate([width / 2, height / 2]);
};
return function(planet) {
globe = planet;
planet.onInit(function() {
needsCentering = true;
d3.select(window).on('resize', function() {
needsCentering = true;
});
});
planet.onDraw(function() {
if (needsCentering) { resize(); needsCentering = false; }
});
};
}
|
javascript
|
{
"resource": ""
}
|
q46681
|
autoscale
|
train
|
function autoscale(options) {
options = options || {};
return function(planet) {
planet.onInit(function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
planet.projection.scale(Math.min(width, height) / 2);
});
};
}
|
javascript
|
{
"resource": ""
}
|
q46682
|
train
|
function() {
$module
.data(metadata.promise, false)
.data(metadata.xhr, false)
;
$context
.removeClass(className.error)
.removeClass(className.loading)
;
}
|
javascript
|
{
"resource": ""
}
|
|
q46683
|
train
|
function(member) {
users = $module.data('users');
if(member.id != 'anonymous' && users[ member.id ] === undefined ) {
users[ member.id ] = member.info;
if(settings.randomColor && member.info.color === undefined) {
member.info.color = settings.templates.color(member.id);
}
html = settings.templates.userList(member.info);
if(member.info.isAdmin) {
$(html)
.prependTo($userList)
;
}
else {
$(html)
.appendTo($userList)
;
}
if(settings.partingMessages) {
$log
.append( settings.templates.joined(member.info) )
;
module.message.scroll.test();
}
module.user.updateCount();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46684
|
train
|
function(member) {
users = $module.data('users');
if(member !== undefined && member.id !== 'anonymous') {
delete users[ member.id ];
$module
.data('users', users)
;
$userList
.find('[data-id='+ member.id + ']')
.remove()
;
if(settings.partingMessages) {
$log
.append( settings.templates.left(member.info) )
;
module.message.scroll.test();
}
module.user.updateCount();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46685
|
train
|
function(members) {
users = {};
members.each(function(member) {
if(member.id !== 'anonymous' && member.id !== 'undefined') {
if(settings.randomColor && member.info.color === undefined) {
member.info.color = settings.templates.color(member.id);
}
// sort list with admin first
html = (member.info.isAdmin)
? settings.templates.userList(member.info) + html
: html + settings.templates.userList(member.info)
;
users[ member.id ] = member.info;
}
});
$module
.data('users', users)
.data('user', users[members.me.id] )
.removeClass(className.loading)
;
$userList
.html(html)
;
module.user.updateCount();
$.proxy(settings.onJoin, $userList.children())();
}
|
javascript
|
{
"resource": ""
}
|
|
q46686
|
train
|
function() {
$log
.animate({
width: (module.width.log - module.width.userList)
}, {
duration : settings.speed,
easing : settings.easing,
complete : module.message.scroll.move
})
;
}
|
javascript
|
{
"resource": ""
}
|
|
q46687
|
train
|
function(message) {
if( !module.utils.emptyString(message) ) {
$.api({
url : settings.endpoint.message,
method : 'POST',
data : {
'message': {
content : message,
timestamp : new Date().getTime()
}
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46688
|
train
|
function(response) {
message = response.data;
users = $module.data('users');
loggedInUser = $module.data('user');
if(users[ message.userID] !== undefined) {
// logged in user's messages already pushed instantly
if(loggedInUser === undefined || loggedInUser.id != message.userID) {
message.user = users[ message.userID ];
module.message.display(message);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46689
|
train
|
function(message) {
$log
.append( settings.templates.message(message) )
;
module.message.scroll.test();
$.proxy(settings.onMessage, $log.children().last() )();
}
|
javascript
|
{
"resource": ""
}
|
|
q46690
|
train
|
function() {
var
message = $messageInput.val(),
loggedInUser = $module.data('user')
;
if(loggedInUser !== undefined && !module.utils.emptyString(message)) {
module.message.send(message);
// display immediately
module.message.display({
user: loggedInUser,
text: message
});
module.message.scroll.move();
$messageInput
.val('')
;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46691
|
train
|
function() {
if( !$module.hasClass(className.expand) ) {
$expandButton
.addClass(className.active)
;
module.expand();
}
else {
$expandButton
.removeClass(className.active)
;
module.contract();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46692
|
train
|
function() {
if( !$log.is(':animated') ) {
if( !$userListButton.hasClass(className.active) ) {
$userListButton
.addClass(className.active)
;
module.user.list.show();
}
else {
$userListButton
.removeClass('active')
;
module.user.list.hide();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46693
|
train
|
function(source, id, url) {
module.debug('Changing video to ', source, id, url);
$module
.data(metadata.source, source)
.data(metadata.id, id)
.data(metadata.url, url)
;
settings.onChange();
}
|
javascript
|
{
"resource": ""
}
|
|
q46694
|
train
|
function() {
module.debug('Playing video');
var
source = $module.data(metadata.source) || false,
url = $module.data(metadata.url) || false,
id = $module.data(metadata.id) || false
;
$embed
.html( module.generate.html(source, id, url) )
;
$module
.addClass(className.active)
;
settings.onPlay();
}
|
javascript
|
{
"resource": ""
}
|
|
q46695
|
train
|
function(source, id, url) {
module.debug('Generating embed html');
var
width = (settings.width == 'auto')
? $module.width()
: settings.width,
height = (settings.height == 'auto')
? $module.height()
: settings.height,
html
;
if(source && id) {
if(source == 'vimeo') {
html = ''
+ '<iframe src="http://player.vimeo.com/video/' + id + '?=' + module.generate.url(source) + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
else if(source == 'youtube') {
html = ''
+ '<iframe src="http://www.youtube.com/embed/' + id + '?=' + module.generate.url(source) + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
}
else if(url) {
html = ''
+ '<iframe src="' + url + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
else {
module.error(error.noVideo);
}
return html;
}
|
javascript
|
{
"resource": ""
}
|
|
q46696
|
train
|
function(source) {
var
api = (settings.api)
? 1
: 0,
autoplay = (settings.autoplay)
? 1
: 0,
hd = (settings.hd)
? 1
: 0,
showUI = (settings.showUI)
? 1
: 0,
// opposite used for some params
hideUI = !(settings.showUI)
? 1
: 0,
url = ''
;
if(source == 'vimeo') {
url = ''
+ 'api=' + api
+ '&title=' + showUI
+ '&byline=' + showUI
+ '&portrait=' + showUI
+ '&autoplay=' + autoplay
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
if(source == 'ustream') {
url = ''
+ 'autoplay=' + autoplay
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
else if(source == 'youtube') {
url = ''
+ 'enablejsapi=' + api
+ '&autoplay=' + autoplay
+ '&autohide=' + hideUI
+ '&hq=' + hd
+ '&modestbranding=1'
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
|
q46697
|
_getPostings
|
train
|
function _getPostings (options, markup) {
let
$ = cheerio.load(markup),
// hostname = options.hostname,
posting = {},
postings = [],
secure = options.secure;
$('div.content')
.find('.result-row')
.each((i, element) => {
let
// introducing fix for #11 - Craigslist markup changed
details = $(element)
.find('.result-title')
.attr('href')
.split(/\//g)
.filter((term) => term.length)
.map((term) => term.split(RE_HTML)[0]),
// fix for #6 and #24
detailsUrl = url.parse($(element)
.find('.result-title')
.attr('href'));
// ensure hostname and protocol are properly set
detailsUrl.hostname = detailsUrl.hostname || options.hostname;
detailsUrl.protocol = secure ? PROTOCOL_SECURE : PROTOCOL_INSECURE;
posting = {
category : details[DEFAULT_CATEGORY_DETAILS_INDEX],
coordinates : {
lat : $(element).attr('data-latitude'),
lon : $(element).attr('data-longitude')
},
date : ($(element)
.find('time')
.attr('datetime') || '')
.trim(),
hasPic : RE_TAGS_MAP
.test($(element)
.find('.result-tags')
.text() || ''),
location : ($(element)
.find('.result-hood')
.text() || '')
.trim(),
pid : ($(element)
.attr('data-pid') || '')
.trim(),
price : ($(element)
.find('.result-meta .result-price')
.text() || '')
.replace(/^\&\#x0024\;/g, '')
.trim(), // sanitize
title : ($(element)
.find('.result-title')
.text() || '')
.trim(),
url : detailsUrl.format()
};
// make sure lat / lon is valid
if (typeof posting.coordinates.lat === 'undefined' ||
typeof posting.coordinates.lon === 'undefined') {
delete posting.coordinates;
}
postings.push(posting);
});
return postings;
}
|
javascript
|
{
"resource": ""
}
|
q46698
|
multiplyInteger
|
train
|
function multiplyInteger(x, k) {
var temp,
carry = 0,
i = x.length;
for (x = x.slice(); i--;) {
temp = x[i] * k + carry;
x[i] = temp % BASE | 0;
carry = temp / BASE | 0;
}
if (carry) x.unshift(carry);
return x;
}
|
javascript
|
{
"resource": ""
}
|
q46699
|
getBase10Exponent
|
train
|
function getBase10Exponent(x) {
var e = x.e * LOG_BASE,
w = x.d[0];
// Add the number of digits of the first word of the digits array.
for (; w >= 10; w /= 10) e++;
return e;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.