_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q46500
|
_convertDetails
|
train
|
function _convertDetails(type, details) {
var convertedDetails = {}
for (var data in details) {
const string = type + '[' + data + ']';
convertedDetails[string] = details[data];
}
return convertedDetails;
}
|
javascript
|
{
"resource": ""
}
|
q46501
|
_parseJSON
|
train
|
async function _parseJSON(token) {
if (token._bodyInit == null) {
return token;
} else {
const body = await token.json();
return body;
}
}
|
javascript
|
{
"resource": ""
}
|
q46502
|
highlightMatches
|
train
|
function highlightMatches(chunks) {
return $.map(chunks, function (chunk) {
var text = utils.escapeHtml(chunk.text);
if (text && chunk.matched) {
text = '<strong>' + text + '</strong>';
}
return text;
}).join('');
}
|
javascript
|
{
"resource": ""
}
|
q46503
|
train
|
function (origin, elLayout) {
var that = this,
scrollLeft = that.$viewport.scrollLeft(),
style;
if (that.isMobile) {
style = that.options.floating ? {
left: scrollLeft + 'px',
top: elLayout.top + elLayout.outerHeight + 'px'
} : {
left: origin.left - elLayout.left + scrollLeft + 'px',
top: origin.top + elLayout.outerHeight + 'px'
};
style.width = that.$viewport.width() + 'px';
} else {
style = that.options.floating ? {
left: elLayout.left + 'px',
top: elLayout.top + elLayout.borderTop + elLayout.innerHeight + 'px'
} : {
left: origin.left + 'px',
top: origin.top + elLayout.borderTop + elLayout.innerHeight + 'px'
};
// Defer to let body show scrollbars
utils.delay(function () {
var width = that.options.width;
if (width === 'auto') {
width = that.el.outerWidth();
}
that.$container.outerWidth(width);
});
}
that.$container
.toggleClass(that.classes.mobile, that.isMobile)
.css(style);
that.containerItemsPadding = elLayout.left + elLayout.borderLeft + elLayout.paddingLeft - scrollLeft;
}
|
javascript
|
{
"resource": ""
}
|
|
q46504
|
train
|
function () {
var that = this;
return that.suggestions.length > 1 ||
(that.suggestions.length === 1 &&
(!that.selection || $.trim(that.suggestions[0].value) !== $.trim(that.selection.value))
);
}
|
javascript
|
{
"resource": ""
}
|
|
q46505
|
train
|
function () {
var that = this;
that.uniqueId = utils.uniqueId('i');
that.createWrapper();
that.notify('initialize');
that.bindWindowEvents();
that.setOptions();
that.fixPosition();
}
|
javascript
|
{
"resource": ""
}
|
|
q46506
|
train
|
function () {
var that = this,
events = 'mouseover focus keydown',
timer,
callback = function () {
that.initializer.resolve();
that.enable();
};
that.initializer.always(function(){
that.el.off(events, callback);
clearInterval(timer);
});
that.disabled = true;
that.el.on(events, callback);
timer = setInterval(function(){
if (that.el.is(':visible')) {
callback();
}
}, that.options.initializeInterval);
}
|
javascript
|
{
"resource": ""
}
|
|
q46507
|
train
|
function (e) {
var that = this,
elLayout = {},
wrapperOffset,
origin;
that.isMobile = that.$viewport.width() <= that.options.mobileWidth;
if (!that.isInitialized() || (e && e.type == 'scroll' && !(that.options.floating || that.isMobile))) return;
that.$container.appendTo(that.options.floating ? that.$body : that.$wrapper);
that.notify('resetPosition');
// reset input's padding to default, determined by css
that.el.css('paddingLeft', '');
that.el.css('paddingRight', '');
elLayout.paddingLeft = parseFloat(that.el.css('paddingLeft'));
elLayout.paddingRight = parseFloat(that.el.css('paddingRight'));
$.extend(elLayout, that.el.offset());
elLayout.borderTop = that.el.css('border-top-style') == 'none' ? 0 : parseFloat(that.el.css('border-top-width'));
elLayout.borderLeft = that.el.css('border-left-style') == 'none' ? 0 : parseFloat(that.el.css('border-left-width'));
elLayout.innerHeight = that.el.innerHeight();
elLayout.innerWidth = that.el.innerWidth();
elLayout.outerHeight = that.el.outerHeight();
elLayout.componentsLeft = 0;
elLayout.componentsRight = 0;
wrapperOffset = that.$wrapper.offset();
origin = {
top: elLayout.top - wrapperOffset.top,
left: elLayout.left - wrapperOffset.left
};
that.notify('fixPosition', origin, elLayout);
if (elLayout.componentsLeft > elLayout.paddingLeft) {
that.el.css('paddingLeft', elLayout.componentsLeft + 'px');
}
if (elLayout.componentsRight > elLayout.paddingRight) {
that.el.css('paddingRight', elLayout.componentsRight + 'px');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46508
|
train
|
function () {
var that = this,
fullQuery = that.extendedCurrentValue(),
currentValue = that.el.val(),
resolver = $.Deferred();
resolver
.done(function (suggestion) {
that.selectSuggestion(suggestion, 0, currentValue, { hasBeenEnriched: true });
that.el.trigger('suggestions-fixdata', suggestion);
})
.fail(function () {
that.selection = null;
that.el.trigger('suggestions-fixdata');
});
if (that.isQueryRequestable(fullQuery)) {
that.currentValue = fullQuery;
that.getSuggestions(fullQuery, { count: 1, from_bound: null, to_bound: null })
.done(function (suggestions) {
// data fetched
var suggestion = suggestions[0];
if (suggestion) {
resolver.resolve(suggestion);
} else {
resolver.reject();
}
})
.fail(function () {
// no data fetched
resolver.reject();
});
} else {
resolver.reject();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46509
|
train
|
function () {
var that = this,
parentInstance = that.getParentInstance(),
parentValue = parentInstance && parentInstance.extendedCurrentValue(),
currentValue = $.trim(that.el.val());
return utils.compact([parentValue, currentValue]).join(' ');
}
|
javascript
|
{
"resource": ""
}
|
|
q46510
|
train
|
function (query, customParams, requestOptions) {
var response,
that = this,
options = that.options,
noCallbacks = requestOptions && requestOptions.noCallbacks,
useEnrichmentCache = requestOptions && requestOptions.useEnrichmentCache,
method = requestOptions && requestOptions.method || that.requestMode.method,
params = that.constructRequestParams(query, customParams),
cacheKey = $.param(params || {}),
resolver = $.Deferred();
response = that.cachedResponse[cacheKey];
if (response && $.isArray(response.suggestions)) {
resolver.resolve(response.suggestions);
} else {
if (that.isBadQuery(query)) {
resolver.reject();
} else {
if (!noCallbacks && options.onSearchStart.call(that.element, params) === false) {
resolver.reject();
} else {
that.doGetSuggestions(params, method)
.done(function (response) {
// if response is correct and current value has not been changed
if (that.processResponse(response) && query == that.currentValue) {
// Cache results if cache is not disabled:
if (!options.noCache) {
if (useEnrichmentCache) {
that.enrichmentCache[query] = response.suggestions[0];
} else {
that.enrichResponse(response, query);
that.cachedResponse[cacheKey] = response;
if (options.preventBadQueries && response.suggestions.length === 0) {
that.badQueries.push(query);
}
}
}
resolver.resolve(response.suggestions);
} else {
resolver.reject();
}
if (!noCallbacks) {
options.onSearchComplete.call(that.element, query, response.suggestions);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
resolver.reject();
if (!noCallbacks && textStatus !== 'abort') {
options.onSearchError.call(that.element, query, jqXHR, textStatus, errorThrown);
}
});
}
}
}
return resolver;
}
|
javascript
|
{
"resource": ""
}
|
|
q46511
|
train
|
function (params, method) {
var that = this,
request = $.ajax(
that.getAjaxParams(method, { data: utils.serialize(params) })
);
that.abortRequest();
that.currentRequest = request;
that.notify('request');
request.always(function () {
that.currentRequest = null;
that.notify('request');
});
return request;
}
|
javascript
|
{
"resource": ""
}
|
|
q46512
|
train
|
function (response) {
var that = this,
suggestions;
if (!response || !$.isArray(response.suggestions)) {
return false;
}
that.verifySuggestionsFormat(response.suggestions);
that.setUnrestrictedValues(response.suggestions);
if ($.isFunction(that.options.onSuggestionsFetch)) {
suggestions = that.options.onSuggestionsFetch.call(that.element, response.suggestions);
if ($.isArray(suggestions)) {
response.suggestions = suggestions;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q46513
|
train
|
function (suggestion, selectionOptions) {
var that = this,
formatSelected = that.options.formatSelected || that.type.formatSelected,
hasSameValues = selectionOptions && selectionOptions.hasSameValues,
hasBeenEnriched = selectionOptions && selectionOptions.hasBeenEnriched,
formattedValue,
typeFormattedValue = null;
if ($.isFunction(formatSelected)) {
formattedValue = formatSelected.call(that, suggestion);
}
if (typeof formattedValue !== 'string') {
formattedValue = suggestion.value;
if (that.type.getSuggestionValue) {
typeFormattedValue = that.type.getSuggestionValue(that, {
suggestion: suggestion,
hasSameValues: hasSameValues,
hasBeenEnriched: hasBeenEnriched,
});
if (typeFormattedValue !== null) {
formattedValue = typeFormattedValue;
}
}
}
return formattedValue;
}
|
javascript
|
{
"resource": ""
}
|
|
q46514
|
train
|
function (suggestions) {
var that = this,
shouldRestrict = that.shouldRestrictValues(),
label = that.getFirstConstraintLabel();
$.each(suggestions, function (i, suggestion) {
if (!suggestion.unrestricted_value) {
suggestion.unrestricted_value = shouldRestrict ? label + ', ' + suggestion.value : suggestion.value;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46515
|
sameParentChecker
|
train
|
function sameParentChecker (preprocessFn) {
return function (suggestions) {
if (suggestions.length === 0) {
return false;
}
if (suggestions.length === 1) {
return true;
}
var parentValue = preprocessFn(suggestions[0].value),
aliens = suggestions.filter(function (suggestion) {
return preprocessFn(suggestion.value).indexOf(parentValue) !== 0;
});
return aliens.length === 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q46516
|
belongsToArea
|
train
|
function belongsToArea(suggestion, instance){
var parentSuggestion = instance.selection,
result = parentSuggestion && parentSuggestion.data && instance.bounds;
if (result) {
collection_util.each(instance.bounds.all, function (bound, i) {
return (result = parentSuggestion.data[bound] === suggestion.data[bound]);
});
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q46517
|
train
|
function (data) {
var that = this,
restrictedKeys = [],
unrestrictedData = {},
maxSpecificity = -1;
// Find most specific location that could restrict current data
collection_util.each(that.constraints, function (constraint, id) {
collection_util.each(constraint.locations, function (location, i) {
if (location.containsData(data) && location.specificity > maxSpecificity) {
maxSpecificity = location.specificity;
}
});
});
if (maxSpecificity >= 0) {
// Для городов-регионов нужно также отсечь и город
if (data.region_kladr_id && data.region_kladr_id === data.city_kladr_id) {
restrictedKeys.push.apply(restrictedKeys, that.type.dataComponentsById['city'].fields);
}
// Collect all fieldnames from all restricted components
collection_util.each(that.type.dataComponents.slice(0, maxSpecificity + 1), function (component, i) {
restrictedKeys.push.apply(restrictedKeys, component.fields);
});
// Copy skipping restricted fields
collection_util.each(data, function (value, key) {
if (restrictedKeys.indexOf(key) === -1) {
unrestrictedData[key] = value;
}
});
} else {
unrestrictedData = data;
}
return unrestrictedData;
}
|
javascript
|
{
"resource": ""
}
|
|
q46518
|
setAlternateAngular
|
train
|
function setAlternateAngular() {
// This method cannot be called more than once
if (alt_angular) {
throw new Error('setAlternateAngular can only be called once.');
} else {
alt_angular = {};
}
// Make sure that bootstrap has been called
checkBootstrapped();
// Create a a copy of orig_angular with on demand loading capability
orig_angular.extend(alt_angular, orig_angular);
// Custom version of angular.module used as cache
alt_angular.module = function (name, requires) {
if (typeof requires === 'undefined') {
// Return module from alternate_modules if it was created using the alt_angular
if (alternate_modules_tracker.hasOwnProperty(name)) {
return alternate_modules[name];
} else {
return orig_angular.module(name);
}
} else {
var orig_mod = orig_angular.module.apply(null, arguments),
item = { name: name, module: orig_mod};
alternate_queue.push(item);
orig_angular.extend(orig_mod, onDemandLoader);
/*
Use `alternate_modules_tracker` to track which module has been created by alt_angular
but use `alternate_modules` to cache the module created. This is to simplify the
removal of cached modules after .processQueue.
*/
alternate_modules_tracker[name] = true;
alternate_modules[name] = orig_mod;
// Return created module
return orig_mod;
}
};
window.angular = alt_angular;
if (require.defined('angular')) {
require.undef('angular');
define('angular', [], alt_angular);
}
}
|
javascript
|
{
"resource": ""
}
|
q46519
|
applyBasePath
|
train
|
function applyBasePath(search) {
if (_.isUndefined(config.basePath)) {
return search;
}
var modifyKeys = ['Bucket', 'CopySource'];
var ret = _.mapObject(search, function (value, key) {
if (_.indexOf(modifyKeys, key) === -1) {
return value;
}
else {
return config.basePath + '/' + value;
}
})
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q46520
|
S3Mock
|
train
|
function S3Mock(options) {
if (!_.isUndefined(options) && !_.isUndefined(options.params)) {
this.defaultOptions = _.extend({}, applyBasePath(options.params));
}
this.config = {
update: function() {}
};
}
|
javascript
|
{
"resource": ""
}
|
q46521
|
train
|
function(params, callback) {
var err = null;
if (typeof(params) === "object" && params !== null)
{
if(typeof(params.Bucket) !== "string" || params.Bucket.length <= 0)
{
err = new Error("Mock-AWS-S3: Argument 'params' must contain a 'Bucket' (String) property");
}
}
else {
err = new Error("Mock-AWS-S3: Argument 'params' must be an Object");
}
var opts = _.extend({}, this.defaultOptions, applyBasePath(params));
if (err !== null) {
callback(err);
}
var bucketPath = opts.basePath || "";
bucketPath += opts.Bucket;
fs.remove(bucketPath, function(err) {
return callback(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46522
|
CRC8
|
train
|
function CRC8(polynomial) { // constructor takes an optional polynomial type from CRC8.POLY
if (polynomial == null) polynomial = CRC8.POLY.CRC8_CCITT
//if (polynomial == null) polynomial = CRC8.POLY.CRC8_DALLAS_MAXIM
this.table = CRC8.generateTable(polynomial);
}
|
javascript
|
{
"resource": ""
}
|
q46523
|
createElements
|
train
|
function createElements(tagName, attrs, children) {
const element = isSVG(tagName)
? document.createElementNS('http://www.w3.org/2000/svg', tagName)
: document.createElement(tagName)
// one or multiple will be evaluated to append as string or HTMLElement
const fragment = createFragmentFrom(children)
element.appendChild(fragment)
Object.keys(attrs || {}).forEach(prop => {
if (prop === 'style') {
// e.g. origin: <element style={{ prop: value }} />
Object.assign(element.style, attrs[prop])
} else if (prop === 'ref' && typeof attrs.ref === 'function') {
attrs.ref(element, attrs)
} else if (prop === 'className') {
element.setAttribute('class', attrs[prop])
} else if (prop === 'xlinkHref') {
element.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', attrs[prop])
} else if (prop === 'dangerouslySetInnerHTML') {
// eslint-disable-next-line no-underscore-dangle
element.innerHTML = attrs[prop].__html
} else {
// any other prop will be set as attribute
element.setAttribute(prop, attrs[prop])
}
})
return element
}
|
javascript
|
{
"resource": ""
}
|
q46524
|
composeToFunction
|
train
|
function composeToFunction(JSXTag, elementProps, children) {
const props = Object.assign({}, JSXTag.defaultProps || {}, elementProps, { children })
const bridge = JSXTag.prototype.render ? new JSXTag(props).render : JSXTag
const result = bridge(props)
switch (result) {
case 'FRAGMENT':
return createFragmentFrom(children)
// Portals are useful to render modals
// allow render on a different element than the parent of the chain
// and leave a comment instead
case 'PORTAL':
bridge.target.appendChild(createFragmentFrom(children))
return document.createComment('Portal Used')
default:
return result
}
}
|
javascript
|
{
"resource": ""
}
|
q46525
|
versionRelease
|
train
|
function versionRelease(version) {
return new Promise((resolve, reject) => {
const [pkgPath, pkg] = getPackageObject();
const bumpVersion = (version, isReleaseType, throwOnEqual) => {
const newVersion = isReleaseType ? semver.inc(pkg.version, version) : semver.valid(version);
if (newVersion === null) {
reject(new Error(`version must be one of: "recommended", first", major", "minor", "patch", or a semantic version`));
return;
}
if (throwOnEqual && semver.eq(pkg.version, newVersion)) {
reject(new Error(`version to be bumped is equal to package version: ${newVersion}`));
return;
}
const oldVersion = pkg.version;
pkg.version = newVersion;
try {
fs.writeFileSync(pkgPath, JSON.stringify(pkg, undefined, tabAsSpace));
// Update version in package-lock file
const [pkgLckPath, pkgLck] = getPackageObject(undefined, "package-lock.json");
pkgLck.version = newVersion;
fs.writeFileSync(pkgLckPath, JSON.stringify(pkgLck, undefined, tabAsSpace));
} catch (err) {
reject(new Error(`version couldn't be bumped: ${err.message}`));
return;
}
resolve(`bumped from ${oldVersion} to ${newVersion}`);
};
if (version === "recommended") {
conventionalRecommendedBump({
preset: "angular"
}, (err, result) => {
if (err) {
reject(new Error(`conventional recommended bump failed: ${err.message}`));
return;
}
bumpVersion(result.releaseType, true, true);
});
return;
}
if (version === "first") {
bumpVersion(pkg.version, false, false);
return;
}
const isReleaseType = version === "major" || version === "minor" || version === "patch";
bumpVersion(version, isReleaseType, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q46526
|
cutRelease
|
train
|
function cutRelease(releaseNote) {
const [pkgPath, pkg] = getPackageObject();
const msg = getCommitTagMessage(pkg.version);
return updateChangelogInternal(pkg.version, releaseNote)
// Stage and commit all new, modified, and deleted files in the entire working directory
.then(() => runCommand("git add --all"))
.then(() => runCommand(`git commit --no-verify -m "${msg}"`))
// Make an unsigned annotated tag, replacing an existing tag with the same version
.then(output => {
return runCommand(`git tag -a -f -m "${msg}" v${pkg.version}`)
.then(() => `updated CHANGELOG, committed and tagged ${output}\n\n` +
"You can now push the tagged release: npm run push-release");
});
}
|
javascript
|
{
"resource": ""
}
|
q46527
|
publishRelease
|
train
|
function publishRelease(npmDistTag) {
const tag = npmDistTag || "latest";
const distPath = path.resolve(process.cwd(), "dist");
const distFolders = [];
const asyncInSeries = (items, asyncFunc) => {
return new Promise((resolve, reject) => {
const series = index => {
if (index === items.length) {
resolve();
return;
}
asyncFunc(items[index])
.then(() => series(index + 1))
.catch(error => reject(error));
};
series(0);
});
};
for (const file of fs.readdirSync(distPath)) {
let projectPath = path.join(distPath, file);
if (fs.lstatSync(projectPath).isFile() && file === "package.json") {
// Assume the dist folder itself is the only project to be published
distFolders.splice(0);
distFolders.push(distPath);
break;
}
if (fs.lstatSync(projectPath).isDirectory()) {
distFolders.push(projectPath);
}
}
return Promise.resolve()
// Authentication is based on an OAuth provider.
// Get the relevant authentication and paste it into your ~/.npmrc or invoke "npm adduser".
// For details see here
// https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-NpmPublish(DeployingPackages)
// .then(() => runCommandWithRedirectedIo(`npm login --always-auth --registry=${reg}`))
.then(() => asyncInSeries(distFolders, folder => runCommandWithRedirectedIo(`npm publish "${folder}" --tag=${tag}`)))
.then(() => `published ${distFolders.length} distribution packages on '${tag}' tag to npm registry`);
}
|
javascript
|
{
"resource": ""
}
|
q46528
|
runCommand
|
train
|
function runCommand(command) {
return new Promise((resolve, reject) => {
utils.logInfo(`Command: ${command}`);
childProcess.exec(command, (error, stdout, stderr) => {
// If exec returns content in stderr, but no error, print it as a warning.
// If exec returns an error, reject the promise.
if (error) {
reject(error);
return;
} else if (stderr) {
utils.logInfo(stderr);
}
resolve(stdout);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q46529
|
clean
|
train
|
function clean() {
const distDir = "./dist";
try {
fse.readdirSync(distDir).forEach(file => {
let filePath = path.resolve(distDir, file);
if (fse.lstatSync(filePath).isDirectory()) {
logInfo("Clean distribution package " + file);
try {
rimraf.sync(filePath);
} catch (e) {
logError("Could not clean distribution package: " + e);
}
}
});
} catch (e) { }
}
|
javascript
|
{
"resource": ""
}
|
q46530
|
build
|
train
|
function build(pkgName, pkgVersion) {
clean();
// Update framework name/version/build date in Runtime class
updateRuntimeInfo(Date.now(), pkgName, pkgVersion);
const buildDir = "./build";
fse.readdirSync(buildDir).forEach(file => {
if (file.match(/tsconfig\..+\.json/gi)) {
const tsconfigPath = path.resolve(buildDir, file);
const opts = require(tsconfigPath).compilerOptions;
const target = opts.target + "-" + opts.module;
const targetDir = "./dist/" + target + "/";
logInfo("Build distribution package " + target);
// First, bring the desired tsconfig file into place
fse.copySync(tsconfigPath, "./" + TS_TARGETDIR + "/tsconfig.json");
// Transpile TS into JS code, using TS compiler in local typescript npm package.
// Remove all comments except copy-right header comments, and do not
// generate corresponding .d.ts files (see next step below).
childProcess.execSync(path.resolve("./node_modules/.bin/tsc") +
" --project " + TS_TARGETDIR +
" --outDir " + targetDir +
" --removeComments true --declaration false",
// redirect child output to parent's stdin, stdout and stderr
{ stdio: "inherit" });
// Only emit .d.ts files, using TS compiler in local typescript npm package.
// The generated declaration files include all comments so that
// IDEs can provide this information to developers.
childProcess.execSync(path.resolve("./node_modules/.bin/tsc") +
" --project " + TS_TARGETDIR +
" --outDir " + targetDir +
" --removeComments false --declaration true --emitDeclarationOnly true",
// redirect child output to parent's stdin, stdout and stderr
{ stdio: "inherit" });
// Copy scripts folder into distribution package
fse.copySync("./scripts", targetDir + "scripts");
// Copy readme into distribution package
fse.copySync("./README.md", targetDir + "README.md");
// Copy license into distribution package
fse.copySync("./LICENSE", targetDir + "LICENSE");
// Copy tslint.json into distribution package (for use by Coaty projects)
fse.copySync("./build/tslint.json", targetDir + "tslint-config.json");
// Copy .npmignore into distribution package
fse.copySync("./.npmignore", targetDir + ".npmignore");
// Copy package.json into distribution package
fse.copySync("./package.json", targetDir + "package.json");
// Update package.json to include distribution as prerelease in version
updatePackageInfo(target, targetDir + "package.json", file !== "tsconfig.es5-commonjs.json");
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46531
|
info
|
train
|
function info(agentInfoFolder, defaultBuildMode) {
return new Promise((resolve, reject) => {
const result = generateAgentInfoFile(agentInfoFolder || "./src/", undefined, undefined, defaultBuildMode);
resolve(result[1]);
});
}
|
javascript
|
{
"resource": ""
}
|
q46532
|
gulpBuildAgentInfo
|
train
|
function gulpBuildAgentInfo(agentInfoFolder, agentInfoFilename, packageFile) {
if (agentInfoFilename === undefined) {
agentInfoFilename = "agent.info.ts";
}
if (packageFile === undefined) {
packageFile = "package.json";
}
return () => {
const gulp = require("gulp");
const result = generateAgentInfoFile(agentInfoFolder, agentInfoFilename, packageFile);
return gulp.src(result[0]);
};
}
|
javascript
|
{
"resource": ""
}
|
q46533
|
generateAgentInfoFile
|
train
|
function generateAgentInfoFile(agentInfoFolder, agentInfoFilename, packageFile, defaultBuildMode) {
if (agentInfoFilename === undefined) {
agentInfoFilename = "agent.info.ts";
}
if (packageFile === undefined) {
packageFile = "package.json";
}
const fs = require("fs");
const path = require("path");
const agentInfoResult = generateAgentInfo(packageFile, defaultBuildMode);
const agentInfoCode = agentInfoResult[0];
const buildMode = agentInfoResult[1];
const file = path.resolve(agentInfoFolder, agentInfoFilename);
if (fs.statSync(path.resolve(agentInfoFolder)).isDirectory()) {
fs.writeFileSync(file, agentInfoCode);
return [file, buildMode];
}
throw new Error(`specified agentInfoFolder is not a directory: ${agentInfoFolder}`);
}
|
javascript
|
{
"resource": ""
}
|
q46534
|
generateAgentInfo
|
train
|
function generateAgentInfo(packageFile, defaultBuildMode) {
if (defaultBuildMode === undefined) {
defaultBuildMode = "development";
}
const path = require("path");
const pkg = require(path.resolve(packageFile));
const buildMode = process.env.COATY_ENV || defaultBuildMode;
const buildDate = utils.toLocalIsoString(new Date());
const serviceHost = process.env.COATY_SERVICE_HOST || "";
const copyrightYear = new Date().getFullYear();
return ["/*! -----------------------------------------------------------------------------\n * <auto-generated>\n * This code was generated by a tool.\n * Changes to this file may cause incorrect behavior and will be lost if\n * the code is regenerated.\n * </auto-generated>\n * ------------------------------------------------------------------------------\n * Copyright (c) " + copyrightYear + " Siemens AG. Licensed under the MIT License.\n */\n\nimport { AgentInfo } from \"coaty/runtime\";\n\nexport const agentInfo: AgentInfo = {\n packageInfo: {\n name: \"" + (pkg.name || "n.a.") + "\",\n version: \"" + (pkg.version || "n.a.") + "\",\n },\n buildInfo: {\n buildDate: \"" + buildDate + "\",\n buildMode: \"" + buildMode + "\",\n },\n configInfo: {\n serviceHost: \"" + serviceHost + "\",\n },\n};\n",
buildMode];
}
|
javascript
|
{
"resource": ""
}
|
q46535
|
toLocalIsoString
|
train
|
function toLocalIsoString(date, includeMillis) {
if (includeMillis === undefined) {
includeMillis = false;
}
const pad = (n, length, padChar) => {
if (length === undefined) { length = 2; }
if (padChar === undefined) { padChar = "0"; }
let str = "" + n;
while (str.length < length) {
str = padChar + str;
}
return str;
};
const getOffsetFromUTC = () => {
const offset = date.getTimezoneOffset();
if (offset === 0) {
return "Z";
}
return (offset < 0 ? "+" : "-")
+ pad(Math.abs(offset / 60), 2) + ":"
+ pad(Math.abs(offset % 60), 2);
};
return date.getFullYear() + "-"
+ pad(date.getMonth() + 1) + "-"
+ pad(date.getDate()) + "T"
+ pad(date.getHours()) + ":"
+ pad(date.getMinutes()) + ":"
+ pad(date.getSeconds())
+ (includeMillis ? "." + pad(date.getMilliseconds(), 3) : "")
+ getOffsetFromUTC();
}
|
javascript
|
{
"resource": ""
}
|
q46536
|
copy
|
train
|
function copy(text) {
var fakeElem = document.body.appendChild(document.createElement('textarea'));
fakeElem.style.position = 'absolute';
fakeElem.style.left = '-9999px';
fakeElem.setAttribute('readonly', '');
fakeElem.value = text;
fakeElem.select();
try {
return document.execCommand('copy');
} catch (err) {
return false;
} finally {
fakeElem.parentNode.removeChild(fakeElem);
}
}
|
javascript
|
{
"resource": ""
}
|
q46537
|
cleanPipeName
|
train
|
function cleanPipeName(str) {
if (process.platform === 'win32' && !str.startsWith('\\\\.\\pipe\\')) {
str = str.replace(/^\//, '');
str = str.replace(/\//g, '-');
return '\\\\.\\pipe\\' + str;
} else {
return str;
}
}
|
javascript
|
{
"resource": ""
}
|
q46538
|
emitOverFastPath
|
train
|
function emitOverFastPath(state, msgObj, messageJson) {
if (!state.options.node.useFastPath) return; // disabled
var others = OTHER_INSTANCES[state.channelName].filter(function (s) {
return s !== state;
});
var checkObj = {
time: msgObj.time,
senderUuid: msgObj.uuid,
token: msgObj.token
};
others.filter(function (otherState) {
return _filterMessage(checkObj, otherState);
}).forEach(function (otherState) {
otherState.messagesCallback(messageJson);
});
}
|
javascript
|
{
"resource": ""
}
|
q46539
|
whenDeathListener
|
train
|
function whenDeathListener(msg) {
if (msg.context === 'leader' && msg.action === 'death') {
leaderElector.applyOnce().then(function () {
if (leaderElector.isLeader) finish();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q46540
|
writeMessage
|
train
|
function writeMessage(db, readerUuid, messageJson) {
var time = new Date().getTime();
var writeObject = {
uuid: readerUuid,
time: time,
data: messageJson
};
var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');
return new Promise(function (res, rej) {
transaction.oncomplete = function () {
return res();
};
transaction.onerror = function (ev) {
return rej(ev);
};
var objectStore = transaction.objectStore(OBJECT_STORE_ID);
objectStore.add(writeObject);
});
}
|
javascript
|
{
"resource": ""
}
|
q46541
|
readNewMessages
|
train
|
function readNewMessages(state) {
// channel already closed
if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages
if (!state.messagesCallback) return Promise.resolve();
return getMessagesHigherThen(state.db, state.lastCursorId).then(function (newerMessages) {
var useMessages = newerMessages.map(function (msgObj) {
if (msgObj.id > state.lastCursorId) {
state.lastCursorId = msgObj.id;
}
return msgObj;
}).filter(function (msgObj) {
return _filterMessage(msgObj, state);
}).sort(function (msgObjA, msgObjB) {
return msgObjA.time - msgObjB.time;
}); // sort by time
useMessages.forEach(function (msgObj) {
if (state.messagesCallback) {
state.eMIs.add(msgObj.id);
state.messagesCallback(msgObj.data);
}
});
return Promise.resolve();
});
}
|
javascript
|
{
"resource": ""
}
|
q46542
|
listenerFn
|
train
|
function listenerFn(msgObj) {
channel._addEL[msgObj.type].forEach(function (obj) {
if (msgObj.time >= obj.time) {
obj.fn(msgObj.data);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46543
|
_sendMessage
|
train
|
function _sendMessage(leaderElector, action) {
const msgJson = {
context: 'leader',
action,
token: leaderElector.token
};
return leaderElector._channel.postInternal(msgJson);
}
|
javascript
|
{
"resource": ""
}
|
q46544
|
createSocketInfoFile
|
train
|
function createSocketInfoFile(channelName, readerUuid, paths) {
const pathToFile = socketInfoPath(channelName, readerUuid, paths);
return writeFile(
pathToFile,
JSON.stringify({
time: microSeconds()
})
).then(() => pathToFile);
}
|
javascript
|
{
"resource": ""
}
|
q46545
|
countChannelFolders
|
train
|
async function countChannelFolders() {
await ensureBaseFolderExists();
const folders = await readdir(TMP_FOLDER_BASE);
return folders.length;
}
|
javascript
|
{
"resource": ""
}
|
q46546
|
getReadersUuids
|
train
|
async function getReadersUuids(channelName, paths) {
paths = paths || getPaths(channelName);
const readersPath = paths.readers;
const files = await readdir(readersPath);
return files
.map(file => file.split('.'))
.filter(split => split[1] === 'json') // do not scan .socket-files
.map(split => split[0]);
}
|
javascript
|
{
"resource": ""
}
|
q46547
|
create
|
train
|
async function create(channelName, options = {}) {
options = fillOptionsWithDefaults(options);
const time = microSeconds();
const paths = getPaths(channelName);
const ensureFolderExistsPromise = ensureFoldersExist(channelName, paths);
const uuid = randomToken(10);
const state = {
time,
channelName,
options,
uuid,
paths,
// contains all messages that have been emitted before
emittedMessagesIds: new ObliviousSet(options.node.ttl * 2),
messagesCallbackTime: null,
messagesCallback: null,
// ensures we do not read messages in parrallel
writeBlockPromise: Promise.resolve(),
otherReaderClients: {},
// ensure if process crashes, everything is cleaned up
removeUnload: unload.add(() => close(state)),
closed: false
};
if (!OTHER_INSTANCES[channelName]) OTHER_INSTANCES[channelName] = [];
OTHER_INSTANCES[channelName].push(state);
await ensureFolderExistsPromise;
const [
socketEE,
infoFilePath
] = await Promise.all([
createSocketEventEmitter(channelName, uuid, paths),
createSocketInfoFile(channelName, uuid, paths),
refreshReaderClients(state)
]);
state.socketEE = socketEE;
state.infoFilePath = infoFilePath;
// when new message comes in, we read it and emit it
socketEE.emitter.on('data', data => {
// if the socket is used fast, it may appear that multiple messages are flushed at once
// so we have to split them before
const singleOnes = data.split('|');
singleOnes
.filter(single => single !== '')
.forEach(single => {
try {
const obj = JSON.parse(single);
handleMessagePing(state, obj);
} catch (err) {
throw new Error('could not parse data: ' + single);
}
});
});
return state;
}
|
javascript
|
{
"resource": ""
}
|
q46548
|
handleMessagePing
|
train
|
async function handleMessagePing(state, msgObj) {
/**
* when there are no listener, we do nothing
*/
if (!state.messagesCallback) return;
let messages;
if (!msgObj) {
// get all
messages = await getAllMessages(state.channelName, state.paths);
} else {
// get single message
messages = [
getSingleMessage(state.channelName, msgObj, state.paths)
];
}
const useMessages = messages
.filter(msgObj => _filterMessage(msgObj, state))
.sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); // sort by time
// if no listener or message, so not do anything
if (!useMessages.length || !state.messagesCallback) return;
// read contents
await Promise.all(
useMessages
.map(
msgObj => readMessage(msgObj).then(content => msgObj.content = content)
)
);
useMessages.forEach(msgObj => {
state.emittedMessagesIds.add(msgObj.token);
if (state.messagesCallback) {
// emit to subscribers
state.messagesCallback(msgObj.content.data);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46549
|
train
|
function () {
/**
* The callback function grabbed from the array-like arguments
* object. The first argument should always be the callback.
*
* @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}
* @type {*}
*/
var callback = arguments[0];
/**
* Arguments to be passed to the callback. These are taken
* from the array-like arguments object. The first argument
* is stripped because that should be the callback function.
*
* @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}
* @type {Array}
*/
var args = Array.prototype.slice.call(arguments, 1);
if (angular.isDefined(callback)) {
scope.$evalAsync(function () {
if (angular.isFunction(callback)) {
callback(args);
} else {
throw new Error('ui-ace use a function as callback.');
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46550
|
train
|
function (callback) {
return function (e) {
var newValue = session.getValue();
if (ngModel && newValue !== ngModel.$viewValue &&
// HACK make sure to only trigger the apply outside of the
// digest loop 'cause ACE is actually using this callback
// for any text transformation !
!scope.$$phase && !scope.$root.$$phase) {
scope.$evalAsync(function () {
ngModel.$setViewValue(newValue);
});
}
executeUserCallback(callback, e, acee);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q46551
|
train
|
function (current, previous) {
if (current === previous) return;
opts = angular.extend({}, options, scope.$eval(attrs.uiAce));
opts.callbacks = [ opts.onLoad ];
if (opts.onLoad !== options.onLoad) {
// also call the global onLoad handler
opts.callbacks.unshift(options.onLoad);
}
// EVENTS
// unbind old change listener
session.removeListener('change', onChangeListener);
// bind new change listener
onChangeListener = listenerFactory.onChange(opts.onChange);
session.on('change', onChangeListener);
// unbind old blur listener
//session.removeListener('blur', onBlurListener);
acee.removeListener('blur', onBlurListener);
// bind new blur listener
onBlurListener = listenerFactory.onBlur(opts.onBlur);
acee.on('blur', onBlurListener);
setOptions(acee, session, opts);
}
|
javascript
|
{
"resource": ""
}
|
|
q46552
|
addGraphics
|
train
|
function addGraphics(buffer) {
layer.add(new Graphic({
geometry: meteorPoint,
symbol: pointSym
}));
layer.add(new Graphic({
geometry: buffer,
symbol: polySym
}));
return buffer;
}
|
javascript
|
{
"resource": ""
}
|
q46553
|
zoomTo
|
train
|
function zoomTo(geom) {
// when the view is ready
return self.view.when(function() {
// zoom to the buffer geometry
return self.view.goTo({
target: geom,
scale: 24000,
tilt: 0,
heading: 0
}).then(function() {
// resolve the promises with the input geometry
return geom;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q46554
|
train
|
function(path) {
var pathParts = this.getPathParts(path),
tabs,
page;
if (pathParts.length === 0) {
return;
}
page = pathParts[0];
if (!page) {
return;
}
if (page === 'examples' && pathParts.length > 1) {
tabs = [];
tabs.push('app/examples/' + pathParts[1] + '.html');
tabs.push('app/examples/' + pathParts[1] + '.js');
return tabs;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46555
|
train
|
function(data, configUpdater) {
var updater = configUpdater || function(config) {return config;};
$rootScope.$broadcast('event:auth-loginConfirmed', data);
httpBuffer.retryAll(updater);
}
|
javascript
|
{
"resource": ""
}
|
|
q46556
|
train
|
function(updater) {
for (var i = 0; i < buffer.length; ++i) {
var _cfg = updater(buffer[i].config);
if (_cfg !== false)
retryHttpRequest(_cfg, buffer[i].deferred);
}
buffer = [];
}
|
javascript
|
{
"resource": ""
}
|
|
q46557
|
train
|
function(color) {
var self = this;
var $colorSpan = self.$colorList.find('> span.color').filter(function() {
return $(this).data('color').toLowerCase() === color.toLowerCase();
});
if ($colorSpan.length > 0) {
self.selectColorSpan($colorSpan);
} else {
console.error("The given color '" + color + "' could not be found");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46558
|
findMatchingSimulator
|
train
|
function findMatchingSimulator(simulators, simulatorName) {
if (!simulators.devices) {
return null;
}
const devices = simulators.devices;
var match;
for (let version in devices) {
// Making sure the version of the simulator is an iOS (Removes Apple Watch, etc)
if (version.indexOf('iOS') !== 0) {
continue;
}
for (let i in devices[version]) {
let simulator = devices[version][i];
// Skipping non-available simulator
if (simulator.availability !== '(available)') {
continue;
}
// If there is a booted simulator, we'll use that as instruments will not boot a second simulator
if (simulator.state === 'Booted') {
if (simulatorName !== null) {
console.warn("We couldn't boot your defined simulator due to an already booted simulator. We are limited to one simulator launched at a time.");
}
return {
udid: simulator.udid,
name: simulator.name,
version
};
}
if (simulator.name === simulatorName) {
return {
udid: simulator.udid,
name: simulator.name,
version
};
}
// Keeps track of the first available simulator for use if we can't find one above.
if (simulatorName === null && !match) {
match = {
udid: simulator.udid,
name: simulator.name,
version
};
}
}
}
if (match) {
return match;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q46559
|
sign
|
train
|
function sign(file_data) {
var first_time = file_data.indexOf(TOKEN) !== -1;
if (!first_time) {
if (is_signed(file_data))
file_data = file_data.replace(PATTERN, signing_token());
else
throw exports.TokenNotFoundError;
}
var signature = md5_hash_hex(file_data, 'utf8');
var signed_data = file_data.replace(TOKEN, 'SignedSource<<'+signature+'>>');
return { first_time: first_time, signed_data: signed_data };
}
|
javascript
|
{
"resource": ""
}
|
q46560
|
verify_signature
|
train
|
function verify_signature(file_data) {
var match = PATTERN.exec(file_data);
if (!match)
return exports.SIGN_UNSIGNED;
// Replace the signature with the TOKEN, then hash and see if it matches
// the value in the file. For backwards compatibility, also try with
// OLDTOKEN if that doesn't match.
var k, token, with_token, actual_md5, expected_md5 = match[1];
for (k in TOKENS) {
token = TOKENS[k];
with_token = file_data.replace(PATTERN, '@'+'generated '+token);
actual_md5 = md5_hash_hex(with_token, 'utf8');
if (expected_md5 === actual_md5)
return exports.SIGN_OK;
}
return exports.SIGN_INVALID;
}
|
javascript
|
{
"resource": ""
}
|
q46561
|
copyToClipBoard
|
train
|
function copyToClipBoard(content) {
switch (process.platform) {
case 'darwin':
var child = spawn('pbcopy', []);
child.stdin.end(new Buffer(content, 'utf8'));
return true;
default:
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q46562
|
generate
|
train
|
function generate(argv, config) {
return new Promise((resolve, reject) => {
_generate(argv, config, resolve, reject);
});
}
|
javascript
|
{
"resource": ""
}
|
q46563
|
server
|
train
|
function server(argv, config, args) {
const roots = args.projectRoots.concat(args.root);
args.projectRoots = roots.concat(
findSymlinksPaths(NODE_MODULES, roots)
);
console.log(formatBanner(
'Running packager on port ' + args.port + '.\n\n' +
'Keep this packager running while developing on any JS projects. ' +
'Feel free to close this tab and run your own packager instance if you ' +
'prefer.\n\n' +
'https://github.com/facebook/react-native', {
marginLeft: 1,
marginRight: 1,
paddingBottom: 1,
})
);
console.log(
'Looking for JS files in\n ',
chalk.dim(args.projectRoots.join('\n ')),
'\n'
);
process.on('uncaughtException', error => {
if (error.code === 'EADDRINUSE') {
console.log(
chalk.bgRed.bold(' ERROR '),
chalk.red('Packager can\'t listen on port', chalk.bold(args.port))
);
console.log('Most likely another process is already using this port');
console.log('Run the following command to find out which process:');
console.log('\n ', chalk.bold('lsof -n -i4TCP:' + args.port), '\n');
console.log('You can either shut down the other process:');
console.log('\n ', chalk.bold('kill -9 <PID>'), '\n');
console.log('or run packager on different port.');
} else {
console.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message));
const errorAttributes = JSON.stringify(error);
if (errorAttributes !== '{}') {
console.error(chalk.red(errorAttributes));
}
console.error(chalk.red(error.stack));
}
console.log('\nSee', chalk.underline('http://facebook.github.io/react-native/docs/troubleshooting.html'));
console.log('for common problems and solutions.');
process.exit(11);
});
runServer(args, config, () => console.log('\nReact packager ready.\n'));
}
|
javascript
|
{
"resource": ""
}
|
q46564
|
findParentDirectory
|
train
|
function findParentDirectory(currentFullPath, filename) {
const root = path.parse(currentFullPath).root;
const testDir = (parts) => {
if (parts.length === 0) {
return null;
}
const fullPath = path.join(root, parts.join(path.sep));
var exists = fs.existsSync(path.join(fullPath, filename));
return exists ? fullPath : testDir(parts.slice(0, -1));
};
return testDir(currentFullPath.substring(root.length).split(path.sep));
}
|
javascript
|
{
"resource": ""
}
|
q46565
|
changedKeys
|
train
|
function changedKeys(props, newProps) {
return Object.keys(props).filter(key => {
return props[key] !== newProps[key];
});
}
|
javascript
|
{
"resource": ""
}
|
q46566
|
computedReduxProperty
|
train
|
function computedReduxProperty(key, getProps) {
return computed({
get: () => getProps()[key],
set: () => { assert(`Cannot set redux property "${key}". Try dispatching a redux action instead.`); }
});
}
|
javascript
|
{
"resource": ""
}
|
q46567
|
getAttrs
|
train
|
function getAttrs(context) {
const keys = Object.keys(context.attrs || {});
return getProperties(context, keys);
}
|
javascript
|
{
"resource": ""
}
|
q46568
|
train
|
function (index) {
var $rating = this.$rating;
// Get the index of the last whole symbol.
var i = Math.floor(index);
// Hide completely hidden symbols background.
$rating.find('.rating-symbol-background')
.css('visibility', 'visible')
.slice(0, i).css('visibility', 'hidden');
var $rates = $rating.find('.rating-symbol-foreground');
// Reset foreground
$rates.width(0);
// Fill all the foreground symbols up to the selected one.
$rates.slice(0, i).width('auto')
.find('span').attr('class', this.options.filled);
// Amend selected symbol.
$rates.eq(index % 1 ? i : i - 1)
.find('span').attr('class', this.options.filledSelected);
// Partially fill the fractional one.
$rates.eq(i).width(index % 1 * 100 + '%');
}
|
javascript
|
{
"resource": ""
}
|
|
q46569
|
train
|
function (index) {
return this.options.start + Math.floor(index) * this.options.step +
this.options.step * this._roundToFraction(index % 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q46570
|
train
|
function (index) {
// Get the closest top fraction.
var fraction = Math.ceil(index % 1 * this.options.fractions) / this.options.fractions;
// Truncate decimal trying to avoid float precission issues.
var p = Math.pow(10, this.options.scale);
return Math.floor(index) + Math.floor(fraction * p) / p;
}
|
javascript
|
{
"resource": ""
}
|
|
q46571
|
train
|
function (rate) {
var value = parseFloat(rate);
if (this._contains(value)) {
this._fillUntil(this._rateToIndex(value));
this.$input.val(value);
} else if (rate === '') {
this._fillUntil(0);
this.$input.val('');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46572
|
isModifiedSince
|
train
|
function isModifiedSince(req, res) {
try {
if (req.headers['if-unmodified-since']) {
const jobTime = Date.parse(req.headers['if-unmodified-since']);
const revInfo = mwUtil.parseETag(res.headers.etag);
return revInfo && uuid.fromString(revInfo.tid).getDate() >= jobTime;
}
} catch (e) {
// Ignore errors from date parsing
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q46573
|
_dependenciesUpdate
|
train
|
function _dependenciesUpdate(hyper, req, newContent = true) {
const rp = req.params;
return mwUtil.getSiteInfo(hyper, req)
.then((siteInfo) => {
const baseUri = siteInfo.baseUri.replace(/^https?:/, '');
const publicURI = `${baseUri}/page/html/${encodeURIComponent(rp.title)}`;
const body = [ { meta: { uri: `${publicURI}/${rp.revision}` } } ];
if (newContent) {
body.push({ meta: { uri: publicURI } });
}
return hyper.post({
uri: new URI([rp.domain, 'sys', 'events', '']),
body
}).catch((e) => {
hyper.logger.log('warn/bg-updates', e);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q46574
|
checkContentType
|
train
|
function checkContentType(hyper, req, next, expectedContentType, responsePromise) {
return responsePromise
.then((res) => {
// Do not check or re-render if the response was only rendered within
// the last two minutes.
if (res.headers && res.headers.etag &&
Date.now() - mwUtil.extractDateFromEtag(res.headers.etag) < 120000) {
return res;
}
if (res.headers && res.headers === undefined) {
delete res.headers['content-type'];
}
if (res.headers &&
res.headers['content-type'] &&
res.headers['content-type'] !== expectedContentType) {
// Parse the expected & response content type, and compare profiles.
const expectedProfile = cType.parse(expectedContentType).parameters.profile;
const actualProfile = cType.parse(res.headers['content-type']).parameters.profile;
if (actualProfile && actualProfile !== expectedProfile) {
if (!expectedProfile) {
return res;
}
// Check if actual content type is newer than the spec
const actualProfileParts = splitProfile(actualProfile);
const expectedProfileParts = splitProfile(expectedProfile);
if (actualProfileParts.path === expectedProfileParts.path &&
semver.gt(actualProfileParts.version, expectedProfileParts.version)) {
return res;
}
}
// Re-try request with no-cache header
if (!mwUtil.isNoCacheRequest(req)) {
req.headers['cache-control'] = 'no-cache';
return checkContentType(hyper, req, next, expectedContentType, next(hyper, req));
} else {
// Log issue
hyper.logger.log('warn/content-type/upgrade_failed', {
msg: 'Could not update the content-type',
expected: expectedContentType,
actual: res.headers['content-type']
});
// Disable response caching, as we aren't setting a vary
// either.
res.headers['cache-control'] = 'max-age=0, s-maxage=0';
}
}
// Default: Just return.
return res;
});
}
|
javascript
|
{
"resource": ""
}
|
q46575
|
getUserFromSocket
|
train
|
function getUserFromSocket(socket, callback) {
let wait = false;
try {
if (socket.handshake.headers.cookie && (!socket.request || !socket.request._query || !socket.request._query.user)) {
let cookie = decodeURIComponent(socket.handshake.headers.cookie);
let m = cookie.match(/connect\.sid=(.+)/);
if (m) {
// If session cookie exists
let c = m[1].split(';')[0];
let sessionID = cookieParser.signedCookie(c, that.settings.secret);
if (sessionID) {
// Get user for session
wait = true;
that.settings.store.get(sessionID, function (err, obj) {
if (obj && obj.passport && obj.passport.user) {
socket._sessionID = sessionID;
if (typeof callback === 'function') {
callback(null, obj.passport.user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
}
if (!wait) {
let user = socket.request._query.user;
let pass = socket.request._query.pass;
if (user && pass) {
wait = true;
that.adapter.checkPassword(user, pass, function (res) {
if (res) {
that.adapter.log.debug('Logged in: ' + user);
if (typeof callback === 'function') {
callback(null, user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
that.adapter.log.warn('Invalid password or user name: ' + user + ', ' + pass[0] + '***(' + pass.length + ')');
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
} catch (e) {
that.adapter.log.error(e);
wait = false;
}
if (!wait && typeof callback === 'function') {
callback('Cannot detect user');
}
}
|
javascript
|
{
"resource": ""
}
|
q46576
|
updateSession
|
train
|
function updateSession(socket) {
if (socket._sessionID) {
let time = (new Date()).getTime();
if (socket._lastActivity && time - socket._lastActivity > settings.ttl * 1000) {
socket.emit('reauthenticate');
socket.disconnect();
return false;
}
socket._lastActivity = time;
if (!socket._sessionTimer) {
socket._sessionTimer = setTimeout(function () {
socket._sessionTimer = null;
that.settings.store.get(socket._sessionID, function (err, obj) {
if (obj) {
that.adapter.setSession(socket._sessionID, settings.ttl, obj);
} else {
socket.emit('reauthenticate');
socket.disconnect();
}
});
}, 60000);
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q46577
|
verifyModules
|
train
|
function verifyModules(filePaths) {
return Promise.all(
_.map(filePaths, function(filePath) {
return firstline(filePath).then(function(line) {
var matches = line.match(/^(?:(?:port|effect)\s+)?module\s+(\S+)\s*/);
if (matches) {
var moduleName = matches[1];
var testModulePaths = moduleFromTestName(moduleName);
var modulePath = moduleFromFilePath(filePath);
// A module path matches if it lines up completely with a known one.
if (
!testModulePaths.every(function(testModulePath, index) {
return testModulePath === modulePath[index];
})
) {
return Promise.reject(
filePath +
' has a module declaration of "' +
moduleName +
'" - which does not match its filename!'
);
}
} else {
return Promise.reject(
filePath +
' has an invalid module declaration. Check the first line of the file and make sure it has a valid module declaration there!'
);
}
});
})
);
}
|
javascript
|
{
"resource": ""
}
|
q46578
|
_VirtualDom_pairwiseRefEqual
|
train
|
function _VirtualDom_pairwiseRefEqual(as, bs)
{
for (var i = 0; i < as.length; i++)
{
if (as[i] !== bs[i])
{
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q46579
|
mousedown
|
train
|
function mousedown(e, space) {
var offset = plate.offset(),
isTouch = /^touch/.test(e.type),
x0 = offset.left + dialRadius,
y0 = offset.top + dialRadius,
dx = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
dy = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0,
z = Math.sqrt(dx * dx + dy * dy),
moved = false;
// When clicking on minutes view space, check the mouse position
if (space && (z < outerRadius - tickRadius || z > outerRadius + tickRadius))
return;
e.preventDefault();
// Set cursor style of body after 200ms
var movingTimer = setTimeout(function(){
self.popover.addClass('clockpicker-moving');
}, 200);
// Place the canvas to top
if (svgSupported)
plate.append(self.canvas);
// Clock
self.setHand(dx, dy, !space, true);
// Mousemove on document
$doc.off(mousemoveEvent).on(mousemoveEvent, function(e){
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0;
if (! moved && x === dx && y === dy)
// Clicking in chrome on windows will trigger a mousemove event
return;
moved = true;
self.setHand(x, y, false, true);
});
// Mouseup on document
$doc.off(mouseupEvent).on(mouseupEvent, function(e) {
$doc.off(mouseupEvent);
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.changedTouches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.changedTouches[0] : e).pageY - y0;
if ((space || moved) && x === dx && y === dy)
self.setHand(x, y);
if (self.currentView === 'hours')
self.toggleView('minutes', duration / 2);
else
if (options.autoclose) {
self.minutesView.addClass('clockpicker-dial-out');
setTimeout(function(){
self.done();
}, duration / 2);
}
plate.prepend(canvas);
// Reset cursor style of body
clearTimeout(movingTimer);
self.popover.removeClass('clockpicker-moving');
// Unbind mousemove event
$doc.off(mousemoveEvent);
});
}
|
javascript
|
{
"resource": ""
}
|
q46580
|
setScopeValues
|
train
|
function setScopeValues(scope, attrs) {
scope.List = [];
scope.Hide = false;
scope.page = parseInt(scope.page) || 1;
scope.total = parseInt(scope.total) || 0;
scope.dots = scope.dots || '...';
scope.ulClass = scope.ulClass || attrs.ulClass || 'pagination';
scope.adjacent = parseInt(scope.adjacent) || 2;
scope.activeClass = 'active';
scope.disabledClass = 'disabled';
scope.scrollTop = scope.$eval(attrs.scrollTop);
scope.hideIfEmpty = scope.$eval(attrs.hideIfEmpty);
scope.showPrevNext = scope.$eval(attrs.showPrevNext);
scope.useSimplePrevNext = scope.$eval(attrs.useSimplePrevNext);
}
|
javascript
|
{
"resource": ""
}
|
q46581
|
validateScopeValues
|
train
|
function validateScopeValues(scope, pageCount) {
// Block where the page is larger than the pageCount
if (scope.page > pageCount) {
scope.page = pageCount;
}
// Block where the page is less than 0
if (scope.page <= 0) {
scope.page = 1;
}
// Block where adjacent value is 0 or below
if (scope.adjacent <= 0) {
scope.adjacent = 2;
}
// Hide from page if we have 1 or less pages
// if directed to hide empty
if (pageCount <= 1) {
scope.Hide = scope.hideIfEmpty;
}
}
|
javascript
|
{
"resource": ""
}
|
q46582
|
internalAction
|
train
|
function internalAction(scope, page) {
page = page.valueOf();
// Block clicks we try to load the active page
if (scope.page == page) {
return;
}
// Update the page in scope and fire any paging actions
scope.page = page;
scope.paginationAction({
page: page
});
// If allowed scroll up to the top of the page
if (scope.scrollTop) {
scrollTo(0, 0);
}
}
|
javascript
|
{
"resource": ""
}
|
q46583
|
addRange
|
train
|
function addRange(start, finish, scope) {
var i = 0;
for (i = start; i <= finish; i++) {
var item = {
value: $sce.trustAsHtml(i.toString()),
liClass: scope.page == i ? scope.activeClass : 'waves-effect',
action: function() {
internalAction(scope, this.value);
}
};
scope.List.push(item);
}
}
|
javascript
|
{
"resource": ""
}
|
q46584
|
build
|
train
|
function build(scope, attrs) {
// Block divide by 0 and empty page size
if (!scope.pageSize || scope.pageSize < 0)
{
return;
}
// Assign scope values
setScopeValues(scope, attrs);
// local variables
var start,
size = scope.adjacent * 2,
pageCount = Math.ceil(scope.total / scope.pageSize);
// Validation Scope
validateScopeValues(scope, pageCount);
// Add the Next and Previous buttons to our list
addPrevNext(scope, pageCount, 'prev');
if (pageCount < (5 + size)) {
start = 1;
addRange(start, pageCount, scope);
} else {
var finish;
if (scope.page <= (1 + size)) {
start = 1;
finish = 2 + size + (scope.adjacent - 1);
addRange(start, finish, scope);
addLast(pageCount, scope, finish);
} else if (pageCount - size > scope.page && scope.page > size) {
start = scope.page - scope.adjacent;
finish = scope.page + scope.adjacent;
addFirst(scope, start);
addRange(start, finish, scope);
addLast(pageCount, scope, finish);
} else {
start = pageCount - (1 + size + (scope.adjacent - 1));
finish = pageCount;
addFirst(scope, start);
addRange(start, finish, scope);
}
}
addPrevNext(scope, pageCount, 'next');
}
|
javascript
|
{
"resource": ""
}
|
q46585
|
init
|
train
|
function init() {
element.addClass("tooltipped");
$compile(element.contents())(scope);
$timeout(function () {
// https://github.com/Dogfalo/materialize/issues/3546
// if element.addClass("tooltipped") would not be executed, then probably this would not be needed
if (element.attr('data-tooltip-id')){
element.tooltip('remove');
}
element.tooltip();
});
rmDestroyListener = scope.$on('$destroy', function () {
element.tooltip("remove");
});
}
|
javascript
|
{
"resource": ""
}
|
q46586
|
getFilePathFromUrl
|
train
|
function getFilePathFromUrl(url, basePath, { pathLib = path } = {}) {
if (!basePath) {
throw new Error('basePath must be specified');
}
if (!pathLib.isAbsolute(basePath)) {
throw new Error(`${basePath} is invalid - must be absolute`);
}
const relativePath = url.split('?')[0];
if (relativePath.indexOf('../') > -1) {
// any path attempting to traverse up the directory should be rejected
return 'dummy';
}
const absolutePath = pathLib.join(basePath, relativePath);
if (
!absolutePath.startsWith(basePath) || // if the path has broken out of the basePath, it should be rejected
absolutePath.endsWith(pathLib.sep) // only files (not folders) can be served
) {
return 'dummy';
}
return absolutePath;
}
|
javascript
|
{
"resource": ""
}
|
q46587
|
Lock
|
train
|
function Lock(target, name, descriptor) {
let fn = descriptor.value;
let $$LockIsDoing = false;
let reset = ()=>$$LockIsDoing=false;
descriptor.value = function(...args) {
if ($$LockIsDoing) return;
$$LockIsDoing = true;
let ret = fn.apply(this, args);
if (ret && ret.then) {
// is promise
return ret.then((succ)=>{
reset();
return Promise.resolve(succ);
}, (fail)=>{
reset();
return Promise.reject(fail);
});
} else {
reset();
return ret;
}
};
return descriptor;
}
|
javascript
|
{
"resource": ""
}
|
q46588
|
Deprecate
|
train
|
function Deprecate(methodDescriptor) {
let {descriptor, key} = methodDescriptor;
let fn = descriptor.value;
descriptor.value = function(...args) {
console.warn(`DEPRECATE: [${key}] This function will be removed in future versions.`);
return fn.apply(this, args);
};
return {
...methodDescriptor,
descriptor,
};
}
|
javascript
|
{
"resource": ""
}
|
q46589
|
train
|
function(template) {
// Automatically add the `.html` extension.
template = template + ".html";
// Put this fetch into `async` mode to work better in the Node environment.
var done = this.async();
// By default read in the file from the filesystem relative to the code
// being executed.
fs.readFile(template, function(err, contents) {
// Ensure the contents are a String.
contents = String(contents);
// Any errors should be reported.
if (err) {
console.error("Unable to load file " + template + " : " + err);
return done(null);
}
// Pass the template contents back up.
done(_.template(contents));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46590
|
train
|
function(rendered, manager, def) {
// Actually put the rendered contents into the element.
if (_.isString(rendered)) {
// If no container is specified, we must replace the content.
if (manager.noel) {
rendered = $.parseHTML(rendered, true);
// Remove extra root elements.
this.$el.slice(1).remove();
// Swap out the View on the first top level element to avoid
// duplication.
this.$el.replaceWith(rendered);
// Don't delegate events here - we'll do that in resolve()
this.setElement(rendered, false);
} else {
this.html(this.$el, rendered);
}
}
// Resolve only after fetch and render have succeeded.
def.resolveWith(this, [this]);
}
|
javascript
|
{
"resource": ""
}
|
|
q46591
|
done
|
train
|
function done(context, template) {
// Store the rendered template someplace so it can be re-assignable.
var rendered;
// Trigger this once the render method has completed.
manager.callback = function(rendered) {
// Clean up asynchronous manager properties.
delete manager.isAsync;
delete manager.callback;
root._applyTemplate(rendered, manager, def);
};
// Ensure the cache is up-to-date.
LayoutManager.cache(url, template);
// Render the View into the el property.
if (template) {
rendered = root.renderTemplate.call(root, template, context);
}
// If the function was synchronous, continue execution.
if (!manager.isAsync) {
root._applyTemplate(rendered, manager, def);
}
}
|
javascript
|
{
"resource": ""
}
|
q46592
|
Layout
|
train
|
function Layout(options) {
// Grant this View superpowers.
this.manage = true;
// Give this View access to all passed options as instance properties.
_.extend(this, options);
// Have Backbone set up the rest of this View.
Backbone.View.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q46593
|
train
|
function(selector, view) {
// If the `view` argument exists, then a selector was passed in. This code
// path will forward the selector on to `setView`.
if (view) {
return this.setView(selector, view, true);
}
// If no `view` argument is defined, then assume the first argument is the
// View, somewhat now confusingly named `selector`.
return this.setView(selector, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q46594
|
train
|
function(views) {
// If an array of views was passed it should be inserted into the
// root view. Much like calling insertView without a selector.
if (_.isArray(views)) {
return this.setViews({ "": views });
}
_.each(views, function(view, selector) {
views[selector] = _.isArray(view) ? view : [view];
});
return this.setViews(views);
}
|
javascript
|
{
"resource": ""
}
|
|
q46595
|
train
|
function(fn) {
var views;
// If the filter argument is a String, then return a chained Version of the
// elements. The value at the specified filter may be undefined, a single
// view, or an array of views; in all cases, chain on a flat array.
if (typeof fn === "string") {
fn = this.sections[fn] || fn;
views = this.views[fn] || [];
// If Views is undefined you are concatenating an `undefined` to an array
// resulting in a value being returned. Defaulting to an array prevents
// this.
//return _.chain([].concat(views || []));
return _.chain([].concat(views));
}
// Generate an array of all top level (no deeply nested) Views flattened.
views = _.chain(this.views).map(function(view) {
return _.isArray(view) ? view : [view];
}, this).flatten();
// If the argument passed is an Object, then pass it to `_.where`.
if (typeof fn === "object") {
return views.where(fn);
}
// If a filter function is provided, run it on all Views and return a
// wrapped chain. Otherwise, simply return a wrapped chain of all Views.
return typeof fn === "function" ? views.filter(fn) : views;
}
|
javascript
|
{
"resource": ""
}
|
|
q46596
|
train
|
function(fn) {
var views;
// Allow an optional selector or function to find the right model and
// remove nested Views based off the results of the selector or filter.
views = this.getViews(fn).each(function(nestedView) {
nestedView.remove();
});
// call value incase the chain is evaluated lazily to ensure the views get
// removed
views.value();
return views;
}
|
javascript
|
{
"resource": ""
}
|
|
q46597
|
train
|
function(views) {
// Iterate over all the views and use the View's view method to assign.
_.each(views, function(view, name) {
// If the view is an array put all views into insert mode.
if (_.isArray(view)) {
return _.each(view, function(view) {
this.insertView(name, view);
}, this);
}
// Assign each view using the view function.
this.setView(name, view);
}, this);
// Allow for chaining
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q46598
|
resolve
|
train
|
function resolve() {
// Insert all subViews into the parent at once.
_.each(root.views, function(views, selector) {
// Fragments aren't used on arrays of subviews.
if (_.isArray(views)) {
root.htmlBatch(root, views, selector);
}
});
// If there is a parent and we weren't attached to it via the previous
// method (single view), attach.
if (parent && !manager.insertedViaFragment) {
if (!root.contains(parent.el, root.el)) {
// Apply the partial using parent's html() method.
parent.partial(parent.$el, root.$el, rentManager, manager);
}
}
// Ensure events are always correctly bound after rendering.
root.delegateEvents();
// Set this View as successfully rendered.
root.hasRendered = true;
manager.renderInProgress = false;
// Clear triggeredByRAF flag.
delete manager.triggeredByRAF;
// Only process the queue if it exists.
if (manager.queue && manager.queue.length) {
// Ensure that the next render is only called after all other
// `done` handlers have completed. This will prevent `render`
// callbacks from firing out of order.
(manager.queue.shift())();
} else {
// Once the queue is depleted, remove it, the render process has
// completed.
delete manager.queue;
}
// Reusable function for triggering the afterRender callback and event.
function completeRender() {
var console = window.console;
var afterRender = root.afterRender;
if (afterRender) {
afterRender.call(root, root);
}
// Always emit an afterRender event.
root.trigger("afterRender", root);
// If there are multiple top level elements and `el: false` is used,
// display a warning message and a stack trace.
if (manager.noel && root.$el.length > 1) {
// Do not display a warning while testing or if warning suppression
// is enabled.
if (_.isFunction(console.warn) && !root.suppressWarnings) {
console.warn("`el: false` with multiple top level elements is " +
"not supported.");
// Provide a stack trace if available to aid with debugging.
if (_.isFunction(console.trace)) {
console.trace();
}
}
}
}
// If the parent is currently rendering, wait until it has completed
// until calling the nested View's `afterRender`.
if (rentManager && (rentManager.renderInProgress || rentManager.queue)) {
// Wait until the parent View has finished rendering, which could be
// asynchronous, and trigger afterRender on this View once it has
// completed.
parent.once("afterRender", completeRender);
} else {
// This View and its parent have both rendered.
completeRender();
}
return def.resolveWith(root, [root]);
}
|
javascript
|
{
"resource": ""
}
|
q46599
|
completeRender
|
train
|
function completeRender() {
var console = window.console;
var afterRender = root.afterRender;
if (afterRender) {
afterRender.call(root, root);
}
// Always emit an afterRender event.
root.trigger("afterRender", root);
// If there are multiple top level elements and `el: false` is used,
// display a warning message and a stack trace.
if (manager.noel && root.$el.length > 1) {
// Do not display a warning while testing or if warning suppression
// is enabled.
if (_.isFunction(console.warn) && !root.suppressWarnings) {
console.warn("`el: false` with multiple top level elements is " +
"not supported.");
// Provide a stack trace if available to aid with debugging.
if (_.isFunction(console.trace)) {
console.trace();
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.