Example #1
0
        public static string RedPeanutCLI(IAgentInstance agent, string module)
        {
            string input;

            if (agent == null)
            {
                PrintCLI(module);
                input = ReadLine.Read();

                if (input.Trim().Length > 0)
                {
                    ReadLine.AddHistory(input);
                }

                return(input);
            }
            else
            {
                PrintCLI(agent.AgentId, module);
                input = ReadLine.Read();
                StandardCommand cmd = new StandardCommand(agent);
                if (cmd.Execute(input))
                {
                    input = "";
                }

                if (input.Trim().Length > 0)
                {
                    ReadLine.AddHistory(input);
                }

                return(input);
            }
        }
Example #2
0
        private void buttonLoadApps_Click(object sender, EventArgs e)
        {
            string ReadLine;

            string[] array;
            string   Path = @"D:\apk.txt";

            this.comboxQcProName.Items.Clear();
            StreamReader reader = new StreamReader(Path, System.Text.Encoding.GetEncoding("GB2312"));

            while (reader.Peek() >= 0)
            {
                try
                {
                    ReadLine = reader.ReadLine();
                    if (ReadLine != "")
                    {
                        ReadLine = ReadLine.Replace("\"", "").Substring(8);
                        array    = ReadLine.Split(',');
                        Console.WriteLine(array);
                        if (array.Length == 0)
                        {
                            MessageBox.Show("您选择的导入数据类型有误,请重试!");
                            return;
                        }
                        this.comboxQcProName.Items.Add(array[0]);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                comboxQcProName.Text = "Select apk";
            }
        }
Example #3
0
        private void RunPrompt()
        {
            PrintBanner();
            ReadLine.HistoryEnabled        = true;
            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            while (true)
            {
                string command = ReadLine.Read("> ");

                if (command.ToLowerInvariant() == "/quit" || command.ToLowerInvariant() == "/exit")
                {
                    break;
                }
                else if (command.ToLowerInvariant() == "/help")
                {
                    ShowHelp();
                    continue;
                }

                // REPL mode is more relaxed: -Wno-error is enabled for all warnings by default. It simply makes sense
                // to be less strict in this mode, since it's often used in an ad-hoc fashion for exploratory
                // programming.
                Run(command, CompilerWarningAsWarning);
            }
        }
Example #4
0
        public string GetString(DialogArgs args, List <string> options)
        {
            WritePromptFor(args);

            ReadLine.AutoCompletionHandler = new AutoComplete(options);
            return(ReadLine.Read());
        }
Example #5
0
        public static void Main(string[] args)
        {
            Console.WriteLine("ReadLine Library Demo");
            Console.WriteLine("---------------------");
            Console.WriteLine();

            string[] history = new string[] { "ls -a", "dotnet run", "git init" };
            ReadLine.AddHistory(history);

            ReadLine.AutoCompletionHandler = (t, s) =>
            {
                if (t.StartsWith("git "))
                {
                    return new string[] { "init", "clone", "pull", "push" }
                }
                ;
                else
                {
                    return(null);
                }
            };

            string input = ReadLine.Read("(prompt)> ");

            Console.Write(input);
        }
        private void OnInputThreadStart()
        {
            while (m_IsAlive)
            {
                try
                {
                    if (System.Console.KeyAvailable)
                    {
                        var command = m_ReadLineEnabled
                            ? ReadLine.Read()
                            : System.Console.ReadLine();

                        if (!string.IsNullOrWhiteSpace(command))
                        {
                            // Enqueue command because inputCommitted is expected on main thread/
                            m_CommandQueue.Enqueue(command);
                        }
                    }
                }
                catch (IOException ex)
                {
                    m_Logger.LogDebug(ex, "Exception occured in Console Input Thread");
                }

                Thread.Sleep(10);
            }
        }
Example #7
0
        static void Main(string[] args)
        {
            var path = Path.GetFullPath(args.Length > 0 ? args[0].Replace("\"", "") : "./ ");

            Console.Write($"Processing Assemblies under {path} ... ");
            _nephilaInstance = new Nephila(new ConsoleLogger(), path);

            Console.WriteLine("Done");
            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            while (true)
            {
                var input = ReadLine.Read(_prompt);
                if (input.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
                {
                    break;
                }

                var assemblyRefPairs = _nephilaInstance.GetReferencePairs(input);
                if (assemblyRefPairs.Count <= 0)
                {
                    Console.WriteLine($"No result for {input}.");
                    continue;
                }

                DrawAssemblyReferenceDiagram(assemblyRefPairs, input);
            }
        }
Example #8
0
        public void StartProcessing(TicTacToeWithEvents game)
        {
            string command = null;

            Console.Out.WriteLine("Welcome to greatest Tic Tac Toe game! Type START to play ");
            while (true)
            {
                command = ReadLine.Read("> ");
                var splitCommand = command.Split(new char[0]);
                switch (splitCommand[0].ToLower())
                {
                case "start":
                    game.StartGame();
                    break;

                case "exit":
                    break;

                case "move":
                    var x = int.Parse(splitCommand[1]);
                    var y = int.Parse(splitCommand[2]);
                    game.MakeMove(x, y);
                    break;
                }
            }
        }
Example #9
0
        protected override void Execute(object options, IContext context)
        {
            if (context.Database.IsDirty)
            {
                while (true)
                {
                    var answer = ReadLine.Read("You have unsaved chanages. What to do? (save/discard/cancel)? ");

                    if (answer == "save" || answer == "s")
                    {
                        context.DatabaseManager.SaveDatabase(context.Database, context.DatabasePath);
                        break;
                    }
                    else if (answer == "discard" || answer == "d")
                    {
                        break;
                    }
                    else if (answer == "cancel" || answer == "c")
                    {
                        return;
                    }
                }
            }

            context.ShouldExit = true;
        }
Example #10
0
        /// <summary>
        /// A asynchronous Run method for an REPL
        /// </summary>
        /// <param name="configuration">Prompt Configuration, null for using default settings</param>
        /// <param name="token">Cancellation Token, allows the task to exit nicely</param>
        /// <returns></returns>
        public static async Task RunAsync(IPromptConfiguration configuration = null, CancellationToken token = default)
        {
            var prompt = new Prompt(configuration);
            var cmd    = string.Empty;

            while (!string.Equals(cmd, "exit", StringComparison.OrdinalIgnoreCase))
            {
                var promptText = $"{prompt.Configuration.GetOption("PromptPreFix")}{prompt.CurrentFolder}{prompt.Configuration.GetOption("PromptPostFix")}";
                // ReadLine is not await able, hence running as a Task.Run. Improve foreign project to
                // include ReadLine.ReadAsync( with CancellationToken)
                await Task.Run(() => cmd = ReadLine.Read(promptText), token);

                try
                {
                    prompt.Run(cmd);
                }
                catch (Exception exception)
                {
                    // Don't allow an exception to crash the application by a throw
                    Console.WriteLine(exception);
                }
            }

            HistoryFile.Save(configuration);
        }
Example #11
0
 public override void Prompt()
 {
     InputEnabled = true;
     //string prompt = Context.Peek().Label.StartsWith("INPUT_") ? "|*>" : "|>";
     string i =  ReadLine.Read(PromptString);
     HandleInput(DateTime.Now, i);
 }
Example #12
0
        // Driver code
        static void Main()
        {
            string str1 = new ReadLine(Console.ReadLine);
            string str2 = new ReadLine(Console.ReadLine);

            Console.WriteLine(FindSum(str1, str2));
        }
Example #13
0
        private static void StartingMainLoop()
        {
            // System.Console.WriteLine("Strating main loop");
            keyEventCts?.Cancel();
            mainCts = new CancellationTokenSource();
            var mainToken = mainCts.Token;

            Task.Factory.StartNew(() =>
            {
                while (!mainToken.IsCancellationRequested)
                {
                    try
                    {
                        string input = ReadLine.Read(PROMPT_TITLE);
                        if (!string.IsNullOrEmpty(input) || !string.IsNullOrWhiteSpace(input))
                        {
                            GenerateCommands();
                            ReadLine.AddHistory(input);
                            app.Execute(input.Split(' ').ToArray());
                        }
                    }
                    catch
                    {
                    }
                }
            }, mainToken);
        }
Example #14
0
        public void UpdateHistory(string statement)
        {
            try
            {
                if (!File.Exists(HistoryFilePath))
                {
                    File.Create(HistoryFilePath).Dispose();
                }

                if (!SecuredCommands.Any(statement.Contains))
                {
                    List <string> history = ReadLine.GetHistory();
                    if (history.LastOrDefault() != statement)
                    {
                        ReadLine.AddHistory(statement);
                        _historyCloned.Insert(0, statement);
                    }
                }
                else
                {
                    ReadLine.AddHistory(_removedString);
                    _historyCloned.Insert(0, statement);
                }

                File.WriteAllLines(HistoryFilePath, _historyCloned.Distinct().Reverse().ToArray());
            }
            catch (Exception e)
            {
                if (writeFailNotReported)
                {
                    writeFailNotReported = false;
                    _cliConsole.WriteErrorLine($"Could not write cmd history to {HistoryFilePath} {e.Message}");
                }
            }
        }
Example #15
0
        public static async Task <string> StartSession()
        {
            Console.Write("Enter username: "******"Enter password: "******"/api/Users/Login");
            string jsonRequest   = JsonConvert.SerializeObject(loginInput);
            var    stringContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

            request.Content = stringContent;
            var response = await client.SendAsync(request);

            var responseString = await response.Content.ReadAsStringAsync();

            var    responseJson = JsonConvert.DeserializeObject <LoginOutput>(responseString);
            string userToken    = responseJson.Token;

            return(userToken);
        }
Example #16
0
        public static string GetText(string prompt, string defaultValue)
        {
            var fullPrompt = FullPrompt(prompt, defaultValue);
            var input      = ReadLine.Read(fullPrompt, defaultValue);

            return(string.IsNullOrWhiteSpace(input) ? defaultValue : input);
        }
Example #17
0
        private static void StartInteractiveMode()
        {
            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            while (true)
            {
                var input = ReadLine.Read(_prompt);
                if (input.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
                {
                    break;
                }

                var hostSolutions = _centipedeInstance.GetHostSolutions(input);
                if (hostSolutions.Count() <= 0)
                {
                    Console.WriteLine($"No result for {input}.");
                    continue;
                }
                else
                {
                    Console.WriteLine("This file is in the following solutions: ");
                    foreach (var solution in hostSolutions)
                    {
                        Console.WriteLine(solution.Path);
                    }
                }
            }
        }
Example #18
0
        private static List <DatabaseConnection> PromptConnectionOptions(List <DatabaseConnection> possible_connections)
        {
            foreach (var option in RequiredConnectionOptions)
            {
                var withOption = possible_connections.Where(c => c.ContainsOption(option)).ToList();
                if (withOption.Any())
                {
                    possible_connections = withOption;
                }
                else
                {
                    var prompt = $"{option}:";
                    var value  = option == PasswordOption
                        ? ReadLine.ReadPassword(prompt)
                        : ReadLine.Read(prompt);

                    foreach (var connection in possible_connections)
                    {
                        connection.SetOption(option, value);
                    }
                }
            }

            return(possible_connections);
        }
Example #19
0
        public void TestGetCorrectHistory()
        {
            var history = ReadLine.GetHistory();

            Assert.Equal(3, history.Count);
            Assert.Equal("git init", history.Last());
        }
Example #20
0
        public static async Task <string> Readline(WorkItemManager manager, WorkItem wi, PropertyDescriptor propertyDescriptor, string currentValue)
        {
            ReadLine.ClearHistory();
            ReadLine.AutoCompletionHandler = null;

            if (propertyDescriptor.ValueProvider != null)
            {
                var valueProvider = manager.ValidationManager.CreateValueProvider(wi, propertyDescriptor.ValueProvider);
                if (valueProvider.IsUserExpierenceEnumerable)
                {
                    foreach (var providedValue in await valueProvider.ProvideAllValuesAsync())
                    {
                        ReadLine.AddHistory(providedValue.Value);
                    }
                }

                ReadLine.AutoCompletionHandler = new ValueProviderReadLineAutoCompletion(valueProvider);
            }

            string result;

            if (string.IsNullOrWhiteSpace(currentValue))
            {
                result = ReadLine.Read($"{propertyDescriptor.Name}: ");
            }
            else
            {
                result = ReadLine.Read($"{propertyDescriptor.Name} [{currentValue}]: ");
            }

            return(result);
        }
Example #21
0
        static void Main(string[] args)
        {
            ReadLine.AutoCompletionHandler = new LispAutoCompletionHandler(coreLisp);
            ReadLine.HistoryEnabled        = true;
            string input = ReadLine.Read("> ");

            while (input != "quit")
            {
                bool isCommand = false;
                foreach (var command in Commands)
                {
                    if (input.StartsWith(command.Key))
                    {
                        command.Value(input);
                        isCommand = true;
                        break;
                    }
                }


                if (!isCommand)
                {
                    var t = coreLisp.Run(input);
                    Console.WriteLine(t);
                }

                input = ReadLine.Read(">");
            }
        }
Example #22
0
        private void Worker(object cancellationToken)
        {
            var token = (CancellationToken)cancellationToken;

            while (!token.IsCancellationRequested)
            {
                using (var me = Process.GetCurrentProcess())
                    Console.WriteLine($"Worker: {DateTime.Now} - Hello, I am {me.ProcessName} ({me.Id}) invoked by {Environment.CommandLine}");

                if (IsInteractive)
                {
                    var read = ReadLine.Read(token, "q to exit: ");

                    ////Console.Write("q to exit: ");
                    ////var read = ConsoleEx.ReadLine(token); // Cannot use the regular ReadLine here: it is blocking...
                    Console.WriteLine($">line read: '{read}'");
                    if (token.IsCancellationRequested || read?.ToLowerInvariant() == "q")
                    {
                        break;
                    }
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }

            Console.WriteLine("## Worker: thread ended by user");
            Terminated?.Invoke(this, EventArgs.Empty);
        }
Example #23
0
        static string ReadQuery()
        {
            StringBuilder sb = new StringBuilder();
            string        line;

            while (true)
            {
                if ((line = System.ReadLine.Read()) == null)
                {
                    sb.Length = 0;

                    break;
                }
                else
                {
                    sb.AppendLine(line);

                    if (line.EndsWith("/") || line.StartsWith("!") || line.EndsWith("."))
                    {
                        break;
                    }

                    Console.Write("|  ");
                }
            }

            ReadLine.AddHistory(sb.ToString().TrimEnd(Environment.NewLine.ToCharArray()));
            return(sb.ToString());
        }
Example #24
0
        public static void StartListening()
        {
            s_IsRunning = true;
            do
            {
                var line = ReadLine.Read().Trim();
                if (!string.IsNullOrEmpty(line))
                {
                    if (line.Equals("exit", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }

                    try
                    {
                        OnCommandExecute?.Invoke(line);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString(), Color.DarkRed);
                        Debugger.Break();
                    }
                }
            } while (s_IsRunning);
        }
        private static int Auth(AuthOptions options)
        {
            var clientId = ReadLine.Read("Client id:");

            if (string.IsNullOrEmpty(clientId))
            {
                Log.Logger.Error("You must provide a client id.");
                return(1);
            }

            var clientSecret = ReadLine.Read("Client secret:");

            if (string.IsNullOrEmpty(clientSecret))
            {
                Log.Logger.Error("You must provide a client secret.");
                return(1);
            }

            var youtubeAuthFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".youtube-dump-auth.json");

            if (File.Exists(youtubeAuthFile))
            {
                File.Delete(youtubeAuthFile);
            }

            File.WriteAllText(youtubeAuthFile, JsonConvert.SerializeObject(new ClientSecrets
            {
                ClientId     = clientId,
                ClientSecret = clientSecret
            }, Formatting.Indented));

            Console.WriteLine("Saved!");

            return(0);
        }
Example #26
0
        static async Task Main()
        {
            Console.WriteLine("Dual Numbers 1.0\n1D function must starts from 't =>'\n3D function must starts from 'p =>'");
            Console.WriteLine("Examples:\nSqrt(2*2)\nt => Sin(t)\nt => Vec(1, 2, t)\np => p^Vec(0, 0, 1)");
            ReadLine.AddHistory("Sqrt(2*2)", "t => Sin(t)", "t => Vec(1, 2, t)", "p => p^Vec(0, 0, 1)");

            while (true)
            {
                try
                {
                    var code = ReadLine.Read("(prompt)> ");
                    if (code.StartsWith("t =>"))
                    {
                        await Func <DualNumber>(code);
                    }
                    else if (code.StartsWith("p =>"))
                    {
                        await Func <DualVectorGrad>(code);
                    }
                    else
                    {
                        await Expr(code);
                    }
                }
                catch (Exception ex)
                {
                    PrintError(ex);
                }
            }
        }
        /// <summary>
        /// Gets suggestions for the command line
        /// </summary>
        /// <param name="text">Console strings typed to get suggestions</param>
        /// <param name="index"></param>
        /// <returns>String array of matches</returns>
        public string[] GetSuggestions(string text, int index)
        {
            var sug = new List <string>();

            try
            {
                sug.AddRange(new List <string> {
                    "quit", "--help"
                });
                //Automatically and conveniently updates list with history
                sug.AddRange(ReadLine.GetHistory().ToImmutableHashSet().ToList());

                // NOTE: Add string collections to return suggestions.
                if (_additionalSeedStrings != null)
                {
                    sug.AddRange(_additionalSeedStrings);
                }

                return(sug.ToArray().Where(x => x.StartsWith(text)).ToArray());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(sug.ToArray());
        }
Example #28
0
        public void ReadData()//Read Data from File to List
        {
            try
            {
                StreamReader read = new StreamReader(path);
                string       ReadLine;

                while ((ReadLine = read.ReadLine()) != null)
                {
                    String[] data = ReadLine.Split(','); //Split String into Array of String with any char i want

                    Event tmp = new Event();
                    tmp.name          = data[0];
                    tmp.place         = data[1];
                    tmp.startDateTime = Convert.ToDateTime(data[2]);
                    tmp.endDateTime   = Convert.ToDateTime(data[3]);
                    tmp.CheckDone();
                    if (tmp.Done == false)
                    {
                        eventList.Add(tmp);
                        AddToListView(tmp);
                    }
                    else
                    {
                        Finished_Event.Add(tmp);
                    }
                }
                read.Close();//Add to Finally
            }
            catch { }
        }
Example #29
0
        static void LaunchInteractive()
        {
            ReadLine.HistoryEnabled        = true;
            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            while (true)
            {
                string   input = ReadLine.Read("spectabis > ");
                string[] args  = input.ParseAsArguments().ToArray();

                if (!string.IsNullOrEmpty(input) && !string.IsNullOrWhiteSpace(input) && args.Count() != 0)
                {
                    Console.WriteLine(String.Empty);

                    string   commandArg = args[0].ToLower();
                    string[] arguments  = args.Where(x => x != args[0]).ToArray();

                    try
                    {
                        ConsoleCommand command = CommandTable[commandArg];
                        command.CommandDelegate(arguments);
                    }
                    catch (KeyNotFoundException)
                    {
                        PrettyPrinter.Print($"'{commandArg}' command not found");
                    }
                }
            }
        }
 private static void SaveHistory()
 {
     if (ReadLine.HistoryEnabled)
     {
         var data = ReadLine.GetHistory().Where(a => !string.IsNullOrWhiteSpace(a));
         File.WriteAllLines(GetHistoryFile(), data.Skip(Math.Max(0, data.Count() - 100)));
     }
 }