/*
Helper for QuickEdit jump-to-definition request.
965545
function quickEditHelper() {
            var offset     = session.getCursor(),
                response   = ScopeManager.requestJumptoDef(session, session.editor.document, offset);

            return response;
        }
638117
function shorten(term, match, opts) {
  var matchOpts = {pre: opts.pre, post: opts.post};
  var shared = util.getUnion(term, match.dir);
  var cutoff = shared.lastIndexOf(path.sep) + 1;
  match.dir = match.dir.slice(cutoff);
  match.shared = shared.slice(0, cutoff);

  var filepath = path.join(match.dir, match.file);
  term = getRelativeTerm(term, match.shared);

  var relativeMatch = fuzzy.match(term, filepath, matchOpts);
  if(relativeMatch) {
    match.rendered = relativeMatch.rendered;
  }
}
21101
public ShortToken visitShort(EditsElement e) throws IOException {
    return (ShortToken)visit(tokenizer.read(new ShortToken(e)));
  }
740972
function shortcutRequest(req){
  req.get = shortcut(req, 'GET')
  req.post = shortcut(req, 'POST')
  req.put = shortcut(req, 'PUT')
  req.patch = shortcut(req, 'PATCH')
  req['delete'] = shortcut(req, 'DELETE')
  req.options = shortcut(req, 'OPTIONS')
  req.head = shortcut(req, 'HEAD')
  req.trace = shortcut(req, 'TRACE')
  req.connect = shortcut(req, 'CONNECT')
  return req
}
997390
function requestFindReferences(session, offset) {
            var response = requestFindRefs(session, session.editor.document, offset);

            if (response && response.hasOwnProperty("promise")) {
                response.promise.done(handleFindRefs).fail(function () {
                    result.reject();
                });
            }
        }
927832
function quickReply(payload, callback)
{
  if (typeof payload.payload != 'string')
  {
    payload.payload = JSON.stringify(payload.payload);
  }

  callback(null, payload);
}
839096
function todoKeyPressed(todo, event) {
    if (event.keyCode === ENTER_KEY) {
      var inputEditTodo = document.getElementById('input_' + todo._id);
      inputEditTodo.blur();
    }
  }
1205476
function editText(text) {
    var $newedit = editor.$edit.clone().val(text);
    editor.$edit.replaceWith($newedit);
    editor.$edit = $newedit;
    editor.$edit.on('keyup', editorUpdate);
  }
98245
function optionToDefinition(option, defaults) {
            if (!option) {
                return defaults;
            }

            return typeof option === "string"
                ? optionDefinitions[option]
                : Object.assign({}, defaults, option);
        }
237831
function (id) {
                var plugin = null;
                util.each(this.get('plugins'), function (p) {
                    // user defined takes priority
                    var pluginId = p.get && p.get('pluginId') || p.pluginId;
                    if (pluginId === id) {
                        plugin = p;
                        return false;
                    }
                    return undefined;
                });
                return plugin;
            }
102136
def jump_to(self, mark, offset=0):
        """"""
        self._offset = self._bookmarks[mark] + offset
1051106
private void inlineDefinitions(MarkupDocBuilder markupDocBuilder, List<ObjectType> definitions, String uniquePrefix) {
        if (CollectionUtils.isNotEmpty(definitions)) {
            for (ObjectType definition : definitions) {
                addInlineDefinitionTitle(markupDocBuilder, definition.getName(), definition.getUniqueName());

                List<ObjectType> localDefinitions = new ArrayList<>();
                propertiesTableComponent.apply(markupDocBuilder, PropertiesTableComponent.parameters(
                        definition.getProperties(),
                        uniquePrefix,
                        localDefinitions
                ));
                for (ObjectType localDefinition : localDefinitions)
                    inlineDefinitions(markupDocBuilder, Collections.singletonList(localDefinition), localDefinition.getUniqueName());
            }
        }

    }

    private void buildConsumesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        List<String> consumes = operation.getOperation().getConsumes();
        if (CollectionUtils.isNotEmpty(consumes)) {
            consumesComponent.apply(markupDocBuilder, ConsumesComponent.parameters(consumes,
                    getSectionTitleLevel()));
        }

    }

    private void buildProducesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        List<String> produces = operation.getOperation().getProduces();
        if (CollectionUtils.isNotEmpty(produces)) {
            producesComponent.apply(markupDocBuilder, ProducesComponent.parameters(produces,
                    getSectionTitleLevel()));
        }
    }

    private void buildTagsSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            List<String> tags = operation.getOperation().getTags();
            if (CollectionUtils.isNotEmpty(tags)) {
                buildSectionTitle(markupDocBuilder, labels.getLabel(TAGS));
                if (config.getTagOrdering() != null) {
                    tags.sort(config.getTagOrdering());
                }
                markupDocBuilder.unorderedList(tags);
            }
        }
    }

    /**
     * Builds the security section of a Swagger Operation.
     *
     * @param operation the Swagger Operation
     */
    private void buildSecuritySchemeSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        if (config.isPathSecuritySectionEnabled()) {
            securitySchemeComponent.apply(markupDocBuilder, SecuritySchemeComponent.parameters(
                    operation,
                    getSectionTitleLevel()
            ));
        }
    }

    /**
     * Retrieves the title level for sections
     */
    private int getSectionTitleLevel() {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            return 3;
        } else {
            return 4;
        }
    }

    /**
     * Builds the example section of a Swagger Operation.
     *
     * @param operation the Swagger Operation
     */
    private void buildExamplesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation, List<PageBreakLocations> locations) {

        Map<String, Object> generatedRequestExampleMap = ExamplesUtil.generateRequestExampleMap(config.isGeneratedExamplesEnabled(), operation, definitions, definitionDocumentResolver, markupDocBuilder);
        Map<String, Object> generatedResponseExampleMap = ExamplesUtil.generateResponseExampleMap(config.isGeneratedExamplesEnabled(), operation, definitions, definitionDocumentResolver, markupDocBuilder);

        boolean beforeExampleRequestBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_REQUEST);
        boolean afterExampleRequestBreak = locations.contains(AFTER_OPERATION_EXAMPLE_REQUEST);
        boolean beforeExampleResponseBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_RESPONSE);
        boolean afterExampleResponseBreak = locations.contains(AFTER_OPERATION_EXAMPLE_RESPONSE);

        exampleMap(markupDocBuilder, generatedRequestExampleMap, labels.getLabel(EXAMPLE_REQUEST), labels.getLabel(REQUEST), beforeExampleRequestBreak, afterExampleRequestBreak);
        exampleMap(markupDocBuilder, generatedResponseExampleMap, labels.getLabel(EXAMPLE_RESPONSE), labels.getLabel(RESPONSE), beforeExampleResponseBreak, afterExampleResponseBreak);
    }

    private void exampleMap(MarkupDocBuilder markupDocBuilder, Map<String, Object> exampleMap, String operationSectionTitle, String sectionTitle, boolean beforeBreak, boolean afterBreak) {
        if (exampleMap.size() > 0) {
            if (beforeBreak) markupDocBuilder.pageBreak();
            buildSectionTitle(markupDocBuilder, operationSectionTitle);
            for (Map.Entry<String, Object> entry : exampleMap.entrySet()) {

                // Example title, like "Response 200" or "Request Body"
                buildExampleTitle(markupDocBuilder, sectionTitle + " " + entry.getKey());

                if (NumberUtils.isNumber(entry.getKey())) {
                    // Section header is an HTTP status code (numeric)
                    JsonNode rootNode = parseExample(entry.getValue());
                    Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();



                    if (!fieldsIterator.hasNext()) {
                        // rootNode contains a single example, no need to further iterate.
                        String example = Json.pretty(rootNode);
//                        String example = Json.pretty(stripExampleQuotes(rootNode.toString()));
//                        example = Json.pretty(example);
                        markupDocBuilder.listingBlock(example, "json");
                    }
                    while (fieldsIterator.hasNext()) {
                        Map.Entry<String, JsonNode> field = fieldsIterator.next();

                        if (field.getKey().equals("application/json")) {
                            String example = Json.pretty(field.getValue());
                            example = stripExampleQuotes(StringEscapeUtils.unescapeJson(example));

                            markupDocBuilder.listingBlock(example, "json");

                        } else if (field.getKey().equals("application/xml")) {

                            String example = stripExampleQuotes(field.getValue().toString());
                            example = StringEscapeUtils.unescapeJava(example);

                            //TODO: pretty print XML

                            markupDocBuilder.listingBlock(example, "xml");
                        } else {
                            String example = Json.pretty(entry.getValue());
                            markupDocBuilder.listingBlock(example, "json");
                            break; // No need to print the same example multiple times
                        }
                    }
                } else if (entry.getKey().equals("path")) {
                    // Path shouldn't have quotes around it
                    markupDocBuilder.listingBlock(entry.getValue().toString());
                } else if (entry.getKey().equals("header")){
                    // Header should have format: apikey:"string"
                    markupDocBuilder.listingBlock(entry.getValue().toString(), "json");
                } else {
                    
                    Object value = entry.getValue();
                    
                    if (value instanceof Map) {
                        
                        @SuppressWarnings("unchecked")
                        Map<String, String> examplesByContentType = (Map<String, String>) value;
                        
                        for (Entry<String, String> entryByType : examplesByContentType.entrySet()) {
                            if (entryByType.getKey().equals("application/json")) {
                                String example = Json.pretty(entryByType.getValue());
                                example = stripExampleQuotes(StringEscapeUtils.unescapeJson(example));
    
                                markupDocBuilder.listingBlock(example, "json");
    
                            } else if (entryByType.getKey().equals("application/xml")) {
    
                                String example = stripExampleQuotes(entryByType.getValue().toString());
                                example = StringEscapeUtils.unescapeJava(example);
    
                                //TODO: pretty print XML
    
                                markupDocBuilder.listingBlock(example, "xml");
                            } else {
                                String example = Json.pretty(entry.getValue());
                                markupDocBuilder.listingBlock(example, "json");
                                break; // No need to print the same example multiple times
                            }
                        }
                    } else {
                        markupDocBuilder.listingBlock(Json.pretty(value), "json");
                    }
                }
            }
            if (afterBreak) markupDocBuilder.pageBreak();
        }
    }

    /**
     * Strip leading and trailing quotes from a string
     *
     * @param raw String containing leading or trailing quotes
     * @return parsed String
     */
    private String stripExampleQuotes(String raw) {
        return raw
                .replaceAll("^\"+", "")  // Strip leading quotes
                .replaceAll("\"+$", ""); // Strip trailing quotes
    }

    /**
     * Parse a JSON array
     *
     * @param raw Object containing a JSON string
     * @return JsonNode[contentType, example]
     * @throws RuntimeException when the given JSON string cannot be parsed
     */
    private JsonNode parseExample(Object raw) throws RuntimeException {
        try {
            JsonFactory factory = new JsonFactory();
            ObjectMapper mapper = new ObjectMapper(factory);
            return mapper.readTree(Json.pretty(raw));
        } catch (Exception ex) {
            throw new RuntimeException("Failed to read example", ex);
        }
    }

    /**
     * Adds a example title to the document.
     *
     * @param title the section title
     */
    private void buildExampleTitle(MarkupDocBuilder markupDocBuilder, String title) {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            markupDocBuilder.sectionTitleLevel4(title);
        } else {
            markupDocBuilder.sectionTitleLevel5(title);
        }
    }

    /**
     * Apply extension context to all OperationsContentExtension.
     *
     * @param context context
     */
    private void applyPathsDocumentExtension(PathsDocumentExtension.Context context) {
        extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.apply(context));
    }

    public static class Parameters {

        private final PathOperation operation;

        public Parameters(PathOperation operation) {
            this.operation = Validate.notNull(operation, "PathOperation must not be null");
        }
    }
}
367476
function(definition, callback) {
      // if no definition is provided, then the user wants see all the indexes
      if (typeof definition === 'function' || typeof definition === 'undefined') {
        callback = definition;
        return nano.request({ path: encodeURIComponent(db) + '/_index' }, callback);
      } else {
        // the user wants to create a new index
        return nano.request({ path: encodeURIComponent(db) + '/_index',
          method: 'post',
          body: definition}, callback);
      }
    }
5413
def upload(self, path, engine, description=None):
        """"""

        if description is None:
            head, tail = ntpath.split(path)
            description = tail or ntpath.basename(head)

        url = "http://quickslice.{}/config/raw/".format(self.config.host)

        with open(path) as config_file:
            content = config_file.read()

        payload = {"engine": engine,
                   "description": description,
                   "content": content}

        post_resp = requests.post(url, json=payload, cookies={"session": self.session})
        if not post_resp.ok:
            raise errors.ResourceError("config upload to slicing service failed")

        self.description = description

        self.location = post_resp.headers["Location"]
380092
function queueEdit(applyEdit, editType, complete, error, keyUpdate, updateSlots, undo) {
                    var editQueueTail = editQueue.prev,
                        edit = {
                            prev: editQueueTail,
                            next: editQueue,
                            applyEdit: applyEdit,
                            editType: editType,
                            complete: complete,
                            error: error,
                            keyUpdate: keyUpdate
                        };
                    editQueueTail.next = edit;
                    editQueue.prev = edit;
                    editsQueued = true;

                    // If there's a refresh in progress, abandon it, but request that a new one be started once the edits complete
                    if (refreshRequested || refreshInProgress) {
                        currentRefreshID++;
                        refreshInProgress = false;
                        refreshRequested = true;
                    }

                    if (editQueue.next === edit) {
                        // Attempt the edit immediately, in case it completes synchronously
                        applyNextEdit();
                    }

                    // If the edit succeeded or is still pending, apply it to the slots (in the latter case, "optimistically")
                    if (!edit.failed) {
                        updateSlots();

                        // Supply the undo function now
                        edit.undo = undo;
                    }

                    if (!editsInProgress) {
                        completeEdits();
                    }
                }
228801
function (text, skipUnchangedTerm) {
      if (!this.dropdown) { this.initialize(); }
      text != null || (text = this.adapter.getTextFromHeadToCaret());
      var searchQuery = this._extractSearchQuery(text);
      if (searchQuery.length) {
        var term = searchQuery[1];
        // Ignore shift-key, ctrl-key and so on.
        if (skipUnchangedTerm && this._term === term && term !== "") { return; }
        this._term = term;
        this._search.apply(this, searchQuery);
      } else {
        this._term = null;
        this.dropdown.deactivate();
      }
    }
245842
function addPreset(name, definition) {
      definition = definition || {};
      definition.methods = definition.methods || [];
      definition.options = definition.options || function() { return {}; };

      if (/^cancel|hide|show$/.test(name)) {
        throw new Error("Preset '" + name + "' in " + interimFactoryName + " is reserved!");
      }
      if (definition.methods.indexOf('_options') > -1) {
        throw new Error("Method '_options' in " + interimFactoryName + " is reserved!");
      }
      providerConfig.presets[name] = {
        methods: definition.methods.concat(EXPOSED_METHODS),
        optionsFactory: definition.options,
        argOption: definition.argOption
      };
      return provider;
    }