_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q50800
|
processItem
|
train
|
function processItem(params) {
var nestedMenu = extractNestedMenu(params);
// if html property is not defined, fallback to text, otherwise use default text
// if first item in the item array is a function then invoke .call()
// if first item is a string, then text should be the string.
var text = DEFAULT_ITEM_TEXT;
var currItemParam = angular.extend({}, params);
var item = params.item;
var enabled = item.enabled === undefined ? item[2] : item.enabled;
currItemParam.nestedMenu = nestedMenu;
currItemParam.enabled = resolveBoolOrFunc(enabled, params);
currItemParam.text = createAndAddOptionText(currItemParam);
registerCurrentItemEvents(currItemParam);
}
|
javascript
|
{
"resource": ""
}
|
q50801
|
renderContextMenu
|
train
|
function renderContextMenu (params) {
/// <summary>Render context menu recursively.</summary>
// Destructuring:
var $scope = params.$scope;
var event = params.event;
var options = params.options;
var modelValue = params.modelValue;
var level = params.level;
var customClass = params.customClass;
// Initialize the container. This will be passed around
var $ul = initContextMenuContainer(params);
params.$ul = $ul;
// Register this level of the context menu
_contextMenus.push($ul);
/*
* This object will contain any promises that we have
* to wait for before trying to adjust the context menu.
*/
var $promises = [];
params.$promises = $promises;
angular.forEach(options, function (item) {
if (item === null) {
appendDivider($ul);
} else {
// If displayed is anything other than a function or a boolean
var displayed = resolveBoolOrFunc(item.displayed, params);
// Only add the <li> if the item is displayed
if (displayed) {
var $li = $('<li>');
var itemParams = angular.extend({}, params);
itemParams.item = item;
itemParams.$li = $li;
if (typeof item[0] === 'object') {
custom.initialize($li, item);
} else {
processItem(itemParams);
}
if (resolveBoolOrFunc(item.hasTopDivider, itemParams, false)) {
appendDivider($ul);
}
$ul.append($li);
if (resolveBoolOrFunc(item.hasBottomDivider, itemParams, false)) {
appendDivider($ul);
}
}
}
});
if ($ul.children().length === 0) {
var $emptyLi = angular.element('<li>');
setElementDisabled($emptyLi);
$emptyLi.html('<a>' + _emptyText + '</a>');
$ul.append($emptyLi);
}
$document.find('body').append($ul);
doAfterAllPromises(params);
$rootScope.$broadcast(ContextMenuEvents.ContextMenuOpened, {
context: _clickedElement,
contextMenu: $ul,
params: params
});
}
|
javascript
|
{
"resource": ""
}
|
q50802
|
removeContextMenus
|
train
|
function removeContextMenus (level) {
while (_contextMenus.length && (!level || _contextMenus.length > level)) {
var cm = _contextMenus.pop();
$rootScope.$broadcast(ContextMenuEvents.ContextMenuClosed, { context: _clickedElement, contextMenu: cm });
cm.remove();
}
if(!level) {
$rootScope.$broadcast(ContextMenuEvents.ContextMenuAllClosed, { context: _clickedElement });
}
}
|
javascript
|
{
"resource": ""
}
|
q50803
|
resolveBoolOrFunc
|
train
|
function resolveBoolOrFunc(a, params, defaultValue) {
var item = params.item;
var $scope = params.$scope;
var event = params.event;
var modelValue = params.modelValue;
defaultValue = isBoolean(defaultValue) ? defaultValue : true;
if (isBoolean(a)) {
return a;
} else if (angular.isFunction(a)) {
return a.call($scope, $scope, event, modelValue);
} else {
return defaultValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q50804
|
ModuleDef
|
train
|
function ModuleDef (path) {
this.path = path;
this.friendlyPath = path;
util.splitPath(path, this);
this.directory = util.resolve(ENV.getCwd(), this.directory);
}
|
javascript
|
{
"resource": ""
}
|
q50805
|
loadModule
|
train
|
function loadModule (baseLoader, fromDir, fromFile, item, opts) {
var modulePath = item.from;
var possibilities = util.resolveModulePath(modulePath, fromDir);
for (var i = 0, p; p = possibilities[i]; ++i) {
var path = possibilities[i].path;
if (!opts.reload && (path in jsio.__modules)) {
return possibilities[i];
}
if (path in failedFetch) { possibilities.splice(i--, 1); }
}
if (!possibilities.length) {
if (opts.suppressErrors) { return false; }
var e = new Error('Could not import `' + item.from + '`'
+ "\tImport Stack:\n"
+ "\t\t" + processStack().join("\n\t\t"));
e.jsioLogged = true;
e.code = MODULE_NOT_FOUND;
throw e;
}
var moduleDef = findModule(possibilities);
if (!moduleDef) {
if (opts.suppressErrors) { return false; }
var paths = [];
for (var i = 0, p; p = possibilities[i]; ++i) { paths.push(p.path); }
var e = new Error("Could not import `" + modulePath + "`\n"
+ "\tlooked in:\n"
+ "\t\t" + paths.join('\n\t\t') + "\n"
+ "\tImport Stack:\n"
+ "\t\t" + processStack().join("\n\t\t"));
e.code = MODULE_NOT_FOUND;
throw e;
}
// a (potentially) nicer way to refer to a module -- how it was referenced in code when it was first imported
moduleDef.friendlyPath = modulePath;
// cache the base module's path in the path cache so we don't have to
// try out all paths the next time we see the same base module.
if (moduleDef.baseMod && !(moduleDef.baseMod in jsioPath.cache)) {
jsioPath.cache[moduleDef.baseMod] = moduleDef.basePath;
}
// don't apply the standard preprocessors to base.js. If we're reloading
// the source code, always apply them. We also don't want to run them
// if they've been run once -- moduleDef.pre is set to true already
// if we're reading the code from the source cache.
if (modulePath != 'base' && (opts.reload || !opts.dontPreprocess && !moduleDef.pre)) {
moduleDef.pre = true;
applyPreprocessors(fromDir, moduleDef, ["import", "inlineSlice"], opts);
}
// any additional preprocessors?
if (opts.preprocessors) {
applyPreprocessors(fromDir, moduleDef, opts.preprocessors, opts);
}
return moduleDef;
}
|
javascript
|
{
"resource": ""
}
|
q50806
|
train
|
function() {
var packageName;
var parentFolderName = path.basename(path.resolve('..'));
var isSubPackage = parentFolderName === 'node_modules';
var isLocalDepsAvailable = fs.existsSync('node_modules/grunt-autoprefixer') && fs.existsSync('node_modules/grunt-contrib-cssmin');
if (isSubPackage && !isLocalDepsAvailable) {
packageName = 'load-grunt-parent-tasks';
} else {
packageName = 'load-grunt-tasks';
}
return packageName;
}
|
javascript
|
{
"resource": ""
}
|
|
q50807
|
train
|
function (req, res, parseObj) {
var data = {};
var body = req.body;
var reqID = body.id || req.query.id;
var cats = body.cats || req.query.cats;
var reqFilter = body.filter || req.query.filter;
var reqFilterOut = body.filterOut || req.query.filterOut;
var parsedData = parseObj;
var msgDataNotFound = 'API: Specs data not found, please restart the app.';
if (reqID) {
var dataByID = parsedData.getByID(reqID);
if (dataByID && typeof dataByID === 'object') {
res.status(config.statusCodes.OK).json(dataByID);
} else {
if (typeof dataByID === 'undefined') console.warn(msgDataNotFound);
res.status(config.statusCodes.notFound).json({
message: "id not found"
});
}
} else if (reqFilter || reqFilterOut) {
var dataFiltered = parsedData.getFilteredData({
filter: reqFilter,
filterOut: reqFilterOut
});
if (dataFiltered && typeof dataFiltered === 'object') {
res.status(config.statusCodes.OK).json(dataFiltered);
} else {
console.warn(msgDataNotFound);
res.status(config.statusCodes.notFound).json({
message: "data not found"
});
}
} else {
data = parsedData.getAll(cats);
if (data) {
res.status(config.statusCodes.OK).json(data);
} else {
console.warn(msgDataNotFound);
res.status(config.statusCodes.notFound).json({
message: "data not found"
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50808
|
train
|
function (req, res, parseObj) {
var data = {};
var body = req.body;
var reqID = body.id || req.query.id;
var reqSections = body.sections || req.query.sections;
var sections = reqSections ? reqSections.split(',') : undefined;
var parsedData = parseObj;
var msgDataNotFound = 'API: HTML data not found, please sync API or run PhantomJS parser.';
if (reqID) {
var responseData = '';
if (reqSections) {
responseData = parsedData.getBySection(reqID, sections);
} else {
responseData = parsedData.getByID(reqID);
}
if (responseData && typeof responseData === 'object') {
res.status(config.statusCodes.OK).json(responseData);
} else {
if (typeof responseData === 'undefined') console.warn(msgDataNotFound);
res.status(config.statusCodes.notFound).json({
message: "id and requested sections not found"
});
}
} else {
data = parsedData.getAll();
if (data) {
res.status(config.statusCodes.OK).json(data);
} else {
console.warn(msgDataNotFound);
res.status(config.statusCodes.notFound).json({
message: "data not found"
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50809
|
train
|
function (req, res, dataPath) {
var body = req.body;
var data = body.data;
var dataUnflatten = body.unflatten;
if (dataUnflatten) {
data = unflatten(data, { delimiter: '/', overwrite: 'root' });
}
htmlTree.writeDataFile(data, true, dataPath, function(err, finalData){
if (err || !finalData) {
res.status(config.statusCodes.error).json({
message: err
});
} else {
res.status(config.statusCodes.OK).json(finalData);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50810
|
train
|
function (req, res, dataPath) {
var body = req.body;
var reqID = body.id || req.query.id;
htmlTree.deleteFromDataFile(dataPath, reqID, function(err, finalData){
if (err || !finalData) {
res.status(config.statusCodes.error).json({
message: err
});
} else {
res.status(config.statusCodes.OK).json(finalData);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50811
|
train
|
function() {
var navHash = utils.parseNavHash();
openSpoiler($(navHash));
//Close other closed by default sections
for (var i = 0; i < sectionsOnPage.length; i++) {
var t = $(sectionsOnPage[i]);
var tID = t.attr('id');
if (t.attr('data-def-stat') === 'closed' && navHash !== '#' + tID) {
closeSpoiler(t);
}
}
if (navHash !== '') {
utils.scrollToSection(navHash);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50812
|
train
|
function(config, data) {
var isNewInstance = !context;
context = context || this;
context.data = data ? data : initialBlocksData;
if (!isNewInstance) {
context.render();
return context;
}
var modulesOptions = context.options.modulesOptions;
modulesOptions.modalBox = $.extend(true, {
"classes": {
"box": [context.options.mainClass, context.options.colMain, "source_modal_box"].join(' '),
"title": "source_modal_title",
"body": "source_modal_body",
"close": "source_modal_close"
},
"labels": {
"close": "Close extended search results"
},
"appendTo": ".source_main"
}, modulesOptions.modalBox, config);
context.init();
}
|
javascript
|
{
"resource": ""
}
|
|
q50813
|
train
|
function() {
new Css('/source/assets/js/lib/prism/prism.css', 'core');
var selection = onlyStatic ? $('.source_section pre[class*="src-"].source_visible > code') : $('.source_section pre[class*="src-"] > code');
selection.each(function () {
var _this = $(this);
var parent = _this.parent();
var langClass='';
if (!parent.hasClass('src-json')) {
if (parent.hasClass('src-css')) {
langClass = SourceCodeToggleCSS;
} else if (parent.hasClass('src-js')) {
langClass = SourceCodeToggleJS;
} else {
langClass = SourceCodeToggleHTML;
}
if (parent.hasClass('source_visible')) {
parent.wrap('<div class="'+SourceCode+' '+SourceCodeStatic+'"><div class="' + SourceCodeCnt + '"></div></div>');
}
else if (!parent.hasClass('src-json')) {
parent.wrap('<div class="'+SourceCode+'"><div class="' + SourceCodeCnt + '"></div></div>');
_this.closest('.' + SourceCode).prepend('' +
'<a href="" class="' + SourceCodeToggle + ' ' + langClass + '"><span class="source_hide">' + RES_HIDE_CODE + '</span><span class="source_show">' + RES_SHOW_CODE + '</span> ' + RES_CODE + '</a>' +
'');
}
Prism.highlightElement(_this[0]);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50814
|
train
|
function() {
$('.source_container').on('click', '.' + SourceCodeToggle, function (e) {
e.preventDefault();
var codeCnt = $(this).closest('.' + SourceCode);
codeCnt.toggleClass(SourceCodeMin);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50815
|
train
|
function () {
var headersLength = sourceHeaders.length;
var minDistance = Number.MAX_VALUE;
var closestHeader = -1;
var fileNameInUrl = filename === '' ? '' : filename + '.' + extension;
if ((document.body.scrollTop || document.documentElement.scrollTop) < hashThreshold) {
if (!!window.location.hash) {
currentHeader = -1;
if (!!(window.history && history.pushState)) {
window.history.replaceState({anchor: 0}, document.title, window.location.pathname);
}
}
return;
}
// catch section which is closed for top window border
for (var i=0; i < headersLength; i++) {
if ((sourceHeaders[i].tagName === 'H3') && (!utils.hasClass(utils.closest(sourceHeaders[i], 'source_section'), 'source_section__open')) ) {
continue;
}
var currentDist = Math.abs( utils.offsetTop(sourceHeaders[i]) - 60 - window.pageYOffset ); //60 = Header heights
if (currentDist < minDistance) {
closestHeader = i;
minDistance = currentDist;
}
}
if (closestHeader !== currentHeader) {
utils.removeClass( document.querySelector('.source_main_nav_li.__active'), '__active');
utils.removeClass( document.querySelector('.source_main_nav_a.__active'), '__active');
utils.addClass(navHeaders[closestHeader], '__active');
var parent = utils.closest(navHeaders[closestHeader], 'source_main_nav_li');
var hashFromLink = navHeaders[closestHeader].getAttribute('href');
if (!!parent && parent) {
utils.addClass(parent, '__active');
}
if (_this.conf.updateHash) {
// TODO: pause hash change when scrolling - append it only on stand-still
// Modern browsers uses history API for correct back-button-browser functionality
if (!!(window.history && history.pushState)) {
window.history.replaceState({anchor: closestHeader+1}, document.title, fileNameInUrl + hashFromLink);
} else { // ie9 fallback
window.location.hash = hashFromLink;
}
}
currentHeader = closestHeader;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50816
|
train
|
function(options, section, option, value) {
var req = {url: this.urlPrefix + "/_config/"};
if (section) {
req.url += encodeURIComponent(section) + "/";
if (option) {
req.url += encodeURIComponent(option);
}
}
if (value === null) {
req.type = "DELETE";
} else if (value !== undefined) {
req.type = "PUT";
req.data = toJSON(value);
req.contentType = "application/json";
req.processData = false
}
ajax(req, options,
"An error occurred retrieving/updating the server configuration"
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50817
|
train
|
function(options) {
$.extend(options, {successStatus: 202});
ajax({
type: "POST", url: this.uri + "_compact",
data: "", processData: false
},
options,
"The database could not be compacted"
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50818
|
getChangesSince
|
train
|
function getChangesSince() {
var opts = $.extend({heartbeat : 10 * 1000}, options, {
feed : "longpoll",
since : since
});
ajax(
{url: db.uri + "_changes"+encodeOptions(opts)},
options,
"Error connecting to "+db.uri+"/_changes."
);
}
|
javascript
|
{
"resource": ""
}
|
q50819
|
train
|
function(docId, options, ajaxOptions) {
options = options || {};
if (db_opts.attachPrevRev || options.attachPrevRev) {
$.extend(options, {
beforeSuccess : function(req, doc) {
rawDocs[doc._id] = {
rev : doc._rev,
raw : req.responseText
};
}
});
} else {
$.extend(options, {
beforeSuccess : function(req, doc) {
if (doc["jquery.couch.attachPrevRev"]) {
rawDocs[doc._id] = {
rev : doc._rev,
raw : req.responseText
};
}
}
});
}
ajax({url: this.uri + encodeDocId(docId) + encodeOptions(options)},
options,
"The document could not be retrieved",
ajaxOptions
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50820
|
train
|
function(doc, options) {
options = options || {};
var db = this;
var beforeSend = fullCommit(options);
if (doc._id === undefined) {
var method = "POST";
var uri = this.uri;
} else {
var method = "PUT";
var uri = this.uri + encodeDocId(doc._id);
}
var versioned = maybeApplyVersion(doc);
$.ajax({
type: method, url: uri + encodeOptions(options),
contentType: "application/json",
dataType: "json", data: toJSON(doc),
beforeSend : beforeSend,
complete: function(req) {
var resp = $.parseJSON(req.responseText);
if (req.status == 200 || req.status == 201 || req.status == 202) {
doc._id = resp.id;
doc._rev = resp.rev;
if (versioned) {
db.openDoc(doc._id, {
attachPrevRev : true,
success : function(d) {
doc._attachments = d._attachments;
if (options.success) options.success(resp);
}
});
} else {
if (options.success) options.success(resp);
}
} else if (options.error) {
options.error(req.status, resp.error, resp.reason);
} else {
throw "The document could not be saved: " + resp.reason;
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50821
|
train
|
function(docs, options) {
var beforeSend = fullCommit(options);
$.extend(options, {successStatus: 201, beforeSend : beforeSend});
ajax({
type: "POST",
url: this.uri + "_bulk_docs" + encodeOptions(options),
contentType: "application/json", data: toJSON(docs)
},
options,
"The documents could not be saved"
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50822
|
train
|
function(docs, options){
docs.docs = $.each(
docs.docs, function(i, doc){
doc._deleted = true;
}
);
$.extend(options, {successStatus: 201});
ajax({
type: "POST",
url: this.uri + "_bulk_docs" + encodeOptions(options),
data: toJSON(docs)
},
options,
"The documents could not be deleted"
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50823
|
train
|
function(propName, options, ajaxOptions) {
ajax({url: this.uri + propName + encodeOptions(options)},
options,
"The property could not be retrieved",
ajaxOptions
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50824
|
train
|
function(propName, propValue, options, ajaxOptions) {
ajax({
type: "PUT",
url: this.uri + propName + encodeOptions(options),
data : JSON.stringify(propValue)
},
options,
"The property could not be updated",
ajaxOptions
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50825
|
train
|
function(source, target, ajaxOptions, repOpts) {
repOpts = $.extend({source: source, target: target}, repOpts);
if (repOpts.continuous && !repOpts.cancel) {
ajaxOptions.successStatus = 202;
}
ajax({
type: "POST", url: this.urlPrefix + "/_replicate",
data: JSON.stringify(repOpts),
contentType: "application/json"
},
ajaxOptions,
"Replication failed"
);
}
|
javascript
|
{
"resource": ""
}
|
|
q50826
|
train
|
function(cacheNum) {
if (cacheNum === undefined) {
cacheNum = 1;
}
if (!uuidCache.length) {
ajax({url: this.urlPrefix + "/_uuids", data: {count: cacheNum}, async:
false}, {
success: function(resp) {
uuidCache = resp.uuids;
}
},
"Failed to retrieve UUID batch."
);
}
return uuidCache.shift();
}
|
javascript
|
{
"resource": ""
}
|
|
q50827
|
askAndroidPrompt
|
train
|
function askAndroidPrompt() {
prompt.get({
name: 'using_android',
description: 'Are you using Android (y/n)',
default: 'y'
}, function(err, result) {
if (err) {
return console.log(err);
}
mergeConfig(result);
askAndroidPromptResult(result);
if (usingiOS || usingAndroid) {
promptQuestions();
} else {
askSaveConfigPrompt();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50828
|
promptQuestions
|
train
|
function promptQuestions() {
prompt.get([{
name: 'api_key',
description: 'Your Fabric API Key',
default: ''
}, {
name: 'api_secret',
description: 'Your Fabric API Secret',
default: ''
}], function(err, result) {
if (err) {
return console.log(err);
}
mergeConfig(result);
promptQuestionsResult(result);
askSaveConfigPrompt();
});
}
|
javascript
|
{
"resource": ""
}
|
q50829
|
writePodFile
|
train
|
function writePodFile(result) {
if (!fs.existsSync(directories.ios)) {
fs.mkdirSync(directories.ios);
}
try {
fs.writeFileSync(directories.ios + '/Podfile',
`use_frameworks!
pod 'Fabric', '${FABRIC_IOS_FABRIC}'
pod 'Crashlytics', '${FABRIC_IOS_CRASHLYTICS}'
# Crashlytics works best without bitcode
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = "NO"
end
end
end
`);
console.log('Successfully created iOS (Pod) file.');
} catch (e) {
console.log('Failed to create iOS (Pod) file.');
console.log(e);
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q50830
|
writeGradleFile
|
train
|
function writeGradleFile() {
if (!fs.existsSync(directories.android)) {
fs.mkdirSync(directories.android);
}
try {
fs.writeFileSync(directories.android + '/include.gradle',
`
android {
}
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
}
repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
compile('com.crashlytics.sdk.android:crashlytics:${FABRIC_ANDROID_CRASHLYTICS}@aar') {
transitive = true;
}
compile('com.crashlytics.sdk.android:answers:${FABRIC_ANDROID_ANSWERS}@aar') {
transitive = true;
}
}
`);
console.log('Successfully created Android (include.gradle) file.');
} catch (e) {
console.log('Failed to create Android (include.gradle) file.');
console.log(e);
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q50831
|
writeFabricServiceGradleHook
|
train
|
function writeFabricServiceGradleHook(config) {
console.log("Install Fabric-build-gradle hook.");
try {
if (!fs.existsSync(path.join(appRoot, "hooks"))) {
fs.mkdirSync(path.join(appRoot, "hooks"));
}
if (!fs.existsSync(path.join(appRoot, "hooks", "after-prepare"))) {
fs.mkdirSync(path.join(appRoot, "hooks", "after-prepare"));
}
var scriptContent =
`
var path = require("path");
var fs = require("fs");
module.exports = function($logger, $projectData, hookArgs) {
var platform = hookArgs.platform.toLowerCase();
function updateAppGradleScript(file) {
var appBuildGradleContent = fs.readFileSync(file).toString();
if (!appBuildGradleContent.match(/.*fabric.*/)) {
$logger.trace("Configuring Fabric for Android");
var search = -1;
search = appBuildGradleContent.indexOf("repositories {", 0);
if (search == -1) {
return;
}
appBuildGradleContent = appBuildGradleContent.substr(0, search + 14) + ' maven { url "https://maven.fabric.io/public" }\\n' + appBuildGradleContent.substr(search + 14);
// TODO add to buildTypes entry
// appBuildGradleContent = appBuildGradleContent + '\\ndebug { \\n ext.enableCrashlytics = false\\n}\\n';
search = appBuildGradleContent.indexOf("apply plugin: \\"com.android.application\\"");
if (search == -1) {
return;
}
appBuildGradleContent = appBuildGradleContent.substr(0, search + 39) + '\\napply plugin: "io.fabric"\\n' + appBuildGradleContent.substr(search + 39);
fs.writeFileSync(file, appBuildGradleContent);
$logger.trace('Written build.gradle');
}
if (appBuildGradleContent.indexOf("buildMetadata.finalizedBy(copyMetadata)") === -1) {
appBuildGradleContent = appBuildGradleContent.replace("ensureMetadataOutDir.finalizedBy(buildMetadata)", "ensureMetadataOutDir.finalizedBy(buildMetadata)\\n\\t\\tbuildMetadata.finalizedBy(copyMetadata)");
appBuildGradleContent += \`
task copyMetadata {
doLast {
copy {
from "$projectDir/src/main/assets/metadata"
def toDir = project.hasProperty("release") ? "release" : "debug";
if (new File("$projectDir/build/intermediates/assets").listFiles() != null) {
toDir = new File("$projectDir/build/intermediates/assets").listFiles()[0].name
if (toDir != 'debug' && toDir != 'release') {
toDir += "/release"
}
}
into "$projectDir/build/intermediates/assets/" + toDir + "/metadata"
}
}
}
\`;
fs.writeFileSync(file, appBuildGradleContent);
$logger.trace('Written build.gradle');
}
}
function updateGradleScript(file) {
var buildGradleContent = fs.readFileSync(file).toString();
if (!buildGradleContent.match(/.*fabric.*/)) {
$logger.trace("Configuring Fabric for Android");
var search = -1;
search = buildGradleContent.indexOf("repositories", 0);
if (search == -1) {
return;
}
search = buildGradleContent.indexOf("}", search);
buildGradleContent = buildGradleContent.substr(0, search - 1) + ' maven { url "https://maven.fabric.io/public" }\\n' + buildGradleContent.substr(search - 1);
search = buildGradleContent.indexOf("dependencies", search);
if (search == -1) {
return;
}
search = buildGradleContent.indexOf("}", search);
if (search == -1) {
return;
}
buildGradleContent = buildGradleContent.substr(0, search - 1) + ' classpath "io.fabric.tools:gradle:${FABRIC_GRADLE_TOOLS}"\\n' + buildGradleContent.substr(search - 1);
fs.writeFileSync(file, buildGradleContent);
$logger.trace('Written build.gradle');
}
}
if (platform === 'android') {
var apiKey = "${config.api_key}";
var apiSecret = "${config.api_secret}";
var androidPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android');
var androidAppPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android', 'app');
var gradleScript = path.join(androidPlatformDir, 'build.gradle');
var gradleAppScript = path.join(androidAppPlatformDir, 'build.gradle');
if (fs.existsSync(gradleAppScript)) {
updateAppGradleScript(gradleAppScript);
updateGradleScript(gradleScript);
} else {
updateGradleScript(gradleScript);
}
var settingsJson = path.join(__dirname, "..", "..", "platforms", "android", "app", "src", "main", "res", "fabric.properties");
var propertiesContent = '# Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public\\n';
propertiesContent+='apiKey = ' + apiKey + '\\n';
propertiesContent+='apiSecret = ' + apiSecret + '\\n';
fs.writeFileSync(settingsJson, propertiesContent);
$logger.trace('Written fabric.properties');
}
};
`;
console.log("Writing 'nativescript-fabric-gradle.js' to " + appRoot + "hooks/after-prepare");
var scriptPath = path.join(appRoot, "hooks", "after-prepare", "nativescript-fabric-gradle.js");
fs.writeFileSync(scriptPath, scriptContent);
} catch (e) {
console.log("Failed to install nativescript-fabric-gradle hook.");
console.log(e);
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q50832
|
defer
|
train
|
function defer(fn)
{
var nextTick = typeof setImmediate == 'function'
? setImmediate
: (
typeof process == 'object' && typeof process.nextTick == 'function'
? process.nextTick
: null
);
if (nextTick)
{
nextTick(fn);
}
else
{
setTimeout(fn, 0);
}
}
|
javascript
|
{
"resource": ""
}
|
q50833
|
readFile
|
train
|
function readFile (archive, name, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
return maybe(cb, async function () {
opts = opts || {}
if (typeof opts === 'string') {
opts = { encoding: opts }
}
opts.encoding = toValidEncoding(opts.encoding)
// check that it's a file
const st = await stat(archive, name)
if (!st.isFile()) {
throw new NotAFileError()
}
// read the file
return new Promise((resolve, reject) => {
archive.readFile(name, opts, (err, data) => {
if (err) reject(toBeakerError(err, 'readFile'))
else resolve(data)
})
})
})
}
|
javascript
|
{
"resource": ""
}
|
q50834
|
readdir
|
train
|
function readdir (archive, name, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
opts = opts || {}
return maybe(cb, async function () {
// options
var recursive = (opts && !!opts.recursive)
// run first readdir
var promise = new Promise((resolve, reject) => {
archive.readdir(name, (err, names) => {
if (err) reject(toBeakerError(err, 'readdir'))
else resolve(names)
})
})
var results = await promise
// recurse if requested
if (recursive) {
var rootPath = name
const readdirSafe = name => new Promise(resolve => {
archive.readdir(name, (_, names) => resolve(names || []))
})
const recurse = async function (names, parentPath) {
await Promise.all(names.map(async function (name) {
var thisPath = path.join(parentPath, name)
var subnames = await readdirSafe(thisPath)
await recurse(subnames, thisPath)
results = results.concat(subnames.map(subname => normalize(rootPath, thisPath, subname)))
}))
}
await recurse(results, name)
}
return results
})
}
|
javascript
|
{
"resource": ""
}
|
q50835
|
exportArchiveToFilesystem
|
train
|
function exportArchiveToFilesystem (opts, cb) {
return maybe(cb, async function () {
assert(opts && typeof opts === 'object', 'opts object is required')
// core arguments, dstPath and srcArchive
var srcArchive = opts.srcArchive
var dstPath = opts.dstPath
assert(srcArchive && typeof srcArchive === 'object', 'srcArchive is required')
assert(dstPath && typeof dstPath === 'string', 'dstPath is required')
// options
var srcPath = typeof opts.srcPath === 'string' ? opts.srcPath : '/'
var overwriteExisting = opts.overwriteExisting === true
var skipUndownloadedFiles = opts.skipUndownloadedFiles === true
var ignore = Array.isArray(opts.ignore) ? opts.ignore : DEFAULT_IGNORE
// abort if nonempty and not overwriting existing
if (!overwriteExisting) {
let files
try {
files = await fse.readdir(dstPath)
} catch (e) {
// target probably doesnt exist, continue and let ensureDirectory handle it
}
if (files && files.length > 0) {
throw new DestDirectoryNotEmpty()
}
}
const statThenExport = async function (srcPath, dstPath) {
// apply ignore filter
if (ignore && match(ignore, srcPath)) {
return
}
// export by type
var srcStat = await stat(srcArchive, srcPath)
if (srcStat.isFile()) {
await exportFile(srcPath, srcStat, dstPath)
} else if (srcStat.isDirectory()) {
await exportDirectory(srcPath, dstPath)
}
}
const exportFile = async function (srcPath, srcStat, dstPath) {
// skip undownloaded files
if (skipUndownloadedFiles && srcStat.downloaded < srcStat.blocks) {
return
}
// fetch dest stats
var dstFileStats = null
try {
dstFileStats = await fse.stat(dstPath)
} catch (e) {}
// track the stats
stats.fileCount++
stats.totalSize += srcStat.size || 0
if (dstFileStats) {
if (dstFileStats.isDirectory()) {
// delete the directory-tree
await fse.remove(dstPath)
stats.addedFiles.push(dstPath)
} else {
stats.updatedFiles.push(dstPath)
}
} else {
stats.addedFiles.push(dstPath)
}
// write the file
return new Promise((resolve, reject) => {
pump(
srcArchive.createReadStream(srcPath),
fse.createWriteStream(dstPath),
err => {
if (err) reject(err)
else resolve()
}
)
})
}
const exportDirectory = async function (srcPath, dstPath) {
// make sure the destination folder exists
await fse.ensureDir(dstPath)
// list the directory
var fileNames = await readdir(srcArchive, srcPath)
// recurse into each
var promises = fileNames.map(name => {
return statThenExport(path.join(srcPath, name), path.join(dstPath, name))
})
await Promise.all(promises)
}
// recursively export
var stats = { addedFiles: [], updatedFiles: [], skipCount: 0, fileCount: 0, totalSize: 0 }
await statThenExport(srcPath, dstPath)
return stats
})
}
|
javascript
|
{
"resource": ""
}
|
q50836
|
readManifest
|
train
|
function readManifest (archive, cb) {
return maybe(cb, async function () {
var data = await readFile(archive, DAT_MANIFEST_FILENAME)
data = JSON.parse(data.toString())
if (data.links) data.links = massageLinks(data.links)
return data
})
}
|
javascript
|
{
"resource": ""
}
|
q50837
|
writeManifest
|
train
|
function writeManifest (archive, manifest, cb) {
manifest = generateManifest(manifest)
return writeFile(archive, DAT_MANIFEST_FILENAME, JSON.stringify(manifest, null, 2), cb)
}
|
javascript
|
{
"resource": ""
}
|
q50838
|
updateManifest
|
train
|
function updateManifest (archive, updates, cb) {
return maybe(cb, async function () {
var manifest
try {
manifest = await readManifest(archive)
} catch (e) {
manifest = {}
}
Object.assign(manifest, generateManifest(updates))
return writeManifest(archive, manifest)
})
}
|
javascript
|
{
"resource": ""
}
|
q50839
|
generateManifest
|
train
|
function generateManifest (manifest = {}) {
var { url, title, description, type, author, links, web_root, fallback_page } = manifest
if (isString(url)) manifest.url = url
else delete manifest.url
if (isString(title)) manifest.title = title
else delete manifest.title
if (isString(description)) manifest.description = description
else delete manifest.description
if (isString(type)) type = type.split(' ')
if (isArrayOfStrings(type)) manifest.type = type
else delete manifest.type
if (isObject(links)) manifest.links = massageLinks(links)
else delete manifest.links
if (isString(web_root)) manifest.web_root = web_root
else delete manifest.web_root
if (isString(fallback_page)) manifest.fallback_page = fallback_page
else delete manifest.fallback_page
if (isString(author)) {
if (author.startsWith('dat://') || DAT_HASH_REGEX.test(author)) {
author = {url: author}
} else {
author = {name: author}
}
}
if (isObject(author)) {
manifest.author = {}
if (isString(author.name)) manifest.author.name = author.name
if (isString(author.url) && (author.url.startsWith('dat://') || DAT_HASH_REGEX.test(author.url))) {
manifest.author.url = author.url
}
} else {
delete manifest.author
}
return manifest
}
|
javascript
|
{
"resource": ""
}
|
q50840
|
stat
|
train
|
function stat (archive, name, cb) {
return maybe(cb, new Promise((resolve, reject) => {
// run stat operation
archive.stat(name, (err, st) => {
if (err) reject(toBeakerError(err, 'stat'))
else {
// read download status
st.downloaded = 0
if (!archive.key) {
// fs, not an archive
st.downloaded = st.blocks
} else if (st.isFile()) {
if (archive.content && archive.content.length) {
st.downloaded = archive.content.downloaded(st.offset, st.offset + st.blocks)
}
}
resolve(st)
}
})
}))
}
|
javascript
|
{
"resource": ""
}
|
q50841
|
Version
|
train
|
function Version(major, minor, micro, build) {
if (typeof major === "number" && major % 1 === 0)
this._major = major;
else
throw new Error("Invalid major version number '" + major + "'");
if (typeof minor === "number" && minor % 1 === 0)
this._minor = minor;
else
throw new Error("Invalid minor version number '" + minor + "'");
if (typeof micro === "number" && micro % 1 === 0)
this._micro = micro;
else
throw new Error("Invalid micro version number '" + micro + "'");
if (typeof build === "number" && build % 1 === 0)
this._build = build;
else
throw new Error("Invalid build version number '" + build + "'");
}
|
javascript
|
{
"resource": ""
}
|
q50842
|
initMembers
|
train
|
function initMembers(rootPath) {
this._rootPath = rootPath;
ShellJS.mkdir(this._rootPath);
this._appPath = this._rootPath + Path.sep + "app";
ShellJS.mkdir(this._appPath);
this._logPath = Path.join(OS.tmpdir(), "crosswalk-app-tools-" + this._packageId);
ShellJS.mkdir(this._logPath);
// Packages end up in working dir
this._pkgPath = process.cwd();
this._prjPath = this._rootPath + Path.sep + "prj";
ShellJS.mkdir(this._prjPath);
}
|
javascript
|
{
"resource": ""
}
|
q50843
|
TemplateFile
|
train
|
function TemplateFile(path) {
this._buffer = FS.readFileSync(path, {"encoding": "utf8"});
if (!this._buffer || this._buffer.length === 0) {
throw new Error("Could not read " + path);
}
}
|
javascript
|
{
"resource": ""
}
|
q50844
|
OutputTee
|
train
|
function OutputTee(logfileOutput, terminalOutput) {
this._outputs = [];
this._outputs[_OUTPUT_TEE_LOGFILE] = logfileOutput;
this._outputs[_OUTPUT_TEE_TERMINAL] = terminalOutput;
}
|
javascript
|
{
"resource": ""
}
|
q50845
|
WinPlatform
|
train
|
function WinPlatform(PlatformBase, baseData) {
// Create base instance.
var instance = new PlatformBase(baseData);
// Override manually, because Object.extend() is not yet available on node.
var names = Object.getOwnPropertyNames(WinPlatform.prototype);
for (var i = 0; i < names.length; i++) {
var key = names[i];
if (key != "constructor") {
instance[key] = WinPlatform.prototype[key];
}
}
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q50846
|
CrosswalkZip
|
train
|
function CrosswalkZip(path) {
this._adm = new AdmZip(path);
// Derive root entry name from the filename
var base = Path.basename(path, ".zip");
this._root = base + "/";
// Extract version
var version = base.split("-")[1];
var numbers = version.split(".");
this._version = new Version(+numbers[0], +numbers[1], +numbers[2], +numbers[3]);
}
|
javascript
|
{
"resource": ""
}
|
q50847
|
AndroidPlatform
|
train
|
function AndroidPlatform(PlatformBase, baseData) {
// Create base instance.
var instance = new PlatformBase(baseData);
var o = instance.output;
// Override manually, because Object.extend() is not yet available on node.
var names = Object.getOwnPropertyNames(AndroidPlatform.prototype);
for (var i = 0; i < names.length; i++) {
var key = names[i];
if (key != "constructor") {
instance[key] = AndroidPlatform.prototype[key];
}
}
instance._sdk = new AndroidSDK(instance.application);
instance._channel = "stable";
instance._lite = false;
instance._shared = false;
instance._apiTarget = null;
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q50848
|
CrosswalkDir
|
train
|
function CrosswalkDir(path) {
this._path = path;
this._root = "./";
var versionFilePath = Path.join(path, "VERSION");
if (ShellJS.test("-f", versionFilePath)) {
this._version = Version.createFromFile(versionFilePath);
} else {
this._version = Version.createFromPath(path);
}
if (!this._version) {
throw new Error("Failed to determine crosswalk version");
}
}
|
javascript
|
{
"resource": ""
}
|
q50849
|
Download01Org
|
train
|
function Download01Org(application, platform, channel) {
this._application = application;
if (Download01Org.PLATFORMS.indexOf(platform) == -1) {
throw new Error("Unknown platform " + platform);
}
this._platform = platform;
if (Download01Org.CHANNELS.indexOf(channel) == -1) {
throw new Error("Unknown channel " + channel);
}
this._channel = channel;
this._flavor = "crosswalk";
this._androidWordSize = "32";
}
|
javascript
|
{
"resource": ""
}
|
q50850
|
LogfileOutput
|
train
|
function LogfileOutput(path) {
this._path = path;
var options = {
flags: "w",
mode: 0600
};
FS.writeFileSync(this._path, "");
/* TODO
if (!this._fp) {
throw new FileCreationFailed("Could not open file " + path);
}
*/
}
|
javascript
|
{
"resource": ""
}
|
q50851
|
PlatformInfo
|
train
|
function PlatformInfo(PlatformCtor, platformId) {
this._Ctor = PlatformCtor;
this._platformId = platformId;
// Prefix all platform-specific args with the platform name
var argSpec = PlatformCtor.getArgs ? PlatformCtor.getArgs() : {};
this._argSpec = {};
for (var cmd in argSpec) {
var cmdArgSpec = argSpec[cmd];
var platformCmdArgSpec = {};
for (var key in cmdArgSpec) {
platformCmdArgSpec["--" + platformId + "-" + key] = cmdArgSpec[key];
}
this._argSpec[cmd] = platformCmdArgSpec;
}
// Look for platforms env vars
this._envSpec = PlatformCtor.getEnv ? PlatformCtor.getEnv() : {};
}
|
javascript
|
{
"resource": ""
}
|
q50852
|
CommandParser
|
train
|
function CommandParser(output, argv) {
this._output = output;
if (!(argv instanceof Array)) {
throw new TypeError("CommandParser(argv) must be of type Array.");
}
this._argv = argv;
}
|
javascript
|
{
"resource": ""
}
|
q50853
|
AndroidManifest
|
train
|
function AndroidManifest(output, path) {
this._output = output;
this._path = path;
var doc = this.read();
this._package = doc.documentElement.getAttribute("package");
this._versionCode = doc.documentElement.getAttribute("android:versionCode");
this._versionName = doc.documentElement.getAttribute("android:versionName");
this._applicationIcon = null;
var appNode = this.findApplicationNode(doc);
if (appNode) {
this._applicationIcon = appNode.getAttribute("android:icon");
}
this._applicationLabel = null;
appNode = this.findApplicationNode(doc);
if (appNode) {
this._applicationLabel = appNode.getAttribute("android:label");
}
var activityNode = this.findChildNode(appNode, "activity");
if (activityNode) {
this._screenOrientation = activityNode.getAttribute("android:screenOrientation");
}
// TODO read other values from manifest and initialize members
}
|
javascript
|
{
"resource": ""
}
|
q50854
|
WixSDK
|
train
|
function WixSDK(rootPath, manifest, output) {
this._rootPath = rootPath;
this._manifest = manifest;
this._output = output;
this._existing_ids = {};
}
|
javascript
|
{
"resource": ""
}
|
q50855
|
installExtensionDlls
|
train
|
function installExtensionDlls(source_dir_path, dest_folder_object) {
var app_files = readDir.readSync(source_dir_path);
app_files.forEach(function (name) {
var suffix = name.substring(name.length - ".dll".length);
if (suffix && suffix.toLowerCase() === ".dll") {
AddFileComponent(dest_folder_object, source_dir_path, name);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50856
|
updateObjWith
|
train
|
function updateObjWith (obj, upd) {
for (const key in upd) {
obj[key] = upd[key]
}
return obj
}
|
javascript
|
{
"resource": ""
}
|
q50857
|
inferRAMLTypeName
|
train
|
function inferRAMLTypeName (fileName) {
const cleanName = fileName.replace(/^.*[\\/]/, '')
const filename = cleanName.split('.')[0]
return capitalize(filename)
}
|
javascript
|
{
"resource": ""
}
|
q50858
|
dt2jsCLI
|
train
|
function dt2jsCLI (ramlFile, ramlTypeName) {
const rootFileDir = ramlFile.split(path.sep).slice(0, -1).join(path.sep)
const ramlData = fs.readFileSync(ramlFile).toString()
dt2js.setBasePath(rootFileDir)
return dt2js.dt2js(ramlData, ramlTypeName)
}
|
javascript
|
{
"resource": ""
}
|
q50859
|
js2dtCLI
|
train
|
function js2dtCLI (jsonFile, ramlTypeName) {
const jsonData = fs.readFileSync(jsonFile).toString()
if (ramlTypeName != null) {
const raml = js2dt.js2dt(jsonData, ramlTypeName)
return `#%RAML 1.0 Library\n${yaml.safeDump({ types: raml }, { 'noRefs': true })}`
} else {
const typeName = 'this__should__be__the__only__type'
const raml = js2dt.js2dt(jsonData, typeName)
const keys = Object.keys(raml)
if (keys.length !== 1 || !keys.includes(typeName)) {
throw new Error(`There is more than one type (${JSON.stringify(keys)}), please specify a name for the raml library`)
}
return `#%RAML 1.0 DataType\n${yaml.safeDump(raml[typeName], { 'noRefs': true })}`
}
}
|
javascript
|
{
"resource": ""
}
|
q50860
|
getRAMLContext
|
train
|
function getRAMLContext (ramlData, rootFileDir) {
rootFileDir = rootFileDir || '.'
const ast = yap.load(ramlData)
const libraries = extractLibraries(ast, rootFileDir)
const jsContent = {}
traverse(jsContent, ast, rootFileDir, libraries)
return jsContent.types
}
|
javascript
|
{
"resource": ""
}
|
q50861
|
destringify
|
train
|
function destringify (val) {
if (!isNaN(Number(val))) return Number(val)
if (val === 'true') return true
if (val === 'false') return false
return val
}
|
javascript
|
{
"resource": ""
}
|
q50862
|
traverse
|
train
|
function traverse (obj, ast, rootFileDir, libraries) {
function recurse (keys, currentNode, nodeFileDir) {
if (currentNode.key) {
keys = keys.concat([currentNode.key.value])
}
// kind 5 is an include
if (currentNode.value && currentNode.value.kind === 5) {
const location = currentNode.value.value
const [include, contentType, newNodeFileDir] = resolveInclude(rootFileDir, nodeFileDir, location)
// If it's json, parse it
const ramlContentTypes = [
'application/raml+yaml',
'text/yaml',
'text/x-yaml',
'application/yaml',
'application/x-yaml'
]
if (path.extname(location) === '.json' || contentType === 'application/json') {
deep(obj, keys.join('.'), JSON.parse(include))
// If it's raml or yaml, parse it as raml
} else if (['.raml', '.yaml', '.yml'].indexOf(path.extname(location)) > -1 || ramlContentTypes.indexOf(contentType) > -1) {
currentNode.value = yap.load(include)
if (currentNode.value.errors.length > 0) {
throw new Error('Invalid RAML data in one of the included files')
}
recurse(keys, currentNode.value, newNodeFileDir)
// If it's anything else, just add it as a string.
} else {
currentNode.value = include
}
// a leaf node to be added
} else if (currentNode.value && currentNode.value.value) {
let val = !currentNode.value.doubleQuoted
// convert back from string type
? destringify(currentNode.value.value)
: currentNode.value.value
val = libraryOrValue(libraries, val)
deep(obj, keys.join('.'), val)
// a leaf that is an array
} else if (currentNode.value && currentNode.value.items) {
const values = currentNode.value.items.map(function (el) { return el.value })
deep(obj, keys.join('.'), values)
// an object that needs further traversal
} else if (currentNode.mappings) {
for (let i = 0; i < currentNode.mappings.length; i++) {
recurse(keys, currentNode.mappings[i], nodeFileDir)
}
} else if (currentNode.key && currentNode.key.value === 'examples') {
const vals = currentNode.value.mappings.map(function (el) {
return el.value.value
})
deep(obj, keys.join('.'), vals)
// an object that needs further traversal
} else if (currentNode.value && currentNode.value.mappings) {
for (let o = 0; o < currentNode.value.mappings.length; o++) {
recurse(keys, currentNode.value.mappings[o], nodeFileDir)
}
}
}
recurse([], ast, rootFileDir)
}
|
javascript
|
{
"resource": ""
}
|
q50863
|
dt2js
|
train
|
function dt2js (ramlData, typeName) {
const ctx = getRAMLContext(ramlData, basePath)
if (!(ctx instanceof Object)) throw new Error('Invalid RAML data')
if (ctx[typeName] === undefined) throw new Error('type ' + typeName + ' does not exist')
const expanded = expandedForm(ctx[typeName], ctx)
const canonical = canonicalForm(expanded)
let schema = schemaForm(canonical)
schema = addRootKeywords(schema)
return schema
}
|
javascript
|
{
"resource": ""
}
|
q50864
|
processArray
|
train
|
function processArray (arr, reqStack) {
const accum = []
arr.forEach(function (el) {
accum.push(schemaForm(el, reqStack))
})
return accum
}
|
javascript
|
{
"resource": ""
}
|
q50865
|
convertType
|
train
|
function convertType (data) {
switch (data.type) {
case 'union':
// If union of arrays
if (Array.isArray(data.anyOf) && data.anyOf[0].type === 'array') {
const items = data.anyOf.map(function (e) { return e.items })
data.items = { anyOf: [] }
data.items.anyOf = items
data['type'] = 'array'
delete data.anyOf
} else {
data['type'] = 'object'
}
break
case 'nil':
data['type'] = 'null'
break
case 'file':
data = convertFileType(data)
break
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q50866
|
convertFileType
|
train
|
function convertFileType (data) {
data['type'] = 'string'
data['media'] = { 'binaryEncoding': 'binary' }
if (data.fileTypes) {
data['media']['anyOf'] = []
data.fileTypes.forEach(function (el) {
data['media']['anyOf'].push({ 'mediaType': el })
})
delete data.fileTypes
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q50867
|
convertDateType
|
train
|
function convertDateType (data) {
switch (data.type) {
case 'date-only':
data['type'] = 'string'
data['pattern'] = constants.dateOnlyPattern
break
case 'time-only':
data['type'] = 'string'
data['pattern'] = constants.timeOnlyPattern
break
case 'datetime-only':
data['type'] = 'string'
data['pattern'] = constants.dateTimeOnlyPattern
break
case 'datetime':
data['type'] = 'string'
if (data.format === undefined || data.format.toLowerCase() === constants.RFC3339) {
data['pattern'] = constants.RFC3339DatetimePattern
} else if (data.format.toLowerCase() === constants.RFC2616) {
data['pattern'] = constants.RFC2616DatetimePattern
}
delete data.format
break
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q50868
|
convertPatternProperties
|
train
|
function convertPatternProperties (data) {
Object.keys(data.properties).map(function (key) {
if (/^\/.*\/$/.test(key)) {
data.patternProperties = data.patternProperties || {}
const stringRegex = key.slice(1, -1)
data.patternProperties[stringRegex] = data.properties[key]
delete data.properties[key]
}
})
return data
}
|
javascript
|
{
"resource": ""
}
|
q50869
|
processNested
|
train
|
function processNested (data, reqStack) {
const updateWith = {}
for (const key in data) {
const val = data[key]
if (val instanceof Array) {
updateWith[key] = processArray(val, reqStack)
continue
}
if (val instanceof Object) {
updateWith[key] = schemaForm(val, reqStack, key)
continue
}
}
return updateWith
}
|
javascript
|
{
"resource": ""
}
|
q50870
|
schemaForm
|
train
|
function schemaForm (data, reqStack = [], prop) {
if (!(data instanceof Object)) {
return data
}
const lastEl = reqStack[reqStack.length - 1]
if (data.type && data.required !== false && lastEl && prop) {
if (lastEl.props.indexOf(prop) > -1 && (prop[0] + prop[prop.length - 1]) !== '//') {
lastEl.reqs.push(prop)
}
}
delete data.required
const isObj = data.type === 'object'
if (isObj) {
reqStack.push({
'reqs': [],
'props': Object.keys(data.properties || {})
})
}
const updateWith = processNested(data, reqStack)
data = utils.updateObjWith(data, updateWith)
if (isObj) {
let reqs = reqStack.pop().reqs
// Strip duplicates from reqs
reqs = reqs.filter(function (value, index, self) {
return self.indexOf(value) === index
})
if (reqs.length > 0) {
data.required = reqs
}
}
if (data.type) {
data = convertType(data)
data = convertDateType(data)
}
if (data.displayName) {
data = convertDisplayName(data)
}
if (data.properties) {
convertPatternProperties(data)
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q50871
|
js2dt
|
train
|
function js2dt (jsonData, typeName) {
const data = JSON.parse(jsonData)
const raml = new RamlConverter(data, typeName).toRaml()
return raml
}
|
javascript
|
{
"resource": ""
}
|
q50872
|
convertAdditionalProperties
|
train
|
function convertAdditionalProperties (data, additionalProperties) {
if (additionalProperties !== undefined) {
let val = data
if (typeof additionalProperties === 'boolean') val = additionalProperties
if (typeof additionalProperties === 'object' && Object.keys(additionalProperties).length === 0) val = true
if (typeof additionalProperties === 'object' && Object.keys(additionalProperties).length > 0) {
const type = additionalProperties.type
data.properties['//'] = { type: type }
val = false
}
data.additionalProperties = val
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q50873
|
convertFileType
|
train
|
function convertFileType (data) {
data['type'] = 'file'
const anyOf = data.media.anyOf
if (anyOf && anyOf.length > 0) {
data['fileTypes'] = []
anyOf.forEach(function (el) {
if (el.mediaType) {
data.fileTypes.push(el.mediaType)
}
})
if (data.fileTypes.length < 1) {
delete data.fileTypes
}
}
delete data.media
return data
}
|
javascript
|
{
"resource": ""
}
|
q50874
|
convertDateType
|
train
|
function convertDateType (data) {
if (!(data.type === 'string' && data.pattern)) {
return data
}
const pattern = data.pattern
delete data.pattern
switch (pattern) {
case constants.dateOnlyPattern:
data['type'] = 'date-only'
break
case constants.timeOnlyPattern:
data['type'] = 'time-only'
break
case constants.dateTimeOnlyPattern:
data['type'] = 'datetime-only'
break
case constants.RFC3339DatetimePattern:
data['type'] = 'datetime'
data['format'] = constants.RFC3339
break
case constants.RFC2616DatetimePattern:
data['type'] = 'datetime'
data['format'] = constants.RFC2616
break
default:
data['pattern'] = pattern
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q50875
|
convertDefinedFormat
|
train
|
function convertDefinedFormat (data) {
if (!(data.type === 'string' && data.format)) {
return data
}
const format = data.format
delete data.format
switch (format) {
case 'date-time':
data['pattern'] = constants.FORMAT_REGEXPS['date-time']
break
case 'email':
data['pattern'] = constants.FORMAT_REGEXPS['email']
break
case 'hostname':
data['pattern'] = constants.FORMAT_REGEXPS['hostname']
break
case 'ipv4':
data['pattern'] = constants.FORMAT_REGEXPS['ipv4']
break
case 'ipv6':
data['pattern'] = constants.FORMAT_REGEXPS['ipv6']
break
case 'uri':
data['pattern'] = constants.FORMAT_REGEXPS['uri']
break
case 'uri-reference':
data['pattern'] = constants.FORMAT_REGEXPS['uri-reference']
break
case 'json-pointer':
data['pattern'] = constants.FORMAT_REGEXPS['json-pointer']
break
case 'uri-template':
data['pattern'] = constants.FORMAT_REGEXPS['uri-template']
break
default:
data['pattern'] = format
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q50876
|
convertPatternProperties
|
train
|
function convertPatternProperties (data) {
if (!data.patternProperties) {
return data
}
data.properties = data.properties || {}
const patternProperties = data.patternProperties
delete data.patternProperties
Object.keys(patternProperties).map(function (pattern) {
data.properties['/' + pattern + '/'] = patternProperties[pattern]
})
if (data.additionalProperties) delete data.additionalProperties
return data
}
|
javascript
|
{
"resource": ""
}
|
q50877
|
useThrottle
|
train
|
function useThrottle(fun, timeout, changes) {
if (changes === void 0) { changes = []; }
// Create the ref to store timer.
var timer = react_1.useRef(null);
function cancel() {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
}
// Register the
react_1.useEffect(function () { return cancel; }, changes);
return function () {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
cancel();
timer.current = setTimeout(function () {
timer.current = null;
fun.apply(_this, args);
}, timeout);
};
}
|
javascript
|
{
"resource": ""
}
|
q50878
|
initLoadingState
|
train
|
function initLoadingState(btnEl) {
if (cfg.btnLoadingClass && !cfg.addClassToCurrentBtnOnly) {
btnEl.addClass(cfg.btnLoadingClass);
}
if (cfg.disableBtn && !cfg.disableCurrentBtnOnly) {
btnEl.attr('disabled', 'disabled');
}
}
|
javascript
|
{
"resource": ""
}
|
q50879
|
handleLoadingFinished
|
train
|
function handleLoadingFinished(btnEl) {
if ((!cfg.minDuration || minDurationTimeoutDone) && promiseDone) {
if (cfg.btnLoadingClass) {
btnEl.removeClass(cfg.btnLoadingClass);
}
if (cfg.disableBtn && !scope.ngDisabled) {
btnEl.removeAttr('disabled');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q50880
|
initPromiseWatcher
|
train
|
function initPromiseWatcher(watchExpressionForPromise, btnEl) {
// watch promise to resolve or fail
scope.$watch(watchExpressionForPromise, function (mVal) {
minDurationTimeoutDone = false;
promiseDone = false;
// create timeout if option is set
if (cfg.minDuration) {
minDurationTimeout = $timeout(function () {
minDurationTimeoutDone = true;
handleLoadingFinished(btnEl);
}, cfg.minDuration);
}
// for regular promises
if (mVal && mVal.then) {
initLoadingState(btnEl);
// angular promise
if (mVal.finally) {
mVal.finally(function () {
promiseDone = true;
handleLoadingFinished(btnEl);
});
}
// ES6 promises
else {
mVal.then(function () {
promiseDone = true;
handleLoadingFinished(btnEl);
})
.catch(function () {
promiseDone = true;
handleLoadingFinished(btnEl);
});
}
}
// for $resource
else if (mVal && mVal.$promise) {
initLoadingState(btnEl);
mVal.$promise.finally(function () {
promiseDone = true;
handleLoadingFinished(btnEl);
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50881
|
addHandlersForCurrentBtnOnly
|
train
|
function addHandlersForCurrentBtnOnly(btnEl) {
// handle current button only options via click
if (cfg.addClassToCurrentBtnOnly) {
btnEl.on(cfg.CLICK_EVENT, function () {
btnEl.addClass(cfg.btnLoadingClass);
});
}
if (cfg.disableCurrentBtnOnly) {
btnEl.on(cfg.CLICK_EVENT, function () {
btnEl.attr('disabled', 'disabled');
});
}
}
|
javascript
|
{
"resource": ""
}
|
q50882
|
getSubmitBtnChildren
|
train
|
function getSubmitBtnChildren(formEl) {
var submitBtnEls = [];
var allButtonEls = formEl.find(angularPromiseButtons.config.BTN_SELECTOR);
for (var i = 0; i < allButtonEls.length; i++) {
var btnEl = allButtonEls[i];
if (angular.element(btnEl)
.attr('type') === 'submit') {
submitBtnEls.push(btnEl);
}
}
return angular.element(submitBtnEls);
}
|
javascript
|
{
"resource": ""
}
|
q50883
|
sanitizeOptions
|
train
|
function sanitizeOptions(userOptions) {
userOptions = userOptions || {};
let options = {
index: getIndexValue(userOptions)
}
if(userOptions.index){
// required to not interfere with serve-static
delete userOptions.index;
}
if (typeof (userOptions.enableBrotli) !== "undefined") {
options.enableBrotli = !!userOptions.enableBrotli;
}
if (typeof (userOptions.customCompressions) === "object" ) {
options.customCompressions = userOptions.customCompressions;
}
if (typeof (userOptions.orderPreference) === "object" ) {
options.orderPreference = userOptions.orderPreference;
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q50884
|
setupCompressions
|
train
|
function setupCompressions() {
//register all provided compressions
if (opts.customCompressions && opts.customCompressions.length > 0) {
for (var i = 0; i < opts.customCompressions.length; i++) {
var customCompression = opts.customCompressions[i];
registerCompression(customCompression.encodingName, customCompression.fileExtension);
}
}
//enable brotli compression
if (opts.enableBrotli) {
registerCompression("br", "br");
}
//gzip compression is enabled by default
registerCompression("gzip", "gz");
}
|
javascript
|
{
"resource": ""
}
|
q50885
|
convertToCompressedRequest
|
train
|
function convertToCompressedRequest(req, res, compression) {
var type = mime.lookup(req.path);
var charset = mime.charsets.lookup(type);
var search = req.url.split('?').splice(1).join('?');
if (search !== "") {
search = "?" + search;
}
req.url = req.path + compression.fileExtension + search;
res.setHeader("Content-Encoding", compression.encodingName);
res.setHeader("Content-Type", type + (charset ? "; charset=" + charset : ""));
}
|
javascript
|
{
"resource": ""
}
|
q50886
|
findAvailableCompressionForFile
|
train
|
function findAvailableCompressionForFile(compressionList, acceptedEncoding) {
if (acceptedEncoding) {
for (var i = 0; i < compressionList.length; i++) {
if (acceptedEncoding.indexOf(compressionList[i].encodingName) >= 0) {
return compressionList[i];
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q50887
|
findAllCompressionFiles
|
train
|
function findAllCompressionFiles(fs, folderPath) {
// check if folder exists
if (!fs.existsSync(folderPath)) return;
var files = fs.readdirSync(folderPath);
//iterate all files in the current folder
for (var i = 0; i < files.length; i++) {
var filePath = folderPath + "/" + files[i];
var stats = fs.statSync(filePath);
if (stats.isDirectory()) {
//recursively search folders and append the matching files
findAllCompressionFiles(fs, filePath);
} else {
addAllMatchingCompressionsToFile(files[i], filePath);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q50888
|
addAllMatchingCompressionsToFile
|
train
|
function addAllMatchingCompressionsToFile(fileName, fullFilePath) {
for (var i = 0; i < compressions.length; i++) {
if (fileName.endsWith(compressions[i].fileExtension)) {
addCompressionToFile(fullFilePath, compressions[i]);
return;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q50889
|
addCompressionToFile
|
train
|
function addCompressionToFile(filePath, compression) {
var srcFilePath = filePath.replace(rootFolder, "").replace(compression.fileExtension, "");
var existingFile = files[srcFilePath];
if (!existingFile) {
files[srcFilePath] = { compressions: [compression] };
} else {
existingFile.compressions.push(compression);
}
}
|
javascript
|
{
"resource": ""
}
|
q50890
|
registerCompression
|
train
|
function registerCompression(encodingName, fileExtension) {
if (!findCompressionByName(encodingName))
compressions.push(new Compression(encodingName, fileExtension));
}
|
javascript
|
{
"resource": ""
}
|
q50891
|
findCompressionByName
|
train
|
function findCompressionByName(encodingName) {
for (var i = 0; i < compressions.length; i++) {
if (compressions[i].encodingName === encodingName)
return compressions[i];
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q50892
|
initClientRendered
|
train
|
function initClientRendered(widgetDefs, document) {
// Ensure that event handlers to handle delegating events are
// always attached before initializing any widgets
eventDelegation.init();
document = document || window.document;
for (var i=0,len=widgetDefs.length; i<len; i++) {
var widgetDef = widgetDefs[i];
if (widgetDef.children.length) {
initClientRendered(widgetDef.children, document);
}
var widget = initWidget(
widgetDef.type,
widgetDef.id,
widgetDef.config,
widgetDef.state,
widgetDef.scope,
widgetDef.domEvents,
widgetDef.customEvents,
widgetDef.extend,
widgetDef.bodyElId,
widgetDef.existingWidget,
null,
document);
widgetDef.widget = widget;
}
}
|
javascript
|
{
"resource": ""
}
|
q50893
|
train
|
function(type, targetMethod, elId) {
if (!targetMethod) {
// The event handler method is allowed to be conditional. At render time if the target
// method is null then we do not attach any direct event listeners.
return;
}
if (!this.domEvents) {
this.domEvents = [];
}
this.domEvents.push(type);
this.domEvents.push(targetMethod);
this.domEvents.push(elId);
}
|
javascript
|
{
"resource": ""
}
|
|
q50894
|
Widget
|
train
|
function Widget(id, document) {
EventEmitter.call(this);
this.id = id;
this.el = null;
this.bodyEl = null;
this.state = null;
this.__subscriptions = null;
this.__evHandles = null;
this.__lifecycleState = null;
this.__customEvents = null;
this.__scope = null;
this.__dirty = false;
this.__oldState = null;
this.__stateChanges = null;
this.__updateQueued = false;
this.__dirtyState = null;
this.__document = document;
}
|
javascript
|
{
"resource": ""
}
|
q50895
|
getExistingWidget
|
train
|
function getExistingWidget(id, type) {
var existingEl = document.getElementById(id);
var existingWidget;
if (existingEl && (existingWidget = existingEl.__widget) && existingWidget.__type === type) {
return existingWidget;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q50896
|
getIEEvent
|
train
|
function getIEEvent() {
var event = window.event;
// add event.target
event.target = event.target || event.srcElement;
event.preventDefault = event.preventDefault || function() {
event.returnValue = false;
};
event.stopPropagation = event.stopPropagation || function() {
event.cancelBubble = true;
};
event.key = (event.which + 1 || event.keyCode + 1) - 1 || 0;
return event;
}
|
javascript
|
{
"resource": ""
}
|
q50897
|
_createLatLngs
|
train
|
function _createLatLngs(line, from) {
if (line.geometries[0] && line.geometries[0].coords[0]) {
/**
* stores how many times arc is broken over 180 longitude
* @type {number}
*/
let wrap = from.lng - line.geometries[0].coords[0][0] - 360;
return line.geometries
.map(subLine => {
wrap += 360;
return subLine.coords.map(point => L.latLng([point[1], point[0] + wrap]));
})
.reduce((all, latlngs) => all.concat(latlngs));
} else {
return [];
}
}
|
javascript
|
{
"resource": ""
}
|
q50898
|
promptIfMainTheme
|
train
|
function promptIfMainTheme(env) {
return new Promise((resolve, reject) => {
const c = config.shopify[env]
if (!c.api_key) {
console.log(chalk.yellow(`The "${env}" environment in config/shopify.yml does not specify an "api_key". Skipping check for if is main theme.`))
resolve()
return
}
// c.theme_id is live or equal to mainThemeId
if (c.theme_id === 'live' || (mainThemeId && mainThemeId === c.theme_id)) {
const question = 'You are about to deploy to the main theme. Continue ?'
prompt(question, false).then((isYes) => {
if (isYes) {
resolve()
return
}
reject('Aborting. You aborted the deploy.')
})
return
}
// we already have a mainThemeId and it's not c.theme_id
if (mainThemeId && mainThemeId !== c.theme_id) {
resolve()
return
}
fetchMainThemeId(env)
.then((id) => {
mainThemeId = id
promptIfMainTheme(env).then(resolve).catch(reject)
})
.catch(reject)
})
}
|
javascript
|
{
"resource": ""
}
|
q50899
|
hash_password
|
train
|
function hash_password(plain_text, salt, callback) {
// Get the crypto library.
const crypto = require("crypto")
// These should be a *slow* as possible, higher = slower.
// Slow it down until you tweak a bounce change.
const password_iterations = process.env.PW_GEN_PW_ITERS || 4096
// Password length and algorithm.
const password_length = process.env.PW_GEN_PW_LENGTH || 512
const password_algorithm = process.env.PW_GEN_PW_ALG || "sha256"
// Create a hash, we're going to encrypt the password.
// I wish Node had native support for good KDF functions
// like bcrypt or scrypt but PBKDF2 is good for now.
crypto.pbkdf2(plain_text, salt, password_iterations, password_length, password_algorithm, (err, key) => {
// Move on.
callback(key.toString("hex"), salt)
})
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.