_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q8900
|
compareDaySegments
|
train
|
function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
}
|
javascript
|
{
"resource": ""
}
|
q8901
|
composer
|
train
|
function composer(componentMap) {
return buildTemplateData;
/**
* Accepts a Hapi request object (containing Windshield config information) and
* resolves everything Hapi/Vision needs to render an HTML page.
*
* @callback {buildTemplateData}
* @param {Request} request - Hapi request object
* @returns {Promise.<TemplateData>}
*/
async function buildTemplateData(request) {
const filterFn = composePageFilter(request);
const pageContext = await resolvePageContext(request);
const renderer = componentMap.composeFactory(pageContext, request);
const renderedComponentCollection = await renderComponentSchema(pageContext.associations, renderer);
// we only need the data to be in this intermediary format to support
// the filtering logic. We should streamline this out but that would
// be a breaking change.
const rawPageObject = {
attributes: pageContext.attributes,
assoc: renderedComponentCollection,
layout: pageContext.layout,
exported: renderedComponentCollection.exportedData
};
if (process.env.WINDSHIELD_DEBUG) {
request.server.log('info', JSON.stringify(rawPageObject, null, 4));
}
const {assoc, attributes, layout} = await filterFn(rawPageObject);
const template = path.join('layouts', layout);
return {
template,
data: {
attributes,
assoc: assoc.markup,
exported: assoc.exported
}
};
}
}
|
javascript
|
{
"resource": ""
}
|
q8902
|
renderComponentSchema
|
train
|
async function renderComponentSchema(definitionMap, renderComponent) {
/**
* Renders a single Windshield component definition into a rendered
* component object
*
* @param {string} definitionGroupName - Name of the association that contains the component
* @param {ComponentDefinition} definition - Config for a Windshield Component
*
* @return {Promise.<RenderedComponent>}
*/
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
/**
* Renders an array of component definitions by aggregating them
* into a single rendered component object
*
* @param {string} definitionGroupName - They key where the definitions are found in their parent component's associations
* @param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components
* @returns {Promise.<RenderedComponent>}
*/
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
/**
* Iterates through the associations to produce a rendered component collection object
*
* @param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
* @returns {Promise.<RenderedComponentCollection>}
*/
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
return renderAssociationMap(definitionMap);
}
|
javascript
|
{
"resource": ""
}
|
q8903
|
renderOneComponent
|
train
|
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
|
javascript
|
{
"resource": ""
}
|
q8904
|
renderComponentFromArray
|
train
|
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
|
javascript
|
{
"resource": ""
}
|
q8905
|
renderAssociationMap
|
train
|
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
|
javascript
|
{
"resource": ""
}
|
q8906
|
fileIterator
|
train
|
function fileIterator(paths, options, callback) {
var filePacks = [];
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof paths === 'string') {
paths = [paths];
} else if (paths instanceof Array) {
paths = [].concat(paths);
} else {
throw new Error('Invalid first argument `paths`. Expected type of string or array');
}
options = options || {};
var except = [];
//normalize paths
(options.except || []).forEach(function(p) {
except.push(path.resolve(p));
});
paths.forEach(function(p, index) {
if (fs.lstatSync(p).isDirectory()) {
filePacks.push(fs.readdirSync(p));
} else {
//explicit file paths are already complete,
filePacks.push([path.basename(p)]);
paths.splice(index, 1, path.dirname(p));
}
});
filePacks.forEach(function(files, index) {
files.forEach(function(file) {
var pth = path.join(paths[index], file);
var isDir = fs.lstatSync(pth).isDirectory();
//skip paths defined in options.except array
if (except.indexOf(pth) !== -1) {
return;
}
if (isDir) {
fileIterator([pth], options, callback);
} else {
callback(file, paths[index]);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q8907
|
getInfo
|
train
|
function getInfo(hash) {
const info = getHashInfo(hash);
const algo = getAlgorithmFromId(info.id);
info.algorithm = algo.name;
info.options = algo.getOptions(hash, info);
return info;
}
|
javascript
|
{
"resource": ""
}
|
q8908
|
needsRehash
|
train
|
function needsRehash(hash, algo, options) {
const info = getInfo(hash);
if (info.algorithm !== (algo || DEFAULT_ALGO)) {
return true;
}
const algoNeedsRehash = getAlgorithmFromId(info.id).needsRehash;
const result = algoNeedsRehash && algoNeedsRehash(hash, info);
if (typeof result === "boolean") {
return result;
}
const expected = Object.assign(
Object.create(null),
globalOptions[info.algorithm],
options
);
const actual = info.options;
for (const prop in actual) {
const value = actual[prop];
if (typeof value === "number" && value < expected[prop]) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q8909
|
train
|
function (targetIDs, pickerID) {
function matches(id) {
if (id instanceof RegExp) {
return id.test(pickerID);
}
return id === pickerID;
}
if (angular.isArray(targetIDs)) {
return targetIDs.some(matches);
}
return matches(targetIDs);
}
|
javascript
|
{
"resource": ""
}
|
|
q8910
|
train
|
function (config) {
Filter.call(this);
config = config || {};
this.regex = config.regex || '';
if (utils.isString(this.regex)) {
this.regex = new RegExp(this.regex);
}
this.onMatch = config.match || config.onMatch || 'neutral';
this.onMismatch = config.mismatch || config.onMismatch || 'deny';
}
|
javascript
|
{
"resource": ""
}
|
|
q8911
|
_concat
|
train
|
function _concat(buffOne, buffTwo) {
if (!buffOne) return buffTwo;
if (!buffTwo) return buffOne;
let newLength = buffOne.length + buffTwo.length;
return Buffer.concat([buffOne, buffTwo], newLength);
}
|
javascript
|
{
"resource": ""
}
|
q8912
|
train
|
function () {
var pkg = require(process.cwd() + '/package.json');
var licenses = [];
pkg.licenses.forEach(function (license) {
licenses.push(license.type);
});
return '/*! ' + pkg.name + ' - v' + pkg.version + ' - ' + gutil.date("yyyy-mm-dd") + "\n" +
(pkg.homepage ? "* " + pkg.homepage + "\n" : "") +
'* Copyright (c) ' + gutil.date("yyyy") + ' ' + pkg.author.name +
'; Licensed ' + licenses.join(', ') + ' */\n';
}
|
javascript
|
{
"resource": ""
}
|
|
q8913
|
train
|
function(commands, resetCommands) {
// resetCommands defaults to true
if (resetCommands === undefined) {
resetCommands = true;
} else {
resetCommands = !!resetCommands;
}
// Abort previous instances of recognition already running
if (recognition && recognition.abort) {
recognition.abort();
}
// initiate SpeechRecognition
recognition = new SpeechRecognition();
// Set the max number of alternative transcripts to try and match with a command
recognition.maxAlternatives = 5;
// In HTTPS, turn off continuous mode for faster results.
// In HTTP, turn on continuous mode for much slower results, but no repeating security notices
recognition.continuous = root.location.protocol === 'http:';
// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
recognition.lang = 'en-US';
recognition.onstart = function() { invokeCallbacks(callbacks.start); };
recognition.onerror = function(event) {
invokeCallbacks(callbacks.error);
switch (event.error) {
case 'network':
invokeCallbacks(callbacks.errorNetwork);
break;
case 'not-allowed':
case 'service-not-allowed':
// if permission to use the mic is denied, turn off auto-restart
autoRestart = false;
// determine if permission was denied by user or automatically.
if (new Date().getTime()-lastStartedAt < 200) {
invokeCallbacks(callbacks.errorPermissionBlocked);
} else {
invokeCallbacks(callbacks.errorPermissionDenied);
}
break;
}
};
recognition.onend = function() {
invokeCallbacks(callbacks.end);
// annyang will auto restart if it is closed automatically and not by user action.
if (autoRestart) {
// play nicely with the browser, and never restart annyang automatically more than once per second
var timeSinceLastStart = new Date().getTime()-lastStartedAt;
if (timeSinceLastStart < 1000) {
setTimeout(root.annyang.start, 1000-timeSinceLastStart);
} else {
root.annyang.start();
}
}
};
recognition.onresult = function(event) {
invokeCallbacks(callbacks.result);
var results = event.results[event.resultIndex];
var commandText;
// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
for (var i = 0; i<results.length; i++) {
// the text recognized
commandText = results[i].transcript.trim();
// do stuff
$('#speechActivity').html('<h2>Last voice command: ' + commandText + '</h2>');
if (debugState) {
// document.getElementById('speechActivity').innerHTML = commandText;
root.console.log('Speech recognized: %c'+commandText, debugStyle);
}
// try and match recognized text to one of the commands on the list
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
if (debugState) {
root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
if (parameters.length) {
root.console.log('with parameters', parameters);
}
}
// execute the matched command
commandsList[j].callback.apply(this, parameters);
invokeCallbacks(callbacks.resultMatch);
return true;
}
}
}
invokeCallbacks(callbacks.resultNoMatch);
return false;
};
// build commands list
if (resetCommands) {
commandsList = [];
}
if (commands.length) {
this.addCommands(commands);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8914
|
train
|
function(options) {
initIfNeeded();
options = options || {};
if (options.autoRestart !== undefined) {
autoRestart = !!options.autoRestart;
} else {
autoRestart = true;
}
lastStartedAt = new Date().getTime();
recognition.start();
}
|
javascript
|
{
"resource": ""
}
|
|
q8915
|
train
|
function(commandsToRemove) {
if (commandsToRemove === undefined) {
commandsList = [];
return;
}
commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
commandsList = commandsList.filter(function(command) {
for (var i = 0; i<commandsToRemove.length; i++) {
if (commandsToRemove[i] === command.originalPhrase) {
return false;
}
}
return true;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8916
|
start
|
train
|
function start(config) {
if (!isConfigurationParametersDefinedCorrectly(config)) {
throw new Error('license-check - Configuration error');
}
var folders = [];
if (config.src) {
folders = getFoldersToCheck(config.src);
}
if (folders.length === 0) {
gutil.log('license-check', gutil.colors.red('{src} not defined or empty, the plugin will run with the default configuration: **/*'));
folders = getDefaultFolders();
}
var src = vfs.src(folders);
src.pipe(license(config));
return src;
}
|
javascript
|
{
"resource": ""
}
|
q8917
|
getFoldersToCheck
|
train
|
function getFoldersToCheck(src) {
var folders = [];
src.forEach(function (entry) {
if (entry.charAt(0) === '!') {
folders.push(path.join('!' + mainFolder, entry.substring(1, entry.length)));
} else {
if (entry.charAt(0) === '/') {
folders.push(entry);
} else {
folders.push(path.join(mainFolder, entry));
}
}
});
return folders;
}
|
javascript
|
{
"resource": ""
}
|
q8918
|
isConfigurationParametersDefinedCorrectly
|
train
|
function isConfigurationParametersDefinedCorrectly(config) {
if (!config) {
gutil.log('license-check', gutil.colors.red('Config must be defined to run the plugin'));
return false;
}
if (!config.path) {
gutil.log('license-check', gutil.colors.red('License header property {path} must be defined to run the plugin'));
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q8919
|
train
|
function (obj) {
this.obj = obj;
/**
* Check if the wrapped object is defined
* @returns true if the wrapped object is defined, false otherwise
*/
this.isPresent = function () {
return angular.isDefined(this.obj) && this.obj !== null;
};
/**
* Return the wrapped object or an empty object
* @returns the wrapped objector an empty object
*/
this.orEmptyObj = function () {
if (this.isPresent()) {
return this.obj;
}
return {};
};
/**
* Return the wrapped object or the given second choice
* @returns the wrapped object or the given second choice
*/
this.or = function (secondChoice) {
if (this.isPresent()) {
return this.obj;
}
return secondChoice;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8920
|
train
|
function (options) {
return {
options: options,
render: function ($scope, $elem) {
var _this = this, expression = $elem.find('tbody').html(),
// Find the resources from the comment <!-- ngRepeat: item in items --> displayed by angular in the DOM
// This regexp is inspired by the one used in the "ngRepeat" directive
match = expression.match(/^\s*.+\s+in\s+(\w*)\s*/), ngRepeatAttr = match[1];
if (!match) {
throw new Error('Expected expression in form of "_item_ in _collection_[ track by _id_]" but got "{0}".', expression);
}
var oTable, firstCall = true, alreadyRendered = false, parentScope = $scope.$parent;
parentScope.$watch(ngRepeatAttr, function () {
if (oTable && alreadyRendered && !_isDTOldVersion(oTable)) {
oTable.ngDestroy();
}
// This condition handles the case the array is empty
if (firstCall) {
firstCall = false;
$timeout(function () {
if (!alreadyRendered) {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}
}, 1000, false); // Hack I'm not proud of... Don't know how to do it otherwise...
} else {
$timeout(function () {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}, 0, false);
}
}, true);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8921
|
train
|
function (options) {
var oTable;
var _render = function (options, $elem, data, $scope) {
options.aaData = data;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Condition to refresh the dataTable
if (oTable) {
if (_isDTOldVersion(oTable)) {
oTable.fnClearTable();
oTable.fnDraw();
oTable.fnAddData(options.aaData);
} else {
oTable.clear();
oTable.rows.add(options.aaData).draw();
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this, _loadedPromise = null, _whenLoaded = function (data) {
_render(_this.options, $elem, data, $scope);
_loadedPromise = null;
}, _startLoading = function (fnPromise) {
if (angular.isFunction(fnPromise)) {
_loadedPromise = fnPromise();
} else {
_loadedPromise = fnPromise;
}
_showLoading($elem);
_loadedPromise.then(_whenLoaded);
}, _reload = function (fnPromise) {
if (_loadedPromise) {
_loadedPromise.then(function () {
_startLoading(fnPromise);
});
} else {
_startLoading(fnPromise);
}
};
$scope.$watch('dtOptions.fnPromise', function (fnPromise) {
if (angular.isDefined(fnPromise)) {
_reload(fnPromise);
} else {
throw new Error('You must provide a promise or a function that returns a promise!');
}
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_reload($scope.dtOptions.fnPromise);
}
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8922
|
train
|
function (options) {
var oTable;
var _render = function (options, $elem, $scope) {
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Condition to refresh the dataTable
if (oTable) {
if (_hasReloadAjaxPlugin(oTable)) {
// Reload Ajax data using the plugin "fnReloadAjax": https://next.datatables.net/plug-ins/api/fnReloadAjax
// For DataTable v1.9.4
oTable.fnReloadAjax(options.sAjaxSource);
} else if (!_isDTOldVersion(oTable)) {
// For DataTable v1.10+, DT provides methods https://datatables.net/reference/api/ajax.url()
var ajaxUrl = options.sAjaxSource || options.ajax.url || options.ajax;
oTable.ajax.url(ajaxUrl).load();
} else {
throw new Error('Reload Ajax not supported. Please use the plugin "fnReloadAjax" (https://next.datatables.net/plug-ins/api/fnReloadAjax) or use a more recent version of DataTables (v1.10+)');
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this;
// Define default values in case it is an ajax datatables
if (angular.isUndefined(_this.options.sAjaxDataProp)) {
_this.options.sAjaxDataProp = DT_DEFAULT_OPTIONS.sAjaxDataProp;
}
if (angular.isUndefined(_this.options.aoColumns)) {
_this.options.aoColumns = DT_DEFAULT_OPTIONS.aoColumns;
}
$scope.$watch('dtOptions.sAjaxSource', function (sAjaxSource) {
if (angular.isDefined(sAjaxSource)) {
_this.options.sAjaxSource = sAjaxSource;
if (angular.isDefined(_this.options.ajax)) {
if (angular.isObject(_this.options.ajax)) {
_this.options.ajax.url = sAjaxSource;
} else {
_this.options.ajax = { url: sAjaxSource };
}
}
}
_render(options, $elem, $scope);
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_render(options, $elem, $scope);
}
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8923
|
removeSubdomains
|
train
|
function removeSubdomains(hostname) {
const hostnameParts = hostname.split('.');
// A hostname with less than three parts is as short as it will get.
if (hostnameParts.length < 2) {
return hostname;
}
// Try to find a match in the list of ccTLDs.
const ccTld = find(tldList, part => endsWith(hostname, `.${part}`));
if (ccTld) {
// Get one extra part from the hostname.
const partCount = ccTld.split('.').length + 1;
return hostnameParts.slice(0 - partCount).join('.');
}
// If no ccTLDs were matched, return the final two parts of the hostname.
return hostnameParts.slice(-2).join('.');
}
|
javascript
|
{
"resource": ""
}
|
q8924
|
getHostname
|
train
|
function getHostname(url, userOptions = {}) {
const defaults = {
removeSubdomains: true,
};
const options = Object.assign({}, defaults, userOptions);
const domainRegExp = /^(?:[a-z]+:\/\/)?(?:[^/@]+@)?([^/:]+)/i;
const ipAddressRegExp = /^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/;
const domainMatch = url.match(domainRegExp);
if (domainMatch === null) {
throw new Error(`URL is invalid: ${url}`);
}
// If the hostname is an IP address, no further processing can be done.
const hostname = domainMatch[1];
if (ipAddressRegExp.test(hostname)) {
return hostname;
}
// Return the hostname with subdomains removed, if requested.
return (options.removeSubdomains) ? removeSubdomains(hostname) : hostname;
}
|
javascript
|
{
"resource": ""
}
|
q8925
|
train
|
function() {
var self = this;
this.$input = this.$tpl.find('input[type=hidden]:eq(0)');
this.$file = this.$tpl.find('input[type=file]:eq(0)');
this.$file.attr({'name':this.name});
this.$input.attr({'name':this.name+'-hidden'});
this.options.image.before_change = this.options.image.before_change || function(files, dropped) {
var file = files[0];
if(typeof file === "string") {
//files is just a file name here (in browsers that don't support FileReader API)
if(! (/\.(jpe?g|png|gif)$/i).test(file) ) {
if(self.on_error) self.on_error(1);
return false;
}
}
else {//file is a File object
var type = $.trim(file.type);
if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif)$/i).test(type) )
|| ( type.length == 0 && ! (/\.(jpe?g|png|gif)$/i).test(file.name) )//for android default browser!
)
{
if(self.on_error) self.on_error(1);
return false;
}
if( self.max_size && file.size > self.max_size ) {
if(self.on_error) self.on_error(2);
return false;
}
}
if(self.on_success) self.on_success();
return true;
}
this.options.image.before_remove = this.options.image.before_remove || function() {
self.$input.val(null);
return true;
}
this.$file.ace_file_input(this.options.image).on('change', function(){
var $rand = (self.$file.val() || self.$file.data('ace_input_files')) ? Math.random() + "" + (new Date()).getTime() : null;
self.$input.val($rand)//set a random value, so that selected file is uploaded each time, even if it's the same file, because inline editable plugin does not update if the value is not changed!
}).closest('.ace-file-input').css({'width':'150px'}).closest('.editable-input').addClass('editable-image');
}
|
javascript
|
{
"resource": ""
}
|
|
q8926
|
train
|
function (params) {
this.$id = 'graphic';
this.$deps = []; // Position dependency added later if relative positioning is true.
params = _.extend({
alpha: 1,
anchor: {
x: 0.5,
y: 0.5
},
relative: true,
scale: {
x: 1,
y: 1
},
tint: 0xffffff,
translate: {
x: 0,
y: 0
},
visible: true,
z: 0
}, params);
if (params.relative) {
this.$deps.push('position');
}
this.alpha = params.alpha;
this.anchor = params.anchor;
this.relative = params.relative;
this.scale = params.scale;
this.tint = params.tint;
this.translate = params.translate;
this.visible = params.visible;
this.z = params.z;
}
|
javascript
|
{
"resource": ""
}
|
|
q8927
|
train
|
function (config, loggerContext) {
Layout.call(this, config, loggerContext);
this.pattern = this.config.pattern ||
PatternLayout.DEFAULT_CONVERSION_PATTERN;
this.compactObjects = this.config.compactObjects || false;
}
|
javascript
|
{
"resource": ""
}
|
|
q8928
|
train
|
function (gruntfileContent) {
var defaultGruntfilePath = path.join(__dirname, 'default-gruntfile.js');
gruntfileContent = gruntfileContent || fs.readFileSync(defaultGruntfilePath);
this.gruntfile = new Tree(gruntfileContent.toString());
}
|
javascript
|
{
"resource": ""
}
|
|
q8929
|
train
|
function(checks, callback) {
fs.lstat(options.source, function(err, stats) {
/* istanbul ignore else */
if (stats.isFile()) {
copyFile(options, callback);
} else if (stats.isDirectory()) {
copyDir(options, callback);
} else if (stats.isSymbolicLink()) {
copySymlink(options, callback);
} else {
callback(new Error('Unsupported file type !'));
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8930
|
train
|
function(callback) {
fs.exists(options.source, function(exists) {
if(!exists) { callback(new Error('Source file do not exists!')); }
else { callback(null, true); }
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8931
|
train
|
function(linkString, callback) {
fs.exists(_toFile, function (exists) {
callback(null, exists, linkString);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8932
|
train
|
function(exists, linkString, callback) {
if (exists) {
return callback(null, symlink);
}
fs.symlink(linkString, _toFile, function(err) {
callback(err, symlink);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8933
|
train
|
function(stats, callback) {
fs.readFile(file, function(err, data) {
callback(err, data, stats);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8934
|
train
|
function(data, stats, callback) {
fs.writeFile(_toFile, data, stats, function(err) {
callback(err, _toFile);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8935
|
processAuthResultForEntity
|
train
|
function processAuthResultForEntity(err, entity) {
if(stopAll) return
if(err && err.code !== ACL_ERROR_CODE) {
stopAll = true
callback(err, undefined)
} else {
if(entity) {
filteredEntities.push(entity)
}
callbackCount ++
if(callbackCount === entities.length) {
callback(undefined, filteredEntities)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8936
|
_getMatcher
|
train
|
function _getMatcher (element) {
if (_matcher) {
return _matcher;
}
if (element.matches) {
_matcher = element.matches;
return _matcher;
}
if (element.webkitMatchesSelector) {
_matcher = element.webkitMatchesSelector;
return _matcher;
}
if (element.mozMatchesSelector) {
_matcher = element.mozMatchesSelector;
return _matcher;
}
if (element.msMatchesSelector) {
_matcher = element.msMatchesSelector;
return _matcher;
}
if (element.oMatchesSelector) {
_matcher = element.oMatchesSelector;
return _matcher;
}
// if it doesn't match a native browser method
// fall back to the delegator function
_matcher = Delegator.matchesSelector;
return _matcher;
}
|
javascript
|
{
"resource": ""
}
|
q8937
|
_matchesSelector
|
train
|
function _matchesSelector (element, selector, boundElement) {
// no selector means this event was bound directly to this element
if (selector === '_root') {
return boundElement;
}
// if we have moved up to the element you bound the event to
// then we have come too far
if (element === boundElement) {
return;
}
if (_getMatcher(element).call(element, selector)) {
return element;
}
// if this element did not match but has a parent we should try
// going up the tree to see if any of the parent elements match
// for example if you are looking for a click on an <a> tag but there
// is a <span> inside of the a tag that it is the target,
// it should still work
if (element.parentNode) {
_level++;
return _matchesSelector(element.parentNode, selector, boundElement);
}
}
|
javascript
|
{
"resource": ""
}
|
q8938
|
_bind
|
train
|
function _bind (events, selector, callback, remove) {
// fail silently if you pass null or undefined as an alement
// in the Delegator constructor
if (!this.element) {
return;
}
if (!(events instanceof Array)) {
events = [events];
}
if (!callback && typeof (selector) === 'function') {
callback = selector;
selector = '_root';
}
if (selector instanceof window.Element) {
let id;
if (selector.hasAttribute('bind-event-id')) {
id = selector.getAttribute('bind-event-id');
} else {
id = nextEventId();
selector.setAttribute('bind-event-id', id);
}
selector = `[bind-event-id="${id}"]`;
}
let id = this.id;
let i;
function _getGlobalCallback (type) {
return function (e) {
_handleEvent(id, e, type);
};
}
for (i = 0; i < events.length; i++) {
_aliases(events[i]).forEach(alias => {
if (remove) {
_removeHandler(this, alias, selector, callback);
return;
}
if (!_handlers[id] || !_handlers[id][alias]) {
Delegator.addEvent(this, alias, _getGlobalCallback(alias));
}
_addHandler(this, alias, selector, callback);
});
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q8939
|
JSONReporter
|
train
|
function JSONReporter(dir, config) {
this._config = config;
var fileName = config.file || DEFAULT_FILE_NAME;
this._filePath = path.join(dir, fileName);
}
|
javascript
|
{
"resource": ""
}
|
q8940
|
getMutationScore
|
train
|
function getMutationScore(stats) {
return {
total: (stats.all - stats.survived) / stats.all,
killed: stats.killed / stats.all,
survived: stats.survived / stats.all,
ignored: stats.ignored / stats.all,
untested: stats.untested / stats.all
};
}
|
javascript
|
{
"resource": ""
}
|
q8941
|
getResultsPerDir
|
train
|
function getResultsPerDir(results) {
/**
* Decorate the results object with the stats for each directory.
*
* @param {object} results - (part of) mutation testing results
* @returns {object} - Mutation test results decorated with stats
*/
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
/**
* Decorate the results object with the mutation score for each directory.
*
* @param {object} results - (part of) mutation testing results, decorated with mutation stats
* @returns {object} - Mutation test results decorated with mutation scores
*/
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
var resultsPerDir = {};
_.forEach(_.clone(results), function(fileResult) {
_.set(resultsPerDir, IOUtils.getDirectoryList(fileResult.fileName), fileResult);
});
return addMutationScores(addDirStats(resultsPerDir));
}
|
javascript
|
{
"resource": ""
}
|
q8942
|
addDirStats
|
train
|
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
|
javascript
|
{
"resource": ""
}
|
q8943
|
addMutationScores
|
train
|
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
|
javascript
|
{
"resource": ""
}
|
q8944
|
search
|
train
|
function search(platform) {
return new Promise((resolve, reject) => {
if (!platform || platform === '') reject(new Error('platform cannot be blank'));
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
path: `/api/search-exploit?name=${platform}`,
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(JSON.parse(body));
});
});
req.on('error', err => reject(err));
req.end();
});
}
|
javascript
|
{
"resource": ""
}
|
q8945
|
train
|
function (name, loggerContext) {
/**
* Logger name
*/
this.name = name;
/**
* Reference to the logger context that created this logger
*
* The reference is used to create appenders and layouts when
* configuration is applied.
*/
this.loggerContext = loggerContext;
/**
* Parent logger. All loggers have a parent except the root logger
*/
this.parent = null;
/**
* Children loggers. Mostly used during initialization to propagate
* the configuration.
*/
this.children = [];
/**
* Appenders associated with the logger. Set during initialization
*/
this.appenders = [];
/**
* Logger filter. Set during initialization
*/
this.filter = null;
/**
* The trace level of the logger. Log events whose level is below that
* level are logged. Others are discarded.
*/
this.level = 'inherit';
/**
* Additivity flag. Log events are not propagated to the parent logger
* if the flag is not set.
*/
this.additive = true;
/**
* Function used to determine whether a log level is below the
* trace level of the logger
*/
if (this.loggerContext) {
this.isBelow = function (level, referenceLevel) {
return this.loggerContext.logLevel.isBelow(level, referenceLevel);
};
// Set trace functions for all registered levels
utils.each(this.loggerContext.logLevel.getLevels(), function (level) {
var self = this;
if (!this[level]) {
this[level] = function () {
self.traceAtLevel(level, arguments);
};
}
}, this);
}
else {
this.isBelow = function () {
return true;
};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8946
|
train
|
function () {
//check if we are able to execute
if (!canExecuteWrapper.call(options.context || this)) {
//dont attach any global handlers
return instantDeferred(false, null, options.context || this).promise();
}
//notify that we are running and clear any existing error message
isRunning(true);
failed(false);
failMessage('');
//try to invoke the action and get a reference to the deferred object
var promise;
try {
promise = options.action.apply(options.context || this, arguments);
//if the returned result is *not* a promise, create a new one that is already resolved
if (!isPromise(promise)) {
promise = instantDeferred(true, promise, options.context || this).promise();
}
} catch (error) {
promise = instantDeferred(false, error, options.context || this).promise();
}
//set up our callbacks
callbacks.always.forEach(function(callback) {
promise.then(callback, callback);
});
callbacks.fail.forEach(function(callback) {
promise.then(null, callback);
});
callbacks.done.forEach(function(callback) {
promise.then(callback);
});
return promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q8947
|
train
|
function (callback) {
callbacks.fail.push(function () {
var result = callback.apply(this, arguments);
if (result) {
failMessage(result);
}
});
return execute;
}
|
javascript
|
{
"resource": ""
}
|
|
q8948
|
getRegEx
|
train
|
function getRegEx(version) {
switch(version.toLowerCase())
{
case 'v1':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v2':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v3':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v4':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v5':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
default:
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
}
}
|
javascript
|
{
"resource": ""
}
|
q8949
|
uuid
|
train
|
function uuid(version) {
var v = (version) ? version : '';
// verify its a valid string
this.assert(
(typeof this._obj === 'string' || this._obj instanceof String),
'expected #{this} to be of type #{exp} but got #{act}',
'expected #{this} to not be of type #{exp}',
'string',
typeof(this._obj)
);
// assert it is a valid uuid
var regex = getRegEx(v);
this.assert(
regex.test(this._obj),
'expected #{this} to be a valid UUID ' + v,
'expected #{this} to not be a UUID ' + v
);
}
|
javascript
|
{
"resource": ""
}
|
q8950
|
KarmaCodeSpecsMatcher
|
train
|
function KarmaCodeSpecsMatcher(serverPool, config) {
this._serverPool = serverPool;
this._config = _.merge({ karma: { waitForCoverageTime: 5 } }, config);
this._coverageDir = path.join(config.karma.basePath, 'coverage');
}
|
javascript
|
{
"resource": ""
}
|
q8951
|
processScopeVariables
|
train
|
function processScopeVariables(variableDeclaration, loopVariables) {
var identifiers = [], exclusiveCombination;
_.forEach(variableDeclaration.declarations, function(declaration) {
identifiers.push(declaration.id.name);
});
exclusiveCombination = _.xor(loopVariables, identifiers);
return _.intersection(loopVariables, exclusiveCombination);
}
|
javascript
|
{
"resource": ""
}
|
q8952
|
filterObject
|
train
|
function filterObject(gobj, filter) {
let found = true;
let obj = gobj;
// find the value we're interested in
for (let i = 0, len = filter.length; obj && typeof obj === 'object' && i < len; i++) {
if (!obj.hasOwnProperty(filter[i])) {
found = false;
obj = undefined;
break;
}
obj = obj[filter[i]];
}
return { found, obj };
}
|
javascript
|
{
"resource": ""
}
|
q8953
|
hashValue
|
train
|
function hashValue(it) {
const str = JSON.stringify(it) || '';
let hash = 5381;
let i = str.length;
while (i) {
hash = hash * 33 ^ str.charCodeAt(--i);
}
return hash >>> 0;
}
|
javascript
|
{
"resource": ""
}
|
q8954
|
notify
|
train
|
function notify(gobj, source) {
const state = gobj.__gawk__;
if (source === undefined) {
source = gobj;
}
// if we're paused, add this object to the list of objects that may have changed
if (state.queue) {
state.queue.add(gobj);
return;
}
// notify all of this object's listeners
if (state.listeners) {
for (const [ listener, filter ] of state.listeners) {
if (filter) {
const { found, obj } = filterObject(gobj, filter);
// compute the hash of the stringified value
const hash = hashValue(obj);
// check if the value changed
if ((found && !state.previous) || (state.previous && hash !== state.previous.get(listener))) {
listener(obj, source);
}
if (!state.previous) {
state.previous = new WeakMap();
}
state.previous.set(listener, hash);
} else {
listener(gobj, source);
}
}
}
// notify all of this object's parents
if (state.parents) {
for (const parent of state.parents) {
notify(parent, source);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8955
|
copyListeners
|
train
|
function copyListeners(dest, src, compareFn) {
if (isGawked(src) && src.__gawk__.listeners) {
if (dest.__gawk__.listeners) {
for (const [ listener, filter ] of src.__gawk__.listeners) {
dest.__gawk__.listeners.set(listener, filter);
}
} else {
dest.__gawk__.listeners = new Map(src.__gawk__.listeners);
}
}
if (!compareFn) {
return;
}
if (Array.isArray(dest)) {
const visited = [];
for (let i = 0, len = dest.length; i < len; i++) {
if (dest[i] !== null && typeof dest[i] === 'object') {
// try to find a match in src
for (let j = 0, len2 = src.length; j < len2; j++) {
if (!visited[j] && src[j] !== null && typeof src[j] === 'object' && compareFn(dest[i], src[j])) {
visited[j] = 1;
copyListeners(dest[i], src[j], compareFn);
break;
}
}
}
}
return;
}
for (const key of Object.getOwnPropertyNames(dest)) {
if (key === '__gawk__') {
continue;
}
if (dest[key] && typeof dest[key] === 'object') {
copyListeners(dest[key], src[key], compareFn);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8956
|
mix
|
train
|
function mix(objs, deep) {
const gobj = gawk(objs.shift());
if (!isGawked(gobj) || Array.isArray(gobj)) {
throw new TypeError('Expected destination to be a gawked object');
}
if (!objs.length) {
return gobj;
}
// validate the objects are good
for (const obj of objs) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
throw new TypeError('Expected merge source to be an object');
}
}
// we need to detach the parent and all listeners so that they will be notified after everything
// has been merged
gobj.__gawk__.pause();
/**
* Mix an object or gawked object into a gawked object.
* @param {Object} gobj - The destination gawked object.
* @param {Object} src - The source object to copy from.
*/
const mixer = (gobj, src) => {
for (const key of Object.getOwnPropertyNames(src)) {
if (key === '__gawk__') {
continue;
}
const srcValue = src[key];
if (deep && srcValue !== null && typeof srcValue === 'object' && !Array.isArray(srcValue)) {
if (!isGawked(gobj[key])) {
gobj[key] = gawk({}, gobj);
}
mixer(gobj[key], srcValue);
} else if (Array.isArray(gobj[key]) && Array.isArray(srcValue)) {
// overwrite destination with new values
gobj[key].splice(0, gobj[key].length, ...srcValue);
} else {
gobj[key] = gawk(srcValue, gobj);
}
}
};
for (const obj of objs) {
mixer(gobj, obj);
}
gobj.__gawk__.resume();
return gobj;
}
|
javascript
|
{
"resource": ""
}
|
q8957
|
computedBeginDependencyDetectionCallback
|
train
|
function computedBeginDependencyDetectionCallback(subscribable, id) {
var computedObservable = this.computedObservable,
state = computedObservable[computedState];
if (!state.isDisposed) {
if (this.disposalCount && this.disposalCandidates[id]) {
// Don't want to dispose this subscription, as it's still being used
computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
--this.disposalCount;
} else if (!state.dependencyTracking[id]) {
// Brand new subscription - add it
computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
}
// If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
if (subscribable._notificationIsPending) {
subscribable._notifyNextChangeIfValueIsDifferent();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8958
|
train
|
function (sKey) {
return decodeURI(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURI(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
}
|
javascript
|
{
"resource": ""
}
|
|
q8959
|
train
|
function (sKey, sPath) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURI(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sPath ? '; path=' + sPath : '');
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q8960
|
bindingContext
|
train
|
function bindingContext(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, settings) {
var self = this,
isFunc = typeof(dataItemOrAccessor) == "function" && !isObservable(dataItemOrAccessor),
nodes,
subscribable;
// The binding context object includes static properties for the current, parent, and root view models.
// If a view model is actually stored in an observable, the corresponding binding context object, and
// any child contexts, must be updated when the view model is changed.
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
function disposeWhen() {
return nodes && !anyDomNodeIsAttachedToDocument(nodes);
}
if (settings && settings.exportDependencies) {
// The "exportDependencies" option means that the calling code will track any dependencies and re-create
// the binding context when they change.
updateContext();
return;
}
subscribable = computed(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
// At this point, the binding context has been initialized, and the "subscribable" computed observable is
// subscribed to any observables that were accessed in the process. If there is nothing to track, the
// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
// the context object.
if (subscribable.isActive()) {
self._subscribable = subscribable;
// Always notify because even if the model ($data) hasn't changed, other context properties might have changed
subscribable.equalityComparer = null;
// We need to be able to dispose of this computed observable when it's no longer needed. This would be
// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
// we cannot assume that those nodes have any relation to each other. So instead we track any node that
// the context is attached to, and dispose the computed when all of those nodes have been cleaned.
// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
nodes = [];
subscribable._addNode = function(node) {
nodes.push(node);
addDisposeCallback(node, function(node) {
arrayRemoveItem(nodes, node);
if (!nodes.length) {
subscribable.dispose();
self._subscribable = subscribable = undefined;
}
});
};
}
}
|
javascript
|
{
"resource": ""
}
|
q8961
|
updateContext
|
train
|
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
|
javascript
|
{
"resource": ""
}
|
q8962
|
cloneIfElseNodes
|
train
|
function cloneIfElseNodes(element, hasElse) {
var children = childNodes(element),
ifNodes = [],
elseNodes = [],
target = ifNodes;
for (var i = 0, j = children.length; i < j; ++i) {
if (hasElse && isElseNode(children[i])) {
target = elseNodes;
hasElse = false;
} else {
target.push(cleanNode(children[i].cloneNode(true)));
}
}
return {
ifNodes: ifNodes,
elseNodes: elseNodes
};
}
|
javascript
|
{
"resource": ""
}
|
q8963
|
makeWithIfBinding
|
train
|
function makeWithIfBinding(isWith, isNot, isElse, makeContextCallback) {
return {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var didDisplayOnLastUpdate,
hasElse = detectElse(element),
completesElseChain = observable(),
ifElseNodes,
precedingConditional;
set(element, "conditional", {
elseChainSatisfied: completesElseChain,
});
if (isElse) {
precedingConditional = getPrecedingConditional(element);
}
computed(function() {
var rawValue = valueAccessor(),
dataValue = unwrap(rawValue),
shouldDisplayIf = !isNot !== !dataValue || (isElse && rawValue === undefined), // equivalent to (isNot ? !dataValue : !!dataValue) || isElse && rawValue === undefined
isFirstRender = !ifElseNodes,
needsRefresh = isFirstRender || isWith || (shouldDisplayIf !== didDisplayOnLastUpdate);
if (precedingConditional && precedingConditional.elseChainSatisfied()) {
needsRefresh = shouldDisplayIf !== false;
shouldDisplayIf = false;
completesElseChain(true);
} else {
completesElseChain(shouldDisplayIf);
}
if (!needsRefresh) { return; }
if (isFirstRender && (getDependenciesCount() || hasElse)) {
ifElseNodes = cloneIfElseNodes(element, hasElse);
}
if (shouldDisplayIf) {
if (!isFirstRender || hasElse) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.ifNodes));
}
} else if (ifElseNodes) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.elseNodes));
} else {
emptyNode(element);
}
applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, rawValue) : bindingContext, element);
didDisplayOnLastUpdate = shouldDisplayIf;
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
},
allowVirtualElements: true,
bindingRewriteValidator: false
};
}
|
javascript
|
{
"resource": ""
}
|
q8964
|
filterByUrls
|
train
|
function filterByUrls(url) {
if(_config.refererIndependentUrls) {
var isRefererIndependend = false;
for(var i in _config.refererIndependentUrls) {
if(new RegExp(_config.refererIndependentUrls[i]).test(url.split('?')[0])) {
isRefererIndependend = true;
break;
}
}
return isRefererIndependend;
} else {
return url === '/';
}
}
|
javascript
|
{
"resource": ""
}
|
q8965
|
filterByMethods
|
train
|
function filterByMethods(req) {
if(_config.allowedMethods) {
return _config.allowedMethods.indexOf(req.method) > -1;
} else if(_config.blockedMethods){
return !(_config.blockedMethods.indexOf(req.method) > -1);
} else {
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
q8966
|
indexOf
|
train
|
function indexOf(arr, value, start) {
start = start || 0;
if (arr == null) {
return -1;
}
var len = arr.length;
var i = start < 0 ? len + start : start;
while (i < len) {
if (arr[i] === value) {
return i;
}
i++;
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q8967
|
every
|
train
|
function every(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
var result = true;
if (arr == null) {
return result;
}
var len = arr.length;
var i = -1;
while (++i < len) {
if (!cb(arr[i], i, arr)) {
result = false;
break;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8968
|
filter
|
train
|
function filter(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
if (arr == null) {
return [];
}
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (cb(ele, i, arr)) {
res.push(ele);
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q8969
|
filterType
|
train
|
function filterType(arr, type) {
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (typeOf(ele) === type) {
res.push(ele);
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q8970
|
strings
|
train
|
function strings(arr, i) {
var values = filterType(arr, 'string');
return i ? values[i] : values;
}
|
javascript
|
{
"resource": ""
}
|
q8971
|
objects
|
train
|
function objects(arr, i) {
var values = filterType(arr, 'object');
return i ? values[i] : values;
}
|
javascript
|
{
"resource": ""
}
|
q8972
|
functions
|
train
|
function functions(arr, i) {
var values = filterType(arr, 'function');
return i ? values[i] : values;
}
|
javascript
|
{
"resource": ""
}
|
q8973
|
arrays
|
train
|
function arrays(arr, i) {
var values = filterType(arr, 'array');
return i ? values[i] : values;
}
|
javascript
|
{
"resource": ""
}
|
q8974
|
first
|
train
|
function first(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[0];
}
if (typeOf(cb) === 'string') {
return findFirst(arr, isType(cb));
}
return findFirst(arr, cb, thisArg);
}
|
javascript
|
{
"resource": ""
}
|
q8975
|
last
|
train
|
function last(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[arr.length - 1];
}
if (typeOf(cb) === 'string') {
return findLast(arr, isType(cb));
}
return findLast(arr, cb, thisArg);
}
|
javascript
|
{
"resource": ""
}
|
q8976
|
train
|
function (browser, url, proxyURL, pacFileURL, dataDir, bypassList) {
// Firefox pac set
// http://www.indexdata.com/connector-platform/enginedoc/proxy-auto.html
// http://kb.mozillazine.org/Network.proxy.autoconfig_url
// user_pref("network.proxy.autoconfig_url", "http://us2.indexdata.com:9005/id/cf.pac");
// user_pref("network.proxy.type", 2);
return this.detect(browser).then(function (browserPath) {
if (!browserPath) {
throw Error('[Error] can not find browser ' + browser);
} else {
dataDir = dataDir || path.join(os.tmpdir(), 'op-browser');
if (os.platform() === 'win32') {
browserPath = '"' + browserPath + '"';
}
var commandOptions = configUtil[browser](dataDir, url, browserPath, proxyURL, pacFileURL, bypassList);
return new Promise(function (resolve, reject) {
var cmdStr = browserPath + ' ' + commandOptions;
childProcess.exec(cmdStr, {maxBuffer: 50000 * 1024}, function (err) {
if (err) {
reject(err);
} else {
resolve({
path: browserPath,
cmdOptions: commandOptions,
proxyURL: proxyURL,
pacFileURL: pacFileURL
});
}
});
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8977
|
extend
|
train
|
function extend(a,b){
var c={};
for(var i in a){
if(a.hasOwnProperty(i)){
c[i]=a[i];
}
}
for(var i in b){
if(b.hasOwnProperty(i)){
c[i]=b[i];
}
}
return c
}
|
javascript
|
{
"resource": ""
}
|
q8978
|
train
|
function(){
try {
this.preview.backgroundColor = this.format.call(this);
} catch(e) {
this.preview.backgroundColor = this.color.toHex();
}
//set the color for brightness/saturation slider
this.base.backgroundColor = this.color.toHex(this.color.value.h, 1, 1, 1);
//set te color for alpha slider
if (this.alpha) {
this.alpha.backgroundColor = this.color.toHex();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8979
|
train
|
function(unique_id, e, manual_close){
// Remove it then run the callback function
e.remove();
this['_after_close_' + unique_id](e, manual_close);
// Check if the wrapper is empty, if it is.. remove the wrapper
if($('.gritter-item-wrapper').length == 0){
$('#gritter-notice-wrapper').remove();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8980
|
train
|
function(e, unique_id, params, unbind_events){
var params = params || {},
fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
fade_out_speed = params.speed || this.fade_out_speed,
manual_close = unbind_events;
this['_before_close_' + unique_id](e, manual_close);
// If this is true, then we are coming from clicking the (X)
if(unbind_events){
e.unbind('mouseenter mouseleave');
}
// Fade it out or remove it
if(fade){
e.animate({
opacity: 0
}, fade_out_speed, function(){
e.animate({ height: 0 }, 300, function(){
Gritter._countRemoveWrapper(unique_id, e, manual_close);
})
})
}
else {
this._countRemoveWrapper(unique_id, e);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8981
|
train
|
function(unique_id, params, e, unbind_events){
if(!e){
var e = $('#gritter-item-' + unique_id);
}
// We set the fourth param to let the _fade function know to
// unbind the "mouseleave" event. Once you click (X) there's no going back!
this._fade(e, unique_id, params || {}, unbind_events);
}
|
javascript
|
{
"resource": ""
}
|
|
q8982
|
train
|
function(e, unique_id){
var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
this['_int_id_' + unique_id] = setTimeout(function(){
Gritter._fade(e, unique_id);
}, timer_str);
}
|
javascript
|
{
"resource": ""
}
|
|
q8983
|
train
|
function(params){
// callbacks (if passed)
var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};
var wrap = $('#gritter-notice-wrapper');
before_close(wrap);
wrap.fadeOut(function(){
$(this).remove();
after_close();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8984
|
train
|
function(basePath, config) {
this._basePath = basePath;
this._config = config;
var directories = IOUtils.getDirectoryList(basePath, false);
IOUtils.createPathIfNotExists(directories, './');
}
|
javascript
|
{
"resource": ""
}
|
|
q8985
|
loadScript
|
train
|
function loadScript(url, callback, errorCallback, $timeout) {
var script = document.createElement('script'),
body = document.getElementsByTagName('body')[0],
removed = false;
script.type = 'text/javascript';
if (script.readyState) { // IE
script.onreadystatechange = function () {
if (script.readyState === 'complete' ||
script.readyState === 'loaded') {
script.onreadystatechange = null;
$timeout(
function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
}, 30, false);
}
};
} else { // Others
script.onload = function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
};
script.onerror = function () {
if (removed) return;
removed = true;
body.removeChild(script);
errorCallback();
};
}
script.src = url;
script.async = false;
body.appendChild(script);
}
|
javascript
|
{
"resource": ""
}
|
q8986
|
loadLocale
|
train
|
function loadLocale(localeUrl, $locale, localeId, $rootScope, $q, localeCache, $timeout) {
function overrideValues(oldObject, newObject) {
if (activeLocale !== localeId) {
return;
}
angular.forEach(oldObject, function(value, key) {
if (!newObject[key]) {
delete oldObject[key];
} else if (angular.isArray(newObject[key])) {
oldObject[key].length = newObject[key].length;
}
});
angular.forEach(newObject, function(value, key) {
if (angular.isArray(newObject[key]) || angular.isObject(newObject[key])) {
if (!oldObject[key]) {
oldObject[key] = angular.isArray(newObject[key]) ? [] : {};
}
overrideValues(oldObject[key], newObject[key]);
} else {
oldObject[key] = newObject[key];
}
});
}
if (promiseCache[localeId]) return promiseCache[localeId];
var cachedLocale,
deferred = $q.defer();
if (localeId === activeLocale) {
deferred.resolve($locale);
} else if ((cachedLocale = localeCache.get(localeId))) {
activeLocale = localeId;
$rootScope.$evalAsync(function() {
overrideValues($locale, cachedLocale);
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
storage.put(storeKey, localeId);
deferred.resolve($locale);
});
} else {
activeLocale = localeId;
promiseCache[localeId] = deferred.promise;
loadScript(localeUrl, function () {
// Create a new injector with the new locale
var localInjector = angular.injector(['ngLocale']),
externalLocale = localInjector.get('$locale');
overrideValues($locale, externalLocale);
localeCache.put(localeId, externalLocale);
delete promiseCache[localeId];
$rootScope.$apply(function () {
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
storage.put(storeKey, localeId);
deferred.resolve($locale);
});
}, function () {
delete promiseCache[localeId];
$rootScope.$apply(function () {
$rootScope.$broadcast('$localeChangeError', localeId);
deferred.reject(localeId);
});
}, $timeout);
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q8987
|
outputFile
|
train
|
function outputFile(configId, outputdata){
var fname= configId+ '_accounts.csv';
console.log("Outputing file... "+fname);
var input= {
data: outputdata,
fields: ['id','name','status','subscriptionStarts','subscriptionExpires']
};
json2csv(input, function(err, csv) {
if (err) {
console.log('ERROR!');
console.log(err);
} else {
fs.writeFileSync(fname,csv);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q8988
|
train
|
function (originalObj, originalProp, targetObj, targetProp) {
Object.defineProperty(
originalObj,
originalProp,
{
get: function () {
return targetObj[targetProp];
},
set: function (newValue) {
targetObj[targetProp] = newValue;
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q8989
|
train
|
function (originalObj, originalProp, targetObj, targetProp) {
Object.defineProperty(
originalObj,
originalProp,
{
get: function () {
return targetObj[targetProp];
},
set: function (newValue) {
console.error(targetProp + ' is read-only.');
throw new Error('ReadOnly');
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q8990
|
train
|
function (obj, prop, callback, callbackParams) {
var value = obj[prop];
Object.defineProperty(
obj,
prop,
{
get: function () {
return value;
},
set: function (newValue) {
value = newValue;
callback(newValue, callbackParams);
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q8991
|
train
|
function(error, response, body) {
var rspBody = helper.handleCB(error, response, body);
if (rspBody != null) {
var destId = config.get(program.dest).accountId;
var url = 'http://insights.newrelic.com/accounts/' + destId + '/dashboards/' + rspBody.dashboard.id;
console.log('Dashboard created: ' + url);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8992
|
readDashFromFS
|
train
|
function readDashFromFS(fname) {
var dashboardBody = fs.readFileSync(fname);
console.log('Read file:', fname);
// Set the proper account_id on all widgets
if (dashboardBody != null) {
dashboardBody = JSON.parse(dashboardBody);
console.log('Read source dashboard named: ' + dashboardBody.dashboard.title);
var destId = config.get(program.dest).accountId;
dashboardBody = dashboards.updateAccountId(dashboardBody, 1, destId);
console.log(dashboardBody);
} else {
console.error('Problem reading file', fname);
}
return dashboardBody;
}
|
javascript
|
{
"resource": ""
}
|
q8993
|
train
|
function (done) {
glob(path.join(__dirname, "*.ejs"), function (err, files) {
if (err) {
return done(err);
}
var templates = {};
async.forEach(files, function (file, done) {
fs.readFile(file, "utf8", function (err, data) {
if (err) {
return done(err);
} else {
templates[path.basename(file, ".ejs")] = _.template(data);
done();
}
});
}, function (err) {
if (err) {
return done(err);
}
done(null, templates);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8994
|
train
|
function () {
this.update = {
gravity: function (entity, dt) {
// Accelerate entity until it reaches terminal velocity.
if (entity.c.velocity.yspeed < entity.c.gravity.terminal) {
entity.c.velocity.yspeed += hitagi.utils.delta(entity.c.gravity.magnitude, dt);
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8995
|
train
|
function(data) {
//initialise with a few Todos because we are very busy people
self.todoList.insert(data.data.todoList);
self.todoList2.insert(data.data.todoList);
self.todoList3.insert(data.data.todoList);
self.todoList4.insert(data.data.todoList);
}
|
javascript
|
{
"resource": ""
}
|
|
q8996
|
MongoDB
|
train
|
function MongoDB(host, port, database, collection, username, password){
_self = this;
if(arguments.length < 3){
throw ("MongoDB constructor requires at least three arguments!");
}
if(collection){
_collection = collection;
} else{
_collection = DEFAULT_COLLECTION_NAME;
}
_username = username;
_password = password;
_host = host;
//create new database connection
_db = new Db(database, new Server(host, port), {safe:false}, {auto_reconnect: true});
}
|
javascript
|
{
"resource": ""
}
|
q8997
|
train
|
function(cb){
if(!_isOpen){
_self.open(function () {
_self.removeAll(function() {
getCollection(cb);
});
});
} else {
getCollection(cb);
}
function getCollection(cb) {
_db.collection(_collection, cb);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8998
|
hashRound
|
train
|
function hashRound(input, length, hashFunction, rounds, callback) {
if (rounds > 0 || !validatePassword(input, length)) {
process.nextTick(() => {
hashRound(hashFunction(input), length, hashFunction, rounds - 1, callback);
});
return;
}
process.nextTick(() => {
callback(input.substring(0, length));
});
}
|
javascript
|
{
"resource": ""
}
|
q8999
|
selectColor
|
train
|
function selectColor(namespace) {
var hash = 0,
i;
for (i in namespace) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.