_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q19700
|
_fnFindBestMatch
|
train
|
function _fnFindBestMatch(aValues, sBindingPath) {
var iJsonModelMin = -1;
var sJsonModelBestMatch = false;
aValues.forEach(function(sKey) {
var iCurrDest = StringAnalyzer.calculateLevenshteinDistance(sBindingPath, sKey);
if (iJsonModelMin === -1 || iCurrDest < iJsonModelMin) {
iJsonModelMin = iCurrDest;
sJsonModelBestMatch = sKey;
}
});
return sJsonModelBestMatch;
}
|
javascript
|
{
"resource": ""
}
|
q19701
|
train
|
function (vRawValue, oDetails) {
var sPath = typeof vRawValue === "string"
? "/" + oDetails.schemaChildName + "/" + vRawValue
: oDetails.context.getPath();
return oDetails.$$valueAsPromise
? oDetails.context.getModel().fetchValueListType(sPath).unwrap()
: oDetails.context.getModel().getValueListType(sPath);
}
|
javascript
|
{
"resource": ""
}
|
|
q19702
|
train
|
function (oOperand1, oOperand2) {
if (oOperand1.result !== "constant" && oOperand1.category === "number"
&& oOperand2.result === "constant" && oOperand2.type === "Edm.Int64") {
// adjust an integer constant of type "Edm.Int64" to the number
oOperand2.category = "number";
}
if (oOperand1.result !== "constant" && oOperand1.category === "Decimal"
&& oOperand2.result === "constant" && oOperand2.type === "Edm.Int32") {
// adjust an integer constant of type "Edm.Int32" to the decimal
oOperand2.category = "Decimal";
oOperand2.type = oOperand1.type;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19703
|
train
|
function (oPathValue) {
if (oPathValue.value === undefined) {
return undefined;
}
Measurement.average(sPerformanceGetExpression, "", aPerformanceCategories);
if (!bSimpleParserWarningLogged
&& ManagedObject.bindingParser === BindingParser.simpleParser) {
Log.warning("Complex binding syntax not active", null, sAnnotationHelper);
bSimpleParserWarningLogged = true;
}
return Expression.expression(oPathValue).then(function (oResult) {
return Basics.resultToString(oResult, false, oPathValue.complexBinding);
}, function (e) {
if (e instanceof SyntaxError) {
return "Unsupported: " + BindingParser.complexParser.escape(
Basics.toErrorString(oPathValue.value));
}
throw e;
}).finally(function () {
Measurement.end(sPerformanceGetExpression);
}).unwrap();
}
|
javascript
|
{
"resource": ""
}
|
|
q19704
|
getAllLibraries
|
train
|
function getAllLibraries(aExcludedLibraries, bIncludeDistLayer) {
var mLibraries = sap.ui.getCore().getLoadedLibraries(),
sInfoLibName,
bNewLibrary,
oInfo,
i;
// discover what is available in order to also test other libraries than those loaded in bootstrap
oInfo = sap.ui.getVersionInfo();
for (i = 0; i < oInfo.libraries.length; i++) {
sInfoLibName = oInfo.libraries[i].name;
if (jQuery.inArray(sInfoLibName, aExcludedLibraries) === -1 && !mLibraries[sInfoLibName]) {
Log.info("Libary '" + sInfoLibName + "' is not loaded!");
try {
sap.ui.getCore().loadLibrary(sInfoLibName);
bNewLibrary = true;
} catch (e) {
// not a control lib? This happens for e.g. "themelib_sap_bluecrystal"...
}
}
}
// Renew the libraries object if new libraries are added
if (bNewLibrary) {
mLibraries = sap.ui.getCore().getLoadedLibraries();
}
// excluded libraries should even be excluded when already loaded initially
aExcludedLibraries.forEach(function(sLibraryName) {
mLibraries[sLibraryName] = undefined;
});
// ignore dist-layer libraries if requested
if (!bIncludeDistLayer) {
for (var sLibName in mLibraries) {
if (!ControlIterator.isKnownRuntimeLayerLibrary(sLibName)) {
mLibraries[sLibName] = undefined;
}
}
}
return mLibraries;
}
|
javascript
|
{
"resource": ""
}
|
q19705
|
getRequestedLibraries
|
train
|
function getRequestedLibraries(aLibrariesToTest) {
var mLibraries = sap.ui.getCore().getLoadedLibraries(),
bNewLibrary,
i;
// make sure the explicitly requested libraries are there
for (i = 0; i < aLibrariesToTest.length; i++) {
if (!mLibraries[aLibrariesToTest[i]]) {
sap.ui.getCore().loadLibrary(aLibrariesToTest[i]); // no try-catch, as this library was explicitly requested
bNewLibrary = true;
}
}
if (bNewLibrary) {
mLibraries = sap.ui.getCore().getLoadedLibraries();
}
for (var sLibraryName in mLibraries) {
if (aLibrariesToTest.indexOf(sLibraryName) === -1) {
mLibraries[sLibraryName] = undefined;
}
}
return mLibraries;
}
|
javascript
|
{
"resource": ""
}
|
q19706
|
train
|
function(aLibrariesToTest, aExcludedLibraries, bIncludeDistLayer, QUnit) {
var mLibraries = aLibrariesToTest ?
getRequestedLibraries(aLibrariesToTest)
:
getAllLibraries(aExcludedLibraries, bIncludeDistLayer);
QUnit.test("Should load at least one library and some controls", function(assert) {
assert.expect(2);
var bLibFound = false;
for (var sLibName in mLibraries) {
if (mLibraries[sLibName]) {
if (!bLibFound) {
assert.ok(mLibraries[sLibName], "Should have loaded at least one library");
bLibFound = true;
}
var iControls = mLibraries[sLibName].controls ? mLibraries[sLibName].controls.length : 0;
if (iControls > 0) {
assert.ok(iControls > 0, "Should find at least 10 controls in a library");
break;
}
}
}
});
return mLibraries;
}
|
javascript
|
{
"resource": ""
}
|
|
q19707
|
train
|
function(aControls, aControlsToTest, aExcludedControls, bIncludeNonRenderable, bIncludeNonInstantiable, fnCallback) {
return new Promise(function(resolve, reject){
var iControlCountInLib = 0;
var loop = function(i) {
if (i < aControls.length) {
var sControlName = aControls[i];
handleControl(sControlName, aControlsToTest, aExcludedControls, bIncludeNonRenderable, bIncludeNonInstantiable, fnCallback).then(function(bCountThisControl){
if (bCountThisControl) {
iControlCountInLib++;
}
loop(i + 1);
});
} else {
resolve(iControlCountInLib);
}
};
loop(0);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q19708
|
loadResource
|
train
|
function loadResource(sUrl, sType) {
return new Promise(function (resolve, reject) {
jQuery.ajax({
url: sUrl,
async: true,
dataType: sType,
success: function (oJson) {
resolve(oJson);
},
error: function () {
reject();
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q19709
|
MetadataConverter
|
train
|
function MetadataConverter() {
this.aliases = {}; // maps alias -> namespace
this.oAnnotatable = null; // the current annotatable, see function annotatable
this.entityContainer = null; // the current EntityContainer
this.entitySet = null; // the current EntitySet/Singleton
this.namespace = null; // the namespace of the current Schema
this.oOperation = null; // the current operation (action or function)
this.reference = null; // the current Reference
this.schema = null; // the current Schema
this.type = null; // the current EntityType/ComplexType
this.result = null; // the result of the conversion
this.url = null; // the document URL (for error messages)
this.xmlns = null; // the expected XML namespace
}
|
javascript
|
{
"resource": ""
}
|
q19710
|
Measurement
|
train
|
function Measurement(sId, sInfo, iStart, iEnd, aCategories) {
this.id = sId;
this.info = sInfo;
this.start = iStart;
this.end = iEnd;
this.pause = 0;
this.resume = 0;
this.duration = 0; // used time
this.time = 0; // time from start to end
this.categories = aCategories;
this.average = false; //average duration enabled
this.count = 0; //average count
this.completeDuration = 0; //complete duration
}
|
javascript
|
{
"resource": ""
}
|
q19711
|
train
|
function (sTopicId, oModel) {
var oTree = this.byId("tree"),
oData = oModel.getData();
// Find the path to the new node, traversing the model
var aTopicIds = this._oTreeUtil.getPathToNode(sTopicId, oData);
// Expand all nodes on the path to the target node
var oLastItem;
aTopicIds.forEach(function(sId) {
var oItem = this._findTreeItem(sId);
if (oItem) {
oTree.getBinding("items").expand(oTree.indexOfItem(oItem));
oLastItem = oItem;
}
}, this);
// Select the target node and scroll to it
if (oLastItem) {
oLastItem.setSelected(true);
this.oSelectedItem = {
sTopicId: sTopicId,
oModel: oModel
};
// Only scroll after the dom is ready
setTimeout(function () {
if (oLastItem.getDomRef() && !isInViewport(oLastItem.getDomRef())) {
this._scrollTreeItemIntoView(oLastItem);
}
}.bind(this), 0);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19712
|
train
|
function (oEvent) {
// Update filter value
this._sFilter = oEvent.getParameter("newValue").trim();
if (this._filterTimeout) {
clearTimeout(this._filterTimeout);
}
this._filterTimeout = setTimeout(function () {
if (this.buildAndApplyFilters()) {
this._expandAllNodes();
} else {
this._collapseAllNodes();
if (this.oSelectedItem) {
this._expandTreeToNode(this.oSelectedItem.sTopicId, this.oSelectedItem.oModel);
}
}
this._filterTimeout = null;
}.bind(this), 250);
}
|
javascript
|
{
"resource": ""
}
|
|
q19713
|
train
|
function () {
var oBinding = this.byId("tree").getBinding("items");
if (this._sFilter) {
oBinding.filter(new Filter({
path: "name",
operator: FilterOperator.Contains,
value1: this._sFilter
}));
return true;
} else {
oBinding.filter();
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19714
|
train
|
function (oPathValue, sMessage, sComponent) {
sMessage = oPathValue.path + ": " + sMessage;
Log.error(sMessage, Basics.toErrorString(oPathValue.value),
sComponent || sAnnotationHelper);
throw new SyntaxError(sMessage);
}
|
javascript
|
{
"resource": ""
}
|
|
q19715
|
train
|
function (oPathValue, sExpectedType) {
var bError,
vValue = oPathValue.value;
if (sExpectedType === "array") {
bError = !Array.isArray(vValue);
} else {
bError = typeof vValue !== sExpectedType
|| vValue === null
|| Array.isArray(vValue);
}
if (bError) {
Basics.error(oPathValue, "Expected " + sExpectedType);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19716
|
train
|
function (oResult, bExpression, bWithType) {
var vValue = oResult.value;
function binding(bAddType) {
var sConstraints, sResult;
bAddType = bAddType && !oResult.ignoreTypeInPath && oResult.type;
if (bAddType || rBadChars.test(vValue)) {
sResult = "{path:" + Basics.toJSON(vValue);
if (bAddType) {
sResult += ",type:'" + mUi5TypeForEdmType[oResult.type] + "'";
sConstraints = Basics.toJSON(oResult.constraints);
if (sConstraints && sConstraints !== "{}") {
sResult += ",constraints:" + sConstraints;
}
}
return sResult + "}";
}
return "{" + vValue + "}";
}
function constant(oResult) {
switch (oResult.type) {
case "Edm.Boolean":
case "Edm.Double":
case "Edm.Int32":
return String(oResult.value);
default:
return Basics.toJSON(oResult.value);
}
}
switch (oResult.result) {
case "binding":
return (bExpression ? "$" : "") + binding(bWithType);
case "composite":
if (bExpression) {
throw new Error(
"Trying to embed a composite binding into an expression binding");
}
return vValue; // Note: it's already a composite binding string
case "constant":
if (oResult.type === "edm:Null") {
return bExpression ? "null" : null;
}
if (bExpression) {
return constant(oResult);
}
return typeof vValue === "string"
? BindingParser.complexParser.escape(vValue)
: String(vValue);
case "expression":
return bExpression ? vValue : "{=" + vValue + "}";
// no default
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19717
|
train
|
function (vValue) {
var sJSON;
if (typeof vValue !== "function") {
try {
sJSON = Basics.toJSON(vValue);
// undefined --> undefined
// null, NaN, Infinity --> "null"
// all are correctly handled by String
if (sJSON !== undefined && sJSON !== "null") {
return sJSON;
}
} catch (e) {
// "converting circular structure to JSON"
}
}
return String(vValue);
}
|
javascript
|
{
"resource": ""
}
|
|
q19718
|
train
|
function (vValue) {
var sStringified,
bEscaped = false,
sResult = "",
i, c;
sStringified = JSON.stringify(vValue);
if (sStringified === undefined) {
return undefined;
}
for (i = 0; i < sStringified.length; i += 1) {
switch (c = sStringified.charAt(i)) {
case "'": // a single quote must be escaped (can only occur in a string)
sResult += "\\'";
break;
case '"':
if (bEscaped) { // a double quote needs no escaping (only in a string)
sResult += c;
bEscaped = false;
} else { // string begin or end with single quotes
sResult += "'";
}
break;
case "\\":
if (bEscaped) { // an escaped backslash
sResult += "\\\\";
}
bEscaped = !bEscaped;
break;
default:
if (bEscaped) {
sResult += "\\";
bEscaped = false;
}
sResult += c;
}
}
return sResult;
}
|
javascript
|
{
"resource": ""
}
|
|
q19719
|
_trim
|
train
|
function _trim(sValue, aParams) {
var i = 0,
aTrims = aParams;
if (!aTrims) {
aTrims = [" "];
}
while (i < aTrims.length) {
if (_endsWith(sValue, aTrims[i])) {
sValue = sValue.substring(0, sValue.length - aTrims[i].length);
i = 0;
continue;
}
i++;
}
i = 0;
while (i < aTrims.length) {
if (_startsWith(sValue, aTrims[i])) {
sValue = sValue.substring(aTrims[i].length);
i = 0;
continue;
}
i++;
}
return sValue;
}
|
javascript
|
{
"resource": ""
}
|
q19720
|
train
|
function (vCollection, vValue, iFromIndex) {
if (typeof iFromIndex !== 'number') {
iFromIndex = 0;
}
// Use native (Array.prototype.includes, String.prototype.includes) includes functions if available
if (Array.isArray(vCollection)) {
if (typeof vCollection.includes === 'function') {
return vCollection.includes(vValue, iFromIndex);
}
iFromIndex = iFromIndex < 0 ? iFromIndex + vCollection.length : iFromIndex;
iFromIndex = iFromIndex < 0 ? 0 : iFromIndex;
for (var i = iFromIndex; i < vCollection.length; i++) {
if (equals(vCollection[i], vValue)) {
return true;
}
}
return false;
} else if (typeof vCollection === 'string') {
iFromIndex = iFromIndex < 0 ? vCollection.length + iFromIndex : iFromIndex;
if (typeof vCollection.includes === 'function') {
return vCollection.includes(vValue, iFromIndex);
}
return vCollection.indexOf(vValue, iFromIndex) !== -1;
} else {
// values(...) always returns an array therefore deep recursion is avoided
return fnIncludes(values(vCollection), vValue, iFromIndex);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19721
|
train
|
function (oEvent) {
var oSource = oEvent.getSource();
var sLayerBindingPath = oSource.getBindingContextPath().substring(1);
var oLayerModelData = this.getView().getModel("layers").getData();
var sLayerName = oLayerModelData[sLayerBindingPath].name;
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("LayerContentMaster", {"layer": sLayerName});
}
|
javascript
|
{
"resource": ""
}
|
|
q19722
|
refreshMapping
|
train
|
function refreshMapping(oLabel, bDestroy){
var sLabelId = oLabel.getId();
var sOldId = oLabel.__sLabeledControl;
var sNewId = bDestroy ? null : findLabelForControl(oLabel);
if (sOldId == sNewId) {
return;
}
//Invalidate the label itself (see setLabelFor, setAlternativeLabelFor)
if (!bDestroy) {
oLabel.invalidate();
}
//Update the label to control mapping (1-1 mapping)
if (sNewId) {
oLabel.__sLabeledControl = sNewId;
} else {
delete oLabel.__sLabeledControl;
}
//Update the control to label mapping (1-n mapping)
var aLabelsOfControl;
if (sOldId) {
aLabelsOfControl = CONTROL_TO_LABELS_MAPPING[sOldId];
if (aLabelsOfControl) {
aLabelsOfControl = aLabelsOfControl.filter(function(sCurrentLabelId) {
return sCurrentLabelId != sLabelId;
});
if (aLabelsOfControl.length) {
CONTROL_TO_LABELS_MAPPING[sOldId] = aLabelsOfControl;
} else {
delete CONTROL_TO_LABELS_MAPPING[sOldId];
}
}
}
if (sNewId) {
aLabelsOfControl = CONTROL_TO_LABELS_MAPPING[sNewId] || [];
aLabelsOfControl.push(sLabelId);
CONTROL_TO_LABELS_MAPPING[sNewId] = aLabelsOfControl;
}
//Invalidate related controls
var oOldControl = toControl(sOldId, true);
var oNewControl = toControl(sNewId, true);
if (oOldControl) {
oLabel.detachRequiredChange(oOldControl);
}
if (oNewControl) {
oLabel.attachRequiredChange(oNewControl);
}
}
|
javascript
|
{
"resource": ""
}
|
q19723
|
checkLabelEnablementPreconditions
|
train
|
function checkLabelEnablementPreconditions(oControl) {
if (!oControl) {
throw new Error("sap.ui.core.LabelEnablement cannot enrich null");
}
var oMetadata = oControl.getMetadata();
if (!oMetadata.isInstanceOf("sap.ui.core.Label")) {
throw new Error("sap.ui.core.LabelEnablement only supports Controls with interface sap.ui.core.Label");
}
var oLabelForAssociation = oMetadata.getAssociation("labelFor");
if (!oLabelForAssociation || oLabelForAssociation.multiple) {
throw new Error("sap.ui.core.LabelEnablement only supports Controls with a to-1 association 'labelFor'");
}
//Add more detailed checks here ?
}
|
javascript
|
{
"resource": ""
}
|
q19724
|
train
|
function() {
if (!this.metaPath) {
this.oMetaContext = this.oMetaModel.getMetaContext(this.path);
this.metaPath = this.oMetaContext.getPath();
} else {
this.oMetaContext = this.oMetaModel.createBindingContext(this.metaPath);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19725
|
train
|
function(sProperty, vGetter, aArgs, caller) {
if (!vGetter) {
return;
}
if (!caller) {
caller = this;
}
Object.defineProperty(this, sProperty, {
configurable: true,
get: function() {
if (this._mCustomPropertyBag[sProperty]) {
return this._mCustomPropertyBag[sProperty];
}
if (!this._mPropertyBag.hasOwnProperty(sProperty)) {
this._mPropertyBag[sProperty] = new SyncPromise(function(resolve, reject) {
if (typeof vGetter == 'function') {
resolve(vGetter.apply(caller, aArgs));
} else {
resolve(vGetter);
}
});
}
return this._mPropertyBag[sProperty];
},
set: function(vValue) {
this._mCustomPropertyBag[sProperty] = vValue;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q19726
|
train
|
function(sValuePath, sType) {
var sPath = "{";
if (this.modelName) {
sPath = sPath + "model: '" + this.modelName + "',";
}
if (this.sContextPath && sValuePath.startsWith(this.sContextPath)) {
sValuePath = sValuePath.replace(this.sContextPath,"");
}
sPath = sPath + "path: '" + escape(sValuePath) + "'";
if (sType) {
sPath = sPath + ", type: '" + sType + "'";
}
sPath = sPath + "}";
return sPath;
}
|
javascript
|
{
"resource": ""
}
|
|
q19727
|
train
|
function(mTargetAnnotations, mSourceAnnotations) {
// Merge must be done on Term level, this is why the original line does not suffice any more:
// jQuery.extend(true, this.oAnnotations, mAnnotations);
// Terms are defined on different levels, the main one is below the target level, which is directly
// added as property to the annotations object and then in the same way inside two special properties
// named "propertyAnnotations" and "EntityContainer"
var sTarget, sTerm;
var aSpecialCases = ["annotationsAtArrays", "propertyAnnotations", "EntityContainer", "annotationReferences"];
// First merge standard annotations
for (sTarget in mSourceAnnotations) {
if (aSpecialCases.indexOf(sTarget) !== -1) {
// Skip these as they are special properties that contain Target level definitions
continue;
}
// ...all others contain Term level definitions
AnnotationParser._mergeAnnotation(sTarget, mSourceAnnotations, mTargetAnnotations);
}
// Now merge special cases except "annotationsAtArrays"
for (var i = 1; i < aSpecialCases.length; ++i) {
var sSpecialCase = aSpecialCases[i];
mTargetAnnotations[sSpecialCase] = mTargetAnnotations[sSpecialCase] || {}; // Make sure the target namespace exists
for (sTarget in mSourceAnnotations[sSpecialCase]) {
for (sTerm in mSourceAnnotations[sSpecialCase][sTarget]) {
// Now merge every term
mTargetAnnotations[sSpecialCase][sTarget] = mTargetAnnotations[sSpecialCase][sTarget] || {};
AnnotationParser._mergeAnnotation(sTerm, mSourceAnnotations[sSpecialCase][sTarget], mTargetAnnotations[sSpecialCase][sTarget]);
}
}
}
if (mSourceAnnotations.annotationsAtArrays) {
mTargetAnnotations.annotationsAtArrays = (mTargetAnnotations.annotationsAtArrays || [])
.concat(mSourceAnnotations.annotationsAtArrays);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19728
|
train
|
function (mAnnotations) {
if (mAnnotations.annotationsAtArrays) {
mAnnotations.annotationsAtArrays.forEach(function (aSegments) {
AnnotationParser.syncAnnotationsAtArrays(mAnnotations, aSegments);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19729
|
getParam
|
train
|
function getParam(mOptions) {
var oParams = getParameters();
if (mOptions.scopeName) {
oParams = oParams["scopes"][mOptions.scopeName];
} else {
oParams = oParams["default"];
}
var sParam = oParams[mOptions.parameterName];
if (typeof sParam === "undefined" && typeof mOptions.parameterName === "string") {
// compatibility for theming parameters with colon
var iIndex = mOptions.parameterName.indexOf(":");
if (iIndex !== -1) {
mOptions.parameterName = mOptions.parameterName.substr(iIndex + 1);
}
sParam = oParams[mOptions.parameterName];
}
if (mOptions.loadPendingParameters && typeof sParam === "undefined") {
loadPendingLibraryParameters();
sParam = getParam({
parameterName: mOptions.parameterName,
scopeName: mOptions.scopeName,
loadPendingParameters: false // prevent recursion
});
}
return sParam;
}
|
javascript
|
{
"resource": ""
}
|
q19730
|
train
|
function (bRestoreFocus, oEvent) {
if (!this._bBlurOrKeyDownStarted) {
this._bBlurOrKeyDownStarted = true;
if (oEvent) {
RenameHandler._preventDefault.call(this, oEvent);
RenameHandler._stopPropagation.call(this, oEvent);
}
return this._emitLabelChangeEvent()
.then(function (fnErrorHandler) {
this.stopEdit(bRestoreFocus);
if (typeof fnErrorHandler === "function") {
fnErrorHandler(); // contains startEdit() and valueStateMessage
}
}.bind(this));
}
return Promise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
|
q19731
|
train
|
function(oEvent) {
while (oEvent && oEvent.originalEvent && oEvent !== oEvent.originalEvent) {
oEvent = oEvent.originalEvent;
}
return oEvent;
}
|
javascript
|
{
"resource": ""
}
|
|
q19732
|
train
|
function(rm, oRoadMap, bStart){
var sType = bStart ? "Start" : "End";
rm.write("<div");
rm.writeAttribute("id", oRoadMap.getId() + "-" + sType);
rm.writeAttribute("tabindex", "-1");
var hasHiddenSteps = true; //Simply assume that there are hidden steps -> updated later (see function updateScrollState)
rm.addClass(hasHiddenSteps ? "sapUiRoadMap" + sType + "Scroll" : "sapUiRoadMap" + sType + "Fixed");
rm.addClass("sapUiRoadMapDelim");
rm.addClass("sapUiRoadMapContent");
rm.writeClasses();
rm.write("></div>");
}
|
javascript
|
{
"resource": ""
}
|
|
q19733
|
train
|
function(rm, oRoadMap, oStep, aAdditionalClasses, fAddAdditionalBoxContent, sId){
rm.write("<li");
if (sId) { //Write the given Id if available, otherwise use writeControlData
rm.writeAttribute("id", sId);
} else {
rm.writeElementData(oStep);
}
var sStepName = getStepName(oRoadMap, oStep);
oStep.__stepName = sStepName;
var sTooltip = getStepTooltip(oStep);
rm.addClass("sapUiRoadMapContent");
rm.addClass("sapUiRoadMapStep");
if (!oStep.getVisible()) {
rm.addClass("sapUiRoadMapHidden");
}
if (oStep.getEnabled()) {
if (oRoadMap.getSelectedStep() == oStep.getId()) {
rm.addClass("sapUiRoadMapSelected");
}
} else {
rm.addClass("sapUiRoadMapDisabled");
}
if (aAdditionalClasses) { //Write additional CSS classes if available
for (var i = 0; i < aAdditionalClasses.length; i++) {
rm.addClass(aAdditionalClasses[i]);
}
}
rm.writeClasses();
rm.write(">");
renderAdditionalStyleElem(rm, sId ? sId : oStep.getId(), 1);
rm.write("<div");
rm.writeAttribute("id", (sId ? sId : oStep.getId()) + "-box");
rm.writeAttribute("tabindex", "-1");
rm.addClass("sapUiRoadMapStepBox");
rm.writeClasses();
rm.writeAttributeEscaped("title", sTooltip);
writeStepAria(rm, oRoadMap, oStep, fAddAdditionalBoxContent ? true : false);
rm.write("><span>");
rm.write(sStepName);
rm.write("</span>");
//Call callback function to render additional content
if (fAddAdditionalBoxContent) {
fAddAdditionalBoxContent(rm, oRoadMap, oStep);
}
rm.write("</div>");
rm.write("<label");
rm.writeAttribute("id", (sId ? sId : oStep.getId()) + "-label");
rm.addClass("sapUiRoadMapTitle");
rm.writeAttributeEscaped("title", sTooltip);
rm.writeClasses();
rm.write(">");
var sLabel = oStep.getLabel();
if (sLabel) {
rm.writeEscaped(sLabel);
}
rm.write("</label>");
renderAdditionalStyleElem(rm, sId ? sId : oStep.getId(), 2);
rm.write("</li>");
}
|
javascript
|
{
"resource": ""
}
|
|
q19734
|
train
|
function(oStep){
var sTooltip = oStep.getTooltip_AsString();
if (!sTooltip && !oStep.getTooltip() && sap.ui.getCore().getConfiguration().getAccessibility()) {
sTooltip = getText("RDMP_DEFAULT_STEP_TOOLTIP", [oStep.__stepName]);
}
return sTooltip || "";
}
|
javascript
|
{
"resource": ""
}
|
|
q19735
|
train
|
function(rm, oRoadMap, oStep, bIsExpandable){
if (!sap.ui.getCore().getConfiguration().getAccessibility()) {
return;
}
rm.writeAttribute("role", "treeitem");
if (oStep.getEnabled()) {
rm.writeAttribute("aria-checked", oRoadMap.getSelectedStep() == oStep.getId());
} else {
rm.writeAttribute("aria-disabled", true);
}
rm.writeAttribute("aria-haspopup", bIsExpandable);
rm.writeAttribute("aria-level", oStep.getParent() instanceof sap.ui.commons.RoadMap ? 1 : 2);
rm.writeAttribute("aria-posinset", getAriaPosInSet(oStep));
rm.writeAttribute("aria-setsize", getAriaSetSize(oStep));
rm.writeAttributeEscaped("aria-label", getAriaLabel(oStep, oStep.getLabel()));
if (!bIsExpandable) {
return;
}
rm.writeAttribute("aria-expanded", oStep.getExpanded());
}
|
javascript
|
{
"resource": ""
}
|
|
q19736
|
train
|
function(oStep, sLabel){
var bIsExpandable = oStep.getParent() instanceof sap.ui.commons.RoadMap && oStep.getSubSteps().length > 0;
var sResult = sLabel || "";
if (oStep.getEnabled()) {
sResult = getText(bIsExpandable ? "RDMP_ARIA_EXPANDABLE_STEP" : "RDMP_ARIA_STANDARD_STEP", [sResult]);
}
return sResult;
}
|
javascript
|
{
"resource": ""
}
|
|
q19737
|
train
|
function(oStep){
var bIsTopLevel = oStep.getParent() instanceof sap.ui.commons.RoadMap;
var iIdx = oStep.getParent()[bIsTopLevel ? "indexOfStep" : "indexOfSubStep"](oStep);
var iCountInvisible = 0;
var aSteps = oStep.getParent()[bIsTopLevel ? "getSteps" : "getSubSteps"]();
for (var i = 0; i < iIdx; i++) {
if (!aSteps[i].getVisible()) {
iCountInvisible++;
}
}
return iIdx + 1 - iCountInvisible;
}
|
javascript
|
{
"resource": ""
}
|
|
q19738
|
train
|
function(oStep){
var bIsTopLevel = oStep.getParent() instanceof sap.ui.commons.RoadMap;
var aSteps = oStep.getParent()[bIsTopLevel ? "getSteps" : "getSubSteps"]();
var iCount = aSteps.length;
for (var i = 0; i < aSteps.length; i++) {
if (!aSteps[i].getVisible()) {
iCount--;
}
}
return iCount;
}
|
javascript
|
{
"resource": ""
}
|
|
q19739
|
train
|
function(rm, oRoadMap, oStep){
var fCreateIcon = function(rm, oRoadMap, sId, sIcon, sAdditonalClass){
rm.write("<div");
rm.writeAttribute("id", sId + "-ico");
rm.addClass("sapUiRoadMapStepIco");
if (sAdditonalClass) {
rm.addClass(sAdditonalClass);
}
rm.writeClasses();
rm.write("></div>");
};
var bIsExpanded = oStep.getExpanded();
//Render the start step with an additional icon
renderStep(rm, oRoadMap, oStep, bIsExpanded ? ["sapUiRoadMapExpanded"] : null, function(rm, oRoadMap, oStep){
fCreateIcon(rm, oRoadMap, oStep.getId(), bIsExpanded ? "roundtripstart.gif" : "roundtrip.gif");
});
//Render the sub steps
var aSteps = oStep.getSubSteps();
for (var i = 0; i < aSteps.length; i++) {
var aClasses = ["sapUiRoadMapSubStep"];
if (!bIsExpanded && aSteps[i].getVisible()) {
aClasses.push("sapUiRoadMapHidden");
}
renderStep(rm, oRoadMap, aSteps[i], aClasses);
}
//Render the end step with an additional icon
aClasses = ["sapUiRoadMapExpanded", "sapUiRoadMapStepEnd"];
if (!bIsExpanded) {
aClasses.push("sapUiRoadMapHidden");
}
renderStep(rm, oRoadMap, oStep, aClasses, function(rm, oRoadMap, oStep){
fCreateIcon(rm, oRoadMap, oStep.getId() + "-expandend", "roundtripend.gif");
}, oStep.getId() + "-expandend");
}
|
javascript
|
{
"resource": ""
}
|
|
q19740
|
train
|
function(oRoadMap){
var iRTLFactor = getRTLFactor();
var jStepArea = oRoadMap.$("steparea");
var iScrollLeft = getScrollLeft(jStepArea);
var jStartDelim = oRoadMap.$("Start");
jStartDelim.removeClass("sapUiRoadMapStartScroll").removeClass("sapUiRoadMapStartFixed");
jStartDelim.addClass(iRTLFactor * iScrollLeft >= oRoadMap.iStepWidth ? "sapUiRoadMapStartScroll" : "sapUiRoadMapStartFixed");
var jEndDelim = oRoadMap.$("End");
jEndDelim.removeClass("sapUiRoadMapEndScroll").removeClass("sapUiRoadMapEndFixed");
var bEndReached = jStepArea.get(0).scrollWidth - iRTLFactor * iScrollLeft - jStepArea.width() < oRoadMap.iStepWidth;
jEndDelim.addClass(bEndReached ? "sapUiRoadMapEndFixed" : "sapUiRoadMapEndScroll");
}
|
javascript
|
{
"resource": ""
}
|
|
q19741
|
train
|
function(jStepArea, jStep){
var iPos = jStep.position().left;
if (sap.ui.getCore().getConfiguration().getRTL()) { //Recompute in RTL case
iPos = jStepArea.width() - iPos - jStep.outerWidth();
}
return iPos;
}
|
javascript
|
{
"resource": ""
}
|
|
q19742
|
train
|
function(oRoadMap, iNewPos, bSkipAnim, fEndCallBack){
var jStepArea = oRoadMap.$("steparea");
jStepArea.stop(false, true);
if (iNewPos == "next") {
iNewPos = jStepArea.scrollLeft() + oRoadMap.iStepWidth * getRTLFactor();
} else if (iNewPos == "prev") {
iNewPos = jStepArea.scrollLeft() - oRoadMap.iStepWidth * getRTLFactor();
} else if (iNewPos == "keep") {
iNewPos = jStepArea.scrollLeft();
} else {
iNewPos = iNewPos * getRTLFactor();
}
var fDoAfterScroll = function(){
updateDelimiters(oRoadMap);
if (fEndCallBack) {
var jFirstVisibleRef = RoadMapRenderer.getFirstVisibleRef(oRoadMap);
fEndCallBack(jFirstVisibleRef.attr("id"));
}
};
if (!jQuery.fx.off && !bSkipAnim) {
jStepArea.animate({scrollLeft: iNewPos}, "fast", fDoAfterScroll);
} else {
jStepArea.scrollLeft(iNewPos);
fDoAfterScroll();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q19743
|
handleAriaSize
|
train
|
function handleAriaSize (aVisibleTiles) {
var iTilesCount,
i,
oTile;
aVisibleTiles = aVisibleTiles || this._getVisibleTiles();
iTilesCount = aVisibleTiles.length;
for (i = 0; i < iTilesCount; i++) {
oTile = aVisibleTiles[i];
if (oTile._rendered && oTile.getDomRef()) {
oTile.getDomRef().setAttribute("aria-setsize", iTilesCount);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q19744
|
handleAriaPositionInSet
|
train
|
function handleAriaPositionInSet(iStartIndex, iEndIndex, aVisibleTiles) {
var i,
oTile = null;
aVisibleTiles = aVisibleTiles || this._getVisibleTiles();
for (i = iStartIndex; i < iEndIndex; i++) {
oTile = aVisibleTiles[i];
if (oTile) {
oTile.$().attr('aria-posinset', this._indexOfVisibleTile(oTile, aVisibleTiles) + 1);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q19745
|
resolve
|
train
|
function resolve(opt) {
if (opt instanceof Transporters.Base) {
return opt;
} else if (_.isString(opt)) {
let TransporterClass = getByName(opt);
if (TransporterClass)
return new TransporterClass();
if (opt.startsWith("nats://"))
TransporterClass = Transporters.NATS;
else if (opt.startsWith("mqtt://") || opt.startsWith("mqtts://"))
TransporterClass = Transporters.MQTT;
else if (opt.startsWith("redis://") || opt.startsWith("rediss://"))
TransporterClass = Transporters.Redis;
else if (opt.startsWith("amqp://") || opt.startsWith("amqps://"))
TransporterClass = Transporters.AMQP;
else if (opt.startsWith("kafka://"))
TransporterClass = Transporters.Kafka;
else if (opt.startsWith("stan://"))
TransporterClass = Transporters.STAN;
else if (opt.startsWith("tcp://"))
TransporterClass = Transporters.TCP;
if (TransporterClass)
return new TransporterClass(opt);
else
throw new BrokerOptionsError(`Invalid transporter type '${opt}'.`, { type: opt });
} else if (_.isObject(opt)) {
let TransporterClass = getByName(opt.type || "NATS");
if (TransporterClass)
return new TransporterClass(opt.options);
else
throw new BrokerOptionsError(`Invalid transporter type '${opt.type}'.`, { type: opt.type });
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q19746
|
resolve
|
train
|
function resolve(opt) {
if (opt instanceof Cachers.Base) {
return opt;
} else if (opt === true) {
return new Cachers.Memory();
} else if (_.isString(opt)) {
let CacherClass = getByName(opt);
if (CacherClass)
return new CacherClass();
if (opt.startsWith("redis://"))
CacherClass = Cachers.Redis;
if (CacherClass)
return new CacherClass(opt);
else
throw new BrokerOptionsError(`Invalid cacher type '${opt}'.`, { type: opt });
} else if (_.isObject(opt)) {
let CacherClass = getByName(opt.type || "Memory");
if (CacherClass)
return new CacherClass(opt.options);
else
throw new BrokerOptionsError(`Invalid cacher type '${opt.type}'.`, { type: opt.type });
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q19747
|
resolve
|
train
|
function resolve(opt) {
if (Strategies.Base.isPrototypeOf(opt)) {
return opt;
} else if (_.isString(opt)) {
let SerializerClass = getByName(opt);
if (SerializerClass)
return SerializerClass;
else
throw new BrokerOptionsError(`Invalid strategy type '${opt}'.`, { type: opt });
} else if (_.isObject(opt)) {
let SerializerClass = getByName(opt.type || "RoundRobin");
if (SerializerClass)
return SerializerClass;
else
throw new BrokerOptionsError(`Invalid strategy type '${opt.type}'.`, { type: opt.type });
}
return Strategies.RoundRobin;
}
|
javascript
|
{
"resource": ""
}
|
q19748
|
PacketEvent
|
train
|
function PacketEvent(properties) {
this.groups = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19749
|
PacketRequest
|
train
|
function PacketRequest(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19750
|
PacketResponse
|
train
|
function PacketResponse(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19751
|
PacketDiscover
|
train
|
function PacketDiscover(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19752
|
PacketInfo
|
train
|
function PacketInfo(properties) {
this.ipList = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19753
|
Client
|
train
|
function Client(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19754
|
PacketDisconnect
|
train
|
function PacketDisconnect(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19755
|
PacketHeartbeat
|
train
|
function PacketHeartbeat(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19756
|
PacketPing
|
train
|
function PacketPing(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19757
|
PacketPong
|
train
|
function PacketPong(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19758
|
PacketGossipHello
|
train
|
function PacketGossipHello(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19759
|
PacketGossipRequest
|
train
|
function PacketGossipRequest(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19760
|
PacketGossipResponse
|
train
|
function PacketGossipResponse(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q19761
|
shouldMetric
|
train
|
function shouldMetric(ctx) {
if (ctx.broker.options.metrics) {
sampleCounter++;
if (sampleCounter * ctx.broker.options.metricsRate >= 1.0) {
sampleCounter = 0;
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q19762
|
metricStart
|
train
|
function metricStart(ctx) {
ctx.startTime = Date.now();
ctx.startHrTime = process.hrtime();
ctx.duration = 0;
if (ctx.metrics) {
const payload = generateMetricPayload(ctx);
ctx.broker.emit("metrics.trace.span.start", payload);
}
}
|
javascript
|
{
"resource": ""
}
|
q19763
|
generateMetricPayload
|
train
|
function generateMetricPayload(ctx) {
let payload = {
id: ctx.id,
requestID: ctx.requestID,
level: ctx.level,
startTime: ctx.startTime,
remoteCall: ctx.nodeID !== ctx.broker.nodeID
};
// Process extra metrics
processExtraMetrics(ctx, payload);
if (ctx.action) {
payload.action = {
name: ctx.action.name
};
}
if (ctx.service) {
payload.service = {
name: ctx.service.name,
version: ctx.service.version
};
}
if (ctx.parentID)
payload.parent = ctx.parentID;
payload.nodeID = ctx.broker.nodeID;
if (payload.remoteCall)
payload.callerNodeID = ctx.nodeID;
return payload;
}
|
javascript
|
{
"resource": ""
}
|
q19764
|
metricFinish
|
train
|
function metricFinish(ctx, error) {
if (ctx.startHrTime) {
let diff = process.hrtime(ctx.startHrTime);
ctx.duration = (diff[0] * 1e3) + (diff[1] / 1e6); // milliseconds
}
ctx.stopTime = ctx.startTime + ctx.duration;
if (ctx.metrics) {
const payload = generateMetricPayload(ctx);
payload.endTime = ctx.stopTime;
payload.duration = ctx.duration;
payload.fromCache = ctx.cachedResult;
if (error) {
payload.error = {
name: error.name,
code: error.code,
type: error.type,
message: error.message
};
}
ctx.broker.emit("metrics.trace.span.finish", payload);
}
}
|
javascript
|
{
"resource": ""
}
|
q19765
|
assignExtraMetrics
|
train
|
function assignExtraMetrics(ctx, name, payload) {
let def = ctx.action.metrics[name];
// if metrics definitions is boolean do default, metrics=true
if (def === true) {
payload[name] = ctx[name];
} else if (_.isArray(def)) {
payload[name] = _.pick(ctx[name], def);
} else if (_.isFunction(def)) {
payload[name] = def(ctx[name]);
}
}
|
javascript
|
{
"resource": ""
}
|
q19766
|
processExtraMetrics
|
train
|
function processExtraMetrics(ctx, payload) {
// extra metrics (params and meta)
if (_.isObject(ctx.action.metrics)) {
// custom metrics def
assignExtraMetrics(ctx, "params", payload);
assignExtraMetrics(ctx, "meta", payload);
}
}
|
javascript
|
{
"resource": ""
}
|
q19767
|
sanitizeHooks
|
train
|
function sanitizeHooks(hooks, service) {
if (_.isString(hooks))
return service && _.isFunction(service[hooks]) ? service[hooks] : null;
if (Array.isArray(hooks)) {
return _.compact(hooks.map(h => {
if (_.isString(h))
return service && _.isFunction(service[h]) ? service[h] : null;
return h;
}));
}
return hooks;
}
|
javascript
|
{
"resource": ""
}
|
q19768
|
resolve
|
train
|
function resolve(opt) {
if (opt instanceof Serializers.Base) {
return opt;
} else if (_.isString(opt)) {
let SerializerClass = getByName(opt);
if (SerializerClass)
return new SerializerClass();
else
throw new BrokerOptionsError(`Invalid serializer type '${opt}'.`, { type: opt });
} else if (_.isObject(opt)) {
let SerializerClass = getByName(opt.type || "JSON");
if (SerializerClass)
return new SerializerClass(opt.options);
else
throw new BrokerOptionsError(`Invalid serializer type '${opt.type}'.`, { type: opt.type });
}
return new Serializers.JSON();
}
|
javascript
|
{
"resource": ""
}
|
q19769
|
callNext
|
train
|
function callNext() {
/* istanbul ignore next */
if (queue.length == 0) return;
/* istanbul ignore next */
if (currentInFlight >= opts.concurrency) return;
const item = queue.shift();
currentInFlight++;
handler(item.ctx)
.then(res => {
currentInFlight--;
item.resolve(res);
callNext();
})
.catch(err => {
currentInFlight--;
item.reject(err);
callNext();
});
}
|
javascript
|
{
"resource": ""
}
|
q19770
|
recreateError
|
train
|
function recreateError(err) {
const Class = module.exports[err.name];
if (Class) {
switch(err.name) {
case "MoleculerError": return new Class(err.message, err.code, err.type, err.data);
case "MoleculerRetryableError": return new Class(err.message, err.code, err.type, err.data);
case "MoleculerServerError": return new Class(err.message, err.code, err.type, err.data);
case "MoleculerClientError": return new Class(err.message, err.code, err.type, err.data);
case "ValidationError": return new Class(err.message, err.type, err.data);
case "ServiceNotFoundError": return new Class(err.data);
case "ServiceNotAvailableError": return new Class(err.data);
case "RequestTimeoutError": return new Class(err.data);
case "RequestSkippedError": return new Class(err.data);
case "RequestRejectedError": return new Class(err.data);
case "QueueIsFullError": return new Class(err.data);
case "MaxCallLevelError": return new Class(err.data);
case "GracefulStopTimeoutError": return new Class(err.data);
case "ProtocolVersionMismatchError": return new Class(err.data);
case "InvalidPacketDataError": return new Class(err.data);
case "ServiceSchemaError":
case "BrokerOptionsError": return new Class(err.message, err.data);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q19771
|
paramConverterMiddleware
|
train
|
function paramConverterMiddleware(handler, action) {
function convertProperties(obj, schema) {
Object.keys(schema).forEach(key => {
const s = schema[key];
const val = obj[key];
if (val == null)
return;
if (s.type == "string" && typeof val !== "string") {
obj[key] = "" + val;
} else if (s.type == "number" && typeof val !== "number") {
obj[key] = Number(val);
} else if (s.type == "boolean" && typeof val !== "boolean") {
obj[key] = String(val).toLowerCase() === "true";
} else if (s.type == "date" && !(val instanceof Date)) {
obj[key] = new Date(val);
} else if (s.type == "object")
convertProperties(val, s.props);
});
}
// Wrap a param validator
if (action.params && typeof action.params === "object") {
return function convertContextParams(ctx) {
convertProperties(ctx.params, action.params);
return handler(ctx);
};
}
return handler;
}
|
javascript
|
{
"resource": ""
}
|
q19772
|
createBrokers
|
train
|
function createBrokers(transporter) {
let b1 = new ServiceBroker({
transporter,
//requestTimeout: 0,
logger: false,
//logLevel: "debug",
nodeID: "node-1"
});
let b2 = new ServiceBroker({
transporter,
//requestTimeout: 0,
logger: false,
//logLevel: "debug",
nodeID: "node-2"
});
b2.createService({
name: "echo",
actions: {
reply(ctx) {
return ctx.params;
}
}
});
return Promise.all([
b1.start(),
b2.start()
]).then(() => [b1, b2]);
}
|
javascript
|
{
"resource": ""
}
|
q19773
|
processFlags
|
train
|
function processFlags() {
Args
.option("config", "Load the configuration from a file")
.option("repl", "Start REPL mode", false)
.option(["H", "hot"], "Hot reload services if changed", false)
.option("silent", "Silent mode. No logger", false)
.option("env", "Load .env file from the current directory")
.option("envfile", "Load a specified .env file")
.option("instances", "Launch [number] instances node (load balanced)")
.option("mask", "Filemask for service loading");
flags = Args.parse(process.argv, {
mri: {
alias: {
c: "config",
r: "repl",
H: "hot",
s: "silent",
e: "env",
E: "envfile",
i: "instances",
m: "mask"
},
boolean: ["repl", "silent", "hot", "env"],
string: ["config", "envfile", "mask"]
}
});
servicePaths = Args.sub;
}
|
javascript
|
{
"resource": ""
}
|
q19774
|
loadEnvFile
|
train
|
function loadEnvFile() {
if (flags.env || flags.envfile) {
try {
const dotenv = require("dotenv");
if (flags.envfile)
dotenv.config({ path: flags.envfile });
else
dotenv.config();
} catch(err) {
throw new Error("The 'dotenv' package is missing! Please install it with 'npm install dotenv --save' command.");
}
}
}
|
javascript
|
{
"resource": ""
}
|
q19775
|
mergeOptions
|
train
|
function mergeOptions() {
config = _.defaultsDeep(configFile, Moleculer.ServiceBroker.defaultOptions);
if (config.logger == null && !flags.silent)
config.logger = console;
function normalizeEnvValue(value) {
if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
// Convert to boolean
value = value === "true";
} else if (!isNaN(value)) {
// Convert to number
value = Number(value);
}
return value;
}
function overwriteFromEnv(obj, prefix) {
Object.keys(obj).forEach(key => {
const envName = ((prefix ? prefix + "_" : "") + key).toUpperCase();
if (process.env[envName]) {
obj[key] = normalizeEnvValue(process.env[envName]);
}
if (_.isPlainObject(obj[key]))
obj[key] = overwriteFromEnv(obj[key], (prefix ? prefix + "_" : "") + key);
});
const moleculerPrefix = "MOL_";
Object.keys(process.env)
.filter(key => key.startsWith(moleculerPrefix))
.map(key => ({
key,
withoutPrefix: key.substr(moleculerPrefix.length)
}))
.forEach(variable => {
const dotted = variable.withoutPrefix
.split("__")
.map(level => level.toLocaleLowerCase())
.map(level =>
level
.split("_")
.map((value, index) => {
if (index == 0) {
return value;
} else {
return value[0].toUpperCase() + value.substring(1);
}
})
.join("")
)
.join(".");
obj = utils.dotSet(obj, dotted, normalizeEnvValue(process.env[variable.key]));
});
return obj;
}
config = overwriteFromEnv(config);
if (flags.silent) {
config.logger = null;
}
if (flags.hot) {
config.hotReload = true;
}
//console.log("Config", config);
}
|
javascript
|
{
"resource": ""
}
|
q19776
|
loadServices
|
train
|
function loadServices() {
const fileMask = flags.mask || "**/*.service.js";
const serviceDir = process.env.SERVICEDIR || "";
const svcDir = path.isAbsolute(serviceDir) ? serviceDir : path.resolve(process.cwd(), serviceDir);
let patterns = servicePaths;
if (process.env.SERVICES || process.env.SERVICEDIR) {
if (isDirectory(svcDir) && !process.env.SERVICES) {
// Load all services from directory (from subfolders too)
broker.loadServices(svcDir, fileMask);
} else if (process.env.SERVICES) {
// Load services from env list
patterns = Array.isArray(process.env.SERVICES) ? process.env.SERVICES : process.env.SERVICES.split(",");
}
}
if (patterns.length > 0) {
let serviceFiles = [];
patterns.map(s => s.trim()).forEach(p => {
const skipping = p[0] == "!";
if (skipping)
p = p.slice(1);
if (p.startsWith("npm:")) {
// Load NPM module
loadNpmModule(p.slice(4));
} else {
let files;
const svcPath = path.isAbsolute(p) ? p : path.resolve(svcDir, p);
// Check is it a directory?
if (isDirectory(svcPath)) {
files = glob(svcPath + "/" + fileMask, { absolute: true });
if (files.length == 0)
return broker.logger.warn(chalk.yellow.bold(`There is no service files in directory: '${svcPath}'`));
} else if (isServiceFile(svcPath)) {
files = [svcPath.replace(/\\/g, "/")];
} else if (isServiceFile(svcPath + ".service.js")) {
files = [svcPath.replace(/\\/g, "/") + ".service.js"];
} else {
// Load with glob
files = glob(p, { cwd: svcDir, absolute: true });
if (files.length == 0)
broker.logger.warn(chalk.yellow.bold(`There is no matched file for pattern: '${p}'`));
}
if (files && files.length > 0) {
if (skipping)
serviceFiles = serviceFiles.filter(f => files.indexOf(f) === -1);
else
serviceFiles.push(...files);
}
}
});
_.uniq(serviceFiles).forEach(f => broker.loadService(f));
}
}
|
javascript
|
{
"resource": ""
}
|
q19777
|
startBroker
|
train
|
function startBroker() {
let worker = cluster.worker;
if (worker) {
Object.assign(config, {
nodeID: (config.nodeID || utils.getNodeID()) + "-" + worker.id
});
}
// Create service broker
broker = new Moleculer.ServiceBroker(Object.assign({}, config));
loadServices();
return broker.start()
.then(() => {
if (flags.repl && (!worker || worker.id === 1))
broker.repl();
});
}
|
javascript
|
{
"resource": ""
}
|
q19778
|
resetStore
|
train
|
function resetStore() {
if (!logger) return;
logger.debug("Reset circuit-breaker endpoint states...");
store.forEach((item, key) => {
if (item.count == 0) {
logger.debug(`Remove '${key}' endpoint state because it is not used`);
store.delete(key);
return;
}
logger.debug(`Clean '${key}' endpoint state.`);
item.count = 0;
item.failures = 0;
});
}
|
javascript
|
{
"resource": ""
}
|
q19779
|
getEpState
|
train
|
function getEpState(ep, opts) {
let item = store.get(ep.name);
if (!item) {
item = {
ep,
opts,
count: 0,
failures: 0,
state: C.CIRCUIT_CLOSE,
cbTimer: null
};
store.set(ep.name, item);
}
return item;
}
|
javascript
|
{
"resource": ""
}
|
q19780
|
failure
|
train
|
function failure(item, err, ctx) {
item.count++;
item.failures++;
checkThreshold(item, ctx);
}
|
javascript
|
{
"resource": ""
}
|
q19781
|
success
|
train
|
function success(item, ctx) {
item.count++;
if (item.state === C.CIRCUIT_HALF_OPEN_WAIT)
circuitClose(item, ctx);
else
checkThreshold(item, ctx);
}
|
javascript
|
{
"resource": ""
}
|
q19782
|
checkThreshold
|
train
|
function checkThreshold(item, ctx) {
if (item.count >= item.opts.minRequestCount) {
const rate = item.failures / item.count;
if (rate >= item.opts.threshold)
trip(item, ctx);
}
}
|
javascript
|
{
"resource": ""
}
|
q19783
|
trip
|
train
|
function trip(item, ctx) {
item.state = C.CIRCUIT_OPEN;
item.ep.state = false;
if (item.cbTimer) {
clearTimeout(item.cbTimer);
item.cbTimer = null;
}
item.cbTimer = setTimeout(() => halfOpen(item, ctx), item.opts.halfOpenTime);
item.cbTimer.unref();
const rate = item.count > 0 ? item.failures / item.count : 0;
logger.debug(`Circuit breaker has been opened on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name, failures: item.failures, count: item.count, rate });
broker.broadcast("$circuit-breaker.opened", { nodeID: item.ep.id, action: item.ep.action.name, failures: item.failures, count: item.count, rate });
}
|
javascript
|
{
"resource": ""
}
|
q19784
|
halfOpen
|
train
|
function halfOpen(item) {
item.state = C.CIRCUIT_HALF_OPEN;
item.ep.state = true;
logger.debug(`Circuit breaker has been half-opened on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name });
broker.broadcast("$circuit-breaker.half-opened", { nodeID: item.ep.id, action: item.ep.action.name });
if (item.cbTimer) {
clearTimeout(item.cbTimer);
item.cbTimer = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q19785
|
halfOpenWait
|
train
|
function halfOpenWait(item, ctx) {
item.state = C.CIRCUIT_HALF_OPEN_WAIT;
item.ep.state = false;
// Anti-stick protection
item.cbTimer = setTimeout(() => halfOpen(item, ctx), item.opts.halfOpenTime);
item.cbTimer.unref();
}
|
javascript
|
{
"resource": ""
}
|
q19786
|
circuitClose
|
train
|
function circuitClose(item) {
item.state = C.CIRCUIT_CLOSE;
item.ep.state = true;
item.failures = 0;
item.count = 0;
logger.debug(`Circuit breaker has been closed on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name });
broker.broadcast("$circuit-breaker.closed", { nodeID: item.ep.id, action: item.ep.action.name });
if (item.cbTimer) {
clearTimeout(item.cbTimer);
item.cbTimer = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q19787
|
wrapCBMiddleware
|
train
|
function wrapCBMiddleware(handler, action) {
// Merge action option and broker options
const opts = Object.assign({}, this.options.circuitBreaker || {}, action.circuitBreaker || {});
if (opts.enabled) {
return function circuitBreakerMiddleware(ctx) {
// Get endpoint state item
const ep = ctx.endpoint;
const item = getEpState(ep, opts);
// Handle half-open state in circuit breaker
if (item.state == C.CIRCUIT_HALF_OPEN) {
halfOpenWait(item, ctx);
}
// Call the handler
return handler(ctx).then(res => {
const item = getEpState(ep, opts);
success(item, ctx);
return res;
}).catch(err => {
if (opts.check && opts.check(err)) {
// Failure if error is created locally (not came from a 3rd node error)
if (item && (!err.nodeID || err.nodeID == ctx.nodeID)) {
const item = getEpState(ep, opts);
failure(item, err, ctx);
}
}
return this.Promise.reject(err);
});
}.bind(this);
}
return handler;
}
|
javascript
|
{
"resource": ""
}
|
q19788
|
train
|
function (value, options, callback) {
/**
* The post collection load handler.
*
* @param {?Error} err - An Error instance / null, passed from the collection loader.
* @param {Object} collection - The collection / raw JSON object, passed from the collection loader.
* @returns {*}
*/
var done = function (err, collection) {
if (err) {
return callback(err);
}
// ensure that the collection option is present before starting a run
if (!_.isObject(collection)) {
return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE));
}
// ensure that the collection reference is an SDK instance
// @todo - should this be handled by config loaders?
collection = new Collection(Collection.isCollection(collection) ?
// if the option contain an instance of collection, we simply clone it for future use
// create a collection in case it is not one. user can send v2 JSON as a source and that will be
// converted to a collection
collection.toJSON() : collection);
callback(null, collection);
};
// if the collection has been specified as an object, convert to V2 if necessary and return the result
if (_.isObject(value)) {
return processCollection(value, done);
}
externalLoader('collection', value, options, function (err, data) {
if (err) {
return done(err);
}
if (!_.isObject(data)) {
return done(new Error(COLLECTION_LOAD_ERROR_MESSAGE));
}
return processCollection(data, done);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q19789
|
train
|
function (err, collection) {
if (err) {
return callback(err);
}
// ensure that the collection option is present before starting a run
if (!_.isObject(collection)) {
return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE));
}
// ensure that the collection reference is an SDK instance
// @todo - should this be handled by config loaders?
collection = new Collection(Collection.isCollection(collection) ?
// if the option contain an instance of collection, we simply clone it for future use
// create a collection in case it is not one. user can send v2 JSON as a source and that will be
// converted to a collection
collection.toJSON() : collection);
callback(null, collection);
}
|
javascript
|
{
"resource": ""
}
|
|
q19790
|
train
|
function (value, options, callback) {
if (!value.length) {
return callback(); // avoids empty string or array
}
if (Array.isArray(value) && value.length === 1) {
return callback(null, value[0]); // avoids using multipleIdOrName strategy for a single item array
}
callback(null, value);
}
|
javascript
|
{
"resource": ""
}
|
|
q19791
|
train
|
function (location, options, callback) {
if (_.isArray(location)) { return callback(null, location); }
util.fetch(location, function (err, data) {
if (err) {
return callback(err);
}
// Try loading as a JSON, fall-back to CSV. @todo: switch to file extension based loading.
async.waterfall([
(cb) => {
try {
return cb(null, liquidJSON.parse(data.trim()));
}
catch (e) {
return cb(null, undefined); // e masked to avoid displaying JSON parse errors for CSV files
}
},
(json, cb) => {
if (json) {
return cb(null, json);
}
// Wasn't JSON
parseCsv(data, {
columns: true,
escape: '\\',
cast: csvAutoParse,
trim: true
}, cb);
}
], (err, parsed) => {
if (err) {
// todo: Log meaningful stuff here
return callback(err);
}
callback(null, parsed);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q19792
|
train
|
function (next) {
console.info(colors.yellow.bold('Generating and publishing documentation for postman-collection'));
try {
// go to the out directory and create a *new* Git repo
cd('out/docs');
exec('git init');
// inside this git repo we'll pretend to be a new user
// @todo - is this change perpetual?
exec('git config user.name "Doc Publisher"');
exec('git config user.email "autocommit@postmanlabs.com"');
// The first and only commit to this new Git repo contains all the
// files present with the commit message "Deploy to GitHub Pages".
exec('git add .');
exec('git commit -m "Deploy to GitHub Pages"');
}
catch (e) {
console.error(e.stack || e);
return next(e ? 1 : 0);
}
// Force push from the current repo's master branch to the remote
// repo's gh-pages branch. (All previous history on the gh-pages branch
// will be lost, since we are overwriting it.) We silence any output to
// hide any sensitive credential data that might otherwise be exposed.
config.silent = true; // this is apparently reset after exec
exec('git push --force "git@github.com:postmanlabs/newman.git" master:gh-pages', next);
}
|
javascript
|
{
"resource": ""
}
|
|
q19793
|
train
|
function (color) {
return (color === 'off') || (color !== 'on') &&
(Boolean(process.env.CI) || !process.stdout.isTTY); // eslint-disable-line no-process-env
}
|
javascript
|
{
"resource": ""
}
|
|
q19794
|
train
|
function (runOptions) {
var dimension = cliUtils.dimension(),
options = {
depth: 25,
maxArrayLength: 100, // only supported in Node v6.1.0 and up: https://github.com/nodejs/node/pull/6334
colors: !cliUtils.noTTY(runOptions.color),
// note that similar dimension calculation is in utils.wrapper
// only supported in Node v6.3.0 and above: https://github.com/nodejs/node/pull/7499
breakLength: ((dimension.exists && (dimension.width > 20)) ? dimension.width : 60) - 16
};
return function (item) {
return inspect(item, options);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q19795
|
train
|
function () {
var dimension = cliUtils.dimension(),
// note that similar dimension calculation is in utils.wrapper
width = ((dimension.exists && (dimension.width > 20)) ? dimension.width : 60) - 6;
return function (text, indent) {
return wrap(text, {
indent: indent,
width: width,
cut: true
});
};
}
|
javascript
|
{
"resource": ""
}
|
|
q19796
|
train
|
function () {
var tty,
width,
height;
try { tty = require('tty'); }
catch (e) { tty = null; }
if (tty && tty.isatty(1) && tty.isatty(2)) {
if (process.stdout.getWindowSize) {
width = process.stdout.getWindowSize(1)[0];
height = process.stdout.getWindowSize(1)[1];
}
else if (tty.getWindowSize) {
width = tty.getWindowSize()[1];
height = tty.getWindowSize()[0];
}
else if (process.stdout.columns && process.stdout.rows) {
height = process.stdout.rows;
width = process.stdout.columns;
}
}
return {
exists: !(Boolean(process.env.CI) || !process.stdout.isTTY), // eslint-disable-line no-process-env
width: width,
height: height
};
}
|
javascript
|
{
"resource": ""
}
|
|
q19797
|
createRawEchoServer
|
train
|
function createRawEchoServer () {
var server;
server = net.createServer(function (socket) {
socket.on('data', function (chunk) {
if (this.data === undefined) {
this.data = '';
setTimeout(() => {
// Status Line
socket.write('HTTP/1.1 200 ok\r\n');
// Response Headers
socket.write('connection: close\r\n');
socket.write('content-type: text/plain\r\n');
socket.write('raw-request: ' + JSON.stringify(this.data) + '\r\n');
// CRLF
socket.write('\r\n');
// Response Body
if (!this.data.startsWith('HEAD / HTTP/1.1')) {
socket.write(this.data);
}
socket.end();
}, 1000);
}
this.data += chunk.toString();
});
});
server.on('listening', function () {
server.port = this.address().port;
});
enableServerDestroy(server);
return server;
}
|
javascript
|
{
"resource": ""
}
|
q19798
|
defaultGetDefaultFieldNames
|
train
|
function defaultGetDefaultFieldNames(type) {
// If this type cannot access fields, then return an empty set.
if (!type.getFields) {
return [];
}
const fields = type.getFields();
// Is there an `id` field?
if (fields['id']) {
return ['id'];
}
// Is there an `edges` field?
if (fields['edges']) {
return ['edges'];
}
// Is there an `node` field?
if (fields['node']) {
return ['node'];
}
// Include all leaf-type fields.
const leafFieldNames = [];
Object.keys(fields).forEach(fieldName => {
if (isLeafType(fields[fieldName].type)) {
leafFieldNames.push(fieldName);
}
});
return leafFieldNames;
}
|
javascript
|
{
"resource": ""
}
|
q19799
|
buildSelectionSet
|
train
|
function buildSelectionSet(type, getDefaultFieldNames) {
// Unwrap any non-null or list types.
const namedType = getNamedType(type);
// Unknown types and leaf types do not have selection sets.
if (!type || isLeafType(type)) {
return;
}
// Get an array of field names to use.
const fieldNames = getDefaultFieldNames(namedType);
// If there are no field names to use, return no selection set.
if (!Array.isArray(fieldNames) || fieldNames.length === 0) {
return;
}
// Build a selection set of each field, calling buildSelectionSet recursively.
return {
kind: 'SelectionSet',
selections: fieldNames.map(fieldName => {
const fieldDef = namedType.getFields()[fieldName];
const fieldType = fieldDef ? fieldDef.type : null;
return {
kind: 'Field',
name: {
kind: 'Name',
value: fieldName,
},
selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames),
};
}),
};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.