private void RenderPath() { rects = new List <Rectangle>(); for (int i = 1; i < movementPath.Count - 1; i++) { Direction result = HelperFunction.GetIntersectionDir(movementPath[i - 1], movementPath[i], movementPath[i + 1]); switch (result) { case Direction.South: rects.Add(DirectionArrowSpriteSourceRectangle.GetSpriteRectangle(Direction.Center, true)); break; case Direction.East: rects.Add(DirectionArrowSpriteSourceRectangle.GetSpriteRectangle(Direction.Center, false)); break; default: rects.Add(DirectionArrowSpriteSourceRectangle.GetSpriteRectangle(result, false)); break; } } rects.Add(DirectionArrowSpriteSourceRectangle.GetSpriteRectangle(movementPath[movementPath.Count - 2].GetDirectionFromPointAtoPointB(movementPath[movementPath.Count - 1]))); }
public override void Update(GameTime gameTime, InputState inputState, InputState lastInputState) { base.Update(gameTime, inputState, lastInputState); //Chau Van Sang adds isCursor for cursor flickering if (isFocused == true) { temp_speed_flicker += 1; if (temp_speed_flicker == speed_flick) { isCursor_flicker = !isCursor_flicker; temp_speed_flicker = 0; } if (HelperFunction.IsKeyPress(Keys.Back)) { if (textBuffer.Length > 0) { if (Font.MeasureString(textBuffer).X > rect.Width) { textBuffer.Remove(textBuffer.Length - 1, 1); return; } textBuffer.Remove((CursorPosition - 1).Clamp(textBuffer.Length, 0), 1); CursorPosition--; } } } }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { //if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) // Exit(); // TODO: Add your update logic here CONTENT_MANAGER.inputState = new InputState(Mouse.GetState(), Keyboard.GetState()); if (HelperFunction.IsKeyPress(Keys.F1)) { SCREEN_MANAGER.goto_screen("TestAnimationScreen"); } if (HelperFunction.IsKeyPress(Keys.F2)) { Unit.Load(); CONTENT_MANAGER.ShowMessageBox("Unit stats reloaded"); } if (HelperFunction.IsKeyPress(Keys.F3)) { SCREEN_MANAGER.goto_screen("TestConsole"); } SCREEN_MANAGER.Update(gameTime); lastInputState = inputState; base.Update(gameTime); }
public uint Def_FindFiles(string filename, ref FillFindData FillFunction, IntPtr info) { VNode node = new VNode(filename); if (node.isValid) { Console.WriteLine("{0} {1} {2}", node.isFile, node.rootDir, node.curDir); if (node.curDir == node.rootDir) { foreach (string s in services) { WIN32_FIND_DATA Information = new WIN32_FIND_DATA(); Information.cFileName = s; Information.ftCreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.ftLastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.ftLastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.dwFileAttributes = FileAttributes.Directory | FileAttributes.Readonly; Information.nFileSizeLow = 100000; FillFunction(ref Information, info); } } else { switch (node.curDir) { case "WebSearch": foreach (string s in WebSearch) { WIN32_FIND_DATA Information = new WIN32_FIND_DATA(); Information.cFileName = s; Information.ftCreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.ftLastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.ftLastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.dwFileAttributes = FileAttributes.Readonly; Information.nFileSizeLow = 100000; FillFunction(ref Information, info); } break; case "ImagePass": foreach (string s in imageFiles) { WIN32_FIND_DATA Information = new WIN32_FIND_DATA(); Information.cFileName = s; Information.ftCreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.ftLastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.ftLastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.dwFileAttributes = FileAttributes.Readonly; Information.nFileSizeLow = 100000; FillFunction(ref Information, info); } break; default: break; } } } return(0); }
public uint Def_GetVolumeInfo(IntPtr VolumeNameBuffer, uint VolumeNameSize, ref uint SerialNumber, ref uint MaxComponenetLegnth, ref uint FileSystemFeatures, IntPtr FileSystemNameBuffer, uint FileSystemNameSize) { HelperFunction.SetVolumeInfo(VolumeNameBuffer, "REST", (int)VolumeNameSize, FileSystemNameBuffer, "REST", (int)FileSystemNameSize); FileSystemFeatures = (uint)(FILE_FS_ATTRIBUTE_INFORMATION.FILE_UNICODE_ON_DISK | FILE_FS_ATTRIBUTE_INFORMATION.FILE_UNICODE_ON_DISK); MaxComponenetLegnth = 409600; SerialNumber = (uint)GetHashCode(); return(0); }
public TasksServer(ISchedulerFactory schedulerFactory, IMapper mapper) { _schedulerFactory = schedulerFactory ?? throw new ArgumentNullException(nameof(schedulerFactory)); this.mapper = mapper; helperFunction = new HelperFunction(); formalBusiness = new FormalBusiness(schedulerFactory); scheduler = _schedulerFactory.GetScheduler().Result; Db = new PetaPoco.Database("server = .;database = TaskInfo;uid = sa; pwd = 123", "System.Data.SqlClient", null); }
public void AddHelperFunction(HelperFunction function) { if (function == null) { return; } this._helperCollection.Add(function); }
public override void Update(GameTime gameTime) { canvas.Update(CONTENT_MANAGER.inputState, CONTENT_MANAGER.lastInputState); if (HelperFunction.IsKeyPress(Keys.OemTilde)) { console.IsVisible = !console.IsVisible; } }
public void AddHelperFunction_GivenFunction_AddsToCollection() { HelperFunction input = new HelperFunction("test", "alert('test');"); var sut = new RazorJSTemplateBuilder(this._templateCollection.Object, this._helperCollection.Object); sut.AddHelperFunction(input); this._helperCollection.Verify(h => h.Add(input)); }
static void Main(string[] args) { DifferentialEvolution de = new DifferentialEvolution(100, 30, -100, 100, TestFunction.F1, 300000, 0.5, 0.5); double[] solution = de.Run(); Console.WriteLine("{0}", TestFunction.F1(solution)); HelperFunction.Print(solution); }
public uint Def_GetFileInformation(string fileName, ref BY_HANDLE_FILE_INFORMATION information, IntPtr info) { try { RegistryFileBlock FileBlock = new RegistryFileBlock(fileName); if (FileBlock.level == 1) { information.FileAttributes = (uint)FileAttributes.Directory; information.LastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); information.LastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); information.CreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); return(0); } RegistryKey key = GetRegistoryEntry(FileBlock); if (key == null) { return(0xC0000467); } if (FileBlock.level == 3) { // fileName = fileName.Remove(fileName.LastIndexOf(".")); string value; if (key.GetValue(FileBlock.ValueName) == null)//.ToString(); { value = ""; } else { value = key.GetValue(FileBlock.ValueName).ToString(); } information.FileAttributes = (uint)FileAttributes.Readonly; information.FileSizeLow = (uint)value.Length; information.LastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); information.LastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); information.CreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); return(0); } information.FileAttributes = (uint)FileAttributes.Directory; information.LastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); information.LastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); information.CreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); return(0); } catch (Exception ex) { Console.WriteLine("Error : {0}", ex.Message); return(0xC0000467); } }
public void ResetCountryMethod_ShouldResetCountries_WhenCalled() { ICountry italy = CountryFactory.CreateItaly(); italy = HelperFunction.ResetCountry(italy); Assert.AreEqual(italy.CountryName, ""); Assert.AreEqual(italy.CapitalName, ""); Assert.AreEqual(italy.CountryInfo, ""); Assert.AreEqual(italy.CountryPath, ""); }
public RateChange() { InitializeComponent(); hf = new HelperFunction(); genericDbHandler = new GenericClass(); update.Location = new Point(this.Width / 3 + 30, this.Height + 78); MilkTransaction objMilk = new MilkTransaction(); dtrate = objMilk.GetMilkRate(objMilk); }
public override void Update(GameTime gameTime, InputState inputState, InputState lastInputState) { base.Update(gameTime, inputState, lastInputState); if (isPressed) { OnButtonPressed(this, new UIEventArgs(inputState, lastInputState)); } if (HelperFunction.IsKeyPress(Hotkey)) { OnMouseClick(this, new UIEventArgs(inputState, lastInputState)); } }
/* a map file data structure * basically it's a json file serialize from the class Map */ public static Map LoadMap(string data) { data = CompressHelper.UnZip(data); var mapdata = data.Split('|'); string majorver = string.Empty , minorver = string.Empty; try { majorver = JsonConvert.DeserializeObject <string>(mapdata[0]); minorver = JsonConvert.DeserializeObject <string>(mapdata[1]); } catch (Exception e) { Utility.HelperFunction.Log(e); } if (string.Compare(majorver, VersionNumber.MajorVersion) != 0 || string.Compare(minorver, VersionNumber.MinorVersion) != 0) { CONTENT_MANAGER.ShowMessageBox("Cant't load map" + Environment.NewLine + "Version not compatible" + Environment.NewLine + "Game version: " + VersionNumber.GetVersionNumber + Environment.NewLine + "Map version: " + majorver + "." + minorver); return(null); } Map output = new Map(); try { output = JsonConvert.DeserializeObject <Map>(mapdata[2]); } catch (Exception er) { Utility.HelperFunction.Log(er); Environment.Exit(0); } if (output != null) { return(output); } else { HelperFunction.Log(new Exception(output?.ToString())); Environment.Exit(0); throw new NullReferenceException(); } }
//test public void SendNetMessage() { TestByteClass tb = new TestByteClass(); tb.a = 2; tb.b = "hello world"; var packet = HelperFunction.ObjectToByteArray(tb as object); var rpacket = HelperFunction.ByteArrayToObject(packet) as TestByteClass; Debug.Log(rpacket.a + " " + rpacket.b); var friendID = SteamFriends.GetFriendByIndex(0, EFriendFlags.k_EFriendFlagAll); SteamGameServerNetworking.SendP2PPacket(friendID, packet, (uint)(sizeof(byte) * packet.Length), EP2PSend.k_EP2PSendUnreliable); }
public uint Def_GetVolumeInfo(IntPtr VolumeNameBuffer, uint VolumeNameSize, ref uint SerialNumber, ref uint MaxComponenetLegnth, ref uint FileSystemFeatures, IntPtr FileSystemNameBuffer, uint FileSystemNameSize) { try { string VolumeName = "Test123"; string FileSystemName = "Bacho"; HelperFunction.SetVolumeInfo(VolumeNameBuffer, VolumeName, (int)VolumeNameSize, FileSystemNameBuffer, FileSystemName, (int)FileSystemNameSize); MaxComponenetLegnth = 256; FileSystemFeatures = (uint)FILE_FS_ATTRIBUTE_INFORMATION.FILE_READ_ONLY_VOLUME | (uint)FILE_FS_ATTRIBUTE_INFORMATION.FILE_UNICODE_ON_DISK; SerialNumber = (uint)this.GetHashCode(); return(0); } catch (Exception e) { Console.WriteLine(e.Message); return(0xC0000467); } }
public static Map Load(string path, World world) { if (!File.Exists(path)) { throw new FileNotFoundException(path); } var data = HelperFunction.Make1DArray(File.ReadAllLines(path).Select(l => l.Split(',').Select(c => (Terrain)int.Parse(c)).ToArray()).ToArray()); var map = new Map(30, 20); map.SetData(data, world); /* 0,0,0,1,1,1,1,0,0 * 0,0,0,1,1,1,1,0,0 * 0,0,0,1,1,1,1,0,0 * 0,0,0,1,1,1,1,0,0 */ return(map); }
public List <ScenarioMetrics> GetScenarioMetricsByDate(string fromdate, string todate, string cateNames, string Scope) { DataTable dt = new DAL().GetCateIDFromCategoryName(cateNames); string ids = ""; if (dt != null) { for (int i = 0; i < dt.Rows.Count; i++) { ids += dt.Rows[i]["id"].ToString() + ","; } } ids.Remove(ids.Length - 1); DataTable dt_metrics = new DAL().GetMetricsBydata(fromdate, todate, ids, Scope); if (dt_metrics != null && dt_metrics.Rows.Count > 0) { return(HelperFunction <ScenarioMetrics> .ConvertToList(dt_metrics)); } return(null); }
public uint Def_GetFileInformation(string filename, ref BY_HANDLE_FILE_INFORMATION Information, IntPtr info) { VNode Node = new VNode(filename); Console.WriteLine("{0} {1} {2}", Node.isFile, Node.rootDir, Node.curDir); if (Node.isValid) { Information.CreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.LastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.LastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); Information.FileSizeLow = 100000; if (Node.isFile) { Information.FileAttributes = FileAttributes.Readonly; } else { Information.FileAttributes = FileAttributes.Directory | FileAttributes.Readonly; } } return(0); }
private void OnSave() { if (currCountry.CountryName != "" && currCountry.CapitalName != "" && currCountry.CountryInfo != "" && currCountry.CountryPath != "") { ICountry country = CountryFactory.CreateEmptyCountry(); country.CountryName = currCountry.CountryName; country.CapitalName = currCountry.CapitalName; country.CountryInfo = currCountry.CountryInfo; country.CountryPath = currCountry.CountryPath; CountriesDB.Countries.Add(country); //Countries.Add(country); currCountry = HelperFunction.ResetCountry(currCountry); MessageBox.Show($"Country added successfully!"); } }
public async Task <ActionResult> Register(Data.User user) { user.EmailConfirm = false; user.ActiveStatus = (int)CommonContant.ActiveStatus.pasif; user.Password = SimpleLogin.Common.Security.sha512encrypt(user.Password).Substring(0, 70); user.ValidationKey = RandomSfr.Generate(10); Data.SimpleData db = new Data.SimpleData(); db.Entry(user).State = System.Data.Entity.EntityState.Added; try { int result = await db.SaveChangesAsync(); //db ye kayıt edildi if (result == 1) { string link = "http://localhost:58522/Activation/Activate/" + user.Email + "/" + Security.sha512encrypt(user.ValidationKey); string emailFromTemplate = HelperFunction.RenderViewToString(this.ControllerContext, "~/Views/MailTemplates/UserActivation.cshtml", link); //todo: metod async yapılacak Common.MailOperations.sendMailFORapp("WissenApp Kayıt", emailFromTemplate, user.Email); return(RedirectToAction("ActivationInfo")); } } catch (Exception ex) { throw; } return(View()); }
public override void Update(InputState inputState, InputState lastInputState) { base.Update(inputState, lastInputState); //Chau Van Sang adds isCursor for cursor flickering if (isFocused == true) { temp_speed_flicker += 1; if (temp_speed_flicker == speed_flick) { isCursor_flicker = !isCursor_flicker; temp_speed_flicker = 0; } if (HelperFunction.IsKeyPress(Keys.Back)) { if (textBuffer.Length > 0) { if (font.MeasureString(textBuffer).X > rect.Width) { textBuffer.Remove(textBuffer.Length - 1, 1); return; } textBuffer.Remove((CursorPosition - 1).Clamp(textBuffer.Length, 0), 1); CursorPosition--; } } if (inputState.keyboardState.IsKeyDown(Keys.LeftControl) && HelperFunction.IsKeyPress(Keys.V)) { string paste = CONTENT_MANAGER.GetClipboard(); textBuffer.Append(paste); CursorPosition += paste.Length; } } }
private void MoveSnippet() { //with shift : move the whole snippet rectangle //without shift : adjust the size of the snippet rectangle bool checkShift = HelperFunction.IsKeyDown(Keys.LeftShift) || HelperFunction.IsKeyDown(Keys.RightShift); //with ctrl : press to move //without ctrl : hold down to move bool checkCtrl = HelperFunction.IsKeyDown(Keys.LeftControl) || HelperFunction.IsKeyDown(Keys.RightControl); Rectangle rekt = pictureBox_snippet.SourceRectangle; Point position = rekt.Location; Point size = rekt.Size; if ((HelperFunction.IsKeyDown(Keys.Left) && !checkCtrl) || (HelperFunction.IsKeyPress(Keys.Left) && checkCtrl)) { if (checkShift) { //move size size = new Point(MathHelper.Clamp(size.X - 1, 0, size.X), size.Y); } else { position = new Point(MathHelper.Clamp(position.X - 1, 0, position.X), position.Y); } } if ((HelperFunction.IsKeyDown(Keys.Right) && !checkCtrl) || (HelperFunction.IsKeyPress(Keys.Right) && checkCtrl)) { if (checkShift) { //move size size = new Point(size.X + 1, size.Y); } else { position = new Point(position.X + 1, position.Y); } } if ((HelperFunction.IsKeyDown(Keys.Up) && !checkCtrl) || (HelperFunction.IsKeyPress(Keys.Up) && checkCtrl)) { if (checkShift) { //move size size = new Point(size.X, MathHelper.Clamp(size.Y - 1, 0, size.Y)); } else { position = new Point(position.X, MathHelper.Clamp(position.Y - 1, 0, position.Y)); } } if ((HelperFunction.IsKeyDown(Keys.Down) && !checkCtrl) || (HelperFunction.IsKeyPress(Keys.Down) && checkCtrl)) { if (checkShift) { //move size size = new Point(size.X, size.Y + 1); } else { position = new Point(position.X, position.Y + 1); } } rekt.Location = position; rekt.Size = size; if (pictureBox_snippet.SourceRectangle != rekt || scaleChanged) { scaleChanged = false; pictureBox_snippet.SourceRectangle = rekt; label_snippet.Text = rekt.ToString(); if (selectedFrame != null) { selectedFrame.Location = new Point(pictureBox_spritesheet.Position.X + position.X * (int)pictureBox_spritesheet.Scale, pictureBox_spritesheet.Position.Y + position.Y * (int)pictureBox_spritesheet.Scale); selectedFrame.Size = (size.ToVector2() * pictureBox_spritesheet.Scale).ToPoint(); } } }
public override void Update(GameTime gameTime) { mouseInputState = CONTENT_MANAGER.inputState.mouseState; lastMouseInputState = CONTENT_MANAGER.lastInputState.mouseState; keyboardInputState = CONTENT_MANAGER.inputState.keyboardState; lastKeyboardInputState = CONTENT_MANAGER.lastInputState.keyboardState; selectedMapCell = Utility.HelperFunction.TranslateMousePosToMapCellPos(mouseInputState.Position, camera, map.Width, map.Height); if (HelperFunction.IsKeyPress(Keys.OemTilde)) { console.IsVisible = !console.IsVisible; } #region change unit and animation if (console.IsVisible) //suck all input in to the input box { console.Update(CONTENT_MANAGER.inputState, CONTENT_MANAGER.lastInputState); } else //accept input { //cylce through unit if (HelperFunction.IsKeyPress(Keys.Left)) { if (currentUnit == UnitType.Soldier) { currentUnit = UnitType.Battleship; } else { currentUnit = currentUnit.Previous(); } } if (HelperFunction.IsKeyPress(Keys.Right)) { if (currentUnit == UnitType.Battleship) { currentUnit = UnitType.Soldier; } else { currentUnit = currentUnit.Next(); } } //cycle through animation if (HelperFunction.IsKeyPress(Keys.Up)) { if (currentAnimation == AnimationName.idle) { currentAnimation = AnimationName.done; } else { currentAnimation = currentAnimation.Previous(); } } if (HelperFunction.IsKeyPress(Keys.Down)) { if (currentAnimation == AnimationName.done) { currentAnimation = AnimationName.idle; } else { currentAnimation = currentAnimation.Next(); } } //cycle through color if (HelperFunction.IsKeyPress(Keys.E)) { if (currentColor == GameData.Owner.Yellow) { currentColor = GameData.Owner.Red; } else { currentColor = currentColor.Next(); } } if (HelperFunction.IsKeyPress(Keys.Q)) { if (currentColor == GameData.Owner.Red) { currentColor = GameData.Owner.Yellow; } else { currentColor = currentColor.Previous(); } } } Unit unit = map[position].unit; UnitType nextUnit = unit.UnitType; GameData.Owner nextOwner = unit.Owner; AnimationName nextAnimation = unit.Animation.CurntAnimationName.ToEnum <AnimationName>(); bool isChanged = false; if (nextUnit != currentUnit) { isChanged = true; } if (nextOwner != currentColor) { isChanged = true; } if (nextAnimation != currentAnimation) { isChanged = true; } if (isChanged) { map[position].unit = UnitCreationHelper.Create(currentUnit, currentColor, startingAnimation: currentAnimation); } map[position].unit.Animation.Update(gameTime); #endregion if (mouseInputState.LeftButton == ButtonState.Released && lastMouseInputState.LeftButton == ButtonState.Pressed) { SelectUnit(); } //if (isMovingUnitAnimPlaying) //{ // UpdateMovingUnit(gameTime); //} //calculate movepath if (isMovePathCalculated) { if (movementRange.Contains(selectedMapCell) && selectedMapCell != lastSelectedMapCell) { //update movement path movementPath = DijkstraHelper.FindPath(dijkstarGraph, selectedMapCell); dirarrowRenderer.UpdatePath(movementPath); lastSelectedMapCell = selectedMapCell; } } base.Update(gameTime); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { string defaultDir = "C:\\\\ant\\\\_03_LinearModel\\\\_04_LinearSupportVectorRegression\\\\"; string dataFile = null; string targetFile = null; string resultFile = "result.txt"; string workingDir = null; bool fit = false; string Logs = ""; //Optional Data: double C = 1.0; string loss = "epsilon_insensitive"; double epsilon = 0.1; bool dual = true; double tol = 1e-4; bool fit_intercept = true; double intercept_scaling = 1.0; int verbose = 0; string random_state = "None"; int max_iter = 1000; List <double> predicTData = new List <double>(); if (!DA.GetData(0, ref dataFile)) { return; } if (dataFile == null) { return; } if (!DA.GetData(1, ref targetFile)) { return; } if (targetFile == null) { return; } if (!DA.GetData(2, ref workingDir)) { return; } if (workingDir == null) { return; } if (!DA.GetDataList(3, predicTData)) { return; } if (predicTData == null) { return; } if (!DA.GetData(4, ref fit)) { return; } if (fit == false) { return; } long ticks0 = DateTime.Now.Ticks; try { DA.GetData(5, ref C); DA.GetData(6, ref loss); DA.GetData(7, ref epsilon); DA.GetData(8, ref dual); DA.GetData(9, ref tol); DA.GetData(10, ref fit_intercept); DA.GetData(11, ref intercept_scaling); DA.GetData(12, ref verbose); DA.GetData(13, ref random_state); DA.GetData(14, ref max_iter); } catch (Exception ex) { var st = new StackTrace(ex, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Logs += line.ToString() + "\n"; } // 01 Specify the working directory at which pythonFile exists, note that this Python file should run separately using Proccess2 (see 5). process2.StartInfo.WorkingDirectory = workingDir; try { // 02 Initiate helperFunctions HelperFunction helpFunctions = new HelperFunction(); // Put inputData in one list of strings. List <string> dataInput = new List <string>(new string[] { C.ToString(), @"'" + loss + @"'", epsilon.ToString(), dual == true?"True":"False", tol.ToString(), fit_intercept == true?"True":"False", intercept_scaling.ToString(), verbose.ToString(), @"'" + random_state + @"'", max_iter.ToString() }); // 03 Convert data from grasshopper syntax to python NumPy like array. string newString = helpFunctions.dataInput2Python(workingDir, predicTData); // 04 Write the Python file in the working directory helpFunctions.PythonFile(defaultDir, dataFile, targetFile, workingDir, resultFile, newString, "True", workingDir + "logFile.txt", allResources._04_LinearSupportVectorRegressionPy, dataInput); } catch (Exception e) { this.Message = e.ToString(); } // 05 Start running Python file. and wait until it is closed i.e. raising the process_Exited event. process2.Start(); while (!processhasexit) { } try { doc.Load(workingDir + "res.xml"); //TODO : add all the output variables here //AllData = {"prediction":result, "score":sroce, "support":support, "support_vectors":support_vectors, "n_support": n_support, "dual_coef": dual_coef, "coef": coeff, "intercept":intercept} XmlNode res_node = doc.DocumentElement.SelectSingleNode("/result/prediction"); XmlNode score_node = doc.DocumentElement.SelectSingleNode("/result/score"); XmlNode coef_node = doc.DocumentElement.SelectSingleNode("/result/coef"); XmlNode intercept_node = doc.DocumentElement.SelectSingleNode("/result/intercept"); string res = res_node.InnerText; string score = score_node.InnerText; string coef = coef_node.InnerText; string intercept = intercept_node.InnerText; //string res = System.IO.File.ReadAllText(workingDir + "result.txt"); res = res.Replace("[", "").Replace("]", ""); DA.SetData(1, res); DA.SetData(2, score); DA.SetData(3, coef); DA.SetData(4, intercept); long ticks1 = DateTime.Now.Ticks; double timeElaspsed = ((double)ticks1 - (double)ticks0) / 10000000; Logs += "Success !! in : " + timeElaspsed + " Seconds\n "; } catch (Exception e) { var st = new StackTrace(e, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Logs += e.Message + line.ToString() + "\n"; } DA.SetData(0, Logs); processhasexit = false; }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { string defaultDir = "C:\\\\ant\\\\init\\\\LinearRegression\\\\"; string dataFile = null; string targetFile = null; string resultFile = "result.txt"; string logFile = "logFile.txt"; string workingDir = null; bool fit = false; string Logs = ""; List <double> predicTData = new List <double>(); //string mainDir = "C:\\ant\\init\\"; //string workingDir = mainDir + "LinearRegression\\"; //DA.SetData(0, workingDir); if (!DA.GetData(0, ref dataFile)) { return; } if (dataFile == null) { return; } if (!DA.GetData(1, ref targetFile)) { return; } if (targetFile == null) { return; } if (!DA.GetData(2, ref workingDir)) { return; } if (workingDir == null) { return; } if (!DA.GetDataList(3, predicTData)) { return; } if (predicTData == null) { return; } if (!DA.GetData(4, ref fit)) { return; } if (fit == false) { return; } long ticks0 = DateTime.Now.Ticks; //TODO: FILL IN THE DATA INPUT PROPERLY List <string> dataInput = new List <string>(new string[] { "dd", "dd" }); // 01 Specify the working directory at which pythonFile exists, note that this Python file should run separately using Proccess2 (see 5). process2.StartInfo.WorkingDirectory = workingDir; // 02 Initiate helperFunctions HelperFunction helpFunctions = new HelperFunction(); // 03 Convert data from grasshopper syntax to python NumPy like array. string newString = helpFunctions.dataInput2Python(workingDir, predicTData); // 04 Write the Python file in the working directory helpFunctions.PythonFile(defaultDir, dataFile, targetFile, workingDir, resultFile, newString, "True", workingDir + "logFile.txt", Resources.allResources._03_LinearRegression, dataInput); // 05 Start running Python file. and wait until it is closed i.e. raising the process_Exited event. process2.Start(); while (!processhasexit) { } try { doc.Load(workingDir + "res.xml"); //TODO : add all the output variables here //result 0 | coeff 3 | intercept 4 | score 5 XmlNode res_node = doc.DocumentElement.SelectSingleNode("/result/prediction"); XmlNode coeff_node = doc.DocumentElement.SelectSingleNode("/result/coeff"); XmlNode intercept_node = doc.DocumentElement.SelectSingleNode("/result/intercept"); XmlNode score_node = doc.DocumentElement.SelectSingleNode("/result/score"); string res = res_node.InnerText; string coeff = coeff_node.InnerText; string intercept = intercept_node.InnerText; string score = score_node.InnerText; //string res = System.IO.File.ReadAllText(workingDir + "result.txt"); res = res.Replace("[", "").Replace("]", ""); DA.SetData(1, res); DA.SetData(2, score); DA.SetData(3, coeff); DA.SetData(4, intercept); long ticks1 = DateTime.Now.Ticks; long timeElaspsed = (ticks1 - ticks0) / 10000; Logs += "Success !! in : " + timeElaspsed + " Milli Seconds\n "; } catch (Exception e) { Logs += "001 " + e + "\n"; } DA.SetData(0, Logs); processhasexit = false; }
public uint Def_FindFiles(string fileName, ref FillFindData NativeFillFunction, IntPtr info) { try { RegistryFileBlock FileBlock = new RegistryFileBlock(fileName); if (FileBlock.level == 1) { foreach (string name in RootDirectory.Keys) { WIN32_FIND_DATA finfo = new WIN32_FIND_DATA(); finfo.cFileName = name; finfo.dwFileAttributes = (uint)FileAttributes.Directory; finfo.ftLastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); finfo.ftLastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); finfo.ftCreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); NativeFillFunction(ref finfo, info); } return(0); } else { RegistryKey key = GetRegistoryEntry(FileBlock); if (key == null) { Console.WriteLine("Find File Error {0}", fileName); return(0xC0000467); } foreach (string name in key.GetSubKeyNames()) { WIN32_FIND_DATA finfo = new WIN32_FIND_DATA(); finfo.cFileName = name; finfo.dwFileAttributes = (uint)FileAttributes.Directory; finfo.ftLastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); finfo.ftLastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); finfo.ftCreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); NativeFillFunction(ref finfo, info); } foreach (string name in key.GetValueNames()) { WIN32_FIND_DATA finfo = new WIN32_FIND_DATA(); switch (key.GetValueKind(name)) { case RegistryValueKind.Binary: finfo.cFileName = name + ".regbin"; break; case RegistryValueKind.DWord: finfo.cFileName = name + ".regdword"; break; case RegistryValueKind.MultiString: finfo.cFileName = name + ".regmltstr"; break; case RegistryValueKind.QWord: finfo.cFileName = name + ".regqwrod"; break; case RegistryValueKind.String: finfo.cFileName = name + ".regstr"; break; case RegistryValueKind.ExpandString: finfo.cFileName = name + ".regexpstr"; break; case RegistryValueKind.Unknown: finfo.cFileName = name + ".regunk"; break; default: break; } // finfo.cFileName = name; finfo.dwFileAttributes = (uint)FileAttributes.Readonly; finfo.ftLastAccessTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); finfo.ftLastWriteTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); finfo.ftCreationTime = HelperFunction.DateTimeToFileTime(DateTime.Now.ToFileTime()); finfo.nFileSizeLow = (uint)key.GetValue(name).ToString().Length; NativeFillFunction(ref finfo, info); } return(0); } } catch (Exception e) { Console.WriteLine(e.Message); return(0xC0000467); } }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { string defaultDir = "C:\\\\ant\\\\_03_LinearModel\\\\_03_LogisticRegression\\\\"; string dataFile = null; string targetFile = null; string resultFile = "result.txt"; string workingDir = null; bool fit = false; string Logs = ""; //Optional Data: string penalty = ""; bool dual = false; double C = 1.0; bool fit_intercept = true; double intercept_scaling = 1.0; string class_weight = "None"; int max_iter = 100; string random_state = "None"; string solver = "liblinear"; double tol = 0.001; string multi_class = "ovr"; int verbose = 0; List <double> predicTData = new List <double>(); if (!DA.GetData(0, ref dataFile)) { return; } if (dataFile == null) { return; } if (!DA.GetData(1, ref targetFile)) { return; } if (targetFile == null) { return; } if (!DA.GetData(2, ref workingDir)) { return; } if (workingDir == null) { return; } if (!DA.GetDataList(3, predicTData)) { return; } if (predicTData == null) { return; } if (!DA.GetData(4, ref fit)) { return; } if (fit == false) { return; } long ticks0 = DateTime.Now.Ticks; // Optionaldata:| penalty |dual |C |fit_intercept |intercept_scaling |class_weight |max_iter |random_state |solver |tol |multi_class |verbose // indeces: |5 |6 |7 |8 |9 |10 |11 |12 |13 |14 |15 |16 try { DA.GetData(5, ref penalty); DA.GetData(6, ref dual); DA.GetData(7, ref C); DA.GetData(8, ref fit_intercept); DA.GetData(9, ref intercept_scaling); DA.GetData(10, ref class_weight); DA.GetData(11, ref max_iter); DA.GetData(12, ref random_state); DA.GetData(13, ref solver); DA.GetData(14, ref tol); DA.GetData(15, ref multi_class); DA.GetData(16, ref verbose); } catch (Exception ex) { var st = new StackTrace(ex, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Logs += line.ToString() + "\n"; } // Put inputData in one list of strings. List <string> dataInput = new List <string>(new string[] { @"'" + penalty + @"'", dual == true?"True":"False", C.ToString(), fit_intercept == true?"True":"False", intercept_scaling.ToString(), class_weight, max_iter.ToString(), random_state, @"'" + solver + @"'", tol.ToString(), @"'" + multi_class + @"'", verbose.ToString() }); // 01 Specify the working directory at which pythonFile exists, note that this Python file should run separately using Proccess2 (see 5). process2.StartInfo.WorkingDirectory = workingDir; // 02 Initiate helperFunctions HelperFunction helpFunctions = new HelperFunction(); // 03 Convert data from grasshopper syntax to python NumPy like array. string newString = helpFunctions.dataInput2Python(workingDir, predicTData); // 04 Write the Python file in the working directory helpFunctions.PythonFile(defaultDir, dataFile, targetFile, workingDir, resultFile, newString, "True", workingDir + "logFile.txt", allResources._03_LogisticRegression, dataInput); // 05 Start running Python file. and wait until it is closed i.e. raising the process_Exited event. process2.Start(); while (!processhasexit) { } try { doc.Load(workingDir + "res.xml"); //TODO : add all the output variables here //result 1 | score 2 | coef_ 3 | sparse_coef_ 4 | intercept_ 5 XmlNode res_node = doc.DocumentElement.SelectSingleNode("/result/prediction"); XmlNode score_node = doc.DocumentElement.SelectSingleNode("/result/score"); XmlNode coeff_node = doc.DocumentElement.SelectSingleNode("/result/coeff"); XmlNode intercept_node = doc.DocumentElement.SelectSingleNode("/result/intercept"); XmlNode n_inter_node = doc.DocumentElement.SelectSingleNode("/result/n_inter"); string res = res_node.InnerText; string score = score_node.InnerText; string coeff = coeff_node.InnerText; string intercept = intercept_node.InnerText; string n_iterations = n_inter_node.InnerText; //string res = System.IO.File.ReadAllText(workingDir + "result.txt"); res = res.Replace("[", "").Replace("]", ""); DA.SetData(1, res); DA.SetData(2, score); DA.SetData(3, coeff); DA.SetData(4, intercept); DA.SetData(5, n_iterations); long ticks1 = DateTime.Now.Ticks; long timeElaspsed = (ticks1 - ticks0) / 10000; Logs += "Success !! in : " + timeElaspsed + " Milli Seconds\n "; } catch (Exception e) { var st = new StackTrace(e, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Logs += e.Message + line.ToString() + "\n"; } DA.SetData(0, Logs); processhasexit = false; }
private void InitCanvas() { canvas = new Canvas(); Label label_name = new Label("Untitled", new Point(400, 0), new Vector2(200, 20), CONTENT_MANAGER.Fonts["default"]) { Origin = new Vector2(-2, -2), BackgroundColor = Color.LightGray }; label_snippet = new Label("", new Point(400, 30), new Vector2(20, 20), CONTENT_MANAGER.Fonts["default"]) { Origin = new Vector2(-2, -2) }; CONTENT_MANAGER.gameInstance.Window.TextInput += (obj, e) => { //if (label_name.IsFocused) { if (char.IsLetterOrDigit(e.Character)) { label_name.Text += e.Character; } else if (e.Key == Keys.Back) { int cc = label_name.Text.Length - 1; if (cc >= 0) { label_name.Text = label_name.Text.Remove(cc); } } } }; pictureBox_spritesheet = new PictureBox(CONTENT_MANAGER.Sprites[texture], new Point(50, 0), null, null); pictureBox_snippet = new PictureBox(CONTENT_MANAGER.Sprites[texture], new Point(400, 70), Rectangle.Empty, null); pictureBox_spritesheet.MouseDrag += (obj, e) => { if (e.Size != Point.Zero) { //DrawingHelper.RemoveShape(selectedFrame); //selectedFrame = DrawingHelper.GetRectangle(e, Color.Red, false); //DrawingHelper.DrawShape(selectedFrame); selectedFrame = new Rectangle((e.Location.ToVector2() * pictureBox_spritesheet.Scale).ToPoint(), (e.Size.ToVector2() * pictureBox_spritesheet.Scale).ToPoint()); label_snippet.Text = selectedFrame.ToString(); e.Location = new Point(e.Location.X - pictureBox_spritesheet.Position.X, e.Location.Y - pictureBox_spritesheet.Position.Y); pictureBox_snippet.SourceRectangle = e; } }; pictureBox_spritesheet.KeyPress += (obj, e) => { if (HelperFunction.IsKeyPress(Keys.OemPlus)) { pictureBox_spritesheet.Scale += 0.1f; scaleChanged = true; } if (HelperFunction.IsKeyPress(Keys.OemMinus)) { if (pictureBox_spritesheet.Scale > 1) { pictureBox_spritesheet.Scale -= 0.1f; scaleChanged = true; } } }; Button button_new = new Button("New", new Point(650, 30), new Vector2(60, 30), CONTENT_MANAGER.Fonts["default"]) { ButtonColorReleased = Color.White }; button_new.MouseClick += (o, e) => { animationPlayer.StopAnimation(); label_name.Text = "Untitled"; }; Button button_add_sprite = new Button("Add F", new Point(720, 30), new Vector2(60, 30), CONTENT_MANAGER.Fonts["default"]) { ButtonColorReleased = Color.White }; button_add_sprite.MouseClick += (obj, e) => { if (string.IsNullOrWhiteSpace(label_name.Text)) { label_name.Text = "Please enter the name of this animation"; } else if (!animation_list.ContainsKey(label_name.Text)) { animation_list.Add(label_name.Text, new List <Rectangle>() { pictureBox_snippet.SourceRectangle }); } else { animation_list[label_name.Text].Add(pictureBox_snippet.SourceRectangle); } }; animationPlayer = new AnimationPlayer(new AnimatedEntity(), new Point(700, 70)); Button button_test_animation = new Button("Test", new Point(790, 30), new Vector2(60, 30), CONTENT_MANAGER.Fonts["default"]) { ButtonColorReleased = Color.White }; button_test_animation.MouseClick += (o, e) => { string animationName = label_name.Text; Animation animation = new Animation(animationName, true, 1, null); foreach (var frame in animation_list[animationName]) { animation.AddKeyFrame(frame); } if (animationPlayer.ContainAnimation(animation.Name)) { animationPlayer.RemoveAnimation(animation.Name); } animationPlayer.AddAnimation(animation); animationPlayer.LoadContent(pictureBox_snippet.Texture2D); animationPlayer.PlayAnimation(animation.Name); }; Button button_export = new Button("Export", new Point(860, 30), new Vector2(60, 30), CONTENT_MANAGER.Fonts["default"]) { ButtonColorReleased = Color.White }; button_export.MouseClick += (o, e) => { var animdata = JsonConvert.SerializeObject(animationPlayer.AnimatedEntity, Formatting.Indented); File.WriteAllText($"{label_name.Text}.txt", animdata); }; canvas.AddElement("label_test", label_name); canvas.AddElement("label_snippet", label_snippet); canvas.AddElement("pictureBox_test", pictureBox_spritesheet); canvas.AddElement("pictureBox_snippet", pictureBox_snippet); canvas.AddElement("button_add_sprite", button_add_sprite); canvas.AddElement("animationPlayer", animationPlayer); canvas.AddElement("button_test_animation", button_test_animation); canvas.AddElement("button_export", button_export); canvas.AddElement("button_new", button_new); }