static void Main(string[] args) { Console.WriteLine("Welcome to the Product Manager!"); Product p1 = new Product(); p1.code = ".net"; p1.description = "Murach's C# and .Net"; p1.price = 58.99; Product p2 = new Product("java", "Murach's Java Programming", 59.50); Console.WriteLine("p1 = " + p1); Console.WriteLine($"p2 = {p2}"); String code = MyConsole.GetString("\nEnter product code: "); String desc = MyConsole.GetString("Enter product description: "); double price = MyConsole.GetDouble("Enter product price: "); Product p3 = new Product(code, desc, price); Console.WriteLine("\np3 = " + p3); LineItem l1 = new LineItem(); l1.product = p1; l1.quantity = 1; l1.total = p1.price; Console.WriteLine("\nl1 = " + l1); Console.WriteLine("\nBye"); }
static T Deserialize <T>(string pPath) where T : class { if (!File.Exists(pPath)) { return(null); } object tInfo = null; try { using (var tStream = new MemoryStream(File.ReadAllBytes(pPath))) { if (tStream.Length != 0) { var tFormater = new BinaryFormatter(); tInfo = tFormater.Deserialize(tStream); tStream.Close(); } } } catch (Exception ex) { MyConsole.WriteLine(ex.ToString()); } return(tInfo as T); }
public void Start() { m_server.Start(400); m_server.ConnectionAccepted += AccepteClient; MyConsole.Write(string.Format("Listening on port {0}.", 400)); }
static public void SaveCacheInfo(ScrapBaseInfo pInfo) { if (pInfo == null || pInfo.image == null) { return; } try { var tFolderName = pInfo.GetFolderName(); if (!Directory.Exists(tFolderName)) { Directory.CreateDirectory(tFolderName); } var tPath = Path.Combine(tFolderName, pInfo.GetFileName()); Serialize(pInfo, tPath); tPath = Path.Combine(tFolderName, pInfo.weightInfo.GetFileName()); if (!File.Exists(tPath)) { Serialize(pInfo.weightInfo, tPath); } MyConsole.WriteLine("缓存图片成功. {0}", pInfo.ToString()); } catch (Exception ex) { MyConsole.WriteLine("缓存图片失败. {0}\n{1}", pInfo.ToString(), ex.ToString()); } }
static void Serialize <T>(T pObject, string pPath) where T : class { if (pObject == null) { return; } try { if (File.Exists(pPath)) { File.Delete(pPath); } using (var tStream = new FileStream(pPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { var tFormater = new BinaryFormatter(); tFormater.Serialize(tStream, pObject); tStream.Close(); } } catch (Exception ex) { MyConsole.WriteLine(ex.ToString()); } }
private void _CmdUser_TriggerBuild() { try { var prolog = new PrologEngine(persistentCommandHistory: false); prolog.ConsultFromString(CodeDocument.Text); prolog.GetFirstSolution(CodeDocumentQuery.Text); MyConsole.WriteLine("----------------------"); foreach (var sol in prolog.GetEnumerator()) { var errorInfo = MyPrologUtils.TryToGetErrorFromPrologSolution(sol); if (errorInfo != null) { CurErrorMessage = errorInfo.Message; var errorLine = CodeDocumentQuery.GetLineByNumber(1); CurErrorWordHighlightQuery = new WordHighlight(errorLine.Offset, errorLine.Length); break; } var stringified = sol.VarValuesIterator.Select(val => $"{val.Name}:{val.Value}").StringJoin(", "); MyConsole.WriteLine(stringified); } } catch (Exception ex) { var errorInfo = MyPrologUtils.TryToGetErrorFromException(ex); if (errorInfo.Line != null) { var errorLine = CodeDocument.GetLineByNumber(errorInfo.Line.Value); CurErrorWordHighlight = new WordHighlight(errorLine.Offset, errorLine.Length); } CurErrorMessage = errorInfo.Message; } }
public void LoadMods(string modsDirectory) { List <string> modDirectories = Directory.GetDirectories(modsDirectory).ToList(); LoadingBar.Load(modDirectories.Map(modDirectory => { ModInfo modInfo = null; Assembly assembly = null; return(new Task($"Загружаем моды: мод из папки {modDirectory}", () => { MyConsole.MoveCursorDown(3); LoadingBar.Load( new Task($"Загружаем JSON для мода из папки {modDirectory}...", () => { string modJSON = $"{modDirectory}/mod.json"; modInfo = JsonConvert.DeserializeObject <ModInfo>(File.ReadAllText(modJSON)); modInfo.modDirectory = modDirectory; }), new Task(() => $"Загружаем код для мода '{modInfo.name}'", () => { assembly = Assembly.LoadFrom($"{modDirectory}/{modInfo.dllName}"); }), new Task(() => $"Инициализируем мод '{modInfo.name}...'", () => { Type modDescriptorType = assembly.GetType(modInfo.descriptorClass); ConstructorInfo modDescriptorConstructor = modDescriptorType.GetConstructor(new[] { typeof(ModInfo) }); var modDescriptor = (ModDescriptor)modDescriptorConstructor.Invoke(new[] { modInfo }); modDescriptors.Add(modDescriptor); MyConsole.MoveCursorDown(3); modDescriptor.OnLoadBy(this); MyConsole.MoveCursorUp(3); }) ); MyConsole.MoveCursorUp(3); })); })); }
static void Main(string[] args) { Console.WriteLine("Pig Dice Game"); // ask user how many games they want to play int numOfGames = MyConsole.getInt("How many games do you want to play: "); Console.WriteLine("You selected " + numOfGames + " game(s)"); Console.WriteLine("Here we go..."); int max = 0; // roll the dice for (int i = 0; i < numOfGames; i++) { int roll = 0; int total = 0; while (roll != 1) { Random r = new Random(); roll = r.Next(1, 7); total += roll; } Console.WriteLine("Game #" + i + " score:" + total); max = Math.Max(max, total); roll = 0; total = 0; } Console.WriteLine("===================="); Console.WriteLine("Total games:\t" + numOfGames); Console.WriteLine("Max Score:\t" + max); Console.WriteLine("===================="); }
static void DoLoading() { Task[] realTasks = { new Task("Загружаем ассеты...", () => { Assets = new AssetContainer("assets"); }), new Task("Загружаем классическую кампанию...", () => { MyConsole.MoveCursorDown(3); Campaigns.Add(Campaign.LoadFrom(Assets, "classic-campaign")); MyConsole.MoveCursorUp(3); }), new Task("Загружаем моды...", () => { MyConsole.MoveCursorDown(3); ModLoader.LoadMods("mods"); MyConsole.MoveCursorUp(3); }) }; #if DEBUG LoadingBar.Load(realTasks); #else Task[] funnyTasks = FunnyTasksLoader.Load(); Task[] allTasks = realTasks.Concat(funnyTasks).ToArray(); LoadingBar.Load(allTasks); #endif }
override protected Solution buildSolution() { // Variables Solution s = new Solution(model); // Initializing a new solution structure solution(vector x, vector y) int selJob; bool constructOK = true; // Iterative scheduling of jobs based on priority rule do { // Select the job that has the priority // Implemented in the child class selJob = getJobToAssign(s, rule); if (selJob >= 0) { // MyConsole.display($"Assigning job {selJob}"); constructOK = model.assignJob(s, selJob, 0); if (!constructOK) { MyConsole.displayError($"Could not assign job {selJob}"); } } }while (selJob >= 0 && constructOK); if (constructOK) { model.finalize(s); return(s); } else { return(null); } }
private void BTN_StartPOL_Click(object sender, EventArgs e) { if (this.POLConsole != null) { // already running MessageBox.Show("POL's already running"); // How?! return; } string exepath = Settings.Global.Properties["POLExePath"]; string dirpath = Settings.Global.Properties["POLPath"]; if (!File.Exists(exepath)) { MessageBox.Show("File does not exist in POLExePath!"); return; } if (!Directory.Exists(dirpath)) { dirpath = Path.GetDirectoryName(exepath); } // begin pol console... this.POLConsole = new MyConsole(); this.POLConsole.Start(Path.GetFullPath(exepath), Path.GetFullPath(dirpath), true); this.POLConsole.Exited += new EventHandler(POLConsole_Exited); this.POLConsole.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(POLConsole_OutputDataReceived); BTN_StartPOL.Enabled = false; }
public void commandLine_TextChanged(MyGuiControlTextbox sender) { var text = sender.Text; //do not open autocomplete if text doesn't end with dot if (text.Length == 0 || !sender.Text.ElementAt(sender.Text.Length - 1).Equals('.')) { if (m_autoComplete.Enabled) { m_autoComplete.Enabled = false; m_autoComplete.Deactivate(); } return; } //Sees if what is before the dot is a command MyCommand command; if (MyConsole.TryGetCommand(text.Substring(0, text.Length - 1), out command)) { m_autoComplete.CreateNewContextMenu(); m_autoComplete.Position = new Vector2(((1 - m_screenScale) / 2) + m_margin.X, m_size.Value.Y - 2 * m_margin.Y) + MyGuiManager.MeasureString(MyFontEnum.Debug, new StringBuilder(m_commandLine.Text), m_commandLine.TextScaleWithLanguage); foreach (var method in command.Methods) { m_autoComplete.AddItem(new StringBuilder(method).Append(" ").Append(command.GetHint(method)), userData: method); } m_autoComplete.Enabled = true; m_autoComplete.Activate(false); } }
public override void apply() { foreach (int r in System.Enum.GetValues(typeof(METHOD))) { rule = r; solution = buildSolution(); if (solution != null) { solution = localSearch(solution); if (bestSolution != null) { updateBestSolution(r); } else { bestSolution = solution; fitnessCurve.Add(model.fitness(solution), r); } } else { MyConsole.displayError($"Couldn't find solution using rule {r}"); } } exportFitnessToExcel(); }
public void DoWhileLoopInputTest_ReturnsFalse(string input) { IConsole console = new MyConsole(); bool actual = GetPrivateMethodResults(input); Assert.False(actual); }
static void FinishLoading() { Thread.Sleep(2500); Console.Write("Приготовтесь к..."); Thread.Sleep(1000); MyConsole.ClearLine(); Thread.Sleep(2000); }
public static void Main_6_3_1()//Main_6_3_1 { MyConsole.WriteLine("应用了类的别名。"); BoyPlayer.Play(); GirlPlayer.Play(); Boyspace.Player.Play(); Girlspace.Player.Play(); }
private static double TimeDifferent(DateTime lastDateTime) { var time = DateTime.Now - lastDateTime; MyConsole.Data("TimeDifferent" + time.TotalSeconds); return(time.TotalSeconds); }
static void Main() { SqlDataAccess.GetData(); //OracleDataAccess.GetData(); Circle.Draw(); MyConsole.Write("write this"); MsAccessDataAccess.GetData(); }
private void DataMonitor_Load(object sender, EventArgs e) { MyConsole.Add("数据监控启动", Color.Orange); this.FormClosing += DataMonitor_FormClosing; //创建菜单 contextMenu = new ContextMenuStrip(); contextMenu.Font = new Font("新宋体", 14); contextMenu.Items.Add("更新描述"); contextMenu.Items.Add("清除描述"); //添加点击事件 contextMenu.Items[0].Click += contextMenu_AddDes_Click; contextMenu.Items[1].Click += contextMenu_ClearDes_Click; //添加单元格点击事件 doubleBufferListView1.MouseClick += DoubleBufferListView1_MouseClick; #region 数据列表 datekey[0] = "日期"; datekey[1] = "时间"; datekey[2] = "寄存器类型"; datekey[3] = "寄存器地址"; datekey[4] = "值"; datekey[5] = "更新次数"; datekey[6] = "传输方向"; datekey[7] = "描述"; doubleBufferListView1.FullRowSelect = true;//要选择就是一行 doubleBufferListView1.Columns.Add(datekey[0], 180, HorizontalAlignment.Center); doubleBufferListView1.Columns.Add(datekey[1], 220, HorizontalAlignment.Center); doubleBufferListView1.Columns.Add(datekey[2], 140, HorizontalAlignment.Center); doubleBufferListView1.Columns.Add(datekey[3], 140, HorizontalAlignment.Center); doubleBufferListView1.Columns.Add(datekey[4], 100, HorizontalAlignment.Left); doubleBufferListView1.Columns.Add(datekey[5], 100, HorizontalAlignment.Left); doubleBufferListView1.Columns.Add(datekey[6], 150, HorizontalAlignment.Left); doubleBufferListView1.Columns.Add(datekey[7], -2, HorizontalAlignment.Left); for (int i = 0; i < DataSync.Profinet.Register.Length; i++) { ListViewItem item = new ListViewItem(); item.Text = DateTime.Now.ToString("yyyy-MM-dd"); //"日期"; item.SubItems.Add(DateTime.Now.ToString("HH:mm:ss fff")); // "时间"; item.SubItems.Add("WORD"); // "寄存器类型"; item.SubItems.Add("0"); // "寄存器地址"; item.SubItems.Add("0"); // "值"; item.SubItems.Add("0"); // "更新次数"; item.SubItems.Add(""); // "传输方向"; item.SubItems.Add(""); // "描述"; doubleBufferListView1.Items.Add(item); doubleBufferListView1.Items[i].ForeColor = Color.Gray; doubleBufferListView1.Items[i].BackColor = i % 2 == 0 ? Color.White : Color.FromArgb(0xf0, 0xf5, 0xf5, 0xf5); } #endregion mainThread = new ExThread(func); mainThread.Start(); }
private static void RecevicedTopic(MqttApplicationMessageReceivedEventArgs e) { MyConsole.Info("### RECEIVED APPLICATION MESSAGE ###"); MyConsole.Info($"+ Topic = {e.ApplicationMessage.Topic}"); MyConsole.Info($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); MyConsole.Info($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); MyConsole.Info($"+ Retain = {e.ApplicationMessage.Retain}"); Console.WriteLine(); }
public static List <String> DropItem(List <String> wizardItems) { int enterNumber = MyConsole.GetInt("Number: "); enterNumber--; Console.WriteLine(wizardItems[enterNumber] + " was dropped"); wizardItems.RemoveAt(enterNumber); return(wizardItems); }
private int SetDataBits(int currentSettings) { var ind = _dataBitsList.ToList().IndexOf(currentSettings.ToString()); ind = ind >= 0 ? ind : 0; var str = MyConsole.SelectFromList(_dataBitsList, "BaudRate", ind); return(int.Parse(str)); }
static void Main() { //Fully-qualified naming MySystem.DataAccess.SqlDataAccess.GetData(); //OracleDataAccess.GetData(); Circle.Draw(); MyConsole.Write("write this"); MsAccessDataAccess.GetData(); }
/// <summary> /// 开始解析转换爬取到的Url内容 /// </summary> /// <param name="param">参数</param> /// <returns>新的Urls</returns> public List <string> ParseUrl(params object[] param) { if (param.Length < 3) { return(null); } string content = param[0].ToString(); string baseForlder = param[1].ToString(); string url = param[2].ToString(); MyConsole.AppendLine(string.Format("开始解析Url:{0}的内容", url)); List <string> urls = new List <string>(); Regex regex = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))", RegexOptions.IgnoreCase | RegexOptions.Compiled); if (regex.IsMatch(content)) { MatchCollection collection = regex.Matches(content); foreach (Match item in collection) { urls.Add(item.Groups[1].Value); } } MyConsole.AppendLine(string.Format("找到{0}个锚点..", urls.Count)); regex = new Regex(@"(?i)<img[^>]*?\ssrc\s*=\s*(['""]?)(?<src>[^'""\s>]+)\1[^>]*>"); MatchCollection mc = regex.Matches(content); foreach (Match m in mc) { urls.Add(m.Groups["src"].Value); } MyConsole.AppendLine(string.Format("找到{0}个图片..", mc.Count)); //返回新的Url List <ParseModel> parseModels = RegexCondition as List <ParseModel>; //储存需要的文本 if (parseModels != null && parseModels.Count > 0) { foreach (var item in parseModels) { Regex temp = new Regex(item.RegexString); if (temp.IsMatch(content)) { MatchCollection matches = temp.Matches(content); foreach (Match match in matches) { ContentManger.Save(baseForlder, Encoding.Default.GetBytes(match.Value), item.SaveType, Guid.NewGuid().ToString() + ".txt"); _main.DownloadFileCount++; } } } } return(urls); }
void POLConsole_Exited(object sender, EventArgs e) { txtPOLConsole.Invoke((MethodInvoker) delegate() { txtPOLConsole.Text += "<Process exited>" + System.Environment.NewLine; }); ((MyConsole)sender).Dispose(); this.POLConsole = null; BTN_StartPOL.Invoke((MethodInvoker) delegate() { BTN_StartPOL.Enabled = true; }); }
private void DumpStackTraces(Exception e, FilterStackFrame fsf, ref bool printedHeader) { if (PythonEngine.options.ExceptionDetail) { if (!printedHeader) { MyConsole.WriteLine(e.Message, Style.Error); printedHeader = true; } List <System.Diagnostics.StackTrace> traces = ExceptionConverter.GetExceptionStackTraces(e); if (traces != null) { for (int i = 0; i < traces.Count; i++) { for (int j = 0; j < traces[i].FrameCount; j++) { StackFrame curFrame = traces[i].GetFrame(j); if (fsf == null || fsf(curFrame)) { MyConsole.WriteLine(curFrame.ToString(), Style.Error); } } } } MyConsole.WriteLine(e.StackTrace.ToString(), Style.Error); if (e.InnerException != null) { DumpStackTraces(e.InnerException, ref printedHeader); } } else { // dump inner most exception first, followed by outer most. if (e.InnerException != null) { DumpStackTraces(e.InnerException, ref printedHeader); } if (!printedHeader) { MyConsole.WriteLine("Traceback (most recent call last):", Style.Error); printedHeader = true; } DumpStackTrace(new StackTrace(e, true), fsf); List <StackTrace> traces = ExceptionConverter.GetExceptionStackTraces(e); if (traces != null && traces.Count > 0) { for (int i = 0; i < traces.Count; i++) { DumpStackTrace(traces[i], fsf); } } } }
public static RoleParamType GetRoleParamType(string paramName, string value = null) { RoleParamType roleParamType; lock (RoleParamNameInfo.readerWriterLock) { if (GameDBManager.Flag_Splite_RoleParams_Table != 0) { if (RoleParamNameInfo.RoleParamNameTypeDict.TryGetValue(paramName, out roleParamType)) { return(roleParamType); } int key; if (int.TryParse(paramName, NumberStyles.None, NumberFormatInfo.InvariantInfo, out key) && key >= 0) { if (key < 10000) { int rem; Math.DivRem(key, 10, out rem); roleParamType = new RoleParamType(paramName, paramName, "t_roleparams_char", "idx", "v" + rem, key - rem, key, 2); } else if (key < 20000) { int rem; Math.DivRem(key, 40, out rem); roleParamType = new RoleParamType(paramName, paramName, "t_roleparams_long", "idx", "v" + rem, key - rem, key, 2); } else { roleParamType = new RoleParamType(paramName, paramName, "t_roleparams_2", "pname", "pvalue", key, key, 0); } } else { if (RoleParamNameInfo.GetPrefixParamNameType(paramName) == null && (!RoleParamNameInfo.RoleParamNameTypeExtDict.TryGetValue(paramName, out roleParamType) || roleParamType.Type != -1)) { string msg = string.Format("使用了未配置的角色参数:{0},{1}", paramName, value); MyConsole.WriteLine(msg, new object[0]); LogManager.WriteLog(LogTypes.Error, msg, null, true); } roleParamType = new RoleParamType(paramName, paramName, "t_roleparams_2", "pname", "pvalue", 0, 0, 0); } RoleParamNameInfo.RoleParamNameTypeDict[paramName] = roleParamType; } else { if (RoleParamNameInfo.OldRoleParamNameTypeDict.TryGetValue(paramName, out roleParamType)) { return(roleParamType); } roleParamType = new RoleParamType(paramName, paramName, "t_roleparams", "pname", "pvalue", 0, 0, 0); RoleParamNameInfo.OldRoleParamNameTypeDict[paramName] = roleParamType; } } return(roleParamType); }
public static void Display <T>(this T settings) where T : ISettings, IDescription { MyConsole.WriteNewLineGreen($"Current Settings"); foreach (var setting in settings.GetType().GetProperties()) { var description = settings.GetPropertyDescription(setting.Name); var value = setting.GetValue(settings); MyConsole.WriteLine($"{description,-40} {value}"); } }
public static void RenderArea(Rectangle rect) { var area = activeBuffer.GetArea(ref rect); MyConsole.WriteOutput( area, rect.Size, rect.UpperLeft ); }
public static void RenderOutput() { var chars = activeBuffer.Content; MyConsole.WriteOutput( chars, new Point(chars.GetLength(1), chars.GetLength(0)), new Point(0, 0) ); }
public Interpreter(MyConsole theConsole) { myPreInterpreter = new PreInterpreter(this); this.theConsole = theConsole; myLogger = new InterPreterLogger(this); }
public BenchObjectHandler(MyConsole theConsole) { this.theConsole = theConsole; }