_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q44000 | train | function() {
var context = this.breakContext;
var forkContext = this.forkContext;
this.breakContext = context.upper;
// Process this context here for other than switches and loops.
if (!context.breakable) {
var brokenForkContext = context.brokenForkContext;
if (!brokenForkContext.empty) {
brokenForkContext.add(forkContext.head);
forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
}
}
return context;
} | javascript | {
"resource": ""
} | |
q44001 | train | function(label) {
var forkContext = this.forkContext;
if (!forkContext.reachable) {
return;
}
var context = getBreakContext(this, label);
/* istanbul ignore else: foolproof (syntax error) */
if (context) {
context.brokenForkContext.add(forkContext.head);
}
forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
} | javascript | {
"resource": ""
} | |
q44002 | train | function(label) {
var forkContext = this.forkContext;
if (!forkContext.reachable) {
return;
}
var context = getContinueContext(this, label);
/* istanbul ignore else: foolproof (syntax error) */
if (context) {
if (context.continueDestSegments) {
makeLooped(this, forkContext.head, context.continueDestSegments);
// If the context is a for-in/of loop, this effects a break also.
if (context.type === "ForInStatement" ||
context.type === "ForOfStatement"
) {
context.brokenForkContext.add(forkContext.head);
}
} else {
context.continueForkContext.add(forkContext.head);
}
}
forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
} | javascript | {
"resource": ""
} | |
q44003 | train | function() {
var forkContext = this.forkContext;
if (forkContext.reachable) {
getReturnContext(this).returnedForkContext.add(forkContext.head);
forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
}
} | javascript | {
"resource": ""
} | |
q44004 | train | function() {
var forkContext = this.forkContext;
if (forkContext.reachable) {
getThrowContext(this).thrownForkContext.add(forkContext.head);
forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
}
} | javascript | {
"resource": ""
} | |
q44005 | train | function(children) {
var attempt = 0;
var uniqueName = prefix;
// find a unique name for the new artifact
var possiblyCollidingNames = children.filter(function(child){
return 0 === child.Name.indexOf(prefix);
}).map(function(child){
return child.Name;
});
while (-1 !== possiblyCollidingNames.indexOf(uniqueName)){
attempt++;
uniqueName = prefix.concat(" (").concat(attempt).concat(")"); //$NON-NLS-1$ //$NON-NLS-0$
}
return uniqueName;
} | javascript | {
"resource": ""
} | |
q44006 | createNewArtifact | train | function createNewArtifact(namePrefix, parentItem, isDirectory) {
var createFunction = function(name) {
if (name) {
var location = parentItem.Location;
var functionName = isDirectory ? "createFolder" : "createFile";
var deferred = fileClient[functionName](location, name, {select: true});
progressService.showWhile(deferred, i18nUtil.formatMessage(messages["Creating ${0}"], name)).then(
function(newArtifact) {
},
function(error) {
if (error.status === 400 || error.status === 412) {
var resp = error.responseText;
if (typeof resp === "string") {
try {
resp = JSON.parse(resp);
resp.Message = i18nUtil.formatMessage(messages["FailedToCreateFile"], name);
error = resp;
} catch(error) {}
}
}
errorHandler(error);
}
);
}
};
createUniqueNameArtifact(parentItem, namePrefix, function(uniqueName){
getNewItemName(explorer, parentItem, explorer.getRow(parentItem), uniqueName, function(name) {
createFunction(name);
});
});
} | javascript | {
"resource": ""
} |
q44007 | train | function (annotationModel) {
if (this._annotationModel) {
this._annotationModel.removeEventListener("Changed", this._listener.onAnnotationModelChanged); //$NON-NLS-0$
}
this._annotationModel = annotationModel;
if (this._annotationModel) {
this._annotationModel.addEventListener("Changed", this._listener.onAnnotationModelChanged); //$NON-NLS-0$
}
} | javascript | {
"resource": ""
} | |
q44008 | train | function(lineIndex, e) {
var tooltip = mTooltip.Tooltip.getTooltip(this._view);
if (!tooltip) { return; }
if (tooltip.isVisible() && this._tooltipLineIndex === lineIndex) { return; }
this._tooltipLineIndex = lineIndex;
// Prevent spurious mouse event (e.g. on a scroll)
if (e.clientX === this._lastMouseX
&& e.clientY === this._lastMouseY) {
return;
}
this._lastMouseX = e.clientX;
this._lastMouseY = e.clientY;
if (this._hoverTimeout) {
window.clearTimeout(this._hoverTimeout);
this._hoverTimeout = null;
}
var target = e.target ? e.target : e.srcElement;
var bounds = target.getBoundingClientRect();
this._curElementBounds = Object.create(null);
this._curElementBounds.top = bounds.top;
this._curElementBounds.left = bounds.left;
this._curElementBounds.height = bounds.height;
this._curElementBounds.width = bounds.width;
// If we have the entire ruler selected, just use a 1 pixel high area in the ruler (Bug 463486)
if (target === this.node){
this._curElementBounds.top = e.clientY;
this._curElementBounds.height = 1;
}
var self = this;
self._hoverTimeout = window.setTimeout(function() {
self._hoverTimeout = null;
tooltip.onHover({
getTooltipInfo: function() {
var annotations = self._getAnnotationsAtLineIndex(self._tooltipLineIndex);
var content = self._getTooltipContents(self._tooltipLineIndex, annotations);
return self._getTooltipInfo(content, e.clientY, {source: "ruler", rulerLocation: self.getLocation()}); //$NON-NLS-0$
}
}, e.clientX, e.clientY);
}, 175);
} | javascript | {
"resource": ""
} | |
q44009 | train | function(lineIndex, e) {
if (!this._currentClickGroup) {
this._setCurrentGroup(-1);
}
if (this._hoverTimeout) {
window.clearTimeout(this._hoverTimeout);
this._hoverTimeout = null;
}
} | javascript | {
"resource": ""
} | |
q44010 | LineNumberRuler | train | function LineNumberRuler (annotationModel, rulerLocation, rulerStyle, oddStyle, evenStyle) {
Ruler.call(this, annotationModel, rulerLocation, "page", rulerStyle); //$NON-NLS-0$
this._oddStyle = oddStyle || {style: {backgroundColor: "white"}}; //$NON-NLS-0$
this._evenStyle = evenStyle || {style: {backgroundColor: "white"}}; //$NON-NLS-0$
this._numOfDigits = 0;
this._firstLine = 1;
} | javascript | {
"resource": ""
} |
q44011 | train | function(params) {
var result = [];
for (var i = 0; i < this._templateComponents.length; i++) {
result.push(this._templateComponents[i].expand(params));
}
return result.join("");
} | javascript | {
"resource": ""
} | |
q44012 | train | function(items, userData) {
var selfHostingConfig = this._siteClient.getSelfHostingConfig();
var self = this;
var dialog = new ConvertToSelfHostingDialog({
serviceRegistry: this.serviceRegistry,
fileClient: this.fileClient,
siteClient: this._siteClient,
selfHostingConfig: selfHostingConfig,
func: function(folderInfos) {
var folderLocations = folderInfos.map(function(folderInfo) {
return folderInfo.folder.Location;
});
self._siteClient.convertToSelfHosting(self.getSiteConfiguration(), folderLocations).then(
function(updatedSite) {
self.mappings.deleteAllMappings();
self.mappings.addMappings(updatedSite.Mappings);
self.save();
});
}
});
dialog.show();
} | javascript | {
"resource": ""
} | |
q44013 | train | function(location) {
var deferred = new Deferred();
this._busyWhile(deferred, messages["Loading..."]);
this._siteClient.loadSiteConfiguration(location).then(
function(siteConfig) {
this._setSiteConfiguration(siteConfig);
this.setDirty(false);
deferred.resolve(siteConfig);
}.bind(this),
function(error) {
deferred.reject(error);
});
return deferred;
} | javascript | {
"resource": ""
} | |
q44014 | train | function(site) {
this._detachListeners();
this._modelListeners = this._modelListeners || [];
var editor = this;
function bindText(widget, modelField) {
function commitWidgetValue(event) {
var value = widget.value; //$NON-NLS-0$
var oldValue = site[modelField];
site[modelField] = value;
var isChanged = oldValue !== value;
editor.setDirty(isChanged || editor.isDirty());
}
widget.addEventListener("input", commitWidgetValue); //$NON-NLS-0$
editor._modelListeners.push({target: widget, type: "input", listener: commitWidgetValue}); //$NON-NLS-0$
}
bindText(this.name, messages["Name"]);
bindText(this.hostHint, messages["HostHint"]);
var dirtyListener = function(dirtyEvent) {
editor.setDirty(dirtyEvent.value);
};
this.mappings.addEventListener("dirty", dirtyListener); //$NON-NLS-0$
this._modelListeners.push({target: this.mappings, type: "dirty", listener: dirtyListener}); //$NON-NLS-0$
} | javascript | {
"resource": ""
} | |
q44015 | train | function(refreshUI) {
refreshUI = typeof refreshUI === "undefined" ? true : refreshUI; //$NON-NLS-0$
var siteConfig = this._siteConfiguration;
// Omit the HostingStatus field from the object we send since it's likely to be updated from the
// sites page, and we don't want to overwrite
var status = siteConfig.HostingStatus;
delete siteConfig.HostingStatus;
var self = this;
var deferred = this._siteClient.updateSiteConfiguration(siteConfig.Location, siteConfig).then(
function(updatedSiteConfig) {
self.setDirty(false);
if (refreshUI) {
self._setSiteConfiguration(updatedSiteConfig);
return updatedSiteConfig;
} else {
siteConfig.HostingStatus = status;
self._refreshCommands();
return siteConfig;
}
});
this._busyWhile(deferred);
return true;
} | javascript | {
"resource": ""
} | |
q44016 | RichDropdown | train | function RichDropdown(options) {
this._parentNode = options.parentNode;
this._buttonName = options.buttonName;
this._id = options.id || "dropDown";
this._buttonDecorator = options.buttonDecorator;
this._populateFunction = options.populateFunction;
this._noDropdownArrow = options.noDropdownArrow;
this._initialize();
} | javascript | {
"resource": ""
} |
q44017 | train | function(name, decorator, title) {
var titleText = title || ""; //$NON-NLS-0$
lib.empty(this._dropdownTriggerButtonLabel);
if (decorator) {
this._dropdownTriggerButtonLabel.appendChild(decorator);
}
var nameNode = document.createTextNode(name);
this._dropdownTriggerButtonLabel.appendChild(nameNode);
this._dropdownTriggerButton.title = titleText;
} | javascript | {
"resource": ""
} | |
q44018 | train | function(labelNode) {
labelNode.id = this._dropdownTriggerButtonLabel.id;
this._dropdownTriggerButton.replaceChild(labelNode, this._dropdownTriggerButtonLabel);
this._dropdownTriggerButtonLabel = labelNode;
} | javascript | {
"resource": ""
} | |
q44019 | train | function() {
if (this._dropdownTriggerButton) {
if (this._dropdownTriggerButton.dropdown) {
this._dropdownTriggerButton.dropdown.destroy();
this._dropdownTriggerButton.dropdown = null;
}
this._dropdownTriggerButton = null;
}
} | javascript | {
"resource": ""
} | |
q44020 | train | function(msg, onDone, node, title) {
if(node){
this._commandRegistry.confirmWithButtons(node, msg,[{label:"OK",callback:function(){
onDone(true);
},type:"ok"},{label:"Cancel",callback:function(){
onDone(false);
},type:"cancel"}]);
}else{
var dialog = new mConfirmDialog.ConfirmDialog({
confirmMessage: msg,
title: title || messages.Confirm
});
dialog.show();
var _self = this;
dialog.addEventListener("dismiss", function(event) {
if (event.value === true) {
onDone(true);
}else if(event.value === false){
onDone(false);
}
});
}
} | javascript | {
"resource": ""
} | |
q44021 | CollabClient | train | function CollabClient(editor, inputManager, fileClient, serviceRegistry, commandRegistry, preferences) {
mCollabFileCommands.createFileCommands(serviceRegistry, commandRegistry, fileClient);
this.editor = editor;
this.inputManager = inputManager;
this.fileClient = fileClient;
this.preferences = preferences;
this.textView = this.editor.getTextView();
var self = this;
this.collabMode = false;
this.clientId = '';
this.clientDisplayedName = '';
this.fileClient.addEventListener('Changed', self.sendFileOperation.bind(self));
this.serviceRegistry = serviceRegistry;
this.editor.addEventListener('InputContentsSet', function(event) {self.viewInstalled.call(self, event);});
this.editor.addEventListener('TextViewUninstalled', function(event) {self.viewUninstalled.call(self, event);});
this.projectSessionID = '';
this.inputManager.addEventListener('InputChanged', function(e) {
self.onInputChanged(e)
});
this.ot = null;
this.otOrionAdapter = null;
this.otSocketAdapter = null;
this.socketReconnectAttempt = 0;
this.socketIntentionalyClosing = false;
this.socketPingTimeout = 0;
this.awaitingClients = false;
this.collabFileAnnotations = {};
// Timeout id to indicate whether a delayed update has already been assigned
this.collabFileAnnotationsUpdateTimeoutId = 0;
/**
* A map of clientid -> peer
* @type {Object.<string, CollabPeer>}
*/
this.peers = {};
this.editing = false;
this.guid = guid;
// Initialize current project
var file = this.inputManager.getInput();
var metadata = this.inputManager.getFileMetadata();
if (metadata) {
this.onInputChanged({
metadata: metadata,
input: {
resource: file
}
});
}
} | javascript | {
"resource": ""
} |
q44022 | train | function(callback) {
var self = this;
var userService = this.serviceRegistry.getService("orion.core.user");
var authServices = this.serviceRegistry.getServiceReferences("orion.core.auth");
var authService = this.serviceRegistry.getService(authServices[0]);
authService.getUser().then(function(jsonData) {
userService.getUserInfo(contextPath + jsonData.Location).then(function(accountData) {
var username = accountData.UserName;
self.clientDisplayedName = accountData.FullName || username;
var MASK = 0xFFFFFF + 1;
var MAGIC = 161803398 / 2 % MASK;
self.clientId = username + '.' + guid.substr(0, 4);
callback();
}, function(err) {
console.error(err);
});
});
} | javascript | {
"resource": ""
} | |
q44023 | train | function(e) {
this.location = e.input.resource;
this.updateSelfFileAnnotation();
this.destroyOT();
this.sendCurrentLocation();
if (e.metadata.Attributes) {
var projectSessionID = e.metadata.Attributes.hubID;
if (this.projectSessionID !== projectSessionID) {
this.projectSessionID = projectSessionID;
this.projectChanged(projectSessionID);
}
}
} | javascript | {
"resource": ""
} | |
q44024 | train | function(clientId, contextP, url, editing) {
var peer = this.getPeer(clientId);
// Peer might be loading. Once it is loaded, this annotation will be automatically updated,
// so we can safely leave it blank.
var name = (peer && peer.name) ? peer.name : 'Unknown';
var color = (peer && peer.color) ? peer.color : '#000000';
if (url) {
url = contextP + this.getFileSystemPrefix() + url;
}
this.collabFileAnnotations[clientId] = new CollabFileAnnotation(name, color, url, this.projectRelativeLocation(url), editing);
this._requestFileAnnotationUpdate();
} | javascript | {
"resource": ""
} | |
q44025 | train | function() {
var self = this;
if (!this.collabFileAnnotationsUpdateTimeoutId) {
// No delayed update is assigned. Assign one.
// This is necessary because we don't want duplicate UI action within a short period.
this.collabFileAnnotationsUpdateTimeoutId = setTimeout(function() {
self.collabFileAnnotationsUpdateTimeoutId = 0;
var annotations = [];
var editingFileUsers = {}; // map from location to list of usernames indicating all users that are typing on this file
for (var key in self.collabFileAnnotations) {
if (self.collabFileAnnotations.hasOwnProperty(key)) {
var annotation = self.collabFileAnnotations[key];
annotations.push(annotation);
if (annotation.editing) {
if (!editingFileUsers[annotation.location]) {
editingFileUsers[annotation.location] = [];
}
editingFileUsers[annotation.location].push(annotation.name);
}
}
}
// Add editing annotations
for (var location in editingFileUsers) {
if (editingFileUsers.hasOwnProperty(location)) {
annotations.push(new CollabFileEditingAnnotation(location, editingFileUsers[location]));
}
}
self.fileClient.dispatchEvent({
type: 'AnnotationChanged',
removeTypes: [CollabFileAnnotation],
annotations: annotations
});
}, COLLABORATOR_ANNOTATION_UPDATE_DELAY);
}
} | javascript | {
"resource": ""
} | |
q44026 | train | function(peer) {
if (this.peers[peer.id]) {
// Update
this.peers[peer.id] = peer;
} else {
// Add
this.peers[peer.id] = peer;
}
if (this.collabHasFileAnnotation(peer.id)) {
var annotation = this.getCollabFileAnnotation(peer.id);
this.addOrUpdateCollabFileAnnotation(peer.id, contextPath, annotation.location);
}
if (this.otOrionAdapter && this.textView) {
// Make sure we have view installed
this.otOrionAdapter.updateLineAnnotationStyle(peer.id);
}
} | javascript | {
"resource": ""
} | |
q44027 | train | function(syntaxChecker, timeout) {
var time = timeout;
if (!syntaxChecker){
time = -1;
}
this._autoSyntaxEnabled = time !== -1;
this._autoSyntaxActive = false;
if (!this._idle2) {
var options = {
document: document,
timeout: time
};
this._idle2 = new Idle(options);
this._idle2.addEventListener("Idle", function () { //$NON-NLS-0$
if (this.editor){
this._autoSyntaxActive = true;
if (this.editor._isSyntaxCheckRequired()){
syntaxChecker();
this.editor._setSyntaxCheckRequired(false);
this._autoSyntaxActive = false;
}
}
}.bind(this));
} else {
this._idle2.setTimeout(time);
}
} | javascript | {
"resource": ""
} | |
q44028 | getBidiLayout | train | function getBidiLayout() {
var _bidiLayout = localStorage.getItem(bidiLayoutStorage);
if (_bidiLayout && (_bidiLayout === "rtl" || _bidiLayout === "ltr" || _bidiLayout === "auto")) { //$NON-NLS-0$ //$NON-NLS-1$ //$NON-NLS-2$
return _bidiLayout;
}
return "ltr"; //$NON-NLS-0$
} | javascript | {
"resource": ""
} |
q44029 | getTextDirection | train | function getTextDirection(text) {
bidiLayout = getBidiLayout();
if (!isBidiEnabled()) {
return "";
}
if (bidiLayout === "auto" && util.isIE) { //$NON-NLS-0$
return checkContextual(text);
}
return bidiLayout;
} | javascript | {
"resource": ""
} |
q44030 | foundNestedPseudoClass | train | function foundNestedPseudoClass() {
var openParen = 0;
for (var i = pos + 1; i < source_text.length; i++) {
var ch = source_text.charAt(i);
if (ch === "{") {
return true;
} else if (ch === '(') {
// pseudoclasses can contain ()
openParen += 1;
} else if (ch === ')') {
if (openParen === 0) {
return false;
}
openParen -= 1;
} else if (ch === ";" || ch === "}") {
return false;
}
}
return false;
} | javascript | {
"resource": ""
} |
q44031 | processURLSegments | train | function processURLSegments(parentNode, segments) {
segments.forEach(function(segment) {
if (segment.urlStr){
var link = document.createElement("a"); //$NON-NLS-0$
link.href = segment.urlStr;
link.appendChild(document.createTextNode(segment.segmentStr));
link.dir = bidiUtils.getTextDirection(segment.segmentStr);
parentNode.appendChild(link);
} else {
var plainText = document.createElement("span"); //$NON-NLS-0$
plainText.textContent = segment.segmentStr;
plainText.dir = bidiUtils.getTextDirection(segment.segmentStr);
parentNode.appendChild(plainText);
}
});
} | javascript | {
"resource": ""
} |
q44032 | empty | train | function empty(node) {
while (node && node.hasChildNodes()) {
var child = node.firstChild;
node.removeChild(child);
}
} | javascript | {
"resource": ""
} |
q44033 | onclick | train | function onclick(event) {
autoDismissNodes.forEach(function(autoDismissNode) {
var excludeNodeInDocument = false;
var excluded = autoDismissNode.excludeNodes.some(function(excludeNode) {
if(document.body.contains(excludeNode)) {
excludeNodeInDocument = true;
return excludeNode.contains(event.target);
}
return false;
});
if (excludeNodeInDocument && !excluded) {
try {
autoDismissNode.dismiss(event);
} catch (e) {
if (typeof console !== "undefined" && console) { //$NON-NLS-0$
console.error(e && e.message);
}
}
}
});
autoDismissNodes = autoDismissNodes.filter(function(autoDismissNode) {
// true if at least one excludeNode is in document.body
return autoDismissNode.excludeNodes.some(function(excludeNode) {
return document.body.contains(excludeNode);
});
});
} | javascript | {
"resource": ""
} |
q44034 | getOffsetParent | train | function getOffsetParent(node) {
var offsetParent = node.parentNode, documentElement = document.documentElement;
while (offsetParent && offsetParent !== documentElement) {
var style = window.getComputedStyle(offsetParent, null);
if (!style) { break; }
var overflow = style.getPropertyValue("overflow-y"); //$NON-NLS-0$
if (overflow === "auto" || overflow === "scroll") { break; } //$NON-NLS-1$ //$NON-NLS-0$
offsetParent = offsetParent.parentNode;
}
return offsetParent;
} | javascript | {
"resource": ""
} |
q44035 | stop | train | function stop(event) {
if (window.document.all) {
event.keyCode = 0;
}
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
}
} | javascript | {
"resource": ""
} |
q44036 | createNodes | train | function createNodes(templateString, parentNode) {
var parent = parentNode;
var newNodes = null;
if (undefined === parent) {
parent = document.createElement("div"); //$NON-NLS-0$
}
parent.innerHTML = templateString;
if (parent.children.length > 1) {
newNodes = parent.children;
} else {
newNodes = parent.firstChild;
}
return newNodes;
} | javascript | {
"resource": ""
} |
q44037 | train | function() {
var outputDiv = document.getElementsByClassName("gcli-output")[0]; //$NON-NLS-0$
while (outputDiv.hasChildNodes()) {
outputDiv.removeChild(outputDiv.lastChild);
}
this.output(i18nUtil.formatMessage(messages["AvailableCmdsType"], "<b>help</b>")); //$NON-NLS-0$
} | javascript | {
"resource": ""
} | |
q44038 | train | function(content) {
var output = new mCli.Output();
this.commandOutputManager.onOutput({output: output});
output.complete(content);
} | javascript | {
"resource": ""
} | |
q44039 | enterNode | train | function enterNode(node) {
var comments = this.sourceCode.getComments(node);
emitCommentsEnter(this, comments.leading);
this.original.enterNode(node);
emitCommentsEnter(this, comments.trailing);
} | javascript | {
"resource": ""
} |
q44040 | leaveNode | train | function leaveNode(node) {
var comments = this.sourceCode.getComments(node);
emitCommentsExit(this, comments.trailing);
this.original.leaveNode(node);
emitCommentsExit(this, comments.leading);
} | javascript | {
"resource": ""
} |
q44041 | train | function(proposal) {
if (!proposal) {
return false;
}
// now handle prefixes
// if there is a non-empty selection, then replace it,
// if overwrite is truthy, then also replace the prefix
var view = this.textView;
var sel = view.getSelection();
var start = this._initialCaretOffset;
var mapStart = start;
var end = Math.max(sel.start, sel.end), mapEnd = end;
var model = view.getModel();
if (model.getBaseModel) {
mapStart = model.mapOffset(mapStart);
mapEnd = model.mapOffset(mapEnd);
model = model.getBaseModel();
}
if (proposal.overwrite) {
if(typeof proposal.prefix === 'string') {
start = mapStart-proposal.prefix.length;
} else {
start = this.getPrefixStart(model, mapStart);
}
}
var data = {
proposal: proposal,
start: mapStart,
end: mapEnd
};
this.setState(State.INACTIVE);
var proposalText = typeof proposal === "string" ? proposal : proposal.proposal;
view.setText(proposalText, start, end);
if (proposal.additionalEdits) {
var edit;
for (var i = 0; i < proposal.additionalEdits.length; i++) {
edit = proposal.additionalEdits[i];
view.setText(edit.text, edit.offset, edit.offset + edit.length);
}
}
this.dispatchEvent({type: "ProposalApplied", data: data}); //$NON-NLS-0$
mMetrics.logEvent("contentAssist", "apply"); //$NON-NLS-1$ //$NON-NLS-0$
return true;
} | javascript | {
"resource": ""
} | |
q44042 | train | function() {
// figure out initial offset, it should be the minimum between
// the beginning of the selection and the current caret offset
var offset = this.textView.getCaretOffset();
var sel = this.textView.getSelection();
var selectionStart = Math.min(sel.start, sel.end);
this._initialCaretOffset = Math.min(offset, selectionStart);
this._computedProposals = null;
delete this._autoApply;
this._computeProposals(this._initialCaretOffset).then(function(proposals) {
if (this.isActive()) {
var flatProposalArray = this._flatten(proposals);
//check if flattened proposals form a valid array with at least one entry
if (flatProposalArray && Array.isArray(flatProposalArray) && (0 < flatProposalArray.length)) {
this._computedProposals = proposals;
}
var autoApply = typeof this._autoApply === 'boolean' ? this._autoApply : !this._autoTriggerEnabled;
this.dispatchEvent({type: "ProposalsComputed", data: {proposals: flatProposalArray}, autoApply: autoApply}); //$NON-NLS-0$
if (this._computedProposals && this._filterText) {
// force filtering here because user entered text after
// computeProposals() was called but before the plugins
// returned the computed proposals
this.filterProposals(true);
}
}
}.bind(this));
} | javascript | {
"resource": ""
} | |
q44043 | train | function(proposals) {
// get rid of extra separators and titles
var mappedProposals = proposals.map(function(proposalArray) {
var element = proposalArray.filter(function(proposal, index) {
var keepElement = true;
if (STYLES[proposal.style] === STYLES.hr) {
if ((0 === index) || ((proposalArray.length - 1) === index)) {
keepElement = false; // remove separators at first or last element
} else if (STYLES.hr === STYLES[proposalArray[index - 1].style]) {
keepElement = false; // remove separator preceeded by another separator
}
} else if (STYLES[proposal.style] === STYLES.noemphasis_title) {
var nextProposal = proposalArray[index + 1];
if (nextProposal) {
// remove titles that preceed other titles, all of their subelements have already been filtered out
if (STYLES[nextProposal.style] === STYLES.noemphasis_title) {
keepElement = false;
}
} else {
keepElement = false; //remove titles that are at the end of the array
}
}
return keepElement;
});
return element;
});
return mappedProposals;
} | javascript | {
"resource": ""
} | |
q44044 | train | function(arrayOrObjectArray) {
return arrayOrObjectArray.reduce(function(prev, curr) {
var returnValue = prev;
var filteredArray = null;
if (curr && Array.isArray(curr)) {
filteredArray = curr.filter(function(element){
return element; //filter out falsy elements
});
}
// add current proposal array to flattened array
// skip current elements that are not arrays
if (filteredArray && Array.isArray(filteredArray) && (filteredArray.length > 0)) {
var first = filteredArray;
var last = prev;
var filteredArrayStyle = filteredArray[0].style;
if (filteredArrayStyle && STYLES[filteredArrayStyle] && (0 === STYLES[filteredArrayStyle].indexOf(STYLES.noemphasis))) {
// the style of the first element starts with noemphasis
// add these proposals to the end of the array
first = prev;
last = filteredArray;
}
if (first.length > 0) {
var firstArrayStyle = first[first.length - 1].style;
if (firstArrayStyle && (STYLES.hr !== STYLES[firstArrayStyle])) {
// add separator between proposals from different providers
// if the previous array didn't already end with a separator
first = first.concat({
proposal: '',
name: '',
description: '---------------------------------', //$NON-NLS-0$
style: 'hr', //$NON-NLS-0$
unselectable: true
});
}
}
returnValue = first.concat(last);
}
return returnValue;
}, []);
} | javascript | {
"resource": ""
} | |
q44045 | train | function(update, noContent) {
var tooltip = mTooltip.Tooltip.getTooltip(this.contentAssist.textView);
var self = this;
var target = {
getTooltipInfo: function() {
var bounds = self.widget.parentNode.getBoundingClientRect();
var tipArea = {width: 350, height: bounds.height, top: bounds.top};
if ((bounds.left + bounds.width) >= document.documentElement.clientWidth){
tipArea.left = bounds.left - tipArea.width;
tipArea.left -= 10;
} else {
tipArea.left = bounds.left + bounds.width;
tipArea.left += 10;
}
var info = {
context: {proposal: self.proposals[self.selectedIndex]},
anchorArea: bounds,
tooltipArea: tipArea
};
return info;
}
};
if (update) {
tooltip.update(target, noContent);
} else {
tooltip.show(target, true, false);
}
} | javascript | {
"resource": ""
} | |
q44046 | train | function(cloneNode){
cloneNode.contentAssistProposalIndex = node.contentAssistProposalIndex;
if (cloneNode.hasChildNodes()) {
for (var i = 0 ; i < cloneNode.childNodes.length ; i++){
recursiveSetIndex(cloneNode.childNodes[i]);
}
}
} | javascript | {
"resource": ""
} | |
q44047 | train | function() {
if (this.model) {
this.model.removeEventListener("Changing", this.listener.onModelChanging);
this.model.removeEventListener("Changed", this.listener.onModelChanged);
this.model.removeEventListener("Destroy", this.listener.onDestroy);
}
this.model = null;
this.codeMirror = null;
this.mode = null;
this.lines = null;
this.dirtyLines = null;
clearTimeout(this.timer);
this.timer = null;
} | javascript | {
"resource": ""
} | |
q44048 | train | function(startLine, endLine, partial) {
if (!this.mode) {
return;
}
var lineCount = this.model.getLineCount();
startLine = typeof startLine === "undefined" ? 0 : startLine;
endLine = typeof endLine === "undefined" ? lineCount - 1 : Math.min(endLine, lineCount - 1);
var mode = this.mode;
var state = this.getState(startLine);
for (var i = startLine; i <= endLine; i++) {
var line = this.lines[i];
this.highlightLine(i, line, state);
line.eolState = this.codeMirror.copyState(mode, state);
}
// console.debug("Highlighted " + startLine + " to " + endLine);
this._expandRange(startLine, endLine);
if (!partial) {
this.onHighlightDone();
}
} | javascript | {
"resource": ""
} | |
q44049 | train | function(lineIndex, line, state) {
if (!this.mode) {
return;
}
var model = this.model;
if (model.getLineStart(lineIndex) === model.getLineEnd(lineIndex) && this.mode.blankLine) {
this.mode.blankLine(state);
}
var style = line.style || [];
var text = model.getLine(lineIndex);
var stream = new Stream(text);
var isChanged = !line.style;
var newStyle = [], ws;
for (var i=0; !stream.eol(); i++) {
var tok = this.mode.token(stream, state) || null;
var tokStr = stream.current();
ws = this._whitespaceStyle(tok, tokStr, stream.tokenStart);
if (ws) {
// TODO Replace this (null) token with whitespace tokens. Do something smart
// to figure out isChanged, I guess
}
var newS = [stream.tokenStart, stream.pos, tok]; // shape is [start, end, token]
var oldS = style[i];
newStyle.push(newS);
isChanged = isChanged || !oldS || oldS[0] !== newS[0] || oldS[1] !== newS[1] || oldS[2] !== newS[2];
stream.advance();
}
isChanged = isChanged || (newStyle.length !== style.length);
if (isChanged) { line.style = newStyle.length ? newStyle : null; }
return isChanged;
} | javascript | {
"resource": ""
} | |
q44050 | train | function(token, str, pos) {
if (!token && this.isWhitespaceVisible && /\s+/.test(str)) {
var whitespaceStyles = [], start, type;
for (var i=0; i < str.length; i++) {
var chr = str[i];
if (chr !== type) {
if (type) {
whitespaceStyles.push([pos + start, pos + i, (type === "\t" ? TAB : SPACE)]);
}
start = i;
type = chr;
}
}
whitespaceStyles.push([pos + start, pos + i, (type === "\t" ? TAB : SPACE)]);
return whitespaceStyles;
}
return null;
} | javascript | {
"resource": ""
} | |
q44051 | train | function() {
if (this.modeApplier) {
this.modeApplier.removeEventListener("Highlight", this.listener.onHighlight);
this.modeApplier.destroy();
}
if (this.annotationModel) {
// remove annotation listeners
}
if (this.textView) {
this.textView.removeEventListener("LineStyle", this.listener.onLineStyle);
this.textView.removeEventListener("Destroy", this.listener.onDestroy);
}
this.textView = null;
this.annotationModel = null;
this.modeApplier = null;
this.listener = null;
} | javascript | {
"resource": ""
} | |
q44052 | DiffProvider | train | function DiffProvider(serviceRegistry, filter) {
var allReferences = serviceRegistry.getServiceReferences("orion.core.diff"); //$NON-NLS-0$
var i, _references = allReferences;
if (filter) {
_references = [];
for(i = 0; i < allReferences.length; ++i) {
if (filter(allReferences[i])) {
_references.push(allReferences[i]);
}
}
}
var _patterns = [];
var _services = [];
for(i = 0; i < _references.length; ++i) {
_patterns[i] = new RegExp(_references[i].getProperty("pattern") || ".*");//$NON-NLS-1$ //$NON-NLS-0$
_services[i] = serviceRegistry.getService(_references[i]);
}
this._getService = function(location) {
location = _normalizeURL(location);
for(var i = 0; i < _patterns.length; ++i) {
if (_patterns[i].test(location)) {
return _services[i];
}
}
throw messages["NoDiffServiceLocationMatched"] + location;
};
} | javascript | {
"resource": ""
} |
q44053 | train | function(ast, offset) {
var found = null;
CssVisitor.visit(ast, {
visitNode: function(node) {
if(node.range[0] <= offset) {
if (node.range[1] === -1 || node.range[1] >= offset) {
found = node;
} else {
return Visitor.SKIP;
}
} else {
return Visitor.BREAK;
}
},
endVisitNode: function(node) {
}
});
return found;
} | javascript | {
"resource": ""
} | |
q44054 | getJavaHome | train | function getJavaHome() {
if(!java_home) {
if(typeof process.env.JAVA_HOME === 'string' && process.env.JAVA_HOME) {
java_home = process.env.JAVA_HOME;
} else if(process.platform === 'darwin') {
java_home = cp.execSync("/usr/libexec/java_home").toString().trim();
} else if(process.platform === 'linux') {
//TODO anything magical we can do here to compute the 'default' Java?
} else if(process.platform === 'win32') {
//TODO not sure Windows has any way to know where Java is installed
}
}
return java_home;
} | javascript | {
"resource": ""
} |
q44055 | runJavaServer | train | function runJavaServer(javaHome, options) {
return new Promise(function(resolve, reject) {
const child = path.join(javaHome, '/jre/bin/java'),
params = [];
if (DEBUG) {
params.push('-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044');
}
params.push("-Dlog.level=ALL");
params.push('-Declipse.application=org.eclipse.jdt.ls.core.id1');
params.push('-Dosgi.bundles.defaultStartLevel=4');
params.push('-Declipse.product=org.eclipse.jdt.ls.core.product');
if (DEBUG) {
params.push('-Dlog.protocol=true');
}
var pluginsFolder = path.resolve(__dirname, './plugins');
return fs.readdirAsync(pluginsFolder).then(function(files) {
if (Array.isArray(files) && files.length !== 0) {
for (var i = 0, length = files.length; i < length; i++) {
var file = files[i];
var indexOf = file.indexOf('org.eclipse.equinox.launcher_');
if (indexOf !== -1) {
params.push('-jar');
params.push(path.resolve(__dirname, './plugins/' + file));
//select configuration directory according to OS
var configDir = 'config_win';
if (process.platform === 'darwin') {
configDir = 'config_mac';
} else if (process.platform === 'linux') {
configDir = 'config_linux';
}
params.push('-configuration');
params.push(path.resolve(__dirname, configDir));
params.push('-data');
params.push(options.workspaceDir);
}
}
return fork(child, params, options).then((childProcess) => {
resolve(childProcess);
}, (err) => {
reject(err);
});
}
});
});
} | javascript | {
"resource": ""
} |
q44056 | fork | train | function fork(modulePath, args, options) {
return new Promise((resolve, reject) => {
const newEnv = generatePatchedEnv(process.env, options.IN_PORT, options.OUT_PORT),
childProcess = cp.spawn(modulePath, args, {
silent: true,
cwd: options.cwd,
env: newEnv,
execArgv: options.execArgv
});
childProcess.once('error', function(err) {
logger.error("Java process error event");
logger.error(err);
reject(err);
});
childProcess.once('exit', function(err) {
logger.error("Java process exit event");
logger.error(err);
reject(err);
});
resolve(childProcess);
});
} | javascript | {
"resource": ""
} |
q44057 | populateThemes | train | function populateThemes(){
this.preferences.getTheme(function(themeStyles) {
var selectElement = document.getElementById('editorTheme');//$NON-NLS-0$
while (selectElement.hasChildNodes() ){
selectElement.removeChild(selectElement.lastChild);
}
for (var i =0; i < themeStyles.styles.length; i++) {
var option = document.createElement('option');
option.setAttribute('value', themeStyles.styles[i].name);
//checks if a theme is the current theme
if (themeStyles.styles[i].name === themeStyles.style.name){
option.setAttribute('selected', 'true');
}
option.appendChild(document.createTextNode(themeStyles.styles[i].name));
selectElement.appendChild(option);
}
this.selectTheme(themeStyles.style.name);
}.bind(this));
} | javascript | {
"resource": ""
} |
q44058 | checkForChanges | train | function checkForChanges(){
var changed = false;
for (var i = 0; i < scopeList.length; i++){
// if a scope is modified
if (getValueFromPath(currentTheme, scopeList[i].objPath[0]) !== getValueFromPath(originalTheme, scopeList[i].objPath[0])){
document.getElementById("scopeList").childNodes[i].classList.add('modified');//$NON-NLS-1$ //$NON-NLS-0$
changed = true;
}
else {
document.getElementById("scopeList").childNodes[i].classList.remove('modified');//$NON-NLS-1$ //$NON-NLS-0$
}
}
//when there is a changed value, theme is now deletable/revertable/renamable
if (changed){
document.getElementById("scopeChanged").classList.remove('hide');//$NON-NLS-1$ //$NON-NLS-0$
document.getElementById("scopeOriginal").classList.add('hide');//$NON-NLS-1$ //$NON-NLS-0$
}
else {
document.getElementById("scopeChanged").classList.add('hide');//$NON-NLS-1$ //$NON-NLS-0$
document.getElementById("scopeOriginal").classList.remove('hide');//$NON-NLS-1$ //$NON-NLS-0$
}
} | javascript | {
"resource": ""
} |
q44059 | apply | train | function apply() {
document.getElementById("editorThemeName").value = currentTheme.name; //$NON-NLS-0$
for (var i = 0; i < scopeList.length; i++){
scopeList[i].value = defaultColor; // scopes with no value will have defaultColor showing
for (var l = 0; l < scopeList[i].objPath.length; l++){
var temp = getValueFromPath(currentTheme,scopeList[i].objPath[l]);
if (temp){
scopeList[i].value = temp;
break;
}
}
}
for (i = 0; i < scopeList.length; i++){
var element = document.getElementById(scopeList[i].id);
element.value = scopeList[i].value; // updates the select or input[type=color] with correct value
if (element.type === "color") { //$NON-NLS-0$
// make the color value available in a tooltip and aria-label
makeTooltip(element, scopeList[i]);
}
}
checkForChanges(); // checks if any value is changed
} | javascript | {
"resource": ""
} |
q44060 | generateScopeList | train | function generateScopeList(hiddenValues){
hiddenValues = hiddenValues || [];
var htmlString = "";
var ieClass = util.isIE ? "-ie" : ""; //$NON-NLS-0$
for (var i = 0; i < scopeList.length; i++){
if (scopeList[i].id === "editorThemeFontSize"){
htmlString = htmlString + "<li><label for='editorThemeFontSize'>" + scopeList[i].display + "</label><select id='editorThemeFontSize'>";
for (var l = 8; l < 19; l++){
htmlString = htmlString + "<option value='" + l+"px'>"+l+"px</option>";
}
for(l = 8; l < 19; l++){
htmlString = htmlString + "<option value='" + l+"pt'>"+l+"pt</option>";
}
htmlString += "</select></li>";//$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
}
else {
var hideValueCSS = hiddenValues.indexOf(scopeList[i].id) >= 0 ? "style='display: none'" : ""; //$NON-NLS-0$
htmlString = htmlString + "<li " + hideValueCSS + "><label for='"+scopeList[i].id+"' id='"+scopeList[i].id+"Label'>" + scopeList[i].display + "</label><input id='"+scopeList[i].id+"' aria-labelledby='" + scopeList[i].id + "Label " + scopeList[i].id + "' class='colorpicker-input" + ieClass + "' type='color' value='" + scopeList[i].value + "'></li>";//$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
}
}
return htmlString;
} | javascript | {
"resource": ""
} |
q44061 | containsAssignment | train | function containsAssignment(node) {
if (node.type === "AssignmentExpression") {
return true;
} else if (node.type === "ConditionalExpression" &&
(node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) {
return true;
} else if ((node.left && node.left.type === "AssignmentExpression") ||
(node.right && node.right.type === "AssignmentExpression")) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q44062 | isReturnAssignException | train | function isReturnAssignException(node) {
if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) {
return false;
}
if (node.type === "ReturnStatement") {
return node.argument && containsAssignment(node.argument);
} else if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
return containsAssignment(node.body);
}
return containsAssignment(node);
} | javascript | {
"resource": ""
} |
q44063 | isHeadOfExpressionStatement | train | function isHeadOfExpressionStatement(node) {
var parent = node.parent;
while (parent) {
switch (parent.type) {
case "SequenceExpression":
if (parent.expressions[0] !== node || isParenthesised(node)) {
return false;
}
break;
case "UnaryExpression":
case "UpdateExpression":
if (parent.prefix || isParenthesised(node)) {
return false;
}
break;
case "BinaryExpression":
case "LogicalExpression":
if (parent.left !== node || isParenthesised(node)) {
return false;
}
break;
case "ConditionalExpression":
if (parent.test !== node || isParenthesised(node)) {
return false;
}
break;
case "CallExpression":
if (parent.callee !== node || isParenthesised(node)) {
return false;
}
break;
case "MemberExpression":
if (parent.object !== node || isParenthesised(node)) {
return false;
}
break;
case "ExpressionStatement":
return true;
default:
return false;
}
node = parent;
parent = parent.parent;
}
/* istanbul ignore next */
throw new Error("unreachable");
} | javascript | {
"resource": ""
} |
q44064 | CompareRuler | train | function CompareRuler (annoModel, rulerLocation, rulerOverview, rulerStyle) {
mRulers.Ruler.call(this, annoModel, rulerLocation, rulerOverview, rulerStyle);
} | javascript | {
"resource": ""
} |
q44065 | LineNumberCompareRuler | train | function LineNumberCompareRuler (diffNavigator, mapperColumnIndex , annoModel, rulerLocation, rulerStyle, oddStyle, evenStyle) {
orion.CompareRuler.call(this, annoModel, rulerLocation, "page", rulerStyle); //$NON-NLS-0$
this._diffNavigator = diffNavigator;
this._oddStyle = oddStyle || {style: {backgroundColor: "white"}}; //$NON-NLS-0$
this._evenStyle = evenStyle || {style: {backgroundColor: "white"}}; //$NON-NLS-0$
this._numOfDigits = 0;
this._mapperColumnIndex = mapperColumnIndex;
} | javascript | {
"resource": ""
} |
q44066 | UndoStack | train | function UndoStack (view, size) {
this.size = size !== undefined ? size : 100;
this.reset();
var self = this;
this._listener = {
onChanging: function(e) {
self._onChanging(e);
},
onDestroy: function(e) {
self._onDestroy(e);
}
};
if (view.getModel) {
var model = view.getModel();
if (model.getBaseModel) {
model = model.getBaseModel();
}
this.model = model;
this.setView(view);
} else {
this.shared = true;
this.model = view;
}
this.model.addEventListener("Changing", this._listener.onChanging); //$NON-NLS-0$
} | javascript | {
"resource": ""
} |
q44067 | train | function (change) {
if (this.compoundChange) {
this.compoundChange.add(change);
} else {
var length = this.stack.length;
this.stack.splice(this.index, length-this.index, change);
this.index++;
if (this.stack.length > this.size) {
this.stack.shift();
this.index--;
}
}
} | javascript | {
"resource": ""
} | |
q44068 | train | function() {
this._commitUndo();
var changes = [];
for (var i=this.index; i >= 0; i--) {
changes = changes.concat(this.stack[i].getUndoChanges());
}
return changes;
} | javascript | {
"resource": ""
} | |
q44069 | train | function() {
this._commitUndo();
var change, result = false;
this._ignoreUndo = true;
do {
if (this.index <= 0) {
break;
}
change = this.stack[--this.index];
} while (!(result = change.undo(this.view, true)));
this._ignoreUndo = false;
return result;
} | javascript | {
"resource": ""
} | |
q44070 | train | function() {
this._commitUndo();
var change, result = false;
this._ignoreUndo = true;
do {
if (this.index >= this.stack.length) {
break;
}
change = this.stack[this.index++];
} while (!(result = change.redo(this.view, true)));
this._ignoreUndo = false;
return result;
} | javascript | {
"resource": ""
} | |
q44071 | Completer | train | function Completer(options, components) {
this.requisition = components.requisition;
this.scratchpad = options.scratchpad;
this.input = { typed: '', cursor: { start: 0, end: 0 } };
this.choice = 0;
this.element = components.element;
this.element.classList.add('gcli-in-complete');
this.element.setAttribute('tabindex', '-1');
this.element.setAttribute('aria-live', 'polite');
this.document = this.element.ownerDocument;
this.inputter = components.inputter;
this.inputter.onInputChange.add(this.update, this);
this.inputter.onAssignmentChange.add(this.update, this);
this.inputter.onChoiceChange.add(this.update, this);
this.autoResize = components.autoResize;
if (this.autoResize) {
this.inputter.onResize.add(this.resized, this);
var dimensions = this.inputter.getDimensions();
if (dimensions) {
this.resized(dimensions);
}
}
this.template = util.toDom(this.document, completerHtml);
// We want the spans to line up without the spaces in the template
util.removeWhitespace(this.template, true);
this.update();
} | javascript | {
"resource": ""
} |
q44072 | checkAuthenticated | train | function checkAuthenticated(req, res, next) {
if (!req.user) {
api.writeError(401, res, "Not authenticated");
} else {
req.user.workspaceDir = workspaceDir + (req.user.workspace ? "/" + req.user.workspace : "");
req.user.checkRights = checkRights;
next();
}
} | javascript | {
"resource": ""
} |
q44073 | checkAccessRights | train | function checkAccessRights(req, res, next) {
const uri = (typeof req.contextPath === "string" && req.baseUrl.substring(req.contextPath.length)) || req.baseUrl;
req.user.checkRights(req.user.username, uri, req, res, next);
} | javascript | {
"resource": ""
} |
q44074 | tryLoadRouter | train | function tryLoadRouter(endpoint, options) {
const args = [];
var isEndpoint = typeof endpoint.endpoint === 'string';
if (isEndpoint) {
args.push(endpoint.endpoint);
args.push(responseTime({digits: 2, header: "X-Total-Response-Time", suffix: true}));
}
if (endpoint.authenticated) {
args.push(options.authenticate);
if (endpoint.checkAuthenticated === undefined || endpoint.checkAuthenticated) {
args.push(checkAuthenticated);
}
}
if (isEndpoint) {
args.push(options.basicMiddleware);
}
if (isEndpoint && csrf && (endpoint.checkCSRF === undefined || endpoint.checkCSRF)) { // perform CSRF by default
args.push(csrf);
args.push(function(req, res, next) {
var preamble = options.configParams.get("orion_cookies_name_premable") || "";
var tokenCookie = preamble + 'x-csrf-token';
if (!req.cookies[tokenCookie]) {
var cookieOptions;
var cookiesPath = options.configParams.get("orion_cookies_path");
if (cookiesPath) {
cookieOptions = {path: cookiesPath};
}
res.cookie(tokenCookie, req.csrfToken(), cookieOptions);
}
next();
});
}
if (endpoint.checkAccess) {
args.push(checkAccessRights);
}
try {
const mod = require(endpoint.module);
let fn = null;
if (typeof mod.router === 'function') {
fn = mod.router;
} else if(typeof mod === 'function') {
fn = mod;
} else {
logger.log("Endpoint did not provide the API 'router' function: " + JSON.stringify(endpoint, null, '\t'));
return;
}
if(fn) {
const router = fn(options);
if (!router) {
return; //endpoint does not want to take part in routing, quit
}
args.push(router);
options.app.use.apply(options.app, args);
}
} catch (err) {
logger.error("Failed to load module: " + err.message + "..." + err.stack);
}
} | javascript | {
"resource": ""
} |
q44075 | loadEndpoints | train | function loadEndpoints(endpoints, options, auth) {
if (Array.isArray(endpoints)) {
endpoints.forEach(function(endpoint) {
if (auth !== Boolean(endpoint.authenticated)) {
//after endpoints refactored, remove this check
return;
}
const conditional = endpoint.hasOwnProperty("ifProp");
if (conditional && options.configParams.get(endpoint.ifProp) || !conditional) {
tryLoadRouter(endpoint, options);
}
});
}
} | javascript | {
"resource": ""
} |
q44076 | loadLanguageServers | train | function loadLanguageServers(servers, io, options) {
if (Array.isArray(servers) && options.configParams.get('orion.single.user')) {
const rootPath = path.join(__dirname, "languages");
if (!fs.existsSync(rootPath)) {
logger.log("'languages' folder does not exist. Stopped loading language servers.");
return;
}
addModulePath.addPath(rootPath);
servers.forEach(function(ls) {
if (typeof ls.module !== "string") {
logger.log("Language server metadata is missing 'module' property: " + JSON.stringify(ls, null, '\t'));
return;
}
const lsPath = path.join(rootPath, ls.module);
if (!fs.existsSync(lsPath)) {
logger.log("Language server folder does not exist: " + lsPath);
return;
}
addModulePath.addPath(lsPath);
try {
const server = require(lsPath);
if (server) {
lsregistry.installServer(new server(options), {
io: io,
workspaceDir: workspaceDir,
IN_PORT: 8123,
OUT_PORT: 8124
});
} else {
logger.log("Tried to install language server '" + lsPath + "' but could not instantiate it");
}
} catch (err) {
logger.log("Failed to load language server: " + err);
}
});
}
} | javascript | {
"resource": ""
} |
q44077 | treeJSON | train | function treeJSON(name, location, timestamp, dir, length, addNameToLoc) {
location = api.toURLPath(location);
if (typeof addNameToLoc == 'undefined' || addNameToLoc) {
location += "/" + name;
}
var result = {
Name: name,
LocalTimeStamp: timestamp,
Directory: dir,
Length: length,
Location: location ? contextPath +"/sharedWorkspace/tree/file" + location : contextPath +"/sharedWorkspace/tree",
ChildrenLocation: dir ? (location ? contextPath +"/sharedWorkspace/tree/file" + location + "?depth=1": contextPath +"/sharedWorkspace/tree" + "?depth=1") : undefined,
Parents: fileUtil.getParents(contextPath +'/sharedWorkspace/tree/file' + location.split('/').splice(0, 2).join('/'), location.split('/').splice(2).join('/')),
Attributes: {
ReadOnly: false
}
};
result.ImportLocation = result.Location.replace(/\/sharedWorkspace\/tree\/file/, "/sharedWorkspace/tree/xfer/import").replace(/\/$/, "");
result.ExportLocation = result.Location.replace(/\/sharedWorkspace\/tree\/file/, "/sharedWorkspace/tree/xfer/export").replace(/\/$/, "") + ".zip";
return result;
} | javascript | {
"resource": ""
} |
q44078 | getChildren | train | function getChildren(fileRoot, directory, depth, excludes) {
return fs.readdirAsync(directory)
.then(function(files) {
return Promise.map(files, function(file) {
if (Array.isArray(excludes) && excludes.indexOf(file) !== -1) {
return null; // omit
}
var filepath = path.join(directory, file);
return fs.statAsync(filepath)
.then(function(stats) {
var isDir = stats.isDirectory();
return treeJSON(file, fileRoot, 0, isDir, depth ? depth - 1 : 0);
})
.catch(function() {
return null; // suppress rejection
});
});
})
.then(function(results) {
return results.filter(function(r) { return r; });
});
} | javascript | {
"resource": ""
} |
q44079 | train | function() {
if(!this.model.root) {
return new Deferred().resolve(true);
}
var modelList = this.model.root.children || this.model.root.Children;
if(!modelList) {
return new Deferred().resolve(true);
}
var isDirty = modelList.some( function(child) {
if(child.children && child.children.length === 1 && child.children[0].resourceComparer && child.children[0].resourceComparer.isDirty()) {
return true;
}
});
if(isDirty) {
var dialog = this.registry.getService("orion.page.dialog");
var d = new Deferred();
dialog.confirm(messages.confirmUnsavedChanges, function(result){
if(result){
var promises = [];
modelList.forEach( function(child) {
if(child.children && child.children.length === 1 && child.children[0].resourceComparer && child.children[0].resourceComparer.isDirty() && child.children[0].resourceComparer.save) {
promises.push(child.children[0].resourceComparer.save(true));
}
});
return d.resolve(Deferred.all(promises));
}else{
return d.resolve();
}
});
return d;
} else {
return new Deferred().resolve(true);
}
} | javascript | {
"resource": ""
} | |
q44080 | train | function(node, offset, source) {
if (node){
if (node.type === 'tag'){
var name = node.name ? node.name.toLowerCase() : '';
if (name === 'script' || name === 'style') {
if (node.openrange && node.endrange){
// If we are in the tag itself we are not actually in the script block
if (offset < node.openrange[1] || offset > node.endrange[0]){
return false;
}
}
return true;
}
}
}
return false;
} | javascript | {
"resource": ""
} | |
q44081 | train | function(node, offset, source) {
if(node && source) {
switch(node.type) {
case 'tag': {
// Smarter way now that we have end ranges
if (node.endrange){
return offset > node.endrange[0] && offset < node.endrange[1];
}
// TODO Delete the old way
var _s = source.slice(node.range[0], node.range[1]);
var _r = new RegExp("<\\s*\/\\s*"+node.name+"\\s*>$"); //$NON-NLS-1$ //$NON-NLS-2$
var _m = _r.exec(_s);
if(_m) {
return offset > (_m.index+node.range[0]) && offset < node.range[1];
}
break;
}
default: {
var _p = node.parent;
if(_p && _p.type === 'tag') {
return Array.isArray(_p.children) && _p.children.length > 0 && (offset > _p.children[_p.children.length-1].range[1]) && offset <= _p.range[1];
}
break;
}
}
}
return false;
} | javascript | {
"resource": ""
} | |
q44082 | train | function(node, offset) {
return node && node.type === 'comment' && offset >= node.range[0] && offset <= node.range[1];
} | javascript | {
"resource": ""
} | |
q44083 | train | function(node, source, params) {
if(node) {
var offset = params.offset;
if(node.type === 'tag') {
var tagNameEnd = node.range[0] + 1 + node.name.length;
if(tagNameEnd < offset) {
if (node.openrange){
return offset < node.openrange[1] || (offset === node.openrange[1] && source[offset-1] !== '>' && source[offset-1] !== '<');
}
// TODO openrange from htmlparser2 is more accurate, consider removing this legacy range check
var idx = offset;
while(idx < node.range[1]) {
var char = source[idx];
if(char === '<') {
return false;
} else if(char === '>') {
return true;
}
idx++;
}
}
} else if(node.type === 'attr') {
return offset >= node.range[0] || offset <= node.range[1];
}
}
return false;
} | javascript | {
"resource": ""
} | |
q44084 | train | function(node, params) {
if(node) {
var offset = params.offset;
if(node.type === 'tag') {
if (node.openrange){
if (offset >= node.openrange[0] && offset <= node.openrange[1]){
return true;
}
} else if (offset >= node.range[0] && offset <= node.range[1]){
return true;
}
}
}
return false;
} | javascript | {
"resource": ""
} | |
q44085 | train | function(node, source) {
if(node && node.type === 'tag' && node.name) {
if (node.endrange && node.endrange.length === 2){
// If the HTML is incomplete, the parser recovery sometimes uses the end range of the parent element
return node.name === source.substring(node.endrange[0]+2, node.endrange[1]-1);
}
}
} | javascript | {
"resource": ""
} | |
q44086 | train | function(node, source, params) {
var proposals = [];
var prefix = params.prefix ? params.prefix : "";
// we need to check if we need to rebuild the prefix for completion that contains a '-'
var index = params.offset - prefix.length - 1;
if (index > 0 && index < source.length) {
var precedingChar = source.charAt(index);
if (precedingChar === '=' && prefix.length === 0 && (index - 1) > 0) {
precedingChar = source.charAt(index - 1);
if (/[A-Za-z0-9_]/.test(precedingChar)) {
proposals.push(this.makeComputedProposal("\"\"", Messages['addQuotesToAttributes'], " - \"\"", null, prefix)); //$NON-NLS-1$ //$NON-NLS-2$
return proposals;
}
}
}
var attrs = Attributes.getAttributesForNode(node);
if(Array.isArray(attrs.global)) {
proposals = proposals.concat(this.addProposals(node, attrs.global, params));
}
if(Array.isArray(attrs.formevents)) {
var arr = this.addProposals(node, attrs.formevents, params);
if(arr.length > 0) {
proposals.push({
proposal: '',
description: Messages['formeventsHeader'],
style: 'noemphasis_title', //$NON-NLS-1$
unselectable: true,
kind: 'html' //$NON-NLS-1$
});
proposals = proposals.concat(arr);
}
}
if(Array.isArray(attrs.keyboardevents)) {
arr = this.addProposals(node, attrs.keyboardevents, params);
if(arr.length > 0) {
proposals.push({
proposal: '',
description: Messages['keyboardeventsHeader'],
style: 'noemphasis_title', //$NON-NLS-1$
unselectable: true,
kind: 'html' //$NON-NLS-1$
});
proposals = proposals.concat(arr);
}
}
if(Array.isArray(attrs.mouseevents)) {
arr = this.addProposals(node, attrs.mouseevents, params);
if(arr.length > 0) {
proposals.push({
proposal: '',
description: Messages['mouseeventsHeader'],
style: 'noemphasis_title', //$NON-NLS-1$
unselectable: true,
kind: 'html' //$NON-NLS-1$
});
proposals = proposals.concat(arr);
}
}
if(Array.isArray(attrs.windowevents) && attrs.windowevents.length > 0) {
arr = this.addProposals(node, attrs.windowevents, params);
if(arr.length > 0) {
proposals.push({
proposal: '',
description: Messages['windoweventsHeader'],
style: 'noemphasis_title', //$NON-NLS-1$
unselectable: true,
kind: 'html' //$NON-NLS-1$
});
proposals = proposals.concat(arr);
}
}
if(Array.isArray(attrs.aria)) {
arr = this.addProposals(node, attrs.aria, params);
if(arr.length > 0) {
proposals.push({
proposal: '',
description: 'ARIA', //$NON-NLS-1$
style: 'noemphasis_title', //$NON-NLS-1$
unselectable: true,
kind: 'html' //$NON-NLS-1$
});
proposals = proposals.concat(arr);
}
}
return proposals;
} | javascript | {
"resource": ""
} | |
q44087 | train | function(node, source, params) {
// TODO We can do better with the new parser, handle no quotes cases too
if(node && node.type === 'attr') {
if (node.valueRange) {
var range = node.valueRange;
return range[0] <= params.offset && range[1] >= params.offset;
}
return this.within('"', '"', source, params.offset, node.range) || //$NON-NLS-1$ //$NON-NLS-2$
this.within("'", "'", source, params.offset, node.range); //$NON-NLS-1$ //$NON-NLS-2$
}
return false;
} | javascript | {
"resource": ""
} | |
q44088 | train | function(start, end, source, offset, bounds) {
var idx = offset;
var _c;
var before = false;
while(idx > bounds[0]) {
_c = source[idx];
if(_c === start) {
before = true;
break;
}
idx--;
}
if(before) {
idx = offset;
while(idx < bounds[1]) {
_c = source[idx];
if(_c === end) {
return true;
}
idx++;
}
}
return false;
} | javascript | {
"resource": ""
} | |
q44089 | handle | train | function handle(operationLocation, onSuccess, onError) {
var def = new Deferred();
_trackCancel(operationLocation, def);
_getOperation({location: operationLocation, timeout: 100}, def, onSuccess, onError);
return def;
} | javascript | {
"resource": ""
} |
q44090 | ProblemsView | train | function ProblemsView(options, slideout) {
if(slideout) {
SlideoutViewMode.call(this, slideout);
}
var parentId = options.parentId ? options.parentId : "orion.PropertyPanel.container";
this._parent = lib.node(parentId);
this.serviceRegistry = options.serviceRegistry;
this.commandRegistry = options.commandRegistry;
this.preferences = options.preferences;
this.fileClient = options.fileClient;
this.contentTypeRegistry = options.contentTypeRegistry;
this._init(slideout);
} | javascript | {
"resource": ""
} |
q44091 | _doServiceCall | train | function _doServiceCall(service, methodName, args) {
var serviceMethod = service[methodName];
var clientDeferred = new Deferred();
if (typeof serviceMethod !== 'function') { //$NON-NLS-0$
throw messages['Service method missing: '] + methodName;
}
// On success, just forward the result to the client
var onSuccess = function(result) {
clientDeferred.resolve(result);
};
// On failure we might need to retry
var onError = function(error) {
// Forward other errors to client
clientDeferred.reject(error);
};
serviceMethod.apply(service, args).then(onSuccess, onError);
return clientDeferred;
} | javascript | {
"resource": ""
} |
q44092 | SiteClient | train | function SiteClient(serviceRegistry, siteService, siteServiceRef) {
this._serviceRegistry = serviceRegistry;
this._siteService = siteService;
this._selfHost = siteServiceRef.getProperty('canSelfHost'); //$NON-NLS-0$
this._selfHostConfig = siteServiceRef.getProperty('selfHostingConfig'); //$NON-NLS-0$
this._sitePattern = siteServiceRef.getProperty('sitePattern'); //$NON-NLS-0$
this._filePattern = siteServiceRef.getProperty('filePattern'); //$NON-NLS-0$
this._name = siteServiceRef.getProperty('name'); //$NON-NLS-0$
this._id = siteServiceRef.getProperty('id'); //$NON-NLS-0$
this._getService = function() {
return this._siteService;
};
this._getFilePattern = function() {
return this._filePattern;
};
this._getFileClient = function() {
return getFileClient(this._serviceRegistry, this._getFilePattern());
};
this._canSelfHost = function() {
return this._selfHost;
};
} | javascript | {
"resource": ""
} |
q44093 | train | function(site, file) {
if (!site) {
var d = new Deferred();
d.resolve(false);
return d;
}
return this.getURLOnSite(site, file).then(function(url) {
return url !== null;
});
} | javascript | {
"resource": ""
} | |
q44094 | train | function(item) {
this.scope("");
return this.fileClient.getWorkspace(item.Location).then(function(workspace) {
return this.loadRoot(workspace).then(function() {
return this.showItem(item, false); // call with reroot=false to avoid recursion
}.bind(this));
}.bind(this));
} | javascript | {
"resource": ""
} | |
q44095 | train | function(eventName, listener) {
if (typeof listener === "function" || listener.handleEvent) {
this._namedListeners[eventName] = this._namedListeners[eventName] || [];
this._namedListeners[eventName].push(listener);
}
} | javascript | {
"resource": ""
} | |
q44096 | train | function(eventName, listener) {
var listeners = this._namedListeners[eventName];
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
if (listeners[i] === listener) {
if (listeners.length === 1) {
delete this._namedListeners[eventName];
} else {
listeners.splice(i, 1);
}
break;
}
}
}
} | javascript | {
"resource": ""
} | |
q44097 | NumberType | train | function NumberType(typeSpec) {
// Default to integer values
this._allowFloat = !!typeSpec.allowFloat;
if (typeSpec) {
this._min = typeSpec.min;
this._max = typeSpec.max;
this._step = typeSpec.step || 1;
if (!this._allowFloat &&
(this._isFloat(this._min) ||
this._isFloat(this._max) ||
this._isFloat(this._step))) {
throw new Error('allowFloat is false, but non-integer values given in type spec');
}
}
else {
this._step = 1;
}
} | javascript | {
"resource": ""
} |
q44098 | DelegateType | train | function DelegateType(typeSpec) {
if (typeof typeSpec.delegateType !== 'function') {
throw new Error('Instances of DelegateType need typeSpec.delegateType to be a function that returns a type');
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
} | javascript | {
"resource": ""
} |
q44099 | ArrayType | train | function ArrayType(typeSpec) {
if (!typeSpec.subtype) {
console.error('Array.typeSpec is missing subtype. Assuming string.' +
JSON.stringify(typeSpec));
typeSpec.subtype = 'string';
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
this.subtype = types.getType(this.subtype);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.