_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q57700 | setConfig | train | function setConfig(newConf, isClearPrevious) {
checkIsObject(newConf);
config = isClearPrevious ? Immutable.fromJS(newConf) : config.merge(newConf);
} | javascript | {
"resource": ""
} |
q57701 | getConfigElement | train | function getConfigElement(name) {
checkIsString('name', name);
if (config.has(name)) {
return config.get(name);
}
} | javascript | {
"resource": ""
} |
q57702 | add | train | function add(str, {split, last, only}={}) {
if (only !== 'path') regex += str;
if (filepath && only !== 'regex') {
path.regex += (str === '\\/' ? SEP : str);
if (split) {
if (last) segment += str;
if (segment !== '') {
if (!flags.includes('g')) segment = `^${segment}$`; // change it 'includes'
path.segments.push(new RegExp(segment, flags));
}
segment = '';
} else {
segment += str;
}
}
} | javascript | {
"resource": ""
} |
q57703 | builtInReferenceAction | train | function builtInReferenceAction(referenceNames, skipCache = false) {
return () => {
if (!referenceNames) {
return undefined;
}
return Promise.all(loadManyReferenceList(referenceNames, skipCache))
.then(function successReferenceLoading(data) {
//Rebuilt a constructed information from the map.
const reconstructedData = data.reduce((acc, item) => { acc[item.name] = item.dataList; return acc; }, {})
dispatcher.handleViewAction({ data: reconstructedData, type: 'update', subject: 'reference' });
}, function errorReferenceLoading(err) {
dispatcher.handleViewAction({ data: err, type: 'error' });
});
};
} | javascript | {
"resource": ""
} |
q57704 | _preServiceCall | train | function _preServiceCall({ node, type, preStatus, callerId, shouldDumpStoreOnActionCall }, payload) {
//There is a problem if the node is empty. //Node should be an array
let data = {};
let status = {};
const STATUS = { name: preStatus, isLoading: true };
type = shouldDumpStoreOnActionCall ? 'update' : 'updateStatus';
// When there is a multi node update it should be an array.
if (Array.isArray(node)) {
node.forEach((nd) => {
data[nd] = shouldDumpStoreOnActionCall ? null : (payload && payload[nd]) || null;
status[nd] = STATUS;
});
} else {
data[node] = shouldDumpStoreOnActionCall ? null : (payload || null);
status[node] = STATUS;
}
//Dispatch store cleaning.
dispatcher.handleViewAction({ data, type, status, callerId });
} | javascript | {
"resource": ""
} |
q57705 | _dispatchServiceResponse | train | function _dispatchServiceResponse({ node, type, status, callerId }, json) {
const isMultiNode = Array.isArray(node);
const data = isMultiNode ? json : { [node]: json };
const postStatus = { name: status, isLoading: false };
let newStatus = {};
if (isMultiNode) {
node.forEach((nd) => { newStatus[nd] = postStatus; });
} else {
newStatus[node] = postStatus;
}
dispatcher.handleServerAction({
data,
type,
status: newStatus,
callerId
});
// Update information similar to store::afterChange
return {
properties: Object.keys(data),
data,
status: newStatus,
informations: { callerId }
};
} | javascript | {
"resource": ""
} |
q57706 | _dispatchFieldErrors | train | function _dispatchFieldErrors({ node, callerId }, errorResult) {
const isMultiNode = Array.isArray(node);
const data = {};
if (isMultiNode) {
node.forEach((nd) => {
data[nd] = (errorResult || {})[nd] || null;
});
} else {
data[node] = errorResult;
}
const errorStatus = {
name: 'error',
isLoading: false
};
let newStatus = {};
if (isMultiNode) {
node.forEach((nd) => {
newStatus[nd] = errorStatus;
});
} else {
newStatus[node] = errorStatus;
}
dispatcher.handleServerAction({
data,
type: 'updateError',
status: newStatus,
callerId
});
} | javascript | {
"resource": ""
} |
q57707 | _errorOnCall | train | function _errorOnCall(config, err) {
const errorResult = manageResponseErrors(err, config);
_dispatchFieldErrors(config, errorResult.fields);
} | javascript | {
"resource": ""
} |
q57708 | _processName | train | function _processName(pfx, eltDescName) {
if (pfx === undefined || pfx === null) {
pfx = EMPTY;
}
if (eltDescName === undefined || eltDescName === null) {
return pfx;
}
if (pfx === EMPTY) {
return eltDescName;
}
return pfx + '.' + eltDescName;
} | javascript | {
"resource": ""
} |
q57709 | _processHeaders | train | function _processHeaders(siteDesc, prefix) {
if (!siteDesc.headers) {
return;
}
//console.log('headers', siteDesc.headers, 'prefix', prefix);
let headers = siteDesc.headers;
let isInSiteStructure = false;
if (siteDescriptionReader.checkParams(siteDesc.requiredParams)) {
isInSiteStructure = true;
}
for (let i in headers) {
_processElement(headers[i], prefix, { isInSiteStructure: isInSiteStructure });
}
} | javascript | {
"resource": ""
} |
q57710 | _processPages | train | function _processPages(siteDesc, prefix) {
if (siteDesc.pages !== undefined && siteDesc.pages !== null) {
//console.log('pages', siteDesc.pages, 'prefix', prefix);
for (let i in siteDesc.pages) {
_processElement(siteDesc.pages[i], prefix);
}
}
} | javascript | {
"resource": ""
} |
q57711 | _processRoute | train | function _processRoute(siteDesc, prefix, options) {
options = options || {};
//if (siteDesc.roles !== undefined && siteDesc.url !== undefined)
//console.log('route', siteDesc.url, 'prefix', prefix);
if (userHelper.hasRole(siteDesc.roles)) {
let route = {
roles: siteDesc.roles,
name: prefix,
route: siteDesc.url,
regex: routeToRegExp(siteDesc.url),
requiredParams: siteDesc.requiredParams
};
//Call the Backbone.history.handlers....
//console.log('*****************');
//console.log('ROute name: ',route.route);
//console.log('Route handler name : ', findRouteName(route.route.substring(1)));
routes[findRouteName(route.route.substring(1))] = route;
if (options.isInSiteStructure) {
siteStructure[prefix] = route;
}
}
} | javascript | {
"resource": ""
} |
q57712 | processSiteDescription | train | function processSiteDescription(options) {
options = options || {};
if (!siteDescriptionReader.isProcessed() || options.isForceProcess) {
siteDescription = siteDescriptionReader.getSite();
regenerateRoutes();
return siteDescription;
}
return false;
} | javascript | {
"resource": ""
} |
q57713 | loadListByName | train | function loadListByName(listName, args, skipCache = false) {
checkIsString('listName', listName);
const configurationElement = getElement(listName);
if (typeof configurationElement !== 'function') {
throw new Error(`You are trying to load the reference list: ${listName} which does not have a list configure.`);
}
let now = _getTimeStamp();
if (cache[listName] && (now - cache[listName].timeStamp) < getCacheDuration() && !skipCache) {
_deletePromiseWaiting(listName);
//console.info('data served from cache', listName, cache[listName].value);
return Promise.resolve(cache[listName].value);
}
//Call the service, the service must return a promise.
return configurationElement(args)
.then((data) => {
return _cacheData(listName, data)
});
} | javascript | {
"resource": ""
} |
q57714 | getAutoCompleteServiceQuery | train | function getAutoCompleteServiceQuery(listName) {
return (query) => {
loadListByName(listName, query.term).then((results) => {
query.callback(results);
});
};
} | javascript | {
"resource": ""
} |
q57715 | documentParam | train | function documentParam(param, paramDictionary, procedureOrService) {
let typeString = getTypeStringFromCode(param.type, null, param);
let name = getParamName(param);
let options = {
type: param.type,
paramDictionary: paramDictionary,
paramName: name
};
let description = getParamDescription(options);
if (description !== '') {
return ' * @param ' + typeString + ' ' + name + ' - ' + description;
}
return ' * @param ' + typeString + ' ' + name;
} | javascript | {
"resource": ""
} |
q57716 | setDomains | train | function setDomains(newDomains) {
if (!isObject(newDomains)) {
throw new InvalidException('newDomains should be an object', newDomains);
}
domainsMap = domainsMap.merge(newDomains);
} | javascript | {
"resource": ""
} |
q57717 | setDomain | train | function setDomain(domain) {
checkIsObject('domain', domain);
checkIsString('doamin.name', domain.name);
//test domain, domain.name
domainsMap = domainsMap.set(domain.name, domain);
} | javascript | {
"resource": ""
} |
q57718 | getDomain | train | function getDomain(domainName) {
if (!isString(domainName)) {
throw new InvalidException('domaiName should extists and be a string', domainName);
}
if (!domainsMap.has(domainName)) {
console.warn(`You are trying to access a non existing domain: ${domainName}`);
return Immutable.Map({});
}
return domainsMap.get(domainName);
} | javascript | {
"resource": ""
} |
q57719 | configure | train | function configure(options) {
if (options && isArray(options.globalMessages)) {
globalMessages = options.globalMessages;
}
if (options && isObject(options.errorTypes)) {
errorTypes = options.errorTypes;
}
} | javascript | {
"resource": ""
} |
q57720 | _formatParameters | train | function _formatParameters(parameters) {
let options = {},
formatter, value;
for (let prop in parameters) {
if (parameters.hasOwnProperty(prop)) {
if (parameters[prop].domain) {
let domain = getDomains()[parameters[prop].domain];
formatter = domain ? domain.format : undefined;
} else {
formatter = undefined;
}
value = formatter && formatter.value ? formatter.value(parameters[prop].value) : parameters[prop].value;
options[prop] = value;
}
}
return options;
} | javascript | {
"resource": ""
} |
q57721 | _treatGlobalErrors | train | function _treatGlobalErrors(responseJSON, options) {
options = options || {};
const allMessagesTypes = options.globalMessages || globalMessages;
if (responseJSON !== undefined) {
let globalMessagesContainer = [];
let messages = responseJSON;
//Looping through all messages types.
allMessagesTypes.forEach((globalMessageConf) => {
//Treat all the globals
let msgs = messages[globalMessageConf.name];
if (msgs) {
globalMessagesContainer = [...globalMessagesContainer, ...msgs];
//To remove
_treatGlobalMessagesPerType(msgs, globalMessageConf.type);
}
});
return globalMessagesContainer;
}
return null;
} | javascript | {
"resource": ""
} |
q57722 | _treatEntityDetail | train | function _treatEntityDetail(fieldErrors) {
return Object.keys(fieldErrors || {}).reduce(
(res, field) => {
res[field] = translate(fieldErrors[field]);
return res;
}, {});
} | javascript | {
"resource": ""
} |
q57723 | _treatEntityExceptions | train | function _treatEntityExceptions(responseJSON = {}, options) {
const { node } = options;
const fieldJSONError = responseJSON.fieldErrors || {};
let fieldErrors = {};
if (isArray(node)) {
node.forEach((nd) => { fieldErrors[nd] = _treatEntityDetail(fieldJSONError[nd]); });
} else {
fieldErrors = _treatEntityDetail(fieldJSONError);
}
return fieldErrors;
} | javascript | {
"resource": ""
} |
q57724 | _treatBadRequestExceptions | train | function _treatBadRequestExceptions(responseJSON = {}, options) {
responseJSON.type = responseJSON.type || errorTypes.entity;
if (responseJSON.type !== undefined) {
switch (responseJSON.type) {
case errorTypes.entity:
return _treatEntityExceptions(responseJSON, options);
case errorTypes.collection:
return _treatCollectionExceptions(responseJSON, options);
default:
break;
}
}
return null;
} | javascript | {
"resource": ""
} |
q57725 | manageResponseErrors | train | function manageResponseErrors(responseErrors, options) {
return {
globals: _treatGlobalErrors(responseErrors),
fields: _handleStatusError(responseErrors, options)
};
} | javascript | {
"resource": ""
} |
q57726 | getEntityConfiguration | train | function getEntityConfiguration(nodePath, extendedEntityConfiguration) {
//If a node is specified get the direct sub conf.
if (nodePath) {
return _getNode(nodePath, extendedEntityConfiguration).toJS();
}
return entitiesMap.toJS();
} | javascript | {
"resource": ""
} |
q57727 | _getNode | train | function _getNode(nodePath, extendedConfiguration) {
checkIsString('nodePath', nodePath);
if (!entitiesMap.hasIn(nodePath.split(SEPARATOR))) {
console.warn(`
It seems the definition your are trying to use does not exists in the entity definitions of your project.
The definition you want is ${nodePath} and the definition map is:
`, entitiesMap.toJS()
);
throw new Error('Wrong definition path given, see waning for more details');
}
let conf = entitiesMap.getIn(nodePath.split(SEPARATOR));
if (extendedConfiguration) {
checkIsObject(extendedConfiguration);
conf = conf.mergeDeep(extendedConfiguration);
}
return conf;
} | javascript | {
"resource": ""
} |
q57728 | encodeEnum | train | function encodeEnum(enumDefinition) {
/**
* Takes in a string value and using the provided enum definition encodes it as a `sInt` stored in a [ByteBuffer]{@link https://www.npmjs.com/package/bytebuffer} object for use with the protobufjs library.
* @param value - The value to encode.
* @throws {Error} If the provided value was not found in the enum definition
* @return {ByteBuffer|void}
*/
return function encodeValueBasedOnEnum(value) {
let buffer = new ByteBuffer();
if (value === null) {
return buffer;
}
let foundEnumVal;
Object.keys(enumDefinition).some(function(key) {
let enumValue = enumDefinition[key].toLowerCase();
if (enumValue === value.toLowerCase()) {
foundEnumVal = Number(key);
return true;
}
return false;
});
if (!Number.isInteger(foundEnumVal)) {
throw Error(
`Invalid enum value ${value}, should have been one of ${JSON.stringify(
enumDefinition
)}`
);
}
return encodeSInt32(foundEnumVal);
};
} | javascript | {
"resource": ""
} |
q57729 | renameFunction | train | function renameFunction(func, newName) {
// eslint-disable-next-line no-unused-vars
const prop = Object.getOwnPropertyDescriptor(func, 'name');
if (prop) {
const { value, ...others } = prop;
Object.defineProperty(func, 'name', { value: newName, ...others });
}
} | javascript | {
"resource": ""
} |
q57730 | addStream | train | async function addStream(call, propertyPath, addStreamCallback) {
return _addStream(client, call, propertyPath, addStreamCallback);
} | javascript | {
"resource": ""
} |
q57731 | close | train | async function close(callback) {
await closeStream(client.stream);
await closeStream(client.rpc);
if (callback) {
return callback();
}
} | javascript | {
"resource": ""
} |
q57732 | buildReferenceDefinition | train | function buildReferenceDefinition() {
//Read the current configuration in the reference config.
let referenceConf = refConfigAccessor.get();
//Warn the user if empty.
if (!referenceConf || isEmpty(referenceConf)) {
console.warn('You did not set any reference list in the reference configuration, see Focus.reference.config.set.');
}
//Build an object from the keys.
return Object.keys(referenceConf).reduce((acc, elt) => {
acc[elt] = elt;
return acc;
}, {});
} | javascript | {
"resource": ""
} |
q57733 | _buildFieldInformation | train | function _buildFieldInformation(fieldPath) {
const fieldConf = entityContainer.getFieldConfiguration(fieldPath);
const immutableFieldConf = Immutable.Map(fieldConf);
//Maybe add a domain check existance
let { domain } = fieldConf;
return domainContainer.get(domain).mergeDeep(immutableFieldConf);
} | javascript | {
"resource": ""
} |
q57734 | getEntityInformations | train | function getEntityInformations(entityName, complementaryInformation) {
checkIsString('entityName', entityName);
checkIsObject('complementaryInformation', complementaryInformation);
const key = entityName.split(SEPARATOR);
if (!computedEntityContainer.hasIn(key)) {
_buildEntityInformation(entityName);
}
return computedEntityContainer.get(entityName).mergeDeep(complementaryInformation).toJS();
} | javascript | {
"resource": ""
} |
q57735 | getFieldInformations | train | function getFieldInformations(fieldName, complementaryInformation) {
checkIsString('fieldName', fieldName);
checkIsObject('complementaryInformation', complementaryInformation);
const fieldPath = fieldName.split(SEPARATOR);
if (computedEntityContainer.hasIn(fieldPath)) {
return computedEntityContainer.getIn(fieldPath).toJS();
}
return _buildFieldInformation(fieldPath).mergeDeep(complementaryInformation).toJS();
} | javascript | {
"resource": ""
} |
q57736 | train | function (options) {
// This bundle is for our application
var bundler = browserify({
debug: options.debug, // Need that sourcemapping
standalone: 'flux-react',
// These options are just for Watchify
cache: {}, packageCache: {}, fullPaths: options.watch
})
.require(require.resolve('./src/main.js'), { entry: true })
.external('react');
// The actual rebundle process
var rebundle = function () {
var start = Date.now();
bundler.bundle()
.on('error', gutil.log)
.pipe(source(options.name))
.pipe(gulpif(options.uglify, streamify(uglify())))
.pipe(gulp.dest(options.dest))
.pipe(notify(function () {
// Fix for requirejs
var fs = require('fs');
var file = fs.readFileSync(options.dest + '/' + options.name).toString();
file = file.replace('define([],e)', 'define(["react"],e)');
fs.writeFileSync(options.dest + '/' + options.name, file);
console.log('Built in ' + (Date.now() - start) + 'ms');
}));
};
// Fire up Watchify when developing
if (options.watch) {
bundler = watchify(bundler);
bundler.on('update', rebundle);
}
return rebundle();
} | javascript | {
"resource": ""
} | |
q57737 | train | function () {
var start = Date.now();
bundler.bundle()
.on('error', gutil.log)
.pipe(source(options.name))
.pipe(gulpif(options.uglify, streamify(uglify())))
.pipe(gulp.dest(options.dest))
.pipe(notify(function () {
// Fix for requirejs
var fs = require('fs');
var file = fs.readFileSync(options.dest + '/' + options.name).toString();
file = file.replace('define([],e)', 'define(["react"],e)');
fs.writeFileSync(options.dest + '/' + options.name, file);
console.log('Built in ' + (Date.now() - start) + 'ms');
}));
} | javascript | {
"resource": ""
} | |
q57738 | select | train | function select(segments, selection, buildLog){
var result = [];
segments.forEach(function(seg){
var index =
(seg.myFill.above ? 8 : 0) +
(seg.myFill.below ? 4 : 0) +
((seg.otherFill && seg.otherFill.above) ? 2 : 0) +
((seg.otherFill && seg.otherFill.below) ? 1 : 0);
if (selection[index] !== 0){
// copy the segment to the results, while also calculating the fill status
result.push({
id: buildLog ? buildLog.segmentId() : -1,
start: seg.start,
end: seg.end,
myFill: {
above: selection[index] === 1, // 1 if filled above
below: selection[index] === 2 // 2 if filled below
},
otherFill: null
});
}
});
if (buildLog)
buildLog.selected(result);
return result;
} | javascript | {
"resource": ""
} |
q57739 | split | train | function split(arr, size) {
var out = [];
var sizes = [];
var where = size - 1;
var ptr = 0;
var i, j;
for (i = arr.length - 1; i >= 0; i--) {
sizes[where] = (sizes[where] || 0) + 1;
if (--where === -1) where = size - 1;
}
for (i = 0; i < size; i++) {
for (j = 0; j < sizes[i]; j++) {
if (j === 0) out[i] = [arr[ptr]];
else out[i].push(arr[ptr]);
ptr++;
}
}
return out;
} | javascript | {
"resource": ""
} |
q57740 | writeNormalizeRml | train | function writeNormalizeRml(store, writer) {
normalizeRml(store, function () {
let parsedBlankSubjects = {};
writeBlanks(store, parsedBlankSubjects);
let quads = store.getQuads();
quads.forEach(function (quad) {
if (parsedBlankSubjects[quad.subject]) {
return;
}
if (parsedBlankSubjects[quad.object]) {
writer.addQuad(quad.subject, quad.predicate, writer.blank(parsedBlankSubjects[quad.object]));
return;
}
writer.addTriple(quad);
});
});
} | javascript | {
"resource": ""
} |
q57741 | log | train | function log(logger, message, type) {
if(!logger) return
if(logger.toConsole) {
if (console.group) console.group('i18n-tag-schema')
const log = console[type] || console.log
log(message)
if (console.groupEnd) console.groupEnd()
} else {
const log = logger[type]
if(log) log(message)
}
} | javascript | {
"resource": ""
} |
q57742 | Representation | train | function Representation(factory, self, entity, root) {
this._halacious = factory._halacious;
this.factory = factory;
this.request = factory._request;
this._root = root || this;
this.self = self.href;
this._links = { self: self };
this._embedded = {};
this._namespaces = {};
this._props = {};
this._ignore = {};
this.entity = entity;
} | javascript | {
"resource": ""
} |
q57743 | toHtmlEntities | train | function toHtmlEntities(str) {
str = str || '';
return str.replace(/./gm, function(s) {
return "&#" + s.charCodeAt(0) + ";";
});
} | javascript | {
"resource": ""
} |
q57744 | isEmptyBeforeStep | train | function isEmptyBeforeStep(step) {
return step.keyword.trim() === 'Before' && step.name === undefined && step.embeddings === undefined;
} | javascript | {
"resource": ""
} |
q57745 | isEmptyAfterStep | train | function isEmptyAfterStep(step) {
return step.keyword.trim() === 'After' && step.name === undefined && step.embeddings === undefined;
} | javascript | {
"resource": ""
} |
q57746 | isAfterStepWithScreenshot | train | function isAfterStepWithScreenshot(step) {
return step.keyword.trim() === 'After' && step.embeddings && step.embeddings[0] && step.embeddings[0].mime_type === 'image/png';
} | javascript | {
"resource": ""
} |
q57747 | getScenarioContainer | train | function getScenarioContainer(scenarios) {
var template = grunt.file.read(templates.scenarioContainerTemplate),
scenarioContainer;
scenarioContainer = grunt.template.process(template, {
data: {
scenarios: scenarios
}
});
return scenarioContainer;
} | javascript | {
"resource": ""
} |
q57748 | getScenario | train | function getScenario(scenario, isPassed, steps) {
var template = grunt.file.read(templates.scenarioTemplate),
scenarioTemplate;
scenarioTemplate = grunt.template.process(template, {
data: {
status: isPassed ? statuses.PASSED : statuses.FAILED,
name: scenario.keyword + ': ' + scenario.name,
steps: steps
}
});
return scenarioTemplate;
} | javascript | {
"resource": ""
} |
q57749 | getFeature | train | function getFeature(feature, scenariosNumberInFeature, passedScenariosNumberInFeature, stepsNumberInFeature, passedStepsInFeature) {
var template = grunt.file.read(templates.featureTemplate),
featureTemplate;
featureTemplate = grunt.template.process(template, {
data: {
name: feature.name,
scenariosNumberInFeature: scenariosNumberInFeature,
passedScenariosNumberInFeature: passedScenariosNumberInFeature,
stepsNumberInFeature: stepsNumberInFeature,
passedStepsInFeature: passedStepsInFeature
}
});
return featureTemplate;
} | javascript | {
"resource": ""
} |
q57750 | getHeader | train | function getHeader(scenariosNumber, passedScenarios, stepsNumber, passedSteps, elapsedTime) {
var template = grunt.file.read(templates.headerTemplate),
header = grunt.template.process(template, {
data: {
status: areTestsPassed(scenariosNumber, passedScenarios) ? 'passed' : 'failed',
scenariosSummary: scenariosNumber + ' scenarios ' + '(' + passedScenarios + ' passed)',
stepsSummary: stepsNumber + ' steps ' + '(' + passedSteps + ' passed)',
reportDate: getCurrentDate(),
reportTitle: reportTitle,
elapsedTime: elapsedTime
}
});
return header;
} | javascript | {
"resource": ""
} |
q57751 | generateHTML | train | function generateHTML(testResults) {
var stepsHtml = '',
header = '',
isPassed = false,
passedScenarios = 0,
passedSteps = 0,
stepsNumber = 0,
scenariosNumber = 0,
scenariosNumberInFeature = 0,
passedScenariosNumberInFeature = 0,
stepsNumberInFeature = 0,
passedStepsInFeature = 0,
scenariosHtml = '',
element,
step,
stepDuration = 0;
html = '';
for (var i = 0; i < testResults.length; i++) {
scenariosNumberInFeature = 0;
passedScenariosNumberInFeature = 0;
stepsNumberInFeature = 0;
passedStepsInFeature = 0;
scenariosHtml = '';
if (testResults[i].elements) {
for (var j = 0; j < testResults[i].elements.length; j++) {
element = testResults[i].elements[j];
if (element.type === 'scenario') {
scenariosNumber++;
scenariosNumberInFeature++;
stepsHtml = '';
isPassed = true;
for (var k = 0; k < testResults[i].elements[j].steps.length; k++) {
step = testResults[i].elements[j].steps[k];
if (isEmptyAfterStep(step) || isEmptyBeforeStep(step)) {
continue;
}
if (isAfterStepWithScreenshot(step)) {
stepsHtml += getAfterScreenshotStep(step);
} else {
stepsHtml += getStep(step);
stepDuration += (step.result.duration ? step.result.duration : 0);
stepsNumber++;
stepsNumberInFeature++;
if (step.result.status !== statuses.PASSED) {
isPassed = false;
} else if (step.result.status === statuses.PASSED) {
passedSteps++;
passedStepsInFeature++;
}
}
}
if (isPassed) {
passedScenarios++;
passedScenariosNumberInFeature++;
}
scenariosHtml += getScenarioContainer(getScenario(element, isPassed, stepsHtml));
}
}
}
html += getFeatureWithScenarios(getFeature(testResults[i], scenariosNumberInFeature, passedScenariosNumberInFeature, stepsNumberInFeature, passedStepsInFeature) + scenariosHtml);
}
header = getHeader(scenariosNumber, passedScenarios, stepsNumber, passedSteps, calculateDuration(stepDuration));
return header + html;
} | javascript | {
"resource": ""
} |
q57752 | generateReport | train | function generateReport(html) {
var template = grunt.file.read(templates.reportTemplate);
return grunt.template.process(template, {
data: {
scenarios: html
}
});
} | javascript | {
"resource": ""
} |
q57753 | strictEqualityResolver | train | function strictEqualityResolver() {
var knownValues = [];
function resolveMemoKey(value) {
if (knownValues.indexOf(value) === -1) {
knownValues.push(value);
}
return '' + _.indexOf(knownValues, value);
}
return resolveMemoKey;
} | javascript | {
"resource": ""
} |
q57754 | train | function (rep, next) {
rep.entity.items.forEach(function (item) {
var embed = rep.embed('item', './' + item.id, item);
if (item.googlePlusId) {
embed.link('home', 'http://plus.google.com/' + item.googlePlusId);
embed.ignore('googlePlusId');
}
});
rep.ignore('items');
// dont forget to call next!
next();
} | javascript | {
"resource": ""
} | |
q57755 | _spawn | train | function _spawn(mvn, args) {
const spawn = require('child_process').spawn;
// Command to be executed.
let cmd = mvn.options.cmd || mvnw(mvn.options.cwd) || 'mvn';
return new Promise((resolve, reject) => {
if (isWin) {
args.unshift(cmd);
args.unshift('/c'),
args.unshift('/s');
cmd = process.env.COMSPEC || 'cmd.exe';
}
const proc = spawn(cmd, args, { 'cwd': mvn.options.cwd });
proc.on('error', reject);
proc.on('exit', (code, signal) => {
if (code !== 0) {
reject({ 'code': code, 'signal': signal });
} else {
resolve();
}
});
proc.stdout.on('data', process.stdout.write.bind(process.stdout));
proc.stderr.on('data', process.stderr.write.bind(process.stderr));
});
} | javascript | {
"resource": ""
} |
q57756 | train | function () {
var steps = this.querySelectorAll('.step');
var scenarioArrow = this.querySelector('.scenario-arrow');
for (var k = 0; k < steps.length; k++) {
if (steps[k].style.display === 'block') {
scenarioArrow.classList.remove('fa-angle-up');
scenarioArrow.classList.add('fa-angle-down');
steps[k].style.display = 'none';
} else {
steps[k].style.display = 'block';
scenarioArrow.classList.remove('fa-angle-down');
scenarioArrow.classList.add('fa-angle-up');
}
}
} | javascript | {
"resource": ""
} | |
q57757 | train | function (buttonState) {
var scenarios = document.querySelectorAll('.scenario'),
hasClass,
self = this;
for (var i = 0; i < scenarios.length; i++) {
hasClass = scenarios[i].classList.contains(buttonState);
if (hasClass === true) {
if (scenarios[i].parentNode.style.display === 'none') {
scenarios[i].parentNode.style.display = 'block';
}
} else {
scenarios[i].parentNode.style.display = 'none';
}
}
if (buttonState === 'failed') {
self.currentView = 'failed';
this.hideFeatureContainer('passed');
} else {
self.currentView = 'passed';
this.hideFeatureContainer('failed');
}
} | javascript | {
"resource": ""
} | |
q57758 | train | function (scenarios) {
var self = this;
self.currentView = 'all';
for (var i = 0; i < scenarios.length; i++) {
if (scenarios[i].style.display != 'block') {
scenarios[i].style.display = 'block';
}
}
} | javascript | {
"resource": ""
} | |
q57759 | train | function (filteringButtons, scenarios, steps) {
var self = this,
btnState;
for (var k = 0; k < filteringButtons.length; k++) {
filteringButtons[k].addEventListener('click', function () {
btnState = this.dataset.state;
self.displayAllFeatures();
if (btnState !== 'steps') {
self.removeActiveClass(filteringButtons);
this.classList.add('active');
self.hideSteps(steps);
}
switch (btnState) {
case 'all':
self.displayAllScenarios(scenarios);
break;
case 'chart':
app.chart.toggleChart();
self.displayAllScenarios(scenarios);
break;
case 'steps':
if (self.currentView === 'failed') {
self.toggleStepsVisibilities('.scenario.failed .step', 'passed');
}
else if (self.currentView === 'passed') {
self.toggleStepsVisibilities('.scenario.passed .step', 'failed');
} else {
self.displayAllScenarios(scenarios);
self.toggleSteps(steps);
}
break;
default:
self.filterScenarios(btnState);
break;
}
}, false);
}
} | javascript | {
"resource": ""
} | |
q57760 | train | function (steps) {
var scenarioArrowCollection = document.querySelectorAll('.scenario-arrow'),
allBtn = document.querySelector('.all-btn');
for (var i = 0; i < steps.length; i++) {
var display = steps[i].style.display;
if (display === 'none' || display === '') {
this.addArrowUp(scenarioArrowCollection);
steps[i].style.display = 'block';
allBtn.classList.add('active');
} else {
this.addArrowDown(scenarioArrowCollection);
allBtn.classList.add('active');
steps[i].style.display = 'none';
}
}
} | javascript | {
"resource": ""
} | |
q57761 | train | function (steps) {
for (var i = 0; i < steps.length; i++) {
steps[i].style.display = 'none';
}
} | javascript | {
"resource": ""
} | |
q57762 | train | function (state) {
var features = document.querySelectorAll('.feature-with-scenarios'),
scenarios,
counter = 0;
for (var i = 0; i < features.length; i++) {
scenarios = features[i].querySelectorAll('.scenario');
counter = 0;
for (var j = 0; j < scenarios.length; j++) {
if (scenarios[j].classList.contains(state)) {
counter++;
}
}
if (counter === scenarios.length) {
features[i].classList.add('hidden');
}
}
} | javascript | {
"resource": ""
} | |
q57763 | train | function (r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
} | javascript | {
"resource": ""
} | |
q57764 | train | function (obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {x: curleft, y: curtop};
}
} | javascript | {
"resource": ""
} | |
q57765 | train | function () {
var documentContainer = document.querySelector('.document-container');
if (documentContainer.classList.contains('backdrop-hidden')) {
documentContainer.classList.remove('backdrop-hidden');
documentContainer.style.display = 'none';
}
if (this.classList.contains('chart-hidden')) {
this.classList.remove('chart-hidden');
this.style.display = 'none';
}
} | javascript | {
"resource": ""
} | |
q57766 | train | function () {
var scenarioPassed = document.querySelectorAll('.scenario.passed').length,
scenarioFailed = document.querySelectorAll('.scenario.failed').length,
scenariosAmount = document.querySelectorAll('.scenario').length,
passed = (scenarioPassed / scenariosAmount) * 100,
failed = (scenarioFailed / scenariosAmount) * 100,
statistics;
statistics = {
scenariosAmount: scenariosAmount,
passed: Math.round(Math.floor(passed)),
failed: Math.round(Math.ceil(failed))
};
return statistics;
} | javascript | {
"resource": ""
} | |
q57767 | train | function () {
window.scrollTo(0, 0);
var chart = document.querySelector('.scenario-chart'),
chartBtn = document.querySelectorAll('.btn-chart');
if (chart.style.display != 'block') {
chart.style.display = 'block';
document.body.style.overflow = 'hidden';
} else {
chart.classList.add('chart-hidden');
document.body.style.overflow = 'auto';
app.navigation.removeActiveClass(chartBtn);
}
this.toggleChartBackdrop();
} | javascript | {
"resource": ""
} | |
q57768 | parseXmlFromFile | train | function parseXmlFromFile(fileName) {
try {
var xmlFile = fs.readFileSync(fileName, "utf8");
var xmlDoc = new xmldoc.XmlDocument(xmlFile);
// Single testsuite, not wrapped in a testsuites
if (xmlDoc.name === "testsuite") {
module.exports.testsuites = xmlDoc;
module.exports.testsuiteCount = 1;
} else {
// Multiple testsuites, wrapped in a parent
module.exports.testsuites = xmlDoc.childrenNamed("testsuite");
module.exports.testsuiteCount = module.exports.testsuites.length;
}
return xmlDoc;
} catch (e) {
if (e.code === "ENOENT") {
// Bad directory
return "File not found";
}
// Unknown error
return e;
}
} | javascript | {
"resource": ""
} |
q57769 | listXmlFiles | train | function listXmlFiles(path, recursive) {
try {
var allFiles = recursive ? read(path) : fs.readdirSync(path);
var xmlFiles = allFiles
.map(function(file) {
return fspath.join(path, file);
})
// Fiter out non-files
.filter(function(file) {
return fs.statSync(file).isFile();
})
// Only return files ending in '.xml'
.filter(function(file) {
return file.slice(-4) === ".xml";
});
// No files returned
if (!xmlFiles.length > 0) {
return new Error("No xml files found");
} else {
// Return the array of files ending in '.xml'
return xmlFiles;
}
} catch (e) {
throw e;
}
} | javascript | {
"resource": ""
} |
q57770 | extendUrlWithQuery | train | function extendUrlWithQuery(url, queryArgs) {
if (_.isEmpty(queryArgs)) {
return url;
}
var parts = urlLib.parse(url);
var query = _.extend(qs.parse(parts.query), queryArgs);
parts.search = '?' + qs.stringify(query);
return urlLib.format(_.pick(
parts,
'protocol',
'slashes',
'host',
'auth',
'pathname',
'search',
'hash'
));
} | javascript | {
"resource": ""
} |
q57771 | deriveSelectors | train | function deriveSelectors(selectors) {
const composedSelectors = {}
Object.keys(selectors).forEach(key => {
const selector = selectors[key]
if(selector instanceof Selector) {
composedSelectors[key] = (...args) =>
(composedSelectors[key] = selector.extractFunction(composedSelectors))(...args)
}
else {
composedSelectors[key] = selector
}
})
return composedSelectors
} | javascript | {
"resource": ""
} |
q57772 | askQuestions | train | function askQuestions() {
return request.get('https://app.rung.com.br/api/categories')
.then(prop('body') & map(({ name, alias: value }) => ({ name, value })))
.catch(~[{ name: 'Miscellaneous', value: 'miscellaneous' }])
.then(categories => [
{ name: 'name', message: 'Project name', default: getDefaultName(process.cwd()) },
{ name: 'version', message: 'Version', default: '1.0.0', validate: semver.valid & Boolean },
{ name: 'title', message: 'Title', default: 'Untitled' },
{ name: 'description', message: 'Description' },
{ name: 'category', type: 'list', message: 'Category', default: 'miscellaneous', choices: categories },
{ name: 'license', message: 'license', default: 'MIT' }
])
.then(inquirer.createPromptModule());
} | javascript | {
"resource": ""
} |
q57773 | createBoilerplateFolder | train | function createBoilerplateFolder(answers) {
return createFolder(answers.name)
.tap(createFolder(`${answers.name}/info`))
.catch(~reject(new Error(`Unable to create folder ${answers.name}`)))
.return(answers);
} | javascript | {
"resource": ""
} |
q57774 | getInfoFiles | train | function getInfoFiles(answers) {
const locales = ['en', 'es', 'pt_BR'];
return locales
| map(locale => ({ filename: path.join(answers.name, `info/${locale}.md`), content: '' }));
} | javascript | {
"resource": ""
} |
q57775 | getIndexFile | train | function getIndexFile(answers) {
const content = format(`
import { create } from 'rung-sdk';
import { String as Text } from 'rung-cli/dist/types';
function render(name) {
return <b>{ _('Hello {{name}}', { name }) }</b>;
}
function main(context) {
const { name } = context.params;
return {
alerts: [{
title: _('Welcome'),
content: render(name),
resources: []
}]
};
}
const params = {
name: {
description: _('What is your name?'),
type: Text
}
};
export default create(main, {
params,
primaryKey: true,
title: _(${JSON.stringify(answers.title)}),
description: _(${JSON.stringify(answers.description)}),
preview: render('Trixie')
});
`);
return { filename: path.join(answers.name, 'index.js'), content };
} | javascript | {
"resource": ""
} |
q57776 | fetchRungApi | train | function fetchRungApi() {
const envApi = process.env.RUNG_API;
if (isNil(envApi)) {
return 'https://app.rung.com.br/api';
}
if (!isURL(envApi)) {
emitWarning(`invalid API for Rung: ${JSON.stringify(envApi)}`);
}
return envApi;
} | javascript | {
"resource": ""
} |
q57777 | resolveInputFile | train | function resolveInputFile(args) {
const { file } = args;
return file ? resolve(path.resolve(file)) : build(args);
} | javascript | {
"resource": ""
} |
q57778 | compileProps | train | function compileProps(props) {
const transformKey = when(equals('className'), ~'class');
const transformValue = ifElse(type & equals('Object'),
compileCSS, unary(JSON.stringify));
const result = props
| toPairs
| map(([key, value]) => `${transformKey(key)}=${transformValue(value)}`)
| join(' ');
return result.length === 0 ? '' : ` ${result}`;
} | javascript | {
"resource": ""
} |
q57779 | compileSelfClosingTag | train | function compileSelfClosingTag(tag, props) {
const compiledProps = compileProps(props);
return contains(tag, ['br', 'hr', 'img'])
? `<${tag}${compiledProps} />`
: `<${tag}${compiledProps}></${tag}>`;
} | javascript | {
"resource": ""
} |
q57780 | train | function () {
if (u.hasClass(this._header, this._CssClasses.IS_ANIMATING)) {
return;
}
if (this._content.scrollTop > 0 && !u.hasClass(this._header, this._CssClasses.IS_COMPACT)) {
u.addClass(this._header, this._CssClasses.CASTING_SHADOW)
.addClass(this._header, this._CssClasses.IS_COMPACT)
.addClass(this._header, this._CssClasses.IS_ANIMATING);
} else if (this._content.scrollTop <= 0 && u.hasClass(this._header, this._CssClasses.IS_COMPACT)) {
u.removeClass(this._header, this._CssClasses.CASTING_SHADOW)
.removeClass(this._header, this._CssClasses.IS_COMPACT)
.addClass(this._header, this._CssClasses.IS_ANIMATING);
}
} | javascript | {
"resource": ""
} | |
q57781 | train | function () {
if(u.isIE8 || u.isIE9){
this._screenSizeMediaQuery = {};
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if(w > 1024)
this._screenSizeMediaQuery.matches = false;
else
this._screenSizeMediaQuery.matches = true;
}
if (this._screenSizeMediaQuery.matches) {
u.addClass(this.element, this._CssClasses.IS_SMALL_SCREEN);
} else {
u.removeClass(this.element, this._CssClasses.IS_SMALL_SCREEN);
// Collapse drawer (if any) when moving to a large screen size.
if (this._drawer) {
u.removeClass(this._drawer, this._CssClasses.IS_DRAWER_OPEN);
u.removeClass(this._obfuscator, this._CssClasses.IS_DRAWER_OPEN);
}
}
} | javascript | {
"resource": ""
} | |
q57782 | train | function () {
u.toggleClass(this._drawer, this._CssClasses.IS_DRAWER_OPEN);
u.toggleClass(this._obfuscator, this._CssClasses.IS_DRAWER_OPEN);
} | javascript | {
"resource": ""
} | |
q57783 | train | function () {
if (u.hasClass(this._header, this._CssClasses.IS_COMPACT)) {
u.removeClass(this._header, this._CssClasses.IS_COMPACT);
u.addClass(this._header, this._CssClasses.IS_ANIMATING);
}
} | javascript | {
"resource": ""
} | |
q57784 | train | function () {
if (this._input.disabled) {
u.addClass(this.element, this._CssClasses.IS_DISABLED);
} else {
u.removeClass(this.element, this._CssClasses.IS_DISABLED);
}
} | javascript | {
"resource": ""
} | |
q57785 | train | function () {
if (this._input.value && this._input.value.length > 0) {
u.addClass(this.element, this._CssClasses.IS_DIRTY);
} else {
u.removeClass(this.element, this._CssClasses.IS_DIRTY);
}
} | javascript | {
"resource": ""
} | |
q57786 | train | function (evt) {
if (this.element && this._container && this.for_element) {
var items = this.element.querySelectorAll('.u-menu-item:not([disabled])');
if (items && items.length > 0 && u.hasClass(this._container, 'is-visible')) {
if (evt.keyCode === this._Keycodes.UP_ARROW) {
u.stopEvent(evt);
// evt.preventDefault();
items[items.length - 1].focus();
} else if (evt.keyCode === this._Keycodes.DOWN_ARROW) {
u.stopEvent(evt);
// evt.preventDefault();
items[0].focus();
}
}
}
} | javascript | {
"resource": ""
} | |
q57787 | train | function (evt) {
if (this.element && this._container) {
var items = this.element.querySelectorAll('.u-menu-item:not([disabled])');
if (items && items.length > 0 && u.hasClass(this._container, 'is-visible')) {
var currentIndex = Array.prototype.slice.call(items).indexOf(evt.target);
if (evt.keyCode === this._Keycodes.UP_ARROW) {
u.stopEvent(evt);
// evt.preventDefault();
if (currentIndex > 0) {
items[currentIndex - 1].focus();
} else {
items[items.length - 1].focus();
}
} else if (evt.keyCode === this._Keycodes.DOWN_ARROW) {
u.stopEvent(evt);
// evt.preventDefault();
if (items.length > currentIndex + 1) {
items[currentIndex + 1].focus();
} else {
items[0].focus();
}
} else if (evt.keyCode === this._Keycodes.SPACE ||
evt.keyCode === this._Keycodes.ENTER) {
u.stopEvent(evt);
// evt.preventDefault();
// Send mousedown and mouseup to trigger ripple.
var e = new MouseEvent('mousedown');
evt.target.dispatchEvent(e);
e = new MouseEvent('mouseup');
evt.target.dispatchEvent(e);
// Send click.
evt.target.click();
} else if (evt.keyCode === this._Keycodes.ESCAPE) {
u.stopEvent(evt);
// evt.preventDefault();
this.hide();
}
}
}
} | javascript | {
"resource": ""
} | |
q57788 | train | function (evt) {
if (evt.target.hasAttribute('disabled')) {
u.stopEvent(evt);
// evt.stopPropagation();
} else {
// Wait some time before closing menu, so the user can see the ripple.
this._closing = true;
window.setTimeout(function (evt) {
this.hide();
this._closing = false;
}.bind(this), 150);
}
} | javascript | {
"resource": ""
} | |
q57789 | train | function () {
var cleanup = function () {
u.off(this.element,'transitionend', cleanup);
// this.element.removeEventListener('transitionend', cleanup);
u.off(this.element,'webkitTransitionEnd', cleanup);
// this.element.removeEventListener('webkitTransitionEnd', cleanup);
u.removeClass(this.element, 'is-animating');
}.bind(this);
// Remove animation class once the transition is done.
u.on(this.element,'transitionend', cleanup);
// this.element.addEventListener('transitionend', cleanup);
u.on(this.element,'webkitTransitionEnd', cleanup);
// this.element.addEventListener('webkitTransitionEnd', cleanup);
} | javascript | {
"resource": ""
} | |
q57790 | train | function () {
if (this.element && this._container && this._outline) {
var items = this.element.querySelectorAll('.u-menu-item');
// Remove all transition delays; menu items fade out concurrently.
for (var i = 0; i < items.length; i++) {
items[i].style.transitionDelay = null;
}
// Measure the inner element.
var rect = this.element.getBoundingClientRect();
var height = rect.height;
var width = rect.width;
if(!width){
var left = rect.left;
var right = rect.right;
width = right - left;
}
if(!height){
var top = rect.top;
var bottom = rect.bottom;
height = bottom - top;
}
// Turn on animation, and apply the final clip. Also make invisible.
// This triggers the transitions.
u.addClass(this.element, 'is-animating');
this._applyClip(height, width);
u.removeClass(this._container, 'is-visible');
// Clean up after the animation is complete.
this._addAnimationEndListener();
}
} | javascript | {
"resource": ""
} | |
q57791 | train | function () {
if (this._btnElement.disabled) {
u.addClass(this.element, this._CssClasses.IS_DISABLED);
} else {
u.removeClass(this.element, this._CssClasses.IS_DISABLED);
}
} | javascript | {
"resource": ""
} | |
q57792 | train | function () {
if (this._btnElement.checked) {
u.addClass(this.element, this._CssClasses.IS_CHECKED);
} else {
u.removeClass(this.element, this._CssClasses.IS_CHECKED);
}
} | javascript | {
"resource": ""
} | |
q57793 | localesToPairs | train | function localesToPairs(localeFiles) {
return all(localeFiles.map(localeFile => fs.readFileAsync(localeFile, 'utf-8')
.then(JSON.parse)
.then(json => [localeByFile(localeFile), json])));
} | javascript | {
"resource": ""
} |
q57794 | precompile | train | function precompile({ code, files }) {
return resolve(files)
.then(filter(test(/^locales(\/|\\)[a-z]{2,3}(_[A-Z]{2})?\.json$/)))
.then(localesToPairs)
.then(runInAllLocales(code))
.then(createMetaFile)
.return(['.meta', ...files]);
} | javascript | {
"resource": ""
} |
q57795 | filterFiles | train | async function filterFiles(files) {
const clearModule = replace(/^\.\//, '');
const resources = files | filter(test(/^((icon\.png)|(README(\.\w+)?\.md))$/));
const missing = without(files, requiredFiles);
if (missing.length > 0) {
return reject(Error(`missing ${missing.join(', ')} from the project`));
}
if (!contains('icon.png', files)) {
emitWarning('compiling app without providing an icon.png file');
}
const infoFiles = await listFiles('info')
| filter(test(/[a-z]{2}(_[A-Z]{2,3})?\.md/))
| map(path.join('info/', _));
return fs.readFileAsync('index.js', 'utf-8')
.then(inspect)
.then(over(lensProp('modules'), filter(startsWith('./'))))
.then(({ code, modules }) => ({
code,
files: union(modules.map(clearModule),
[...resources, ...requiredFiles, ...infoFiles])
}));
} | javascript | {
"resource": ""
} |
q57796 | linkAutoComplete | train | function linkAutoComplete() {
return listFiles('autocomplete')
.then(filter(endsWith('.js')) & map(path.join('autocomplete', _)))
.tap(files => all(files.map(file => fs.readFileAsync(file)
.then(ensureNoImports(file)))));
} | javascript | {
"resource": ""
} |
q57797 | linkLocales | train | function linkLocales() {
return listFiles('locales')
.then(filter(test(/^[a-z]{2}(_[A-Z]{2,3})?\.json$/)) & map(path.join('locales', _)))
.filter(location => fs.readFileAsync(location)
.then(JSON.parse & is(Object))
.catchReturn(false))
.catchReturn([]);
} | javascript | {
"resource": ""
} |
q57798 | linkFiles | train | function linkFiles({ code, files }) {
return all([linkLocales(), linkAutoComplete()])
.spread(union)
.then(union(files) & sort(subtract) & (files => ({ code, files })));
} | javascript | {
"resource": ""
} |
q57799 | getProjectName | train | function getProjectName(dir) {
return fs.readFileAsync(path.join(dir, 'package.json'))
.then(JSON.parse & _.name)
.catchThrow(new Error('Failed to parse package.json from the project'));
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.