public Enemy[] AssignEnemies(string level) { CSVReader csv = new CSVReader('e', level); List<string[]> level_enemies = csv.Read(); enemies = new Enemy[level_enemies.Count]; enemyTransforms = new Transform[level_enemies.Count]; for (int i = 0; i < level_enemies.Count; i++) //initialize all pois { if (level_enemies[i][0] == "ranged") poiTransforms[i] = Instantiate(rangedEnemyPrefab) as Transform; else poiTransforms[i] = Instantiate(meleeEnemyPrefab) as Transform; enemies[i] = poiTransforms[i].gameObject.GetComponent<Enemy>(); enemies[i].enabled = true; } int t; for (int i = 0; i < level_enemies.Count; i++) //initialize all pois { for (int j = 0; j < level_enemies[i].Length; j++) { if (int.TryParse(level_enemies[i][j], out t)) enemies[i].points.Add(poi[t]); } } return enemies; }
public PointOfInterest[] AssignPOIs(string level) { CSVReader csv = new CSVReader('p', level); List<string[]> level_pois = csv.Read(); poi = new PointOfInterest[level_pois.Count]; poiTransforms = new Transform[level_pois.Count]; for (int i = 0; i < level_pois.Count; i++) //initialize all pois { poiTransforms[i] = Instantiate(poiPrefab) as Transform; poi[i] = poiTransforms[i].gameObject.GetComponent<PointOfInterest>(); poi[i].enabled = true; } for (int i = 0; i < level_pois.Count; i++) //initialize all pois { for (int j = 0; j < level_pois[i].Length; j++) { if (level_pois[i][j] == "front") poi[i].directionPattern.Add(FacingDirection.Front); //add direction patterns else if (level_pois[i][j] == "back") poi[i].directionPattern.Add(FacingDirection.Back); else if (level_pois[i][j] == "right") poi[i].directionPattern.Add(FacingDirection.Right); else if (level_pois[i][j] == "left") poi[i].directionPattern.Add(FacingDirection.Left); else if (j == level_pois[i].Length - 2) //second to last item is wait time at poi poi[i].restTime = float.Parse(level_pois[i][j]); else if (j == level_pois[i].Length - 1) //last item in line is rotation speed poi[i].rotationSpeed = float.Parse(level_pois[i][j]); } } return poi; }
private List<Proxy> ParseHAProxyStats(string input) { if (string.IsNullOrEmpty(input)) { return new List<Proxy>(); } using (var reader = new CSVReader(new StringReader(input), true)) { var stats = new List<Item>(); foreach (var row in reader) { //Skip the header if (row.Length == 0 || row[0].StartsWith("#")) { continue; } //Collect each stat line as we go, group later stats.Add(Item.FromLine(row)); } var result = stats.GroupBy(s => s.UniqueProxyId).Select(g => new Proxy { Host = this, Name = g.First().ProxyName, Frontend = g.FirstOrDefault(s => s.Type == StatusType.Frontend) as Frontend, Servers = g.OfType<Server>().ToList(), Backend = g.FirstOrDefault(s => s.Type == StatusType.Backend) as Backend, PollDate = DateTime.UtcNow }).ToList(); return result; } }
public ReligionList( EU2.Install install ) { CSVReader reader = new CSVReader( install.GetDBFile( "religion.csv" ) ); try { ReadFromCSV( reader ); } finally { reader.Close(); } }
void Awake() { SetValues(); if(CSVmanager == null){ DontDestroyOnLoad(gameObject); CSVmanager = this; } else if(CSVmanager != this){ Destroy(gameObject); } }
// Use this for initialization void Start() { reader = GetComponent<CSVReader>(); level = 0; wordBank = reader.getLine(wordBankCSV, level); wordChain = reader.getLine(wordChainCSV, level); delimiter = reader.getDelimiter(); // get list of string (filled words) for word chain // get list of string (incomplete words) for word chain // get list of char's for wordBank // instantiate platforms and bridges // instantiate incomplete words on map // instantiate phonemes in word bank wordsToComplete = 3; makeStage (); //TODO! }
public static void Main(string[] args) { CSVWriter cw; CSVReader cr; cw = new CSVWriter("test.csv"); cw.Write("Sample text"); cw.Write(23424); cw.Write("This is a string\"that contains a double quote character."); cw.Close(); cr = new CSVReader("test.csv"); object x; while ((x = cr.ReadNext()) != null) { Console.WriteLine(x); } cr.Close(); }
protected void BtnUploadCsv_Click(object sender, EventArgs e) { if (fileUploadCsv.PostedFile.FileName == string.Empty) { lblMsg.Visible = true; return; } else { //save the file //restrict user to upload other file extenstion string[] FileExt = fileUploadCsv.FileName.Split('.'); string FileEx = FileExt[FileExt.Length - 1]; if (FileEx.ToLower() == "csv" || FileEx.ToLower() == "xlsx") { fileUploadCsv.SaveAs(Server.MapPath("..\\CSVLoad\\" + fileUploadCsv.FileName)); // Server.MapPath("..\\Product\\") + strFileName2) } else { lblMsg.Visible = true; return; } } //create object for CSVReader and pass the stream CSVReader reader = new CSVReader(fileUploadCsv.PostedFile.InputStream); //get the header string[] headers = reader.GetCSVLine(); DataTable dt = new DataTable(); //add headers foreach (string strHeader in headers) { dt.Columns.Add(strHeader); } //string strHeader; string[] data; while ((data = reader.GetCSVLine()) != null) { dt.Rows.Add(data); int product_id = Convert.ToInt32(Convert.ToString(data[0])); string title = Convert.ToString(Convert.ToString(data[1])); // string saletitle = Convert.ToString(Convert.ToString(data[2])); string size = Convert.ToString(Convert.ToString(data[2])); string desc = Convert.ToString(Convert.ToString(data[3])); string image1 = Convert.ToString(Convert.ToString(data[4])); string image2 = Convert.ToString(Convert.ToString(data[5])); string suggest = Convert.ToString(Convert.ToString(data[10])); string recomm = Convert.ToString(Convert.ToString(data[11])); string strpresale = Convert.ToString(data[8]); if (strpresale != "") { presale = Convert.ToDouble(strpresale); } string strprice = Convert.ToString(data[9]); if (strprice != "") { price = Convert.ToDouble(strprice); } //if (saletitle == "" || saletitle==null) //{ // saletitle =" "; //} if (strpresale == "" || strpresale == "0") { int intUpdate_ifnull = dbInfo.UpdateProductPrice_ifnull(product_id, price, size, recomm, suggest); } else { int intUpdate = dbInfo.UpdateProductPrice(product_id, presale, price, size, recomm, suggest); } int intUpdateSize = dbInfo.UpdateProductSize(product_id, size, desc, title, image1, image2); // int intUpdate = dbInfo.UpdateProductPrice(product_id,presale,price,size); } //bind gridview //lblMsg.Visible = true; // lblMsg.Text = "Sucessfully succed"; // gv.DataSource = dt; //gv.DataBind(); BindGrid(); lblMsgError.Visible = false; lblMsg.Visible = true; lblMsg.Text = "Sucessfully updated the prices"; }//
private void ReadAircraftTable(CSVReader reader) { int iColAircraft = -1; int iColTypeCode = -1; int iColModel = -1; // Find the start of the aircraft table string[] rgRow = null; while ((rgRow = reader.GetCSVLine()) != null) { if (rgRow != null && rgRow.Length > 0 && rgRow[0].CompareCurrentCultureIgnoreCase("Aircraft Table") == 0) { break; } } string[] rgHeaders = reader.GetCSVLine(); int cColumnHeader = int.MaxValue; if (rgHeaders != null) { cColumnHeader = rgHeaders.Length; for (int i = 0; i < rgHeaders.Length; i++) { if (rgHeaders[i].CompareCurrentCultureIgnoreCase("AircraftID") == 0) { iColAircraft = i; } else if (rgHeaders[i].CompareCurrentCultureIgnoreCase("TypeCode") == 0) { iColTypeCode = i; } else if (rgHeaders[i].CompareCurrentCultureIgnoreCase("Model") == 0) { iColModel = i; } } } while ((rgRow = reader.GetCSVLine()) != null) { if (rgRow.Length == 0) { break; } if (iColAircraft < 0 || iColAircraft >= rgRow.Length) { break; } string szAircraft = rgRow[iColAircraft]; if (String.IsNullOrWhiteSpace(szAircraft)) { break; } string szModel = (iColModel >= 0) ? rgRow[iColModel] : string.Empty; string szTypeCode = (iColTypeCode >= 0) ? rgRow[iColTypeCode] : string.Empty; ForeFlightAircraftDescriptor ad = new ForeFlightAircraftDescriptor() { AircraftID = szAircraft, Model = szModel, TypeCode = szTypeCode }; dictAircraft[ad.AircraftID] = ad; } }
private void ReadAircraftTable(CSVReader reader) { int iColAircraft = -1; int iColTypeCode = -1; int iColModel = -1; // Find the start of the aircraft table string[] rgHeaders; while ((rgHeaders = reader.GetCSVLine()) != null) { if (rgHeaders != null && rgHeaders.Length > 0 && rgHeaders[0].CompareCurrentCultureIgnoreCase("Aircraft Table") == 0) { break; } } // Now find the next line that isn't generic data types // Look for "Text", "hhmm", "Decimal", "Boolean" - if any of these, skip ahead. while ((rgHeaders = reader.GetCSVLine()) != null) { if (Array.Find(rgHeaders, sz => rDataTypes.IsMatch(sz)) == null) { break; } } if (rgHeaders != null) { for (int i = 0; i < rgHeaders.Length; i++) { if (rgHeaders[i].CompareCurrentCultureIgnoreCase("AircraftID") == 0) { iColAircraft = i; } else if (rgHeaders[i].CompareCurrentCultureIgnoreCase("TypeCode") == 0) { iColTypeCode = i; } else if (rgHeaders[i].CompareCurrentCultureIgnoreCase("Model") == 0) { iColModel = i; } } } string[] rgRow; while ((rgRow = reader.GetCSVLine()) != null) { if (rgRow.Length == 0) { break; } if (iColAircraft < 0 || iColAircraft >= rgRow.Length) { break; } string szAircraft = rgRow[iColAircraft]; if (String.IsNullOrWhiteSpace(szAircraft)) { break; } string szModel = (iColModel >= 0) ? rgRow[iColModel] : string.Empty; string szTypeCode = (iColTypeCode >= 0) ? rgRow[iColTypeCode] : string.Empty; ForeFlightAircraftDescriptor ad = new ForeFlightAircraftDescriptor() { AircraftID = szAircraft, Model = szModel, TypeCode = szTypeCode }; dictAircraft[ad.AircraftID] = ad; } }
public Task<HttpResponseMessage> UploadImportFile() { logger.Debug("Inside DataActionController, UploadImportFile..."); logger.Debug("starting to process incoming files."); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = System.Web.HttpContext.Current.Server.MapPath("~/uploads"); string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty); logger.Debug("saving files to location: " + root); logger.Debug(" and the root url = " + rootUrl); var provider = new MultipartFormDataStreamProvider(root); User me = AuthorizationManager.getCurrentUser(); var db = ServicesContext.Current; var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(o => { if (o.IsFaulted || o.IsCanceled) { logger.Debug("Error: " + o.Exception.Message); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, o.Exception)); } //Look up our project Int32 ProjectId = Convert.ToInt32(provider.FormData.Get("ProjectId")); logger.Debug("And we think the projectid === " + ProjectId); Project project = db.Projects.Find(ProjectId); logger.Debug("Project = " + project); if (!project.isOwnerOrEditor(me)) throw new Exception("Authorization error: The user trying to import is neither an Owner nor an Editor."); else logger.Debug("User authorized = " + me); var newFileName = ""; foreach (MultipartFileData file in provider.FileData) { logger.Debug("Filename = " + file.LocalFileName); logger.Debug("Orig = " + file.Headers.ContentDisposition.FileName); logger.Debug("Name? = " + file.Headers.ContentDisposition.Name); var fileIndex = ActionController.getFileIndex(file.Headers.ContentDisposition.Name); //"uploadedfile0" -> 0 var filename = file.Headers.ContentDisposition.FileName; filename = filename.Replace("\"", string.Empty); if (!String.IsNullOrEmpty(filename)) { try { newFileName = ActionController.relocateProjectFile( file.LocalFileName, ProjectId, filename, true); /* File newFile = new File(); newFile.Title = provider.FormData.Get("Title_" + fileIndex); //"Title_1, etc. newFile.Description = provider.FormData.Get("Description_" + fileIndex); //"Description_1, etc. newFile.Name = info.Name;//.Headers.ContentDisposition.FileName; newFile.Link = rootUrl + "/services/uploads/" + ProjectId + "/" + info.Name; //file.LocalFileName; newFile.Size = (info.Length / 1024).ToString(); //file.Headers.ContentLength.ToString(); newFile.FileTypeId = FileType.getFileTypeFromFilename(info); newFile.UserId = me.Id; logger.Debug(" Adding file " + newFile.Name + " at " + newFile.Link); files.Add(newFile); */ } catch (Exception e) { logger.Debug("Error: " + e.ToString()); } } } logger.Debug("Done saving files."); var data = new ImportDataResult(); var info = new FileInfo(newFileName); // Process the file and return all the data! /* Note: According to Colette, if someone tries to upload a file with an odd extension (.lkg, .fld, MCR, BC1, etc.), * while the extension may vary, it will almost always be a ScrewTrap-PITAGIS related file. * Therefore, we are allowing a wide range of variation in the extensions. */ //var regex = new Regex(@"\.(m|r|ur|mc)\d+$"); //var regexNums = new Regex(@"\.(m|r|ur|mc|bc)\d+$"); //var regexChars = new Regex(@"\.(m|r|ur|mc|bc)\D+$"); var regexNums = new Regex(@"\.(m|r|ur|mc|bc|nb)\d+$"); var regexChars = new Regex(@"\.(m|r|ur|mc|bc|nb)\D+$"); var extension = info.Extension.ToLower(); logger.Debug("extension = " + extension); if (extension == ".xls" || extension == ".xlsx") { logger.Debug("Looks like an excel file!"); var reader = new ExcelReader(newFileName); //ExcelReader doesn't support starting on a certain line for column names... we always assume col 1 data.columns = reader.getColumns(); data.rows = reader.getData().First().Table; reader.close(); } else if (extension == ".csv") { logger.Debug("Looks like a csv file!"); var StartOnLine = Convert.ToInt32(provider.FormData.Get("StartOnLine")); //only applicable to T/CSV var reader = new CSVReader(newFileName); data = reader.getImportDataResult(StartOnLine); // we do it all in one. } else if (extension == ".tsv") { logger.Debug("Looks like a tsv file!"); var StartOnLine = Convert.ToInt32(provider.FormData.Get("StartOnLine")); //only applicable to T/CSV var reader = new TSVReader(newFileName); data = reader.getImportDataResult(StartOnLine); // we do it all in one. } //else if (extension == ".lkg" || extension == ".fld" || regex.Match(extension).Success) else if (extension == ".lkg" || extension == ".fld" || regexNums.Match(extension).Success || regexChars.Match(extension).Success) { logger.Debug("Looks like a PITAGIS file!"); var reader = new PitagisReader(newFileName); data = reader.getImportDataResult(); // we do it all in one. } else { logger.Debug("Looks like an unknown file!"); throw new Exception("File type not compatible. We can do Excel (xls/xslx), CSV (csv), TSV (tsv), and PITAGIS (.lkg/.fld/.m01/.r01/.ur1/.mc1)."); } var result = JsonConvert.SerializeObject(data); //TODO: actual error/success message handling //string result = "{\"message\": \"Success\"}"; var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain"); //to stop IE from being stupid. return resp; }); return task; }
// Use this for initialization void Awake () { Map = new Map (); BiomeHelper.SetupColors (); SelectedBiomePaintIndexListStyle.normal.textColor = Color.white; SelectedBiomePaintIndexListStyle.onHover.background = new Texture2D (2, 2); SelectedBiomePaintIndexListStyle.hover.background = new Texture2D (2, 2); SelectedBiomePaintIndexListStyle.padding.left = 20; SelectedBiomePaintIndexListStyle.padding.right = 20; SelectedBiomePaintIndexListStyle.padding.top = 4; SelectedBiomePaintIndexListStyle.padding.bottom = 4; Config = GetComponent<CSVReader> (); Config.ParseFile (); foreach (KeyValuePair<int,float[]>pair in Config.ParsedData) { Biome tmpBiome = new Biome (pair.Value); BiomeDefinitions.Add (tmpBiome); } //Debug.Log ("Config has " + BiomeDefinitions.Count + " biome definitions"); foreach (Biome b in BiomeDefinitions) { //Debug.Log ("Heat Max:" + b.Heat_Max); } }
/// <summary> /// Check the returned rows against an expected list of rows /// </summary> /// <param name="expectedRows">List of object lists that contains the expected row data</param> /// <param name="reader">Reader to read from</param> private static void CheckExpectedRows(List<List<object>> expectedRows, CSVReader reader) { foreach (List<object> expected in expectedRows) { List<object> actual = reader.ReadRow(); CheckNextRow(actual, expected); } Assert.IsNull(reader.ReadRow(), "ReadRow() should return null if reading past end of file"); }
public void TestFileInfoReadRows() { File.WriteAllText(filename, fileContents); using (CSVReader reader = new CSVReader(new FileInfo(filename))) CheckExpectedRows(expectedRows, reader); }
public void OpenFileTest() { List <CSVField> fields = new List <CSVField>(); fields.Add(new CSVField { FieldName = "Field1" }); fields.Add(new CSVField { FieldName = "Field2" }); fields.Add(new CSVField { FieldName = "Field3" }); fields.Add(new CSVField { FieldName = "Field4" }); Dictionary <string, string> fieldValues = new Dictionary <string, string>(); fieldValues.Add("Field1", "Field1Value"); fieldValues.Add("Field2", "Field2Value"); fieldValues.Add("Field3", "Field3Value"); fieldValues.Add("Field4", "Field4Value"); CSVReader csvr = new CSVReader(); // Create an empty file StreamWriter sw = new StreamWriter(tempFile); sw.Close(); // Try to read the empty file csvr.OpenFile(tempFile, false, fields); Dictionary <string, string> fileValues = csvr.ReadLine(); csvr.Close(); Assert.IsTrue(fileValues == null, "Error: A non-NULL value was returned when NULL was expected"); // Create a file with no headers sw = new StreamWriter(tempFile); string fileLine = ""; for (int i = 0; i < fields.Count; i++) { if (i != 0) { fileLine += ","; } fileLine += fieldValues[fields[i].FieldName]; } sw.WriteLine(fileLine); sw.Close(); // Now read the file csvr.OpenFile(tempFile, false, fields); fileValues = csvr.ReadLine(); csvr.Close(); Assert.IsTrue(fileValues != null, "Error: A NULL value was returned when a non-NULL value was expected"); Assert.IsTrue(fileValues.Count == 4, $"Error: A value of {fieldValues.Count} was returned when 4 was expected"); this.AreEqual(fieldValues, fileValues); // Create a file with headers sw = new StreamWriter(tempFile); fileLine = ""; for (int i = 0; i < fields.Count; i++) { if (i != 0) { fileLine += ","; } fileLine += fields[i].FieldName; } sw.WriteLine(fileLine); fileLine = ""; for (int i = 0; i < fields.Count; i++) { if (i != 0) { fileLine += ","; } fileLine += fieldValues[fields[i].FieldName]; } sw.WriteLine(fileLine); sw.Close(); // Now read the file csvr.OpenFile(tempFile, true); fileValues = csvr.ReadLine(); csvr.Close(); Assert.IsTrue(fileValues != null, "Error: A NULL value was returned when a non-NULL value was expected"); Assert.IsTrue(fileValues.Count == 4, $"Error: A value of {fieldValues.Count} was returned when 4 was expected"); this.AreEqual(fieldValues, fileValues); // Create a file with headers and quotes sw = new StreamWriter(tempFile); fileLine = ""; for (int i = 0; i < fields.Count; i++) { if (i != 0) { fileLine += ","; } fileLine += "\"" + fields[i].FieldName + "\""; } sw.WriteLine(fileLine); fileLine = ""; for (int i = 0; i < fields.Count; i++) { if (i != 0) { fileLine += ","; } fileLine += "\"" + fieldValues[fields[i].FieldName] + "\""; } sw.WriteLine(fileLine); sw.Close(); // Now read the file csvr.OpenFile(tempFile, true); fileValues = csvr.ReadLine(); csvr.Close(); Assert.IsTrue(fileValues != null, "Error: A NULL value was returned when a non-NULL value was expected"); Assert.IsTrue(fileValues.Count == 4, $"Error: A value of {fieldValues.Count} was returned when 4 was expected"); this.AreEqual(fieldValues, fileValues); // Cleanup File.Delete(tempFile); }
// Use this for initialization void Start() { // Return immediately if plot is false if (!plot) { return; } // Pull in the Nexus from DrawCylinder and then the nodes list from the Nexus GameObject nexus = GameObject.Find("LineNexus"); List <GameObject> nodes = nexus.GetComponent <DrawCylinders>().nodes; // Debug checks and heartbeat. if (nexus == null) { print("Nexus not found!"); } print("Hello, Nodes! I'm the DataPlotter Script!"); // References CSVReader.cs, which returns a list compatible with our points variable. points = CSVReader.Read(filename); //Debug to console print(points); // Basic text representation of the CSV File // Declare list of strings, fill with keys (column names) List <string> columnList = new List <string>(points[1].Keys); // Print number of keys (using .count) print("There are " + columnList.Count + " columns in CSV"); foreach (string key in columnList) { print("Column name is " + key); } // Assign column name from columnList to Name variables xName = columnList[columnX]; yName = columnList[columnY]; zName = columnList[columnZ]; //Find the maxes and mins for normalization float xMax = FindMaxValue(xName); float yMax = FindMaxValue(yName); float zMax = FindMaxValue(zName); float xMin = FindMinValue(xName); float yMin = FindMinValue(yName); float zMin = FindMinValue(zName); // Loop through the points and plot the graph for (int i = 0; i < points.Count; i++) { // Find each representative value float x = (Convert.ToSingle(points[i][xName]) - xMin) / (xMax - xMin); // System.Convert.ToSingle just ensures that what we're using is a float float y = (Convert.ToSingle(points[i][yName]) - yMin) / (yMax - yMin); float z = (Convert.ToSingle(points[i][zName]) - zMin) / (yMax - yMin) + 2.0f; // Offset the Z +2 because the HoloLense camera is at the true origin. GameObject temp = Instantiate(ptprefab, new Vector3(x, y, z) * plotScale, Quaternion.identity); temp.name = "PlotData" + i; temp.transform.parent = nexus.transform; // Gets material color and sets it to a new RGBA color we define temp.GetComponent <Renderer>().material.color = new Color(x, y, z, 1.0f); // Try to tack these clones into the Nexus nodes.Add(temp); } }
public void CreateTable(string csv_text) { //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) sections = new List <Section>(); CSVReader cSVReader = new CSVReader(csv_text, "section,type,prm,priority,npcid,anim,posX,posY,posZ,rotX,rotY,rotZ,jp,voiceId", false); Section section = null; while (cSVReader.NextLine()) { string value = string.Empty; NPC_MESSAGE_TYPE value2 = NPC_MESSAGE_TYPE.NONE; int value3 = 0; int value4 = 0; int value5 = 0; string value6 = string.Empty; string value7 = string.Empty; float value8 = 0f; float value9 = 0f; float value10 = 0f; float value11 = 0f; float value12 = 0f; float value13 = 0f; int value14 = 0; cSVReader.Pop(ref value); cSVReader.Pop(ref value2); cSVReader.Pop(ref value3); cSVReader.Pop(ref value4); cSVReader.Pop(ref value5); cSVReader.Pop(ref value6); cSVReader.Pop(ref value8); cSVReader.Pop(ref value9); cSVReader.Pop(ref value10); cSVReader.Pop(ref value11); cSVReader.Pop(ref value12); cSVReader.Pop(ref value13); cSVReader.Pop(ref value7); cSVReader.Pop(ref value14); if (value.Length > 0) { if (section != null) { sections.Add(section); } section = new Section(); section.name = value; } if (value2 != 0) { Message message = new Message(); message.type = value2; message.param = value3; message.priority = value4; message.npc = value5; message.animationStateName = value6; message.pos = new Vector3(value8, value9, value10); message.rot = new Vector3(value11, value12, value13); message.message = value7; message.voice_id = value14; section.messages.Add(message); } } if (section != null) { sections.Add(section); } sections.TrimExcess(); }
private void btnVWAP_Click(object sender, System.EventArgs e) { if (this.txtPath.Text == "") { MessageBox.Show("Path not specified."); return; } Fabrefactum.TimeSeries tSeries = new Fabrefactum.TimeSeries(); using (CSVReader csv = new CSVReader(@txtPath.Text)) { string[] fields; while ((fields = csv.GetCSVLine()) != null) { object[] fieldArray = new object[fields.Length]; fieldArray[0] = DateTime.Parse(fields[0] + " " + fields[1]); for (int i = 2; i < fields.Length; i++) { fieldArray[i-1] = Convert.ToDouble(fields[i]); } if (fieldArray.Length > 1) { tSeries.Add(DateTime.Parse(fieldArray[0].ToString()),fieldArray); } } } // Calculate VWAP int length = 10; if (this.txtLength.Text != "") { length = Convert.ToInt32(txtLength.Text); } Fabrefactum.VWAP.Calculate(tSeries,length,4,6,5); axStockChartX1.ClearValues("EUR.Close"); axStockChartX1.ClearValues("EUR.VWAP"); axStockChartX1.ClearValues("EUR.Volume"); // Add our points for (int i = 0; i < tSeries.Count; i++) { object[] series = (object[])tSeries[i]; if ((double)series[6] != double.NaN) { DateTime date = tSeries.GetDateTime(i); double jDate = axStockChartX1.ToJulianDate(date.Year,date.Month,date.Day,date.Hour,date.Minute,date.Second); axStockChartX1.AppendValue("EUR.Close",jDate,(double)series[4]); axStockChartX1.AppendValue("EUR.VWAP",jDate,(double)series[6]); axStockChartX1.AppendValue("EUR.Volume",jDate,(double)series[5]); } } axStockChartX1.CtlUpdate(); }
// Use this for initialization void Start() { Instance = this; }
public static void LoadAll() { Debug.ClearDeveloperConsole(); Camera screenshotCam = null; List <string> thumbnailPaths = new List <string>(); if (furnitureBase == null) { Refresh(); } try { AssetDatabase.StartAssetEditing(); screenshotCam = ((GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath <GameObject>("Assets/Prefabs/Back-end/Screenshot Camera.prefab"))).GetComponent <Camera>(); //screenshotCam.transform.position = new Vector3(995, 1005.67f, 995); Clear(); TextAsset csvFile = AssetDatabase.LoadAssetAtPath <TextAsset>("Assets/Data/furniture.csv"); //string[][] table = CSVReader.SplitCsvGrid(csvFile.text); DataTable table = CSVReader.CsvToTable(csvFile); Debug.Log("Loading " + table.Rows.Count + " furniture prefabs"); foreach (DataRow row in table.Rows) { GameObject dummyInstance = (GameObject)PrefabUtility.InstantiatePrefab(furnitureBase); string name = row.Field <string>("Furniture Name"); dummyInstance.name = name; //Populate furniture component data Furniture furniture = dummyInstance.GetComponent <Furniture>(); furniture.cost = row.Field <float>("Money Cost"); furniture.unlockCost = float.Parse(row.Field <string>("Prestige Unlock")); furniture.size = new Vector2(row.Field <float>("Size.x"), row.Field <float>("Size.y")); furniture.offset = new Vector3(row.Field <float>("Offset.x"), row.Field <float>("Offset.y"), row.Field <float>("Offset.z")); //Reserve nodes furniture.reservations = new Vector2[] { }; for (int i = 1; i <= 2; i++) { float x = row.Field <float>("Reserve " + i.ToString() + ".x"); float y = row.Field <float>("Reserve " + i.ToString() + ".y"); if (x == 0 && y == 0) { break; } Vector2 xy = new Vector2(x, y); furniture.reservations = furniture.reservations.Append(xy).ToArray(); } string[] tagColumns = { "Aesthetic", "Type" /*, "Room" */ }; List <Furniture.Tags> tags = new List <Furniture.Tags>(); foreach (string header in tagColumns) { string value = row.Field <string>(header); if (Enum.TryParse(value, true, out Furniture.Tags tag)) { tags.Add(tag); } else { Debug.LogError("Tag " + value + " is not defined ('" + header + "' of '" + name + "')"); } } furniture.tags = tags.ToArray(); //Ensure folder exists string folderPath = $"Assets/Resources/Auto/Furniture/{row.Field<string>("Aesthetic")}"; if (!Directory.Exists(folderPath)) { AssetDatabase.CreateFolder("Assets/Resources/Auto/Furniture", row.Field <string>("Aesthetic")); AssetDatabase.CreateFolder($"Assets/Resources/Auto/Furniture/{row.Field<string>("Aesthetic")}", "Thumbnails"); AssetDatabase.Refresh(); } //Add model & texture string modelPath = "Assets/Models/Furniture/" + row.Field <string>("Aesthetic") + "/" + name /*.Replace(" ", string.Empty)*/ + ".fbx"; GameObject model = AssetDatabase.LoadAssetAtPath <GameObject>(modelPath); if (model == null) { Debug.LogWarning("Model not found at " + modelPath); } else { //Apply model List <Material> mats = new List <Material>(); GameObject modelInstance = (GameObject)PrefabUtility.InstantiatePrefab(model, dummyInstance.transform); GameObject screenshotModel = (GameObject)PrefabUtility.InstantiatePrefab(model); modelInstance.layer = LayerMask.NameToLayer("Furniture"); for (int i = 1; i <= 2; i++) { if (row.Field <string>($"Base Material {i}") == "") { continue; } else { string matBasePath = $"Assets/Models/Materials/{row.Field<string>("Base Material " + i)}.mat"; Material matBase = AssetDatabase.LoadAssetAtPath <Material>(matBasePath); if (matBase == null) { Debug.LogError(matBasePath + " returned no material"); continue; } Material mat = new Material(matBase); mat.name = name + i; string texturePath = $"Assets/Models/Furniture/{row.Field<string>("Aesthetic")}/Materials and Textures/{row.Field<string>("Texture " + i)}.png"; Texture texture = AssetDatabase.LoadAssetAtPath <Texture>(texturePath); if (texture == null) { Debug.LogError("Texture not found at " + texturePath); } mat.SetTexture("_MainTex", texture); string matAssetPath = $"Assets/Resources/Auto/Materials/{mat.name}.mat"; AssetDatabase.CreateAsset(mat, matAssetPath); Material matAsset = AssetDatabase.LoadAssetAtPath <Material>(matAssetPath); mats.Add(matAsset); } } modelInstance.GetComponent <Renderer>().materials = mats.ToArray(); screenshotModel.GetComponent <Renderer>().materials = mats.ToArray(); //Create thumbnail image RenderTexture rt = new RenderTexture(256, 256, 0); screenshotCam.targetTexture = rt; RenderTexture.active = rt; screenshotModel.transform.position = new Vector3(999, 999, 999); screenshotModel.transform.Rotate(0, 180, 0); screenshotModel.layer = LayerMask.NameToLayer("Furniture"); //screenshotCam.orthographicSize = Mathf.Max(furniture.size.x, furniture.size.y); screenshotCam.Render(); Texture2D image = new Texture2D(256, 256); image.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); image.Apply(); var Bytes = image.EncodeToPNG(); UnityEngine.Object.DestroyImmediate(image); UnityEngine.Object.DestroyImmediate(screenshotModel); string path = $"{Application.dataPath}/Resources/Auto/Furniture/{row.Field<string>("Aesthetic")}/Thumbnails/{name}.png"; string shortPath = $"Assets/Resources/Auto/Furniture/{row.Field<string>("Aesthetic")}/Thumbnails/{name}.png"; string fPath = $"Assets/Resources/Auto/Furniture/{row.Field<string>("Aesthetic")}/Thumbnails/"; if (!Directory.Exists(fPath + row.Field <string>("Aesthetic"))) { AssetDatabase.CreateFolder(fPath, row.Field <string>("Aesthetic")); AssetDatabase.Refresh(); } File.WriteAllBytes(path, Bytes); thumbnailPaths.Add(shortPath); RenderTexture.active = null; screenshotCam.targetTexture = null; UnityEngine.Object.DestroyImmediate(rt); } //Save prefab string completePath = $"{folderPath}/{name}.prefab"; GameObject newPrefab = PrefabUtility.SaveAsPrefabAsset(dummyInstance, completePath); GameObject.DestroyImmediate(dummyInstance); furniturePrefabs.Add(newPrefab); furniturePaths.Add(completePath); } } finally { AssetDatabase.StopAssetEditing(); RenderTexture.active = null; GameObject.DestroyImmediate(screenshotCam.gameObject); } //Import sprites AssetDatabase.Refresh(); foreach (string path in thumbnailPaths) { //Import thumbnails as sprites AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport); TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter; importer.textureType = TextureImporterType.Sprite; AssetDatabase.WriteImportSettingsIfDirty(path); } //Build asset bundle //AssetBundleBuild buildMap = new AssetBundleBuild(); //buildMap.assetNames = furniturePaths.Concat(thumbnailPaths).ToArray(); //buildMap.assetBundleName = "Furniture Prefabs"; //BuildPipeline.BuildAssetBundles("Assets/AssetBundles", new AssetBundleBuild[]{ buildMap }, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows); Debug.Log("Furniture refresh succeeded"); }
private void StartButton_Click(object sender, RoutedEventArgs e) { this.neuralNetwork = window.neuralNetwork; if (selectedTrainingFile == null || selectedTrainingFile == string.Empty) { consoleTextBox.AppendText("No training data selected !\n"); return; } if (window.neuralNetwork == null) { consoleTextBox.AppendText("No network loaded !\n"); return; } double buffer; TimeSpan timespanBuffer; if (errorTargetTextBox.Text == string.Empty && !TimeSpan.TryParse(LearningTimeTextBox.Text, out timespanBuffer) || errorTargetTextBox.Text == string.Empty && TimeSpan.Parse(LearningTimeTextBox.Text) == TimeSpan.Zero || !Double.TryParse(errorTargetTextBox.Text, out buffer) && TimeSpan.Parse(LearningTimeTextBox.Text) == TimeSpan.Zero || !Double.TryParse(errorTargetTextBox.Text, out buffer) && !TimeSpan.TryParse(LearningTimeTextBox.Text, out timespanBuffer)) { consoleTextBox.AppendText("Invalid error target !\n"); return; } List <double> inputValues = new List <double>(); List <double> outputValues = new List <double>(); try { List <string> readData = CSVReader.ReadCSVFile(selectedTrainingFile); for (int line = 0; line < readData.Count; line++) { string[] splitData = readData[line].Split(';'); for (int data = 0; data < splitData.Length; data++) { if (data < neuralNetwork.Layers[0].Neurons.Count) { inputValues.Add(double.Parse(splitData[data])); } else { outputValues.Add(double.Parse(splitData[data])); } } } } catch (Exception exc) { consoleTextBox.AppendText("Invalid training data !\n"); return; } Task networkTrainer; TimeSpan span = TimeSpan.Parse(LearningTimeTextBox.Text); if (errorTargetTextBox.Text == string.Empty && span.TotalMilliseconds >= 0) { networkTrainer = neuralNetwork.TrainAsync(inputValues, outputValues, span); } else if (span.TotalMilliseconds >= 0) { networkTrainer = neuralNetwork.TrainAsync(inputValues, outputValues, double.Parse(errorTargetTextBox.Text), span); } else { networkTrainer = neuralNetwork.TrainAsync(inputValues, outputValues, double.Parse(errorTargetTextBox.Text)); } Task errorDisplayer = Task.Factory.StartNew(async() => { while (networkTrainer.Status == TaskStatus.WaitingToRun || networkTrainer.Status == TaskStatus.WaitingForActivation || networkTrainer.Status == TaskStatus.WaitingForChildrenToComplete || networkTrainer.Status == TaskStatus.Running || networkTrainer.Status == TaskStatus.Created) { if (neuralNetwork.AbsoluteError != 0) { this.Dispatcher.Invoke(() => { consoleTextBox.AppendText("Training... current error: " + neuralNetwork.AbsoluteError.ToString() + " Elapsed: " + neuralNetwork.elapsed.TotalMilliseconds + " milliseconds" + Environment.NewLine); consoleTextBox.ScrollToEnd(); }); } await Task.Delay(300); } this.Dispatcher.Invoke(() => { consoleTextBox.AppendText("Training finished.\n"); }); }); }
// Use this for initialization void Start() { nActualYear = 0; dataTimeText = GameObject.Find("Data Time Text").GetComponent <Text>(); dataTimeText.text = "Year: " + (years[nActualYear]).ToString(); xInitialProportion = freshWater.transform.localScale.x; numberFish = fishSchool.GetComponent <SchoolController>()._childAmount; listFishSchools = new List <GameObject>(); //Initial points in the real world. The other 2 are calculated from here in a way that all 4 create a perfect square. p1 = new Vector2(53543.941f, 434126.177f); p2 = new Vector2(56260.2f, 430603.6f); Vector2 direction = (p2 - p1).normalized; float sideMagnitude = (p2 - p1).magnitude; Vector2 perpDirection = Vector2.Perpendicular(direction); p3 = p1 + perpDirection * sideMagnitude; p4 = p2 + perpDirection * sideMagnitude; Q = 0.5f * (p2 + p3); //find the minimum and maximum points maxX = -5000; minX = 5000; maxY = -5000; minY = 5000; Vector2[] allpoints; allpoints = new Vector2[4]; allpoints[0] = p1; allpoints[1] = p2; allpoints[2] = p3; allpoints[3] = p4; for (int i = 0; i < allpoints.Length; i++) { if (allpoints[i].x > maxX) { maxX = allpoints[i].x; } if (allpoints[i].x < minX) { minX = allpoints[i].x; } if (allpoints[i].y > maxY) { maxY = allpoints[i].y; } if (allpoints[i].y < minY) { minY = allpoints[i].y; } } RWDiagonalDistance = (p3 - p2).magnitude; upperRight = new Vector2(seaFloorCollider.bounds.max.x, seaFloorCollider.bounds.min.z); downLeft = new Vector2(seaFloorCollider.bounds.min.x, seaFloorCollider.bounds.max.z); VRDiagonalDistance = (upperRight - downLeft).magnitude; print(Q.x); //Load salinity data SalinityPreCalculations preCalculations = new SalinityPreCalculations(); salinityPoints = preCalculations.LoadSalinityPoints(); salinityIndexesXYearMixDLimit = preCalculations.Load(1); salinityIndexesXYearMixUlimit = preCalculations.Load(2); salinityPointsXYear = new List <SalinityPoint> [years.Length]; allUnitSalinityDivisions = new List <GameObject>(); allUnitSecondarySalinityDivisions = new List <GameObject>(); CreateSalinityDivisions(nActualYear); areSalinityPointsVisible = true; for (int i = 0; i < years.Length; i++) { List <SalinityPoint> dummySalinityPoints = new List <SalinityPoint>(); for (int j = 0; j < salinityPoints.Length; j++) { if (years[i] == salinityPoints[j].year) { dummySalinityPoints.Add(salinityPoints[j]); } } salinityPointsXYear[i] = dummySalinityPoints; } //Load fish data List <Dictionary <string, object> > dataFish = CSVReader.Read("Clupea"); Algorithms alg = new Algorithms(); fishPositionsXYear = new List <Vector2> [years.Length]; fishNumberXYearInPos = new List <int> [years.Length]; for (int i = 0; i < years.Length; i++) { List <Vector2> listFishPos = new List <Vector2>(); List <int> listFishNumberInPos = new List <int>(); for (int j = 0; j < dataFish.Count; j++) { double x = double.Parse(dataFish[j]["X"].ToString()); double y = double.Parse(dataFish[j]["Y"].ToString()); int n = (int)dataFish[j]["n"]; string dateExtraction = (string)dataFish[j]["date"]; Vector2 pos = new Vector2((float)x, (float)y); int year = years[i]; string yearMonth = "-5-" + year.ToString(); if (alg.InAreaOfStudy_4Vertices(pos, p1, p2, p3, p4) && dateExtraction.Contains(yearMonth)) { listFishPos.Add(pos); listFishNumberInPos.Add(n); } } int p = 0; fishPositionsXYear[i] = listFishPos; fishNumberXYearInPos[i] = listFishNumberInPos; } int max = -1000; for (int i = 0; i < fishPositionsXYear.Length; i++) { if (fishPositionsXYear[i].Count > max) { max = fishPositionsXYear[i].Count; } } //Instantiate maximum number of fish schools listFishSchools = new List <GameObject>(); for (int i = 0; i < max; i++) { GameObject cloneFishSchool = Instantiate(fishSchool, fishSchool.transform.position, fishSchool.transform.rotation) as GameObject; listFishSchools.Add(cloneFishSchool); } vanishPos = new Vector3(0.0f, -300.0f, 0.0f); //Used to change the number of fish in schools. It doesn't work without a temporal delay. StartCoroutine("WaitRespawn"); }
// Use this for initialization void Start() { // Set pointlist to results of function Reader with argument inputfile pointList = CSVReader.Read(inputfile); //Log to console Debug.Log(pointList); // Declare list of strings, fill with keys (column names) List <string> columnList = new List <string>(pointList[1].Keys); // Print number of keys (using .count) Debug.Log("There are " + columnList.Count + " columns in the CSV"); foreach (string key in columnList) { Debug.Log("Column name is " + key); } // Assign column name from columnList to Name variables xName = columnList[columnX]; yName = columnList[columnY]; zName = columnList[columnZ]; // Get maxes of each axis float xMax = FindMaxValue(xName); float yMax = FindMaxValue(yName); float zMax = FindMaxValue(zName); // Get minimums of each axis float xMin = FindMinValue(xName); float yMin = FindMinValue(yName); float zMin = FindMinValue(zName); //Loop through Pointlist for (var i = 0; i < pointList.Count; i++) { // Get value in poinList at ith "row", in "column" Name, normalize float x = (System.Convert.ToSingle(pointList[i][xName]) - xMin) / (xMax - xMin); float y = (System.Convert.ToSingle(pointList[i][yName]) - yMin) / (yMax - yMin); float z = (System.Convert.ToSingle(pointList[i][zName]) - zMin) / (zMax - zMin); // Instantiate as gameobject variable so that it can be manipulated within loop GameObject dataPoint = Instantiate( PointPrefab, new Vector3(x, y, z) * plotScale, Quaternion.identity); // Make child of PointHolder object, to keep points within container in hiearchy dataPoint.transform.parent = PointHolder.transform; // Assigns original values to dataPointName string dataPointName = pointList[i][xName] + " " + pointList[i][yName] + " " + pointList[i][zName]; // Assigns name to the prefab dataPoint.transform.name = dataPointName; // Gets material color and sets it to a new RGB color we define dataPoint.GetComponent <Renderer>().material.color = new Color(x, y, z, 1.0f); } }
public void TestStringReaderDataTable() { DataTable table; using (CSVReader reader = new CSVReader(new StringReader(fileContents))) table = reader.CreateDataTable(false); CheckTable(table); }
public void IterateTrainingLoop() { List <List <int> > groupLists = new List <List <int> >(); groupLists.Add(group1Indexes); groupLists.Add(group2Indexes); groupLists.Add(group3Indexes); groupLists.Add(group4Indexes); groupLists.Add(group5Indexes); //compare entire table double diff = GetAbsoluteTableDifference(resultTable, CombiResultTableDoubles); if (diff < bestDifference) { Debug.Log("new bestDifference found(" + diff + " < " + bestDifference + ")"); bestDifference = diff; bestWeights = new List <double>(weightsArray); bestTable = resultTable; string allBestWeights = ""; int j = 0; foreach (double weight in bestWeights) { if (j == groupLists[currentGroup][currentGroupIndex]) { allBestWeights += "{{{" + weight.ToString("F1") + "}}}, "; } else { allBestWeights += weight.ToString("F1") + ", "; } j++; } Debug.Log("Weights = " + allBestWeights); } currentWeight++; if (currentWeight > 5) { currentWeight = 0; currentGroupIndex++; if (currentGroupIndex >= groupLists[currentGroup].Count) { //Debug.Log("currentGroupIndex " + currentGroupIndex + " is >= " + currentGroup + "'s " + groupLists[currentGroup].Count); currentGroupIndex = 0; currentGroup++; if (currentGroup >= 5) { currentGroup = 0; currentLoop++; } //this check exists in case the current group has no associated mineral compositions while (groupLists[currentGroup].Count == 0 && currentLoop < 3)//this one goofed? { currentGroup++; if (currentGroup >= 5) { currentGroup = 0; currentLoop++; } } } //Debug.Log("groupLists legnth = " + groupLists.Count); //Debug.Log("groupLists[" + currentGroup + "].Length = " + groupLists[currentGroup].Count); //Debug.Log("minWEights length = " + minWeights.Count); //Debug.Log("currentGroupIndex = " + currentGroupIndex + ", currentGroup = " + currentGroup); float min = minWeights[groupLists[currentGroup][currentGroupIndex]]; float max = maxWeights[groupLists[currentGroup][currentGroupIndex]]; weightRange = new float[] { 0f, min, (0.75f * min) + (0.25f * max), (min + max) / 2, (0.25f * min) + (0.75f * max), max }; } if (currentLoop < 3) { float replacementWeight = weightRange[currentWeight]; //Debug.Log("loading weightRange[" + currentWeight + "] = " + weightRange[currentWeight]); weightsArray = new List <double>(bestWeights); weightsArray[groupLists[currentGroup][currentGroupIndex]] = replacementWeight; StartCoroutine("EnumerateAssayWeightIterator"); } else { //end it Debug.Log("best weights are found"); CSVReader.DebugOutputGrid(bestTable); string bestWeightString = ""; foreach (double weight in bestWeights) { bestWeightString += weight.ToString("F3") + ", "; } Debug.Log(bestWeightString); bothController.loadingMenu.SetActive(false); trainingSubmenu3.SetActive(true); /* */ } }
public void TestEmptyString() { using (CSVReader reader = new CSVReader("")) Assert.IsNull(reader.ReadRow(), "ReadRow() should return null for an empty string"); }
void Awake() { List <Dictionary <string, object> > data = CSVReader.Read(file); //read map values GameObject newsquirrel; for (var i = Random.Range(0, 30); i < data.Count; i += 20) //currently this just spawns every 20th squirrel since i tried spawning them in at once and that was a huge mistake { Vector3 pos = new Vector3(((float)data[i]["X"] - TRANSLATEX) * SCALE, ((float)data[i]["Y"] - TRANSLATEY) * SCALE, 0); //get position of squirrel and transform string squirrelColor = (string)data[i]["Primary Fur Color"]; GameObject sq = null; if (squirrelColor == "Gray") { sq = squirrel_gray; } else if (squirrelColor == "Black") { sq = squirrel_black; } else { sq = squirrel_cinammon; } newsquirrel = Instantiate(sq, pos, Quaternion.identity); //draw a squirrel in each place newsquirrel.transform.RotateAround(new Vector3(0, 0, 0), new Vector3(0, 0, 1), 37); //this rotation is arbitrary and can be tuned later newsquirrel.transform.rotation = Quaternion.identity; //shove variables into squirrel SquirrelAi sqAI = newsquirrel.GetComponent <SquirrelAi>(); sqAI.color = squirrelColor; sqAI.id = (string)data[i]["Unique Squirrel ID"]; sqAI.age = (string)data[i]["Age"]; sqAI.SetAgeSpeed(); //nightmare of data structures Dictionary <string, object> temp = new Dictionary <string, object>(); temp.Add("Kuks", data[i]["Kuks"]); temp.Add("Quaas", data[i]["Quaas"]); temp.Add("Moans", data[i]["Moans"]); sqAI.noise = pickRandomTrue(temp).ToLower(); temp = new Dictionary <string, object>(); //Running,Chasing,Climbing,Eating,Foraging temp.Add("Running", data[i]["Running"]); temp.Add("Chasing", data[i]["Chasing"]); temp.Add("Climbing", data[i]["Climbing"]); temp.Add("Eating", data[i]["Eating"]); temp.Add("Foraging", data[i]["Foraging"]); sqAI.defaultBehavior = pickRandomTrue(temp).ToLower(); temp = new Dictionary <string, object>(); //Runs from, indifferent, approaches temp.Add("Runs from", data[i]["Runs from"]); temp.Add("Approaches", data[i]["Approaches"]); temp.Add("Indifferent", data[i]["Indifferent"]); sqAI.playerBehavior = pickRandomTrue(temp).ToLower(); temp = new Dictionary <string, object>(); //probably extra lol [tail twitches/flags] temp.Add("Tail flags", data[i]["Tail flags"]); temp.Add("Tail twitches", data[i]["Tail twitches"]); sqAI.behaviors = pickRandomTrue(temp).ToLower(); /* * print("X " + data[i]["X"] + " " + * "Y " + data[i]["Y"] + " " + * "ID " + data[i]["Unique Squirrel ID"] + " " + * "Hectare " + data[i]["Hectare"]); */ totSquirrels++; } Player.position = SpawnPoints.GetChild(random.Next(0, SpawnPoints.childCount)).position; }
// Use this for initialization void Start() { // Set pointlist to results of function Reader with argument inputfile pointList = CSVReader.Read(inputfile); // Declare list of strings, fill with keys (column names) columnList = new List <string>(pointList[1].Keys); coorPoints = new List <Vector3>(); //// Print number of keys //Debug.Log("There are " + columnList.Count + " columns in the CSV file."); //foreach (string key in columnList) // Debug.Log("Column name is " + key); // Assign column name from columnList to Name variables xName = columnList[0]; yName = columnList[1]; zName = columnList[2]; // Get maximum of each axis float xMax = FindMaxValue(xName); float yMax = FindMaxValue(yName); float zMax = FindMaxValue(zName); // Get minimum of each axis float xMin = FindMinValue(xName); float yMin = FindMinValue(yName); float zMin = FindMinValue(zName); //Loop through Pointlist for (var i = 0; i < pointList.Count; i++) { // Get value in poinList at i-th "row", in "column" Name, normalize (Convert.ToSingle converts a specified value to a single-precision floating-point number) x = (Convert.ToSingle(pointList[i][xName]) - xMin) / (xMax - xMin); y = (Convert.ToSingle(pointList[i][yName]) - yMin) / (yMax - yMin); z = (Convert.ToSingle(pointList[i][zName]) - zMin) / (zMax - zMin); Vector3 coorPoint = new Vector3(x, y, z) * plotScale; coorPoints.Add(coorPoint); // Instantiate as gameobject variable so that it can be manipulated within loop GameObject dataPoint = Instantiate(pointPrefab, coorPoint, Quaternion.identity); // Make child of PointHolder object, to keep points within container in hiearchy dataPoint.transform.parent = gameObject.transform; // Assigns original values to dataPointName string dataPointName = pointList[i][xName] + " " + pointList[i][yName] + " " + pointList[i][zName]; // Assigns name to the prefab dataPoint.transform.name = dataPointName; // Gets material color dataPoint.GetComponent <Renderer>().material = pointCloudMaterial; if (GameObject.FindGameObjectsWithTag("ClippingPlaneInteractible") != null) { foreach (var clipObject in GameObject.FindGameObjectsWithTag("ClippingPlaneInteractible")) { clipObject.GetComponent <Clipping3DObject>().AddRenderer(dataPoint.GetComponent <Renderer>()); } } if (GameObject.FindGameObjectsWithTag("ClippingPlaneInteractible2") != null) { foreach (var clipObject in GameObject.FindGameObjectsWithTag("ClippingPlaneInteractible2")) { clipObject.GetComponent <Clipping3DObject>().AddRenderer(dataPoint.GetComponent <Renderer>()); } } if (GameObject.FindGameObjectsWithTag("ClippingBoxInteractible") != null) { foreach (var clipObject in GameObject.FindGameObjectsWithTag("ClippingBoxInteractible")) { clipObject.GetComponent <Clipping3DObject>().AddRenderer(dataPoint.GetComponent <Renderer>()); } } } }
public DataManager() { _csvReader = new CSVReader(); LoadDataAndStore(); }
public void DataTableChopTest() { List <SimpleChopClass> list = new List <SimpleChopClass>(); for (int i = 0; i < 5000; i++) { list.Add(new SimpleChopClass() { id = i, name = $"Bob Smith #{i}", email = $"bob.smith.{i}@example.com" }); } for (int i = 5000; i < 10000; i++) { list.Add(new SimpleChopClass() { id = i, name = $"Alice Jones #{i}", email = $"alice.jones.{i}@example.com" }); } for (int i = 10000; i < 15000; i++) { list.Add(new SimpleChopClass() { id = i, name = $"Charlie Jenkins #{i}", email = $"charlie.jenkins.{i}@example.com" }); } // Save this string to a test file string singlefile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".csv"); File.WriteAllText(singlefile, CSV.Serialize <SimpleChopClass>(list)); // Create an empty test folder string dirname = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(dirname); // Chop this file into one-line chunks CSVReader.ChopFile(singlefile, dirname, 5000); // Verify that we got three files string[] files = Directory.GetFiles(dirname); Assert.AreEqual(3, files.Length); // Read in each file and verify that each one has one line var f1 = CSV.Deserialize <SimpleChopClass>(File.ReadAllText(files[0])); Assert.AreEqual(5000, f1.Count); var f2 = CSV.Deserialize <SimpleChopClass>(File.ReadAllText(files[1])); Assert.AreEqual(5000, f2.Count); var f3 = CSV.Deserialize <SimpleChopClass>(File.ReadAllText(files[2])); Assert.AreEqual(5000, f3.Count); // Merge and verify var results = new List <SimpleChopClass>(); results.AddRange(f1); results.AddRange(f2); results.AddRange(f3); for (int i = 0; i < list.Count; i++) { Assert.AreEqual(list[i].id, results[i].id); Assert.AreEqual(list[i].name, results[i].name); Assert.AreEqual(list[i].email, results[i].email); } // Clean up Directory.Delete(dirname, true); File.Delete(singlefile); }
/// <summary> /// 일일퀘스트를 갱신합니다. /// </summary> /// <param name="AUID"></param> /// <param name="QuestCode1"></param> /// <param name="QuestCode2">여러 개를 갱신할 때 입력.</param> /// <param name="QuestCode3">여러 개를 갱신할 때 입력.</param> static public void UpdateDailyQuest(int AUID, string QuestCode1, string QuestCode2 = null, string QuestCode3 = null) { int maxQuest = 3; string[] QuestCode = new string[maxQuest]; int[] oldCount = new int[maxQuest]; int[] newCount = new int[maxQuest]; int[] cutLine = new int[maxQuest]; int[] Complete = new int[maxQuest]; int index = 0; string SQL = string.Format("select * from UserDailyQuest where AUID='{0}' and (QuestCode='{1}' or QuestCode='{2}' or QuestCode='{3}')", AUID, QuestCode1, QuestCode2, QuestCode3); SqlDataReader reader = SQLManager.ExecuteReader(SQL); CSVReader excel = null; if (reader.HasRows) { while (reader.Read()) { QuestCode[index] = reader["QuestCode"].ToString(); Complete[index] = int.Parse(reader["Complete"].ToString()); if (Complete[index] == 0) { if (excel == null) { excel = new CSVReader("TbQuest.txt"); } oldCount[index] = int.Parse(reader["Count"].ToString()); newCount[index] = oldCount[index] + 1; cutLine[index] = int.Parse(ReadJSONData.ReadLine(excel.FindJSONData("QuestCode", QuestCode[index]))[3]); //Debug.Log(CodeManager.GetMethodName() + AUID + " : " + QuestCode[index]); } index++; } } reader.Close(); for (int i = 0; i < index; i++) { if (Complete[i] == 0) { if (newCount[i] >= cutLine[i]) { newCount[i] = cutLine[i]; SQL = string.Format("update UserDailyQuest set Count='{0}', Complete='1' where AUID='{1}' and QuestCode='{2}'", newCount[i], AUID, QuestCode[i]); reader = SQLManager.ExecuteReader(SQL); reader.Close(); SQL = string.Format("insert into UserDailyQuestCompleteNotice values ('{0}','{1}');", AUID, QuestCode[i]); reader = SQLManager.ExecuteReader(SQL); reader.Close(); if (showLog) { Debug.Log(CodeManager.GetMethodName() + AUID + " : " + QuestCode[i] + " 가 갱신되어서 커트라인을 달성했다."); } } else { SQL = string.Format("update UserDailyQuest set Count='{0}' where AUID='{1}' and QuestCode='{2}'", newCount[i], AUID, QuestCode[i]); reader = SQLManager.ExecuteReader(SQL); reader.Close(); if (showLog) { Debug.Log(CodeManager.GetMethodName() + AUID + " : " + QuestCode[i] + " 가 갱신되었다."); } } } else { if (showLog) { Debug.Log(CodeManager.GetMethodName() + AUID + " : " + QuestCode[i] + " 는 이미 커트라인을 달성했다."); } } } }
public void Data_First_Start(GameManager GameMGR) { data = CSVReader.Read("Character_data"); // CSV 파일 불러오기 character_count = 0; // 기본 0으로 초기화 enemy_count = 0; for (int i = 0; i < data.Count; i++) { characters.Add(new Character()); characters[i].Character_info_update(character_count++, data[i]["NAME"].ToString(), int.Parse(data[i]["RATE"].ToString()), int.Parse(data[i]["HP"].ToString()), int.Parse(data[i]["DAMAGE"].ToString()), float.Parse(data[i]["ATKRANGE"].ToString()), int.Parse(data[i]["ATKTYPE"].ToString()), int.Parse(data[i]["VARYMP"].ToString())); GameMGR.mCharacter_Count.Add(characters[i].character_name, 0); switch (characters[i].character_rating) { case Rare_percentage.Low_Level: { Characters_Random_Range.Add(Rare_percentage.Low_Init_value); Max_Character_Range += Rare_percentage.Low_Init_value; break; } case Rare_percentage.Middle_Level: { Characters_Random_Range.Add(Rare_percentage.Middle_Init_value); Max_Character_Range += Rare_percentage.Middle_Init_value; break; } case Rare_percentage.High_Level: { Characters_Random_Range.Add(Rare_percentage.High_Init_value); Max_Character_Range += Rare_percentage.High_Init_value; break; } } // Debug.Log(characters[i].character_name + " / " + Characters_Random_Range[i]); } data = CSVReader.Read("Enemy_data"); // CSV 파일 불러오기 for (int i = 0; i < data.Count; i++) { enemys.Add(new Enemy(enemy_count++, data[i]["NAME"].ToString(), int.Parse(data[i]["HP"].ToString()), int.Parse(data[i]["DAMAGE"].ToString()), float.Parse(data[i]["ATKRANGE"].ToString()), int.Parse(data[i]["VARYMP"].ToString()))); } data = CSVReader.Read("Stage_Enemy"); for (int i = 0; i < data.Count; i++) { Stage_info.Add(new Stage(int.Parse(data[i]["Round"].ToString()), int.Parse(data[i]["EnemyWarrior"].ToString()), int.Parse(data[i]["EnemyWizard"].ToString()), int.Parse(data[i]["EnemyDifencer"].ToString()), int.Parse(data[i]["ICE_DRAGON"].ToString()))); } }
/// <summary> /// 업적을 갱신합니다. (현재 수치와 커트라인을 비교). /// </summary> /// <param name="AUID"></param> /// <param name="AchievementCode1"></param> /// <param name="AchievementCode2">여러 개를 갱신할 때 입력.</param> /// <param name="AchievementCode3">여러 개를 갱신할 때 입력.</param> static public void UpdateAchievementWithNewValue(int AUID, int newValue, string AchievementCode1, string AchievementCode2 = null, string AchievementCode3 = null, string AchievementCode4 = null, string AchievementCode5 = null) { int maxAchievement = 5; string[] AchievementCode = new string[maxAchievement]; int[] oldCount = new int[maxAchievement]; int[] newCount = new int[maxAchievement]; int[] cutLine = new int[maxAchievement]; int[] Complete = new int[maxAchievement]; int index = 0; string SQL = string.Format("select * from UserAchievement where AUID='{0}' and (AchievementCode='{1}' or AchievementCode='{2}' or AchievementCode='{3}' or AchievementCode='{4}' or AchievementCode='{5}')", AUID, AchievementCode1, AchievementCode2, AchievementCode3, AchievementCode4, AchievementCode5); SqlDataReader reader = SQLManager.ExecuteReader(SQL); CSVReader excel = null; if (reader.HasRows) { while (reader.Read()) { AchievementCode[index] = reader["AchievementCode"].ToString(); Complete[index] = int.Parse(reader["Complete"].ToString()); if (Complete[index] == 0) { if (excel == null) { excel = new CSVReader("TbAchievement.txt"); } oldCount[index] = int.Parse(reader["Count"].ToString()); newCount[index] = newValue; cutLine[index] = int.Parse(ReadJSONData.ReadLine(excel.FindJSONData("AchievementCode", AchievementCode[index]))[3]); Debug.Log(CodeManager.GetMethodName() + AUID + " : " + AchievementCode[index]); } index++; } } reader.Close(); for (int i = 0; i < index; i++) { if (Complete[i] == 0) { if (newCount[i] >= cutLine[i]) { newCount[i] = cutLine[i]; SQL = string.Format("update UserAchievement set Count='{0}', Complete='1' where AUID='{1}' and AchievementCode='{2}'", newCount[i], AUID, AchievementCode[i]); reader = SQLManager.ExecuteReader(SQL); reader.Close(); SQL = string.Format("insert into UserAchievementCompleteNotice values ('{0}','{1}');", AUID, AchievementCode[i]); reader = SQLManager.ExecuteReader(SQL); reader.Close(); if (showLog) { Debug.Log(CodeManager.GetMethodName() + AUID + " : " + AchievementCode[i] + " 가 갱신되어서 커트라인을 달성했다."); } } else { SQL = string.Format("update UserAchievement set Count='{0}' where AUID='{1}' and AchievementCode='{2}'", newCount[i], AUID, AchievementCode[i]); reader = SQLManager.ExecuteReader(SQL); reader.Close(); if (showLog) { Debug.Log(CodeManager.GetMethodName() + AUID + " : " + AchievementCode[i] + " 가 갱신되었다."); } } } else { if (showLog) { Debug.Log(CodeManager.GetMethodName() + AUID + " : " + AchievementCode[i] + " 는 이미 커트라인을 달성했다."); } } } }
public override byte[] PreProcess(byte[] rgb) { if (rgb == null) { throw new ArgumentNullException(nameof(rgb)); } base.PreProcess(rgb); using (MemoryStream ms = new MemoryStream(rgb)) { dictAircraft.Clear(); using (CSVReader reader = new CSVReader(ms)) { ReadAircraftTable(reader); string[] rgRow = null; string[] rgHeaders; // Now find the start of the flight table and stop - the regular CSVAnalyzer can pick up from here, and our aircraft table is now set up. while ((rgHeaders = reader.GetCSVLine()) != null) { if (rgHeaders != null && rgHeaders.Length > 0 && rgHeaders[0].CompareCurrentCultureIgnoreCase("Flights Table") == 0) { break; } } // Now find the next line that isn't generic data types // Look for "Text", "hhmm", "Decimal", "Boolean" - if any of these, skip ahead. while ((rgHeaders = reader.GetCSVLine()) != null) { if (Array.Find(rgHeaders, sz => rDataTypes.IsMatch(sz)) == null) { break; } } if (rgHeaders != null) { // Build a *new* byte array from here using (DataTable dt = new DataTable()) { dt.Locale = CultureInfo.CurrentCulture; foreach (string header in rgHeaders) { try { dt.Columns.Add(new DataColumn(header.Trim(), typeof(string))); } catch (DuplicateNameException) { throw new MyFlightbookException(String.Format(CultureInfo.CurrentCulture, Resources.LogbookEntry.errImportDuplicateColumn, header)); } } while ((rgRow = reader.GetCSVLine()) != null) { bool fHasData = false; Array.ForEach <string>(rgRow, (sz) => { fHasData = fHasData || !String.IsNullOrWhiteSpace(sz); }); if (!fHasData) { continue; } DataRow dr = dt.NewRow(); for (int i = 0; i < rgRow.Length && i < rgHeaders.Length; i++) { dr[i] = rgRow[i]; } dt.Rows.Add(dr); } return(Encoding.UTF8.GetBytes(CsvWriter.WriteToString(dt, true, true))); } } } } return(rgb); }
void Start() { //不忽略首尾行全文本读取对象 CSVReader allReader = new CSVReader(asset.text); //首部忽略首部一行和忽略尾部一行,部分文本读取对象 CSVReader partReader = new CSVReader(asset.text, 1, 1); //全文本读取所有行主键为‘1’ string debug1 = "(allReader)GetRows:\r\n"; string[,] gird = allReader.GetRows("1"); for (int i = 0; i < gird.GetLength(0); i++) { debug1 += "第" + (i + 1) + "行数据: # "; for (int j = 0; j < gird.GetLength(1); j++) { debug1 += gird[i, j] + " # "; } debug1 += "\r\n"; } Debug.Log(debug1); //全文本读取第一行主键为‘primaryKeyNote’ string debug2 = "(allReader)GetRowAtFirst: # "; foreach (var item in allReader.GetRowAtFirst("primaryKeyNote")) { debug2 += item + " # "; } Debug.Log(debug2); //全文本读取最后一行主键为‘1’ string debug3 = "(allReader)GetRowAtLast: # "; foreach (var item in allReader.GetRowAtLast("1")) { debug3 += item + " # "; } Debug.Log(debug3); //全文本读取所有列主键为‘key1Note’ string debug4 = "(allReader)GetColumns:\r\n"; string[,] gird2 = allReader.GetColumns("key1Note"); for (int i = 0; i < gird2.GetLength(0); i++) { debug4 += "第" + (i + 1) + "列数据: # "; for (int j = 0; j < gird2.GetLength(1); j++) { debug4 += gird2[i, j] + " # "; } debug4 += "\r\n"; } Debug.Log(debug4); //全文本读取第一列键名为‘key1Note’ //读取单列的时候返回的数据默认忽略了键名 [ignoreRowNum = 1] string debug5 = "(allReader)GetColumnAtFirst: # "; foreach (var item in allReader.GetColumnAtFirst("key1Note")) { debug5 += item + " # "; } Debug.Log(debug5); //全文本读取第一列键名为‘key1Note’ //读取单列的时候返回的数据默认忽略了键名 [ignoreRowNum = 1] string debug6 = "(allReader)GetColumnAtLast: # "; foreach (var item in allReader.GetColumnAtLast("key1Note")) { debug6 += item + " # "; } Debug.Log(debug6); //全文本读取多个值主键为‘1’,键名为key1Note string debug7 = "(allReader)GetValues: # "; foreach (var item in allReader.GetValues("1", "key1Note")) { debug7 += item + " # "; } Debug.Log(debug7); //全文本读取第一个值主键为‘1’,键名为key1Note string debug8 = "(allReader)GetValueAtFirst: "; Debug.Log(debug8 + allReader.GetValueAtFirst("1", "key1Note")); //全文本读取最后一个值主键为‘1’,键名为key1Note string debug9 = "(allReader)GetValueAtLast: "; Debug.Log(debug9 + allReader.GetValueAtLast("1", "key1Note")); /** * * 部分文本读取方式一样,只是部分文本获取数据时忽略了首部第一行注释行和尾部最后一行空行,使得可以控制读取有效数据行 * 中文文本要使用utf-8格式保存,否则读取为空 * **/ }
public override byte[] PreProcess(byte[] rgb) { if (rgb == null) { throw new ArgumentNullException("rgb"); } base.PreProcess(rgb); MemoryStream ms = new MemoryStream(rgb); try { dictAircraft.Clear(); using (CSVReader reader = new CSVReader(ms)) { ms = null; // for CA2202 ReadAircraftTable(reader); string[] rgRow = null; // Now find the start of the flight table and stop - the regular CSVAnalyzer can pick up from here, and our aircraft table is now set up. while ((rgRow = reader.GetCSVLine()) != null) { if (rgRow != null && rgRow.Length > 0 && rgRow[0].CompareCurrentCultureIgnoreCase("Flights Table") == 0) { break; } } string[] rgHeaders = reader.GetCSVLine(); if (rgHeaders != null) { // Build a *new* byte array from here using (DataTable dt = new DataTable()) { dt.Locale = CultureInfo.CurrentCulture; foreach (string header in rgHeaders) { dt.Columns.Add(new DataColumn(header.Trim(), typeof(string))); } while ((rgRow = reader.GetCSVLine()) != null) { bool fHasData = false; Array.ForEach <string>(rgRow, (sz) => { fHasData = fHasData || !String.IsNullOrWhiteSpace(sz); }); if (!fHasData) { continue; } DataRow dr = dt.NewRow(); for (int i = 0; i < rgRow.Length && i < rgHeaders.Length; i++) { dr[i] = rgRow[i]; } dt.Rows.Add(dr); } return(Encoding.UTF8.GetBytes(CsvWriter.WriteToString(dt, true, true))); } } } } finally { if (ms != null) { ms.Dispose(); } } return(rgb); }
public IEnumerator ChangeDataset() { Dataset ds; if (!datasetDict.TryGetValue(datasetDropdown.options[datasetDropdown.value].text, out ds)) { Debug.Log("dataset not found - creating new one"); Dictionary <string, MineralComposition> mineralDict = new Dictionary <string, MineralComposition>(); yield return(StartCoroutine(FastDownload(path + datasetDropdown.options[datasetDropdown.value].text, fileContents => fileContentString = fileContents))); string[,] datasetGrid = CSVReader.SplitCsvGrid(fileContentString); for (int i = 1; i <= datasetGrid.GetUpperBound(1); i++) { string columnHeader = datasetGrid[0, i]; string mineralComp = datasetGrid[0, i]; MineralComposition MC = new MineralComposition(mineralComp); double[] val = new double[] { Double.Parse(datasetGrid[1, i]), Double.Parse(datasetGrid[2, i]), Double.Parse(datasetGrid[3, i]), Double.Parse(datasetGrid[4, i]), Double.Parse(datasetGrid[5, i]), Double.Parse(datasetGrid[6, i]), Double.Parse(datasetGrid[7, i]), Double.Parse(datasetGrid[8, i]), Double.Parse(datasetGrid[9, i]), Double.Parse(datasetGrid[10, i]), Double.Parse(datasetGrid[11, i]), Double.Parse(datasetGrid[12, i]), Double.Parse(datasetGrid[13, i]), Double.Parse(datasetGrid[14, i]), Double.Parse(datasetGrid[15, i]), Double.Parse(datasetGrid[16, i]), Double.Parse(datasetGrid[17, i]), Double.Parse(datasetGrid[18, i]), Double.Parse(datasetGrid[19, i]), Double.Parse(datasetGrid[20, i]), Double.Parse(datasetGrid[21, i]) }; FillMCDatabase(MC, val); MC.weight = double.Parse(datasetGrid[22, i]); MC.startPoint = double.Parse(datasetGrid[23, i]); mineralDict.Add(mineralComp, MC); } ds = new Dataset(mineralDict); datasetDict.Add(datasetDropdown.options[datasetDropdown.value].text, ds); } currentMineralDict = ds.mineralDict; mineralToggles.Clear(); foreach (Transform child in mineralCompScrollView.transform) { GameObject.Destroy(child.gameObject); } int k = 0; foreach (MineralComposition mc in currentMineralDict.Values) { GameObject g = GameObject.Instantiate(mineralCompListPrefab) as GameObject; g.transform.SetParent(mineralCompScrollView.transform, false); MineralCompositionListEntry mcle = g.GetComponent <MineralCompositionListEntry>(); mcle.label.text = mc.mineral; mcle.MineralComp = mc.mineral; mcle.index = k; if (assayMode) { g.GetComponentInChildren <InputField>().text = mc.weight.ToString(); } else { g.GetComponentInChildren <InputField>().text = mc.startPoint.ToString(); } mineralToggles.Add(g.GetComponent <Toggle>()); k++; } foreach (Transform child in elementCompScrollView.transform) { MineralCompositionListEntry mcle = child.gameObject.GetComponent <MineralCompositionListEntry>(); mcle.index = k; k++; } yield return(null); }
public override bool Parse(string szData) { StringBuilder sbErr = new StringBuilder(); TelemetryDataTable m_dt = ParsedData; m_dt.Clear(); Boolean fResult = true; string flightData = FixedFlightData(szData); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(flightData))) { using (CSVReader csvr = new CSVReader(ms)) { try { string[] rgszHeader = null; // Find the first row that looks like columns. try { do { rgszHeader = csvr.GetCSVLine(true); } while (rgszHeader != null && (rgszHeader.Length < 2 || rgszHeader[0].StartsWith("#", StringComparison.OrdinalIgnoreCase) || rgszHeader[0].StartsWith("Date (yyyy-mm-dd)", StringComparison.OrdinalIgnoreCase))); } catch (CSVReaderInvalidCSVException ex) { throw new MyFlightbookException(ex.Message); } if (rgszHeader == null) // no valid CSV header found { sbErr.Append(Resources.FlightData.errNoCSVHeaderRowFound); return(false); } CSVParsingContext pc = new CSVParsingContext(); SetUpContextFromHeaderRow(pc, rgszHeader); string[] rgszRow = null; int iRow = 0; while ((rgszRow = csvr.GetCSVLine()) != null) { iRow++; try { m_dt.Rows.Add(ParseCSVRow(pc, FixRowHack(rgszRow, rgszHeader), iRow)); } catch (MyFlightbookException ex) { sbErr.Append(String.Format(CultureInfo.CurrentCulture, Resources.FlightData.errInRow, iRow, ex.Message)); fResult = false; } catch (System.FormatException ex) { sbErr.Append(String.Format(CultureInfo.CurrentCulture, Resources.FlightData.errInRow, iRow, ex.Message)); fResult = false; } } // Go back and put the derived speeds in. if (pc.fDeriveSpeed) { Position.DeriveSpeed(pc.SamplesList); for (int i = 0; i < m_dt.Rows.Count && i < pc.SamplesList.Count; i++) { if (pc.SamplesList[i].HasSpeed) { m_dt.Rows[i][KnownColumnNames.DERIVEDSPEED] = pc.SamplesList[i].Speed; } } } } catch (MyFlightbookException ex) { sbErr.Append(String.Format(CultureInfo.CurrentCulture, Resources.FlightData.errGeneric, ex.Message)); fResult = false; } catch (System.Data.DuplicateNameException ex) { sbErr.Append(String.Format(CultureInfo.CurrentCulture, Resources.FlightData.errGeneric, ex.Message)); fResult = false; } finally { } } } ErrorString = sbErr.ToString(); return(fResult); }
public static bool cb(CSVReader csv_reader, EquipItemData data, ref uint key) { //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) data.id = key; csv_reader.Pop(ref data.appVer); csv_reader.Pop(ref data.type); csv_reader.Pop(ref data.getType); csv_reader.Pop(ref data.eventId); csv_reader.Pop(ref data.name); csv_reader.Pop(ref data.rarity); csv_reader.Pop(ref data.modelID0); data.modelID1 = data.modelID0; csv_reader.Pop(ref data.modelID1); string value = string.Empty; int num = -1; csv_reader.Pop(ref value); if (value.Length > 1) { num = (int)Enum.Parse(typeof(ELEMENT_TYPE), value); } if (!(bool)csv_reader.PopColor24(ref data.modelColor0)) { if (num != -1) { data.modelColor0 = NGUIMath.ColorToInt(MonoBehaviourSingleton <GlobalSettingsManager> .I.playerVisual.GetModelElementColor(num)); } else { data.modelColor0 = NGUIMath.ColorToInt(MonoBehaviourSingleton <GlobalSettingsManager> .I.playerVisual.modelBaseColor); } } csv_reader.PopColor24(ref data.modelColor1); if (!(bool)csv_reader.PopColor24(ref data.modelColor2)) { if (num != -1) { data.modelColor2 = NGUIMath.ColorToInt(MonoBehaviourSingleton <GlobalSettingsManager> .I.playerVisual.GetModelElementColor2(num)); } else { data.modelColor2 = NGUIMath.ColorToInt(MonoBehaviourSingleton <GlobalSettingsManager> .I.playerVisual.modelBaseColor2); } } csv_reader.Pop(ref data.effectID); data.effectParam = 1f; csv_reader.Pop(ref data.effectParam); if (!(bool)csv_reader.PopColor24(ref data.effectColor)) { if (num != -1) { data.effectColor = NGUIMath.ColorToInt(MonoBehaviourSingleton <GlobalSettingsManager> .I.playerVisual.GetModelElementColor(num)); } else { data.effectColor = NGUIMath.ColorToInt(MonoBehaviourSingleton <GlobalSettingsManager> .I.playerVisual.modelBaseColor); } } csv_reader.Pop(ref data.__iconID); csv_reader.Pop(ref data.maxLv); csv_reader.Pop(ref data.growID); csv_reader.Pop(ref data.needId); csv_reader.Pop(ref data.needUniqueId); csv_reader.Pop(ref data.exceedID); csv_reader.Pop(ref data.shadowEvolveEquipItemId); csv_reader.Pop(ref data.baseAtk); csv_reader.Pop(ref data.baseDef); csv_reader.Pop(ref data.baseHp); data.atkElement = new int[6]; data.defElement = new int[6]; for (int i = 0; i < 6; i++) { csv_reader.Pop(ref data.atkElement[i]); } for (int j = 0; j < 6; j++) { csv_reader.Pop(ref data.defElement[j]); } List <SkillItemTable.SkillSlotData> list = new List <SkillItemTable.SkillSlotData>(); int num2 = 0; int num3 = 0; for (int k = 0; k < 9; k++) { string value2 = string.Empty; uint value3 = 0u; csv_reader.Pop(ref value2); csv_reader.Pop(ref value3); if (!string.IsNullOrEmpty(value2)) { SkillItemTable.SkillSlotData skillSlotData = new SkillItemTable.SkillSlotData(); skillSlotData.slotType = (SKILL_SLOT_TYPE)(int)Enum.Parse(typeof(SKILL_SLOT_TYPE), value2); if (skillSlotData.slotType != 0) { skillSlotData.skill_id = value3; list.Add(skillSlotData); num3++; if (value3 != 0) { num2++; } } } } data._skillSlot = list.ToArray(); data.fixedSkillLength = num2; data.maxSlot = num3; int[] array = new int[3]; int[] array2 = new int[3]; int[] array3 = new int[3]; int num4 = 0; for (int l = 0; l < 3; l++) { csv_reader.Pop(ref array[l]); csv_reader.Pop(ref array2[l]); csv_reader.Pop(ref array3[l]); if (array[l] != 0 && array2[l] != 0) { num4++; } } data.fixedAbility = new EquipItem.Ability[num4]; for (int m = 0; m < num4; m++) { data.fixedAbility[m] = new EquipItem.Ability(); data.fixedAbility[m].id = array[m]; data.fixedAbility[m].pt = array2[m]; data.fixedAbility[m].vr = (0 < array3[m]); } csv_reader.Pop(ref data.sale); csv_reader.Pop(ref data.listId); string value4 = string.Empty; csv_reader.Pop(ref value4); data.obtained = new Obtained(value4); if (!(bool)csv_reader.Pop(ref data.damageDistanceId)) { if (data.type == EQUIPMENT_TYPE.ARROW) { data.damageDistanceId = 0; } else { data.damageDistanceId = -1; } } csv_reader.PopEnum(ref data.atkElementType, ELEMENT_TYPE.MAX); csv_reader.PopEnum(ref data.defElementType, ELEMENT_TYPE.MAX); csv_reader.Pop(ref data.isFormer); csv_reader.PopEnum(ref data.spAttackType, SP_ATTACK_TYPE.NONE); csv_reader.Pop(ref data.spAttackRate); csv_reader.Pop(ref data.evolveId); return(true); }
private void Awake() { data = CSVReader.Read("LibraryEarthquakeLevel"); }
private void InitializeAStartMaps() { map_all = new AStarMap(); Log.Verbose(nameof(AStar), "Started generating map, this may take a while"); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < stationsCodesRotterdam.Count; i++) { Station cur = stations.Find(s => s.Code == stationsCodesRotterdam[i]); AStarNode node = new AStarNode(cur.Position) { Id = cur }; map_all.Nodes.Add(node); } for (int i = 0; i < stops.Count; i++) { Stop cur = stops[i]; AStarNode node = new AStarNode(cur.Position) { Id = cur }; map_all.Nodes.Add(node); } List <RETRoute> retRoutes = PASReader.ReadRoutesFromFile("RET.PAS"); List <RetStop> retStops = CSVReader.GetRetStopsFromFile("RET.HLT"); for (int i = 0; i < retRoutes.Count; i++) { RETRoute cur = retRoutes[i]; Log.Debug(nameof(AStar), $"Adding route: {cur}"); for (int j = 0; j < cur.Stops.Count; j++) { AStarNode curNode; if (!TryGetNode(retStops, cur, j, out curNode)) { continue; } if (j > 0) { AStarNode prevNode; if (!TryGetNode(retStops, cur, j - 1, out prevNode)) { continue; } if (!curNode.Adjason.Contains(prevNode)) { curNode.Adjason.Add(prevNode); } } if (j < cur.Stops.Count - 1) { AStarNode nextNode; if (!TryGetNode(retStops, cur, j + 1, out nextNode)) { continue; } if (!curNode.Adjason.Contains(nextNode)) { curNode.Adjason.Add(nextNode); } } } } map_all.Nodes.RemoveAll(n => n.Adjason.Count == 0); sw.Stop(); Log.Verbose(nameof(AStar), $"Finished generating map, took: {sw.Elapsed}"); }
public void TestFileInfoDataTable() { DataTable table; File.WriteAllText(filename, fileContents); using (CSVReader reader = new CSVReader(new FileInfo(filename))) table = reader.CreateDataTable(false); CheckTable(table); }
private GMapOverlay InitializePolygonLayer(PointLatLng point, GMapOverlay PolyOverlay) { overlay.Polygons.Clear(); map.Overlays.Remove(PolyOverlay); points.Clear(); Gpoints.Clear(); List <Station> stations = CSVReader.GetStationsFromFile($"stations-nl-2015-08.csv"); List <Stop> stops = CSVReader.GetStopsFromFile($"RET-haltebestand.csv"); PointLatLng Stopclosest = new PointLatLng(0, 0); double StopdifCoor = 1000000; PointLatLng Stationclosest = new PointLatLng(0, 0); double StationdifCoor = 1000000; PointLatLng Drawer = new PointLatLng(0, 0); for (int i = 0; i < stops.Count; i++) { Stop cur = stops[i]; double difLat = Math.Abs(cur.Position.Lat - point.Lat); double difLng = Math.Abs(cur.Position.Lng - point.Lng); double InnerdifCoor = difLng + difLat; if (InnerdifCoor < StopdifCoor) { StopdifCoor = InnerdifCoor; InnerdifCoor = 0; Stopclosest = new PointLatLng(cur.Position.Lat, cur.Position.Lng); } } for (int i = 0; i < stations.Count; i++) { Station cur = stations[i]; double difLat = Math.Abs(cur.Position.Lat - point.Lat); double difLng = Math.Abs(cur.Position.Lng - point.Lng); double InnerdifCoor = difLng + difLat; if (InnerdifCoor < StationdifCoor) { StationdifCoor = InnerdifCoor; InnerdifCoor = 0; Stationclosest = new PointLatLng(cur.Position.Lat, cur.Position.Lng); } } if (StationdifCoor > StopdifCoor) { Drawer = Stopclosest; } else if (StationdifCoor < StopdifCoor) { Drawer = Stationclosest; } double radius = 0.01; double Gradius = 0.005; double seg = Math.PI * 2 / (radius * 10000); for (int i = 0; i < 100; i++) { double theta = seg * i; double a = Drawer.Lat + Math.Cos(theta) * radius; double b = Drawer.Lng + Math.Sin(theta) * (radius * 1.7); PointLatLng drawpoint = new PointLatLng(a, b); points.Add(drawpoint); } for (int i = 0; i < 100; i++) { double theta = seg * i; double a = Drawer.Lat + Math.Cos(theta) * Gradius; double b = Drawer.Lng + Math.Sin(theta) * (Gradius * 1.7); PointLatLng Gdrawpoint = new PointLatLng(a, b); Gpoints.Add(Gdrawpoint); } GMapPolygon polygon = new GMapPolygon(points, "Region"); polygon.Fill = new SolidBrush(Color.FromArgb(30, Color.Red)); polygon.Stroke = new Pen(Color.FromArgb(50, Color.Red)); overlay.Polygons.Add(polygon); GMapPolygon Gpolygon = new GMapPolygon(Gpoints, "Region"); Gpolygon.Fill = new SolidBrush(Color.FromArgb(50, Color.Green)); Gpolygon.Stroke = new Pen(Color.FromArgb(50, Color.Green)); overlay.Polygons.Add(Gpolygon); map.Overlays.Add(overlay); return(overlay); }
public void TestNullString() { try { using (CSVReader reader = new CSVReader((string)null)) Assert.IsNull(reader.ReadRow(), "ReadRow() should return null for an empty string"); Assert.Fail(); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentNullException); } }
private void InitializeStopLayer() { GMapOverlay Busoverlay = new GMapOverlay("BusStops"); GMapOverlay Tramoverlay = new GMapOverlay("TramStops"); GMapOverlay Metrooverlay = new GMapOverlay("MetroStops"); stops = CSVReader.GetStopsFromFile($"RET-haltebestand.csv"); List <Stop> busstops = new List <Stop>(); List <Stop> tramstops = new List <Stop>(); List <Stop> metrostops = new List <Stop>(); for (int i = 0; i < stops.Count; i++) { if (stops[i].Type == StopType.Bus) { busstops.Add(stops[i]); } else if (stops[i].Type == StopType.Tram) { tramstops.Add(stops[i]); } else if (stops[i].Type == StopType.Metro) { metrostops.Add(stops[i]); } } Log.Info(nameof(stops), $"Started adding {stops.Count} stop markers"); for (int i = 0; i < busstops.Count; i++) { Stop cur = busstops[i]; if (!CBoxStart.Items.Contains(cur)) { Log.Debug(nameof(stops), $"Adding stop {cur.Name}"); Busoverlay.Markers.Add(new RETMarker(cur)); CBoxStart.Items.Add(cur); CBoxEnd.Items.Add(cur); } } for (int i = 0; i < tramstops.Count; i++) { Stop cur = tramstops[i]; if (!CBoxStart.Items.Contains(cur)) { Log.Debug(nameof(stops), $"Adding stop {cur.Name}"); Tramoverlay.Markers.Add(new RETMarker(cur)); CBoxStart.Items.Add(cur); CBoxEnd.Items.Add(cur); } } for (int i = 0; i < metrostops.Count; i++) { Stop cur = metrostops[i]; if (!CBoxStart.Items.Contains(cur)) { Log.Debug(nameof(stops), $"Adding stop {cur.Name}"); Metrooverlay.Markers.Add(new RETMarker(cur)); CBoxStart.Items.Add(cur); CBoxEnd.Items.Add(cur); } } Log.Info(nameof(stops), $"Finished adding stop markers"); map.Overlays.Add(Busoverlay); map.Overlays.Add(Tramoverlay); map.Overlays.Add(Metrooverlay); }
public void TestStringReadRows() { using (CSVReader reader = new CSVReader(fileContents)) CheckExpectedRows(expectedRows, reader); }
public Task <HttpResponseMessage> UploadImportFile() { logger.Debug("Inside DataActionController, UploadImportFile..."); logger.Debug("starting to process incoming files."); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //string root = System.Web.HttpContext.Current.Server.MapPath("~/uploads"); string root = System.Configuration.ConfigurationManager.AppSettings["UploadsDirectory"] + "\\P\\"; logger.Debug("root location = " + root); string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty); logger.Debug("root Url = " + rootUrl); // Make sure our folder exists DirectoryInfo dirInfo = new DirectoryInfo(@root); if (!dirInfo.Exists) { logger.Debug("Dir does not exist; will create it..."); try { System.IO.Directory.CreateDirectory(root); logger.Debug("Created the dir..."); } catch (IOException ioe) { logger.Debug("Exception: " + ioe.Message + ", " + ioe.InnerException); } } else { logger.Debug("P dir already exists..."); } logger.Debug("saving files to location: " + root); logger.Debug(" and the root url = " + rootUrl); var provider = new MultipartFormDataStreamProvider(root); logger.Debug("provider = " + provider.ToString()); User me = AuthorizationManager.getCurrentUser(); var db = ServicesContext.Current; var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(o => { logger.Debug("Inside task part..."); if (o.IsFaulted || o.IsCanceled) { logger.Debug("Error: " + o.Exception.Message); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, o.Exception)); } //Look up our project logger.Debug("provider.FormData = " + provider.FormData); Int32 ProjectId = Convert.ToInt32(provider.FormData.Get("ProjectId")); logger.Debug("And we think the projectid === " + ProjectId); Int32 DatasetId = Convert.ToInt32(provider.FormData.Get("DatasetId")); logger.Debug("And we think the DatasetId === " + DatasetId); Project project = db.Projects.Find(ProjectId); logger.Debug("Project.Name = " + project.Name); Dataset dataset = db.Datasets.Find(DatasetId); logger.Debug("dataset.Name = " + dataset.Name); if (project == null) { throw new Exception("Project ID not found: " + ProjectId); } if (!project.isOwnerOrEditor(me)) { throw new Exception("Authorization error: The user trying to import is neither an Owner nor an Editor."); } else { logger.Debug("User authorized = " + me); } //If the project/dataset folder does not exist, create it. string datasetPath = root + project.Id + "\\D\\" + dataset.Id; //DirectoryInfo datasetDirInfo = new DirectoryInfo(@root); DirectoryInfo datasetDirInfo = new DirectoryInfo(datasetPath); if (!datasetDirInfo.Exists) { logger.Debug("Dir does not exist; will create it..."); try { System.IO.Directory.CreateDirectory(datasetPath); logger.Debug("Created the dir..."); } catch (IOException ioe) { logger.Debug("Exception: " + ioe.Message + ", " + ioe.InnerException); } } var newFileName = ""; foreach (MultipartFileData file in provider.FileData) { logger.Debug("Filename = " + file.LocalFileName); logger.Debug("Orig = " + file.Headers.ContentDisposition.FileName); logger.Debug("Name? = " + file.Headers.ContentDisposition.Name); var fileIndex = FileController.getFileIndex(file.Headers.ContentDisposition.Name); //"uploadedfile0" -> 0 var filename = file.Headers.ContentDisposition.FileName; filename = filename.Replace("\"", string.Empty); if (!String.IsNullOrEmpty(filename)) { try { newFileName = FileController.relocateDatasetFile( file.LocalFileName, ProjectId, DatasetId, filename, true); // For importing, we do not want to add the file to the Files table. /* * File newFile = new File(); * newFile.Title = provider.FormData.Get("Title_" + fileIndex); //"Title_1, etc. * newFile.Description = provider.FormData.Get("Description_" + fileIndex); //"Description_1, etc. * newFile.Name = info.Name;//.Headers.ContentDisposition.FileName; * newFile.Link = rootUrl + "/services/uploads/" + ProjectId + "/" + info.Name; //file.LocalFileName; * newFile.Size = (info.Length / 1024).ToString(); //file.Headers.ContentLength.ToString(); * newFile.FileTypeId = FileType.getFileTypeFromFilename(info); * newFile.UserId = me.Id; * logger.Debug(" Adding file " + newFile.Name + " at " + newFile.Link); * * files.Add(newFile); */ } catch (Exception e) { logger.Debug("Error: " + e.ToString()); } } } logger.Debug("Done saving files."); var data = new ImportDataResult(); var info = new FileInfo(newFileName); // Process the file and return all the data! /* Note: According to Colette, if someone tries to upload a file with an odd extension (.lkg, .fld, MCR, BC1, etc.), * while the extension may vary, it will almost always be a ScrewTrap-PITAGIS related file. * Therefore, we are allowing a wide range of variation in the extensions. */ //var regex = new Regex(@"\.(m|r|ur|mc)\d+$"); //var regexNums = new Regex(@"\.(m|r|ur|mc|bc)\d+$"); //var regexChars = new Regex(@"\.(m|r|ur|mc|bc)\D+$"); var regexNums = new Regex(@"\.(m|r|ur|mc|bc|nb)\d+$"); var regexChars = new Regex(@"\.(m|r|ur|mc|bc|nb)\D+$"); var extension = info.Extension.ToLower(); logger.Debug("extension = " + extension); if (extension == ".xls" || extension == ".xlsx") { logger.Debug("Looks like an excel file!"); var reader = new ExcelReader(newFileName); //ExcelReader doesn't support starting on a certain line for column names... we always assume col 1 data.columns = reader.getColumns(); data.rows = reader.getData().First().Table; reader.close(); } else if (extension == ".csv") { logger.Debug("Looks like a csv file!"); var StartOnLine = Convert.ToInt32(provider.FormData.Get("StartOnLine")); //only applicable to T/CSV var reader = new CSVReader(newFileName); data = reader.getImportDataResult(StartOnLine); // we do it all in one. } else if (extension == ".tsv") { logger.Debug("Looks like a tsv file!"); var StartOnLine = Convert.ToInt32(provider.FormData.Get("StartOnLine")); //only applicable to T/CSV var reader = new TSVReader(newFileName); data = reader.getImportDataResult(StartOnLine); // we do it all in one. } //else if (extension == ".lkg" || extension == ".fld" || regex.Match(extension).Success) else if (extension == ".lkg" || extension == ".fld" || regexNums.Match(extension).Success || regexChars.Match(extension).Success) { logger.Debug("Looks like a PITAGIS file!"); var reader = new PitagisReader(newFileName); data = reader.getImportDataResult(); // we do it all in one. } else { logger.Debug("Looks like an unknown file!"); throw new Exception("File type not compatible. We can do Excel (xls/xslx), CSV (csv), TSV (tsv), and PITAGIS (.lkg/.fld/.m01/.r01/.ur1/.mc1)."); } var result = JsonConvert.SerializeObject(data); //TODO: actual error/success message handling //string result = "{\"message\": \"Success\"}"; var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain"); //to stop IE from being stupid. return(resp); }); return(task); }
public void TestEmptyFile() { File.WriteAllText(filename, ""); using (CSVReader reader = new CSVReader(new FileInfo(filename))) Assert.IsNull(reader.ReadRow(), "ReadRow() should return null for an empty file"); }
//button用関数 void Process() { csvReader = new CSVReader(inputDataPath); data = csvReader.getDataList().ToArray(); if(data.Length <= 0) { Debug.Log("マップファイルが読み込まれていません"); return; } hashTable = new Hashtable(); //元となる床のオブジェクトの大きさを取得 tileSise = objects[3].transform.localScale.x; //床のテクスチャの大きさを取得 //以降このテクスチャサイズを元にタイルを配置 float x = objects[3].GetComponent<SpriteRenderer>().sprite.texture.width * tileSise / objects[3].GetComponent<SpriteRenderer>().sprite.pixelsPerUnit; float y = objects[3].GetComponent<SpriteRenderer>().sprite.texture.height * tileSise / objects[3].GetComponent<SpriteRenderer>().sprite.pixelsPerUnit; //先にチェックポイントを登録 foreach (Data d in data) { if(d.ID == 1) { GameObject go = (GameObject)Instantiate(objects[1], new Vector3(d.X*x,-d.Y*y), objects[1].transform.rotation); go.name = go.name + d.CheckPointNumber; hashTable.Add(d.CheckPointNumber, go); } } foreach (Data d in data) { if (d.ID < 0) { } else if (d.ID != 1)//オブジェクトIDがCheckPointでない { if (d.CheckPointNumber >= 0)//CheckPointNumberが0以上 { //Debug.Log("num:" + n + " objectId:" + d.ID + " checkID:" + d.CheckPointNumber + " x:" + d.X + " y:" + d.Y); if (hashTable.Contains(d.CheckPointNumber))//チェックポイントが登録されている { //オブジェクトを作成し、チェックポイントに登録 GameObject go = (GameObject)Instantiate(objects[d.ID], new Vector3(d.X * x, -d.Y * y), objects[d.ID].transform.rotation); go.transform.parent = ((GameObject)hashTable[d.CheckPointNumber]).transform; } else { //チェックポイントオブジェクトを作成 GameObject temp = (GameObject)Instantiate(objects[1], new Vector3(0, 0), objects[1].transform.rotation); temp.name = objects[1].name + d.CheckPointNumber; GameObject go = (GameObject)Instantiate(objects[d.ID], new Vector3(d.X * x, -d.Y * y), objects[d.ID].transform.rotation); go.transform.parent = temp.transform; hashTable.Add(d.CheckPointNumber, temp); } } else { //Generatorの子オブジェクトとして登録 GameObject go = (GameObject)Instantiate(objects[d.ID], new Vector3(d.X * x, -d.Y * y), objects[d.ID].transform.rotation); go.transform.parent = transform; } } else { if (!hashTable.ContainsKey(d.CheckPointNumber))//チェックポイントが存在しない { GameObject go = (GameObject)Instantiate(objects[1], Vector3.zero, objects[1].transform.rotation); go.name = go.name + d.CheckPointNumber; hashTable.Add(d.CheckPointNumber, go); } } } foreach (GameObject g in hashTable.Values) { g.transform.parent = transform; } }
public Task<HttpResponseMessage> UploadImportFile() { logger.Debug("starting to process incoming files."); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = System.Web.HttpContext.Current.Server.MapPath("~/uploads"); string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty); logger.Debug("saving files to location: " + root); logger.Debug(" and the root url = " + rootUrl); var provider = new MultipartFormDataStreamProvider(root); User me = AuthorizationManager.getCurrentUser(); var db = ServicesContext.Current; var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(o => { if (o.IsFaulted || o.IsCanceled) { logger.Debug("Error: " + o.Exception.Message); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, o.Exception)); } //Look up our project Int32 ProjectId = Convert.ToInt32(provider.FormData.Get("ProjectId")); logger.Debug("And we think the projectid === " + ProjectId); Project project = db.Projects.Find(ProjectId); if (!project.isOwnerOrEditor(me)) throw new Exception("Authorization error."); var newFileName = ""; foreach (MultipartFileData file in provider.FileData) { logger.Debug("Filename = " + file.LocalFileName); logger.Debug("Orig = " + file.Headers.ContentDisposition.FileName); logger.Debug("Name? = " + file.Headers.ContentDisposition.Name); var fileIndex = ActionController.getFileIndex(file.Headers.ContentDisposition.Name); //"uploadedfile0" -> 0 var filename = file.Headers.ContentDisposition.FileName; filename = filename.Replace("\"", string.Empty); if (!String.IsNullOrEmpty(filename)) { try { newFileName = ActionController.relocateProjectFile( file.LocalFileName, ProjectId, filename, true); /* File newFile = new File(); newFile.Title = provider.FormData.Get("Title_" + fileIndex); //"Title_1, etc. newFile.Description = provider.FormData.Get("Description_" + fileIndex); //"Description_1, etc. newFile.Name = info.Name;//.Headers.ContentDisposition.FileName; newFile.Link = rootUrl + "/services/uploads/" + ProjectId + "/" + info.Name; //file.LocalFileName; newFile.Size = (info.Length / 1024).ToString(); //file.Headers.ContentLength.ToString(); newFile.FileTypeId = FileType.getFileTypeFromFilename(info); newFile.UserId = me.Id; logger.Debug(" Adding file " + newFile.Name + " at " + newFile.Link); files.Add(newFile); */ } catch (Exception e) { logger.Debug("Error: " + e.ToString()); } } } logger.Debug("Done saving files."); ImportDataResult data = new ImportDataResult(); var info = new System.IO.FileInfo(newFileName); //process the file and return all the data! //TODO: refactor this into import plugins via polymorphism. ... but maybe this is enough. :) //CSV or Excel are the only filetypes currently supported. if (info.Extension == ".xls" || info.Extension == ".xlsx") { logger.Debug("Looks like an excel file!"); ExcelReader reader = new ExcelReader(newFileName); //ExcelReader doesn't support starting on a certain line for column names... we always assume col 1 data.columns = reader.getColumns(); data.rows = reader.getData().First().Table; reader.close(); } else if (info.Extension == ".csv") { logger.Debug("Looks like a csv file!"); Int32 StartOnLine = Convert.ToInt32(provider.FormData.Get("StartOnLine")); //only applicable to T/CSV CSVReader reader = new CSVReader(newFileName); data = reader.getImportDataResult(StartOnLine); // we do it all in one. } else if (info.Extension == ".tsv") { logger.Debug("Looks like a tsv file!"); Int32 StartOnLine = Convert.ToInt32(provider.FormData.Get("StartOnLine")); //only applicable to T/CSV TSVReader reader = new TSVReader(newFileName); data = reader.getImportDataResult(StartOnLine); // we do it all in one. } else { logger.Debug("Looks like an unknown file!"); throw new Exception("File type not compatible. We can do Excel (xls/xslx), CSV (csv) and TSV (tsv)."); } string result = JsonConvert.SerializeObject(data); //TODO: actual error/success message handling //string result = "{\"message\": \"Success\"}"; HttpResponseMessage resp = new HttpResponseMessage(System.Net.HttpStatusCode.OK); resp.Content = new System.Net.Http.StringContent(result, System.Text.Encoding.UTF8, "text/plain"); //to stop IE from being stupid. return resp; }); return task; }
public static void ReadGameConst() { GameConst gameConst = new GameConst(); CSVReader.ReadConst(gameConst, "Data/GameConst"); }
public IEnumerator CreateAndValidateTables() { string fileContentString = ""; //Parse Assay file yield return(StartCoroutine(FastDownload(AssayTestingFilename, fileContents => fileContentString = fileContents))); AssayTrainingTable = CSVReader.SplitCsvGrid(fileContentString); //Parse combi file yield return(StartCoroutine(FastDownload(CombiResultsFilename, fileContents => fileContentString = fileContents))); CombiResultTable = CSVReader.SplitCsvGrid(fileContentString); CombiResultTableDoubles = CSVReader.SplitCsvGridJustDoubles(fileContentString); //Parse dataset if (datasetDropdown.value != 0)//if option != 0 { yield return(StartCoroutine(FastDownload(path + datasetDropdown.options[datasetDropdown.value].text, fileContents => fileContentString = fileContents))); DatasetTable = CSVReader.SplitCsvGrid(fileContentString); Dictionary <string, BothController.MineralComposition> mineralDict = new Dictionary <string, BothController.MineralComposition>(); for (int i = 1; i <= DatasetTable.GetUpperBound(1); i++) { string mineralComp = DatasetTable[0, i]; BothController.MineralComposition MC = new BothController.MineralComposition(mineralComp); double[] val = new double[] { Double.Parse(DatasetTable[1, i]), Double.Parse(DatasetTable[2, i]), Double.Parse(DatasetTable[3, i]), Double.Parse(DatasetTable[4, i]), Double.Parse(DatasetTable[5, i]), Double.Parse(DatasetTable[6, i]), Double.Parse(DatasetTable[7, i]), Double.Parse(DatasetTable[8, i]), Double.Parse(DatasetTable[9, i]), Double.Parse(DatasetTable[10, i]), Double.Parse(DatasetTable[11, i]), Double.Parse(DatasetTable[12, i]), Double.Parse(DatasetTable[13, i]), Double.Parse(DatasetTable[14, i]), Double.Parse(DatasetTable[15, i]), Double.Parse(DatasetTable[16, i]), Double.Parse(DatasetTable[17, i]), Double.Parse(DatasetTable[18, i]), Double.Parse(DatasetTable[19, i]), Double.Parse(DatasetTable[20, i]), Double.Parse(DatasetTable[21, i]) }; bothController.FillMCDatabase(MC, val); MC.weight = double.Parse(DatasetTable[22, i]); MC.startPoint = double.Parse(DatasetTable[23, i]); mineralDict.Add(mineralComp, MC); } BothController.Dataset ds = new BothController.Dataset(mineralDict); bothController.datasetDict.Add(datasetDropdown.options[datasetDropdown.value].text, ds); bothController.currentMineralDict = ds.mineralDict; } else { bothController.datasetDict.Add("Default", bothController.defaultDataset); Dictionary <string, BothController.MineralComposition> defaultMineralDict = bothController.defaultDataset.mineralDict; bothController.currentMineralDict = defaultMineralDict; } FillQXRDList(); trainingSubmenu2.SetActive(true); trainingLoadingMenu.SetActive(false); yield return(null); }
/// <summary> /// Import a .CSV file into a DataTable. /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static DataTable Import(string filename, char delimiter) { DataTable dt = new DataTable(); using (CSVReader cr = new CSVReader(filename)) { cr.Separator = delimiter; string[] values = cr.GetCSVLine(); bool firstRow = true; while (values != null) { if (firstRow) { for (int i = 0; i < values.Length; i++) if (!dt.Columns.Contains(values[i])) dt.Columns.Add(values[i]); } else { DataRow dr = dt.NewRow(); for (int i = 0; i < values.Length && i < dt.Columns.Count; i++) dr[i] = values[i]; dt.Rows.Add(dr); } firstRow = false; values = cr.GetCSVLine(); } } return dt; }