Create a new autocomplete `Prompt`
543787
function Prompt() {
  BasePrompt.apply(this, arguments);
  if (typeof this.question.source !== 'function') {
    throw new TypeError('expected source to be defined');
  }

  this.currentChoices = [];
  this.firstRender = true;
  this.selected = 0;

  // Make sure no default is set (so it won't be printed)
  this.question.default = undefined;
  this.paginator = new Paginator();
}
1171580
function prompt (data, key, prompt, done) {
  // skip prompts whose when condition is not met
  if (prompt.when && !evaluate(prompt.when, data)) {
    return done()
  }

  var promptDefault = prompt.default
  if (typeof prompt.default === 'function') {
    promptDefault = function () {
      return prompt.default.bind(this)(data)
    }
  }

  inquirer.prompt([{
    type: promptMapping[prompt.type] || prompt.type,
    name: key,
    message: prompt.message || prompt.label || key,
    default: promptDefault,
    choices: prompt.choices || [],
    validate: prompt.validate || function () { return true }
  }], function (answers) {
    if (Array.isArray(answers[key])) {
      data[key] = {}
      answers[key].forEach(function (multiChoiceAnswer) {
        data[key][multiChoiceAnswer] = true
      })
    } else if (typeof answers[key] === 'string') {
      data[key] = answers[key].replace(/"/g, '\\"')
    } else {
      data[key] = answers[key]
    }
    done()
  })
}
1210002
def input(self, prompt, default=None, show_default=True):
        """"""
        return click.prompt(prompt, default=default, show_default=show_default)
86565
function(e) {

			if ( e.keyCode !== ENTER_KEY ){
				return;
			}

			if ( !this.input.val().trim() ){
				return;
			}

			window.app.Todos.create(this.newAttributes());
			this.input.val('');
		}
602081
function(content, opts, onOk, oncancel) {
        Dialog.setup('prompt', content, opts, onOk, oncancel);
      }
461931
def prompt_for_input(message, input_type=None):
    """"""
    while True:
        output = prompt.query(message)

        if input_type:
            try:
                output = input_type(output)
            except ValueError:
                error_message('Invalid input type')
                continue

        break

    return output
263530
def make_dynamic_prompt(self, prompt):
        """"""
        patterns = ["[\r\n]" + pattern_manager.pattern(
            self.platform, pattern_name, compiled=False) for pattern_name in self.target_prompt_components]

        patterns_re = "|".join(patterns).format(hostname=re.escape(prompt))

        try:
            prompt_re = re.compile(patterns_re)
        except re.error as e:  # pylint: disable=invalid-name
            raise RuntimeError("Pattern compile error: {} ({}:{})".format(e.message, self.platform, patterns_re))

        self.log("Dynamic prompt: '{}'".format(repr(prompt_re.pattern)))
        return prompt_re
799364
def custom_prompt(msg, delims="", completer=lambda: None):
    """"""
    try:
        orig_delims = readline.get_completer_delims()
        orig_completer = readline.get_completer()

        readline.set_completer_delims(delims)
        readline.set_completer(completer)

        try:
            ret = input(msg)
        finally:
            readline.set_completer_delims(orig_delims)
            readline.set_completer(orig_completer)

        return ret
    except EOFError:
        raise UserQuit()
577262
function(yasqe) {
  //instantiate autocompleters
  yasqe.autocompleters = require("./autocompleters/autocompleterBase.js")(root, yasqe);
  if (yasqe.options.autocompleters) {
    yasqe.options.autocompleters.forEach(function(name) {
      if (root.Autocompleters[name]) yasqe.autocompleters.init(name, root.Autocompleters[name]);
    });
  }
  yasqe.emit = function(event, data) {
    root.signal(yasqe, event, data)
  }
  yasqe.lastQueryDuration = null;
  yasqe.getCompleteToken = function(token, cur) {
    return require("./tokenUtils.js").getCompleteToken(yasqe, token, cur);
  };
  yasqe.getPreviousNonWsToken = function(line, token) {
    return require("./tokenUtils.js").getPreviousNonWsToken(yasqe, line, token);
  };
  yasqe.getNextNonWsToken = function(lineNumber, charNumber) {
    return require("./tokenUtils.js").getNextNonWsToken(yasqe, lineNumber, charNumber);
  };
  yasqe.collapsePrefixes = function(collapse) {
    if (collapse === undefined) collapse = true;
    yasqe.foldCode(
      require("./prefixFold.js").findFirstPrefixLine(yasqe),
      root.fold.prefix,
      collapse ? "fold" : "unfold"
    );
  };
  var backdrop = null;
  var animateSpeed = null;
  yasqe.setBackdrop = function(show) {
    if (yasqe.options.backdrop || yasqe.options.backdrop === 0 || yasqe.options.backdrop === "0") {
      if (animateSpeed === null) {
        animateSpeed = +yasqe.options.backdrop;
        if (animateSpeed === 1) {
          //ah, yasqe.options.backdrop was 'true'. Set this to default animate speed 400
          animateSpeed = 400;
        }
      }

      if (!backdrop) {
        backdrop = $("<div>", {
          class: "backdrop"
        })
          .click(function() {
            $(this).hide();
          })
          .insertAfter($(yasqe.getWrapperElement()));
      }
      if (show) {
        backdrop.show(animateSpeed);
      } else {
        backdrop.hide(animateSpeed);
      }
    }
  };
  /**
	 * Execute query. Pass a callback function, or a configuration object (see
	 * default settings below for possible values) I.e., you can change the
	 * query configuration by either changing the default settings, changing the
	 * settings of this document, or by passing query settings to this function
	 *
	 * @method doc.query
	 * @param function|object
	 */
  yasqe.query = function(callbackOrConfig) {
    root.executeQuery(yasqe, callbackOrConfig);
  };

  yasqe.getUrlArguments = function(config) {
    return root.getUrlArguments(yasqe, config);
  };

  /**
	 * Fetch defined prefixes from query string
	 *
	 * @method doc.getPrefixesFromQuery
	 * @return object
	 */
  yasqe.getPrefixesFromQuery = function() {
    return require("./prefixUtils.js").getPrefixesFromQuery(yasqe);
  };

  yasqe.addPrefixes = function(prefixes) {
    return require("./prefixUtils.js").addPrefixes(yasqe, prefixes);
  };
  yasqe.removePrefixes = function(prefixes) {
    return require("./prefixUtils.js").removePrefixes(yasqe, prefixes);
  };
  yasqe.getVariablesFromQuery = function() {
    //Use precise here. We want to be sure we use the most up to date state. If we're
    //not, we might get outdated info from the current query (creating loops such
    //as https://github.com/OpenTriply/YASGUI/issues/84)
    //on caveat: this function won't work when query is invalid (i.e. when typing)
    return $.map(yasqe.getTokenAt({ line: yasqe.lastLine(), ch: yasqe.getLine(yasqe.lastLine()).length }, true).state.variables, function(val,key) {return key});
  }
  //values in the form of {?var: 'value'}, or [{?var: 'value'}]
  yasqe.getQueryWithValues = function(values) {
    if (!values) return yasqe.getValue();
    var injectString;
    if (typeof values === 'string') {
      injectString = values;
    } else {
      //start building inject string
      if (!Array.isArray(values)) values = [values];
      var variables = values.reduce(function(vars, valueObj) {
        for (var v in valueObj) {
          vars[v] = v;
        }
        return vars;
      }, {})
      var varArray = [];
      for (var v in variables) {
        varArray.push(v);
      }

      if (!varArray.length) return yasqe.getValue() ;
      //ok, we've got enough info to start building the string now
      injectString = "VALUES (" + varArray.join(' ') + ") {\n";
      values.forEach(function(valueObj) {
        injectString += "( ";
        varArray.forEach(function(variable) {
          injectString += valueObj[variable] || "UNDEF"
        })
        injectString += " )\n"
      })
      injectString += "}\n"
    }
    if (!injectString) return yasqe.getValue();

    var newQuery = ""
    var injected = false;
    var gotSelect = false;
    root.runMode(yasqe.getValue(), "sparql11", function(stringVal, className, row, col, state) {
      if (className === "keyword" && stringVal.toLowerCase() === 'select') gotSelect = true;
      newQuery += stringVal;
      if (gotSelect && !injected && className === "punc" && stringVal === "{") {
        injected = true;
        //start injecting
        newQuery += "\n" + injectString;
      }
    });
    return newQuery
  }

  yasqe.getValueWithoutComments = function() {
    var cleanedQuery = "";
    root.runMode(yasqe.getValue(), "sparql11", function(stringVal, className) {
      if (className != "comment") {
        cleanedQuery += stringVal;
      }
    });
    return cleanedQuery;
  };
  /**
	 * Fetch the query type (e.g., SELECT||DESCRIBE||INSERT||DELETE||ASK||CONSTRUCT)
	 *
	 * @method doc.getQueryType
	 * @return string
	 *
	 */
  yasqe.getQueryType = function() {
    return yasqe.queryType;
  };
  /**
	 * Fetch the query mode: 'query' or 'update'
	 *
	 * @method doc.getQueryMode
	 * @return string
	 *
	 */
  yasqe.getQueryMode = function() {
    var type = yasqe.getQueryType();
    if (
      type == "INSERT" ||
      type == "DELETE" ||
      type == "LOAD" ||
      type == "CLEAR" ||
      type == "CREATE" ||
      type == "DROP" ||
      type == "COPY" ||
      type == "MOVE" ||
      type == "ADD"
    ) {
      return "update";
    } else {
      return "query";
    }
  };

  yasqe.setCheckSyntaxErrors = function(isEnabled) {
    yasqe.options.syntaxErrorCheck = isEnabled;
    checkSyntax(yasqe);
  };

  yasqe.enableCompleter = function(name) {
    addCompleterToSettings(yasqe.options, name);
    if (root.Autocompleters[name]) yasqe.autocompleters.init(name, root.Autocompleters[name]);
  };
  yasqe.disableCompleter = function(name) {
    removeCompleterFromSettings(yasqe.options, name);
  };
  return yasqe;
}
1162796
function startCmdEditor (config, is_skip_header) {

	if (!is_skip_header) {
		console.log(colors.bold('--------------- Command Editor ---------------'));
	}

	// Show a prompt for choose the mode
	var promise = inquirer.prompt([{
		type: 'list',
		name: 'mode',
		message: 'What you want to do ?',
		choices: [
			'Show commands list', 'Add new command', 'Edit command', 'Delete command'
		]
	}]);

	promise.then(function (answer) {

		var mode = answer.mode;
		var promise = null;

		if (mode == 'Add new command') {
			promise = addCommandOnCmdEditor(config);
		} else if (mode == 'Edit command') {
			promise = editCommandOnCmdEditor(config);
		} else if (mode == 'Delete command') {
			promise = deleteCommandOnCmdEditor(config);
		} else if (mode == 'Show commands list') {
			promise = showCommandsOnCmdEditor(config);
		}

		if (!promise) {
			startCmdEditor(config, true);
			return;
		}

		promise.then(function () {
			startCmdEditor(config, true);
		});

	});

}
559640
function (e) {
			if (e.which !== ENTER_KEY || !this.$input.val().trim()) {
				return;
			}

			app.todos.create(this.newAttributes());
			this.$input.val('');
		}
262645
function prompt(message, options) {
            var template = "\n            <script type=\"text/template\">\n                <section class=\"ui-modal\" data-role=\"popup\" data-corners=\"false\">\n                    <div class=\"ui-content\">\n                        <h1 class=\"ui-title {{_titleState}}\">{{title}}</h1>\n                        <p class=\"ui-message\">{{message}}</p>\n                        <label for=\"_ui-prompt\" class=\"ui-hidden-accessible\"></label>\n                        <input type=\"text\" name=\"_ui-prompt\" id=\"_ui-prompt\">\n                    </div>\n                    <div class=\"ui-modal-footer ui-grid-a\">\n                        <button id=\"{{idNegative}}\" class=\"ui-btn ui-block-a\" data-auto-close=\"true\">{{labelNegative}}</button>\n                        <button id=\"{{idPositive}}\" class=\"command-prompt-ok ui-btn ui-block-b ui-text-emphasis\" data-auto-close=\"false\">{{labelPositive}}</button>\n                    </div>\n                </section>\n            </script>\n        ";
            var dlgPrompt = new DialogPrompt(template, $.extend({}, {
                src: null,
                message: message,
            }, options));
            return dlgPrompt.show();
        }
934278
def newAction(parent, text, slot=None, shortcut=None, icon=None,
              tip=None, checkable=False, enabled=True):
    """"""
    a = QAction(text, parent)
    if icon is not None:
        a.setIcon(newIcon(icon))
    if shortcut is not None:
        if isinstance(shortcut, (list, tuple)):
            a.setShortcuts(shortcut)
        else:
            a.setShortcut(shortcut)
    if tip is not None:
        a.setToolTip(tip)
        a.setStatusTip(tip)
    if slot is not None:
        a.triggered.connect(slot)
    if checkable:
        a.setCheckable(True)
    a.setEnabled(enabled)
    return a
630995
private static Prompt createPrompt(Resource<?> currentResource)
   {
      // [ currentdir]$
      if (OperatingSystemUtils.isWindows())
      {
         List<TerminalCharacter> prompt = new LinkedList<>();
         prompt.add(new TerminalCharacter('['));
         for (char c : currentResource.getName().toCharArray())
         {
            prompt.add(new TerminalCharacter(c));
         }
         prompt.add(new TerminalCharacter(']'));
         prompt.add(new TerminalCharacter('$'));
         prompt.add(new TerminalCharacter(' '));
         return new Prompt(prompt);
      }
      else
      {
         List<TerminalCharacter> prompt = new LinkedList<>();
         prompt.add(new TerminalCharacter('[', new TerminalColor(Color.BLUE, Color.DEFAULT),
                  CharacterType.BOLD));
         for (char c : currentResource.getName().toCharArray())
         {
            prompt.add(new TerminalCharacter(c));
         }
         prompt.add(new TerminalCharacter(']', new TerminalColor(Color.BLUE, Color.DEFAULT),
                  CharacterType.BOLD));
         prompt.add(new TerminalCharacter('$'));
         prompt.add(new TerminalCharacter(' '));
         return new Prompt(prompt);
      }
   }
588506
def interactive_prompt(message, parameters, default_opts):
    

    # pretty-print the message
    lines = message.split('\n')
    max_line_len = max([len(l) for l in lines])

    print('-' * max_line_len)
    print(message)
    print('-' * max_line_len)

    ret = {}
    for param in parameters:
        formatted_param = param
        prompt_str = '{}: '.format(formatted_param)
        if param in default_opts:
            prompt_str = '{} (default: "{}"): '.format(formatted_param, default_opts[param])

        try:
            value = raw_input(prompt_str)
        except KeyboardInterrupt:
            log.debug('Exiting on keyboard interrupt')
            sys.exit(0)

        if len(value) > 0:
            ret[param] = value
        elif param in default_opts:
            ret[param] = default_opts[param]
        else:
            ret[param] = None

    return ret
267187
def autocomplete(self, line):
        """"""
        current_length = len(line)
        self._current_line = line
        if current_length == 1 and self._last_position > 1:
            # Reset state.  This is likely from a user completing
            # a previous command.
            self.reset()
        elif current_length < self._last_position:
            # The user has hit backspace.  We'll need to check
            # the current words.
            return self._handle_backspace()
        elif not line:
            return []
        elif current_length != self._last_position + 1:
            return self._complete_from_full_parse()

        # This position is important.  We only update the _last_position
        # after we've checked the special cases above where that value
        # matters.
        self._last_position = len(line)
        if line and not line.strip():
            # Special case, the user hits a space on a new line so
            # we autocomplete all the top level commands.
            return self._current['commands']

        last_word = line.split()[-1]
        if last_word in self.arg_metadata or last_word in self._global_options:
            # The last thing we completed was an argument, record
            # this as self.last_arg
            self.last_option = last_word
        if line[-1] == ' ':
            # At this point the user has autocompleted a command
            # or an argument and has hit space.  If they've
            # just completed a command, we need to change the
            # current context and traverse into the subcommand.
            # "ec2 "
            #      ^--here, need to traverse into "ec2"
            #
            # Otherwise:
            # "ec2 --no-validate-ssl "
            #                        ^-- here, stay on "ec2" context.
            if not last_word.startswith('-'):
                next_command = self._current['children'].get(last_word)
                if next_command is not None:
                    self._current = next_command
                    self._current_name = last_word
                    self.cmd_path.append(self._current_name)
            elif last_word in self.arg_metadata and \
                    self.arg_metadata[last_word]['example']:
                # Then this is an arg with a shorthand example so we'll
                # suggest that example.
                return [self.arg_metadata[last_word]['example']]
            # Even if we don't change context, we still want to
            # autocomplete all the commands for the current context
            # in either of the above two cases.
            return self._current['commands'][:]
        elif last_word.startswith('-'):
            # TODO: cache this for the duration of the current context.
            # We don't need to recompute this until the args are
            # different.
            all_args = self._get_all_args()
            if self.match_fuzzy:
                return fuzzy_search(last_word, all_args)
            else:
                return substring_search(last_word, all_args)
        if self.match_fuzzy:
            return fuzzy_search(last_word, self._current['commands'])
        else:
            return substring_search(last_word, self._current['commands'])
285254
function(suggestions, completer, token) {
    var hintList = [];
    for (var i = 0; i < suggestions.length; i++) {
      var suggestedString = suggestions[i];
      if (completer.postProcessToken) {
        suggestedString = completer.postProcessToken(token, suggestedString);
      }
      hintList.push({
        text: suggestedString,
        displayText: suggestedString,
        hint: selectHint
      });
    }

    var cur = yasqe.getCursor();
    var returnObj = {
      completionToken: token.string,
      list: hintList,
      from: {
        line: cur.line,
        ch: token.start
      },
      to: {
        line: cur.line,
        ch: token.end
      }
    };
    //if we have some autocompletion handlers specified, add these these to the object. Codemirror will take care of firing these
    if (completer.callbacks) {
      for (var callbackName in completer.callbacks) {
        if (completer.callbacks[callbackName]) {
          YASQE.on(returnObj, callbackName, completer.callbacks[callbackName]);
        }
      }
    }
    return returnObj;
  }