Inheritance: TextWriter
Esempio n. 1
1
        private void SaveLastCode()
        {
            string filename = Path.Combine(localPath, "TestApp.os");
            using (var writer = new StreamWriter(filename, false, Encoding.UTF8))
            {
                // первой строкой запишем имя открытого файла
                writer.Write("//");  // знаки комментария, чтобы сохранить код правильным
                writer.WriteLine(_currentDocPath);
                // второй строкой - признак изменённости
                writer.Write("//");
                writer.WriteLine(_isModified);

                args.Text = args.Text.TrimEnd('\r', '\n');

                // запишем аргументы командной строки
                writer.Write("//");
                writer.WriteLine(args.LineCount);

                for (var i = 0; i < args.LineCount; ++i )
                {
                    string s = args.GetLineText(i).TrimEnd('\r', '\n');
                    writer.Write("//");
                    writer.WriteLine(s);
                }

                // и потом сам код
                writer.Write(txtCode.Text);
            }
        }
        public void Trace(NetState state)
        {
            try
            {
                string path = Path.Combine(Paths.LogsDirectory, "packets.log");                

                using (StreamWriter sw = new StreamWriter(path, true))
                {
                    sw.BaseStream.Seek(sw.BaseStream.Length, SeekOrigin.Begin);

                    byte[] buffer = _data;

                    if (_data.Length > 0)
                        Tracer.Warn(string.Format("Unhandled packet 0x{0:X2}", _data[0]));

                    buffer.ToFormattedString(buffer.Length, sw);

                    sw.WriteLine();
                    sw.WriteLine();
                }
            }
            catch (Exception e)
            {
                Tracer.Error(e);
            }
        }
 private void WriteToFSLocation(string path, string value)
 {
     using (StreamWriter sw = new StreamWriter(path))
     {
         sw.Write(value);
     }
 }
        protected override async void Write(Core.LogEventInfo logEvent)
        {

            var request = (HttpWebRequest) WebRequest.Create(ServerUrl);
            request.ContentType = "application/json; charset=utf-8";
            request.Method = "POST";
            var requestWriter = new StreamWriter(request.GetRequestStream());
            
            requestWriter.Write("{ "
                                + "\"version\": " + "\"" + "1.0" + "\",\n"
                                + "\"host\": " + "\"" + AndroidId + "\",\n"
                                + "\"short_message\": " + "\"" + logEvent.FormattedMessage + "\",\n"
                                + "\"full_message\": " + "\"" + logEvent.FormattedMessage + "\",\n"
                                + "\"timestamp\": " + "\"" + DateTime.Now.ToString(CultureInfo.InvariantCulture) +
                                "\",\n"
                                + "\"level\": " + "\"" +
                                logEvent.Level.Ordinal.ToString(CultureInfo.InvariantCulture) + "\",\n"
                                + "\"facility\": " + "\"" + "NLog Android Test" + "\",\n"
                                + "\"file\": " + "\"" + Environment.CurrentDirectory + "AndroidApp" + "\",\n"
                                + "\"line\": " + "\"" + "123" + "\",\n"
                                + "\"Userdefinedfields\": " + "{}" + "\n"
                                + "}");

            requestWriter.Close();

            LastResponseMessage = (HttpWebResponse) request.GetResponse();
        }
Esempio n. 5
1
    public void CreateLog(Exception ex)
    {
      try
      {
        using (TextWriter writer = new StreamWriter(_filename, false))
        {
          writer.WriteLine("Crash Log: {0}", _crashTime);

          writer.WriteLine("= System Information");
          writer.Write(SystemInfo());
          writer.WriteLine();

          writer.WriteLine("= Disk Information");
          writer.Write(DriveInfo());
          writer.WriteLine();

          writer.WriteLine("= Exception Information");
          writer.Write(ExceptionInfo(ex));
					writer.WriteLine();
					writer.WriteLine();

					writer.WriteLine("= MediaPortal Information");
					writer.WriteLine();
        	IList<string> statusList = ServiceRegistration.Instance.GetStatus();
        	foreach (string status in statusList)
        		writer.WriteLine(status);
        }
      }
      catch (Exception e)
      {
        Console.WriteLine("UiCrashLogger crashed:");
        Console.WriteLine(e.ToString());
      }
    }
Esempio n. 6
1
 public static void SavePointsInFile(string fileName, Path3D path)
 {
     using (StreamWriter file = new StreamWriter(fileName))
     {
         file.Write(path);
     }
 }
Esempio n. 7
1
 public static void SaveTo(string filename, MailAccess mailAccess) {
     using (var streamWriter = new StreamWriter(filename, false, Encoding.UTF8)) {
         streamWriter.WriteLine(mailAccess.Server);
         streamWriter.WriteLine(mailAccess.Username);
         streamWriter.WriteLine(mailAccess.Password);
     }
 }
        public static void Run()
        {
            // ExStart:ExtractTextFromPageRegion
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Open document
            Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf");

            // Create TextAbsorber object to extract text
            TextAbsorber absorber = new TextAbsorber();
            absorber.TextSearchOptions.LimitToPageBounds = true;
            absorber.TextSearchOptions.Rectangle = new Aspose.Pdf.Rectangle(100, 200, 250, 350);

            // Accept the absorber for first page
            pdfDocument.Pages[1].Accept(absorber);

            // Get the extracted text
            string extractedText = absorber.Text;
            // Create a writer and open the file
            TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt");
            // Write a line of text to the file
            tw.WriteLine(extractedText);
            // Close the stream
            tw.Close();
            // ExEnd:ExtractTextFromPageRegion          
            
        }
Esempio n. 9
1
        public static void ConvertFormat(string strInputFile, string strOutputFile)
        {
            StreamReader sr = new StreamReader(strInputFile);
            StreamWriter sw = new StreamWriter(strOutputFile);
            string strLine = null;

            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();

                string[] items = strLine.Split();
                foreach (string item in items)
                {
                    int pos = item.LastIndexOf('[');
                    string strTerm = item.Substring(0, pos);
                    string strTag = item.Substring(pos + 1, item.Length - pos - 2);

                    sw.WriteLine("{0}\t{1}", strTerm, strTag);
                }
                sw.WriteLine();
            }

            sr.Close();
            sw.Close();
        }
Esempio n. 10
1
 static void Main(string[] args)
 {
     using (StreamWriter str = new StreamWriter(args[0]))
     {
         int a = Convert.ToInt32(args[1]);
         int b = Convert.ToInt32(args[2]);
         str.WriteLine("Parameters:");
         str.WriteLine(a);
         str.WriteLine(b);
         int min;
         if (a > b)
             min = b;
         else
             min = a;
         int i = min;
         int c = 0;
         while (i>0&&c==0)
         {
             if ((a % i == 0) && (b % i == 0))
                 c = i;
             i--;
         }
         //c = 0;
         str.WriteLine("Answers:");
         str.WriteLine(Convert.ToString(c));
         //str.WriteLine(a);
     }
 }
        public void AllFieldsEmptyTest()
        {
            using( var stream = new MemoryStream() )
            using( var reader = new StreamReader( stream ) )
            using( var writer = new StreamWriter( stream ) )
            using( var parser = new CsvParser( reader ) )
            {
                writer.WriteLine( ";;;;" );
                writer.WriteLine( ";;;;" );
                writer.Flush();
                stream.Position = 0;

                parser.Configuration.Delimiter = ";;";
                parser.Configuration.HasHeaderRecord = false;

                var row = parser.Read();
                Assert.IsNotNull( row );
                Assert.AreEqual( 3, row.Length );
                Assert.AreEqual( "", row[0] );
                Assert.AreEqual( "", row[1] );
                Assert.AreEqual( "", row[2] );

                row = parser.Read();
                Assert.IsNotNull( row );
                Assert.AreEqual( 3, row.Length );
                Assert.AreEqual( "", row[0] );
                Assert.AreEqual( "", row[1] );
                Assert.AreEqual( "", row[2] );

                row = parser.Read();
                Assert.IsNull( row );
            }
        }
Esempio n. 12
1
        public static void Extract(Category category)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Extract");
            if(!Directory.Exists(path))
                Directory.CreateDirectory(path);

            pset.Clear();
            pdic.Clear();
            string downPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Down", category.Name);
            string fileName = string.Format(@"{0}\{1}.txt", path, category.Name);

            StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
            for (int i = category.DownPageCount; i >= 1; i--)
            {
                string htmlFileName = string.Format(@"{0}\{1}.html", downPath, i);
                if (!File.Exists(htmlFileName))
                    Logger.Instance.Write(string.Format("{0}-{1}.html-not exist", category.Name, i));
                StreamReader sr = new StreamReader(htmlFileName, Encoding.UTF8);
                string text = sr.ReadToEnd();
                sr.Close();

                var action = CreateAction(category.Type);
                if (action == null) continue;

                Extract(text, sw, category.Name,category.DbName, action);
            }
            sw.Close();

            Console.WriteLine("{0}:Extract Data Finished!", category.Name);
        }
Esempio n. 13
1
        public Terminal()
        {
            InitializeComponent();

            if (sw == null)
                sw = new StreamWriter("Terminal-" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".txt");
        }
Esempio n. 14
1
        public void exportCSV(string filename)
        {
            StreamWriter tw = new StreamWriter(filename);

            tw.WriteLine("Filename;Key;Text");
            string fn;
            int i, j;
            List<string> val;
            string str;

            for (i = 0; i < LTX_Texte.Count; i++)
            {
                fn = LTX_Texte[i].Key.ToLower().Replace(".ltx","");
                val = LTX_Texte[i].Value;
                for (j = 0; j < val.Count; j++)
                {
                    str = prepareText(val[j], true);
                    if( str != "" )
                        tw.WriteLine(fn + ";" + j.ToString() + ";" + str);
                }
            }
            for (i = 0; i < DTX_Texte.Count; i++)
            {
                fn = DTX_Texte[i].Key.ToLower().Replace(".dtx","");
                val = DTX_Texte[i].Value;
                for (j = 0; j < val.Count; j++)
                {
                    str = prepareText(val[j], true);
                    if (str != "")
                        tw.WriteLine(fn + ";" + j.ToString() + ";" + str);
                }
            }

            tw.Close();
        }
        public static void Main()
        {
            var url = new Uri(ApiUrl + "?auth-id=" + AuthenticationID + "&auth-token=" + AuthenticationToken);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
                writer.Write(RequestPayload);

            using (var response = request.GetResponse())
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var rawResponse = reader.ReadToEnd();
                Console.WriteLine(rawResponse);

                // Suppose you wanted to use Json.Net to pretty-print the response (delete the next two lines if not):
                // Json.Net: http://http://json.codeplex.com/
                dynamic parsedJson = JsonConvert.DeserializeObject(rawResponse);
                Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));

                // Or suppose you wanted to deserialize the json response to a defined structure (defined below):
                var candidates = JsonConvert.DeserializeObject<CandidateAddress[]>(rawResponse);
                foreach (var address in candidates)
                    Console.WriteLine(address.DeliveryLine1);
            }

            Console.ReadLine();
        }
Esempio n. 16
1
        private void CheckAndChangeNewFile()
        {
            if (this.writer.BaseStream.Length >= this.maxLength)
            {                
                this.writer.Close();
                this.writer = null;

                string fileName = ESBasic.Helpers.FileHelper.GetFileNameNoPath(this.iniPath);
                string dir = ESBasic.Helpers.FileHelper.GetFileDirectory(this.iniPath);
                int pos = fileName.LastIndexOf('.');
                string extendName = null;
                string pureName = fileName;
                if (pos >=0)
                {
                    extendName = fileName.Substring(pos+1);
                    pureName = fileName.Substring(0, pos);
                }

                string newPath = null;
                for(int i=1;i<1000;i++)
                {
                    string newName = pureName + "_" + i.ToString("000");
                    if (extendName != null)
                    {
                        newName += "." + extendName;
                    }
                    newPath = dir + "\\" + newName;
                    if (!File.Exists(newPath))
                    {
                        break;
                    }
                }                
                this.writer = new StreamWriter(File.Open(newPath, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.Read));  
            }
        }
Esempio n. 17
1
 public void Init()
 {
     srStrokes = new StreamReader(opt.StrokesFileName);
     srTypes = new StreamReader(opt.StrokesTypesFileName);
     srCedict = new StreamReader(opt.CedictFileName);
     swOut = new StreamWriter(opt.OutFileName);
 }
Esempio n. 18
1
 /// <summary>
 /// Запись в ЛОГ-файл
 /// </summary>
 /// <param name="str"></param>
 public void WriteToLog(string str, bool doWrite = true)
 {
     if (doWrite)
     {
         StreamWriter sw = null;
         FileStream fs = null;
         try
         {
             string curDir = AppDomain.CurrentDomain.BaseDirectory;
             fs = new FileStream(curDir + "teplouchetlog.pi", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
             sw = new StreamWriter(fs, Encoding.Default);
             if (m_vport == null) sw.WriteLine(DateTime.Now.ToString() + ": Unknown port: adress: " + m_address + ": " + str);
             else sw.WriteLine(DateTime.Now.ToString() + ": " + m_vport.GetName() + ": adress: " + m_address + ": " + str);
             sw.Close();
             fs.Close();
         }
         catch
         {
         }
         finally
         {
             if (sw != null)
             {
                 sw.Close();
                 sw = null;
             }
             if (fs != null)
             {
                 fs.Close();
                 fs = null;
             }
         }
     }
 }
Esempio n. 19
1
        // TODO: hack
        public RubyIO(RubyContext/*!*/ context, StreamReader reader, StreamWriter writer, string/*!*/ modeString)
            : this(context) {
            _mode = ParseIOMode(modeString, out _preserveEndOfLines);
            _stream = new DuplexStream(reader, writer);

            ResetLineNumbersForReadOnlyFiles(context);
        }
Esempio n. 20
1
        void IMapExporter.Save(string filename, Dictionary<string, System.Drawing.Rectangle> map)
        {
            // Original filename                    New filename,     ?, 2D, X         Y,        MAGIC     Width     Height
            //.\Animations\player_fall_ne_9.png		0_Animations.png, 0, 2D, 0.000000, 0.000000, 0.000000, 0.058594, 0.064453

            // copy the files list and sort alphabetically
            string[] keys = new string[map.Count];
            map.Keys.CopyTo(keys, 0);
            List<string> outputFiles = new List<string>(keys);
            outputFiles.Sort();

            using (StreamWriter writer = new StreamWriter(filename))
            {
                foreach (var image in outputFiles)
                {
                    // get the destination rectangle
                    Rectangle destination = map[image];

                    // write out the destination rectangle for this bitmap
                    //line = item.SourceName + "\t\t" + item.Destination + ", 0, 2D, " + item.ScaledRect.X.ToString("0.000000") + ", " +
                    //item.ScaledRect.Y.ToString("0.000000") + ", 0.000000, " + item.ScaledRect.Width.ToString("0.000000") + ", " + item.ScaledRect.Height.ToString("0.000000");

                    writer.WriteLine(string.Format(
                        "{0}\t\t{1}, 0, 2D, {2:F5}, {3:F5}, 0.00000, {4:F5}, {5:F5}",
                     	image,
                        Path.GetFileNameWithoutExtension(filename)+".png",
                     	(float)destination.X / atlasWidth,
                        (float)destination.Y / atlasHeight,
                        (float)destination.Width / atlasWidth,
                        (float)destination.Height / atlasHeight));
                }
            }
        }
Esempio n. 21
1
        public static string EncryptString(string plainText)
        {
            byte[] encrypted;

            AesCryptoServiceProvider provider = createAesProvider();

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = provider.CreateEncryptor(provider.Key, null); // null IV, because ECB mode

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
            // Return the encrypted bytes from the memory stream.
            return encoding.GetString(encrypted);
        }
        private void ChangeCopyright()
        {
            UpdateLabel("searching for rotmg version display string");
            Dictionary<string, string> files = new Dictionary<string, string>();
            string filetext = String.Empty;

            foreach (string path in this.files)
            {
                using (StreamReader rdr = new StreamReader(File.Open(path, FileMode.Open)))
                {
                    filetext = rdr.ReadToEnd();
                    if (filetext.Contains(ROTMG_VERSION_TEXT))
                    {
                        UpdateLabel("request found!");
                        files.Add(path, filetext);
                    }
                }
            }

            foreach (var file in files)
            {
                UpdateLabel("replacing version text");
                filetext = file.Value.Replace(ROTMG_VERSION_TEXT, "<font color='#00CCFF'>Fabiano Swagger of Doom</font> #{VERSION}.{MINORVERSION}");
                filetext = filetext.Replace("{MINOR}", "{MINORVERSION}");
                using (StreamWriter wtr = new StreamWriter(file.Key, false))
                    wtr.Write(filetext);
            }
            UpdateLabel("Version Display: Done!");
        }
Esempio n. 23
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.TextLength != 0)
            {
                string file = Path.Combine(BESFolder, textBox1.Text + ".cbes");

                if (File.Exists(file))
                    File.Delete(file);

                StreamWriter writer = new StreamWriter(file);
                writer.WriteLine(form.GetInitial());
                writer.WriteLine(form.GetExpand());
                writer.WriteLine(form.GetRounds());
                writer.WriteLine(form.GetLeftoff());
                writer.WriteLine(form.GetKey());
                writer.WriteLine(form.GetCipherMode());
                writer.WriteLine(form.GetSeedFunction());
                writer.WriteLine(form.GetGenerationMode());
                writer.Close();
                writer.Dispose();

                RefreshElements();

                this.Close();
            }
        }
Esempio n. 24
0
 //Write the power output file
 //Output is 100 numbers separated by tabs, representing the power at 1% threshold, 2%, 3%... 100%
 public static void powerOutput(string filenameStub,int m, int startRep, int endRep)
 {
     int[] ranks = new int[endRep - startRep + 1];
     double[] power = new double[100];
     int attributes = 1000;
     for (int rep = startRep; rep <= endRep; rep++)
     {
         string filename = filenameStub + rep + ".txt";
         List<ReliefUtils.SNP> SNPs = FileUtilities.Utils.ReadReliefOutput(filename);
         attributes = SNPs.Count;
         //Sort SNPs by descending score
         SNPs.Sort(delegate(ReliefUtils.SNP S1, ReliefUtils.SNP S2) { return S2.W.CompareTo(S1.W); });
         //Find the lower ranked of the 2 informative SNPs (0 and 1)
         int rank0 = SNPs.FindIndex(delegate(ReliefUtils.SNP s) { return s.ID == 0; });
         int rank1 = SNPs.FindIndex(delegate(ReliefUtils.SNP s) { return s.ID == 1; });
         ranks[rep-startRep] = Math.Max(rank0, rank1);
     }
     string powerFilename = filenameStub + startRep + "to" + endRep + ".power.txt";
     StreamWriter powerOutput = new StreamWriter(powerFilename);
     //Find the power by percentiles (% of reps with both SNPs above threshold)
     for (int percentile = 1; percentile <= 100; percentile++)
     {
         int passed = 0;
         for (int rep = 0; rep <= endRep - startRep; rep++)
         {
             if (ranks[rep] <= (attributes * percentile / 100.0))
                 passed++;
         }
         power[percentile - 1] = passed / (endRep - startRep + 1.0);
         Console.WriteLine("Power at " + percentile + "%: " + power[percentile - 1]);
         powerOutput.Write(power[percentile - 1]);
         if (percentile != 100) powerOutput.Write("\t");
     }
     powerOutput.Close();
 }
Esempio n. 25
0
        /// <summary>
        /// Uploads a file to a given URL and verifies the HTTP request
        /// through the XMPP server (XEP-0070).
        /// </summary>
        /// <param name="uri">URI to send the file to.</param>
        /// <param name="jid">JID to send as.</param>
        /// <param name="filename">File to send.</param>
        public void Upload(string uri, string jid, string filename)
        {
            //try
            //{
            StreamReader reader = new StreamReader(filename);
            HttpWebRequest request =
                (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method = "POST";
            request.Headers.Add(HttpRequestHeader.Authorization,
                                "x-xmpp-auth jid=\"" + jid + "\"");

            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(reader.ReadToEnd());

            reader.Close();

            request.BeginGetResponse(new AsyncCallback(ResponseCallback),
                                     request);
            writer.Close();
            // }
            // catch (WebException)
            // {
            // }
        }
Esempio n. 26
0
 private void  InitBlock()
 {
     System.IO.StreamWriter temp_writer;
     temp_writer = new System.IO.StreamWriter(System.Console.OpenStandardOutput(), System.Console.Out.Encoding);
     temp_writer.AutoFlush = true;
     debugStream = temp_writer;
 }
Esempio n. 27
0
        /// <summary>
        /// A method that takes a Query, and writes a log of that Query and when it was
        /// executed to a file on disk. All Queries executed on a given day are written
        /// to a file with that date as the filename. There's not a massive amount
        /// of complex logic here, just StreamWriters.
        /// </summary>
        /// <param name="query">The Query object to log.</param>
        /// <param name="remoteQuery">Whether or not this was a query processed on the server.</param>
        internal static void LogToDisk(Query query, bool remoteQuery)
        {
            string directoryPath = ConfigurationManager.AppSettings["LoggingDirectory"];
            string queryLogString;
            if (remoteQuery)
            {
                queryLogString = query.ToString() + " processed on server";

            }
            else
            {
                queryLogString = query.ToString();
            }

            if(Directory.Exists(directoryPath))
            {
                DateTime currentDay = DateTime.Today.Date;
                if (File.Exists(directoryPath + @"\" + currentDay.ToString(DATE_FORMAT) + ".txt"))
                {

                    using (StreamWriter fileWriter = new StreamWriter(directoryPath + @"\" + currentDay.ToString(DATE_FORMAT) + ".txt", true))
                    {
                        fileWriter.WriteLine(queryLogString);
                    }
                }
                else
                {
                    using (StreamWriter fileWriter = new StreamWriter(directoryPath + @"\" + currentDay.ToString(DATE_FORMAT) + ".txt", false))
                    {
                        fileWriter.WriteLine(queryLogString);
                    }
                }
            }
        }
Esempio n. 28
0
 private void button3_Click(object sender, EventArgs e)
 { 
     if (button3.Text=="Cancel")
         this.Close();
     else
     {
         if (listBox1.SelectedIndex < 0)
         {
             return;
         }
         else
         {
             string str = listBox1.SelectedItem.ToString();
             string str1 = string.Format("learning/" + str + ".txt");
             StreamWriter sw = new StreamWriter(str1, false, Encoding.UTF8);
             foreach (string line in richTextBox1.Lines)
             {
                 sw.WriteLine(line);
             }
             sw.Close();
             button3.Text = "Cancel";
             richTextBox1.ReadOnly = true;
             MessageBox.Show("Đã lưu " + str);
         }
     }
 }
Esempio n. 29
0
        static void UnhandledException( object sender, UnhandledExceptionEventArgs e )
        {
            // So we don't get the normal unhelpful crash dialog on Windows.
            Exception ex = (Exception)e.ExceptionObject;
            string error = ex.GetType().FullName + ": " + ex.Message + Environment.NewLine + ex.StackTrace;
            bool wroteToCrashLog = true;
            try {
                using( StreamWriter writer = new StreamWriter( crashFile, true ) ) {
                    writer.WriteLine( "--- crash occurred ---" );
                    writer.WriteLine( "Time: " + DateTime.Now.ToString() );
                    writer.WriteLine( error );
                    writer.WriteLine();
                }
            } catch( Exception ) {
                wroteToCrashLog = false;
            }

            string message = wroteToCrashLog ?
                "The cause of the crash has been logged to \"" + crashFile + "\". Please consider reporting the crash " +
                "(and the circumstances that caused it) to github.com/UnknownShadow200/ClassicalSharp/issues" :

                "Failed to write the cause of the crash to \"" + crashFile + "\". Please consider reporting the crash " +
                "(and the circumstances that caused it) to github.com/UnknownShadow200/ClassicalSharp/issues" +
                Environment.NewLine + Environment.NewLine + error;

            MessageBox.Show( "Oh dear. ClassicalSharp has crashed." + Environment.NewLine +
                            Environment.NewLine + message, "ClassicalSharp has crashed" );
            Environment.Exit( 1 );
        }
Esempio n. 30
0
        private async void btnSave_Click(object sender, EventArgs e)
        {
            if (tbData.Text.Length <= 0)
            {
                MessageBox.Show(@"No text entered", @"Error!", MessageBoxButtons.OK);
                return;
            }

            try
            {
                //create dir if it does not exists
                while (!Directory.Exists(PathToFile))
                {
                    Directory.CreateDirectory(PathToFile);
                }

                using (StreamWriter fs = new StreamWriter(Path.Combine(PathToFile, FileName), false))
                {
                    await fs.WriteAsync(tbData.Text);
                }
            }
            catch (IOException ex)
            {
                //catch error
                MessageBox.Show(ex.Message, @"Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 31
0
public void EndLevel()
{

	currency.RecordEndMoneyLog ();


	UIManager.instance.ShowEndOfLevel();


	UnityEngine.Debug.LogWarning ("!!!!!!  End Round !!!!  ");


	System.Threading.Thread.Sleep (30);


	var processInfo = new ProcessStartInfo ("/usr/bin/python", "/Users/Franz/Documents/524LoopControl/LoopControl/loopControl.py");
	processInfo.CreateNoWindow = true;
	processInfo.UseShellExecute = false;
	processInfo.RedirectStandardOutput = true;
	processInfo.RedirectStandardError = true;
	var process = Process.Start(processInfo);
	process.WaitForExit();
	int exitCode = process.ExitCode;
	UnityEngine.Debug.LogWarning ("exitCode:  " + exitCode);

	string resLine = process.StandardOutput.ReadToEnd ();
	UnityEngine.Debug.LogWarning ("shell result:  " + resLine);
	string err = process.StandardError.ReadToEnd();
	UnityEngine.Debug.LogWarning ("shell err:  " + err);
	process.Close();

	UnityEngine.Debug.LogWarning ("Run Script Finish!!!!");


	ClearAllData ();



	//while (true) {	
	System.IO.StreamReader file = new System.IO.StreamReader(GetInfoPath(PRJ_ROOT+ "wave_pool/"));
	newWaveFileIndex = System.Int32.Parse(file.ReadLine ());
	file.Close ();
	if (newWaveFileIndex != lastWaveFileIndex) {
		UnityEngine.Debug.LogWarning ("Got new wave, New Round!!!!");
		System.IO.StreamReader xmlReaderFile = new System.IO.StreamReader(PRJ_ROOT + "wave_pool/wave_"+ (newWaveFileIndex-1));
		string xmlContent = xmlReaderFile.ReadToEnd ();
		xmlReaderFile.Close ();

		//		System.IO.StreamReader xmlWriterFile = new System.IO.StreamReader("/Users/Franz/Documents/FinalTowerDefense/TowerDefenseAI/Assets/Data/Level1.xml");

		System.IO.StreamWriter xmlWriterFile = new System.IO.StreamWriter("Assets/Data/Level1.xml");
		xmlWriterFile.Write (xmlContent);
		xmlWriterFile.Close ();


	} else {
		UnityEngine.Debug.LogWarning ("No new wave, try again.....");
		//				System.Threading.Thread.Sleep (30);
	}
	//}



	Start ();
		currency.RecordStartMoneyLog ();

}
Esempio n. 32
0
    public static bool BuildPluginAndroid()
    {
        Debug.Log("building Android Plugin...");
        clear_log();

        EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
        var name             = "UnityPlugin";
        var workdir          = Application.dataPath + "/../PluginProjects/Android";
        var android_ndk_root = "/Applications/android-ndk-r10e";
        var deploydir        = Application.dataPath + "/PluginWork/Plugins/Android";
        var sourcedir        = Application.dataPath + "/PluginWork/Sources";
        var success          = false;

        if (System.IO.Directory.Exists(workdir))
        {
            System.IO.Directory.Delete(workdir, true /* recursive */);
        }
        System.IO.Directory.CreateDirectory(workdir);

        AssetDatabase.Refresh();

        string android_makefile     = workdir + "/Android.mk";
        string application_makefile = workdir + "/Application.mk";

        {
            string AndroidMakefile_content = @"# This file is automatically generated. Don't touch!
include $(CLEAR_VARS)

LOCAL_ARM_MODE  := arm
LOCAL_PATH      := $(NDK_PROJECT_PATH)
LOCAL_MODULE    := lib{0}
LOCAL_CFLAGS    := -Werror
LOCAL_SRC_FILES := {1}
LOCAL_LDLIBS    := -llog

include $(BUILD_SHARED_LIBRARY)
";
            string source_files            = sourcedir + "/interface.cpp";
            string str = string.Format(AndroidMakefile_content,
                                       name,
                                       source_files);
            using (var sw = new System.IO.StreamWriter(android_makefile)) {
                sw.Write(str);
            }
        }
        {
            string ApplicationMakefile_content = @"# This file is automatically generated. Don't touch!
APP_OPTIM        := release
APP_ABI          := armeabi
APP_PLATFORM     := android-8
APP_STL          := stlport_static
APP_BUILD_SCRIPT := {0}
";
            string str = string.Format(ApplicationMakefile_content,
                                       android_makefile);
            using (var sw = new System.IO.StreamWriter(application_makefile)) {
                sw.Write(str);
            }
        }

        success = run(android_ndk_root + "/ndk-build", new string[] {
            "NDK_PROJECT_PATH=" + workdir,
            "NDK_APPLICATION_MK=" + application_makefile,
        });
        if (!success)
        {
            Debug.LogError("failed!");
            return(false);
        }

        if (System.IO.Directory.Exists(deploydir))
        {
            System.IO.Directory.Delete(deploydir, true /* recursive */);
        }
        System.IO.Directory.CreateDirectory(deploydir);

        System.IO.File.Copy(workdir + "/libs/armeabi/lib" + name + ".so",
                            deploydir + "/lib" + name + ".so");
        return(true);
    }
Esempio n. 33
0
 public void ScoreRecord(double cur_Score)
 {
     System.IO.StreamWriter writeFile = new System.IO.StreamWriter("Strategy_Pool/scores", append: true);
     writeFile.WriteLine(cur_Score + "\n");
     writeFile.Close();
 }
    public static void Main()
    {
        // TODO: Pull credentials from file
        var factory = new ConnectionFactory()
        {
            HostName = "192.168.1.2",
            UserName = "******",
            Password = "******"
        };

        using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

                Console.WriteLine(" [*] Waiting for messages.");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (sender, ea) =>
                {
                    var body    = ea.Body.ToArray();
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine("Received Message: {0}", message);

                    var probe = message.Substring(0, 7);
                    var value = message.Substring(8);

                    //TODO: save the message
                    string filePath = string.Empty;
                    if (probe == "Probe_1")
                    {
                        filePath = @"/home/tim/Documents/Programming/RabbitMQ/Worker/probe1.txt";
                    }
                    else if (probe == "Probe_2")
                    {
                        filePath = @"/home/tim/Documents/Programming/RabbitMQ/Worker/probe2.txt";
                    }
                    else
                    {
                        filePath = @"/home/tim/Documents/Programming/RabbitMQ/Worker/otherProbe1.txt";
                    }

                    var time = DateTime.Now.ToString();

                    var entry = time + ", " + value;

                    using (System.IO.StreamWriter file =
                               new System.IO.StreamWriter(filePath, true))
                    {
                        file.WriteLine(entry);
                    }

                    // Note: it is possible to access the channel via
                    //       ((EventingBasicConsumer)sender).Model here
                    channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                };
                channel.BasicConsume(queue: "esp8266_amqp",
                                     autoAck: false,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
    }
Esempio n. 35
0
    //Function to write log file

    public static void Writefile_new(string strErrMesg, string strPath)
    {
        try
        {
            strPath = strPath + "//Log";
            string LogFilename         = "Log" + "_" + DateTime.Now.ToString("yyyyMMdd");
            System.Data.DataSet Dsfile = new System.Data.DataSet();
            if (System.IO.Directory.Exists(strPath) == false)
            {
                System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(strPath);
                dirinfo.Create();
                CreateNewXml(ref Dsfile);
                Dsfile.WriteXml(strPath + " \\XmlData.xml");

                System.IO.FileInfo     objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_0.log");
                System.IO.StreamWriter Tex     = objfile.CreateText();
                Tex.Write(strErrMesg + "\r\n");
                Tex.Close();
                System.GC.Collect();//
                return;
            }

            if (System.IO.File.Exists(strPath + "\\XmlData.xml") == true)
            {
                System.Data.DataRow[] dr;
                int FileIndex = 0;
                Dsfile.ReadXml(strPath + " \\XmlData.xml");
                dr = Dsfile.Tables[0].Select("SysDate ='" + DateTime.Now.ToString("dd-MM-yyyy") + "'");
                if (dr.Length > 0)
                {
                    FileIndex = Convert.ToInt32(dr[0]["Sysvalue"].ToString());
                }
                else
                {
                    Dsfile.Clear();
                    CreateNewXml(ref Dsfile);
                    Dsfile.WriteXml(strPath + "\\XmlData.xml");
                }

                if (System.IO.File.Exists(strPath + "\\" + LogFilename + "_" + FileIndex + ".log"))
                {
                    System.IO.FileInfo objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + FileIndex.ToString() + ".log");
                    if (objfile.Length > 500000)    //523636
                    {
                        System.IO.FileInfo     objfile1 = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + (FileIndex + 1).ToString() + ".log");
                        System.IO.StreamWriter Tex      = objfile1.CreateText();
                        Tex.Write(strErrMesg + "\r\n");
                        Tex.Close();
                        Dsfile.Tables[0].Rows[0]["Sysvalue"] = FileIndex + 1;
                        Dsfile.WriteXml(strPath + "\\XmlData.xml");
                        System.GC.Collect();
                    }
                    else
                    {
                        System.IO.StreamWriter Tex = objfile.AppendText();
                        Tex.Write(strErrMesg + "\r\n");
                        Tex.Close();
                        System.GC.Collect();
                    }
                }
                else
                {
                    System.IO.FileInfo     objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + FileIndex.ToString() + ".log");
                    System.IO.StreamWriter Tex     = objfile.CreateText();
                    Tex.Write(strErrMesg + "\r\n");
                    Tex.Close();
                    System.GC.Collect();
                }
            }
            else
            {
                CreateNewXml(ref Dsfile);
                Dsfile.WriteXml(strPath + "\\XmlData.xml");
                System.IO.FileInfo     objfile = new System.IO.FileInfo(strPath + LogFilename + "_0.log");
                System.IO.StreamWriter Tex     = objfile.CreateText();
                Tex.Write(strErrMesg + "\r\n");
                Tex.Close();
                System.GC.Collect();
            }
        }
        catch (Exception ex)
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(ex.Message);
        }
    }
Esempio n. 36
0
    void Populate()
    {
        NumberToCreate();
        Turbines  = new GameObject[numberToCreate];
        AllSmokes = new GameObject[numberToCreate];
        GameObject newObj; // Create GameObject instance
        float      j = 0;
        int        k = 0;

        GridLineHorizontal = k;
        bool       IsEven       = true;
        float      scale        = 0.5f;
        float      lastScale    = 0;
        GameObject Grid         = GameObject.Find("Cube");
        float      TurbineSizeY = ((FromPreviousScene.Radius * 2) * PopulateGrid.YDiaValue);

        GeneratedPower    = new float[numberToCreate];
        GeneratedPowerSet = new float[100, 5];
        List <string> Lines = new List <string>();

        for (int i = 0; i < numberToCreate; i++)
        {
            TurbineCount++;
            Point = Instantiate(Point, panel.transform);
            //   newObj = (GameObject)Instantiate(Prefab, transform);
            //  newObj.transform.gameObject.name = i.ToString();
            // newObj.GetComponent<Button>().onClick.AddListener( () => Grid.GetComponent<GridButtons>().OnclickButton() );
            //  AllSmokes[i] = Instantiate(Smoke) as GameObject;
            Turbines[i] = Instantiate(TurbinePrefab) as GameObject;
            //Turbines[i].transform.localScale = new Vector3(1f, 1f, 1f);
            Turbines[i].GetComponent <canvasLook>().TurbineNo = i;

            // Turbines[i].GetComponent<canvasLook>().Turbines =Turbines;
            if (IsEven)
            {
                if (Xlocation > (Cube.transform.localScale.x - ((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue))
                {
                    // LatestTurbinePosition = Turbines[i].transform.position.z;
                    j = 0;
                    k++;
                    scale += 0.5f;
                    if (!FromPreviousScene.IsSameHeight)
                    {
                        FromPreviousScene.TurbineSize += 73;
                        //if (k <= 3)
                        //{
                        //    TurbineSizeY =(((30f / 1.5f) * 2f) * 7f);

                        //}
                        //else
                        //{
                        //    TurbineSizeY = ((((k * 10f) / 1.5f) * 2f) * 7f);
                        //}
                        // TurbineSizeEven = TurbineSizeY;
                    }
                    else
                    {
                        //TurbineSizeY = (((80f / 1.5f) * 2f) * 7f);
                        //TurbineSizeEven = TurbineSizeOdd;

                        FromPreviousScene.TurbineSize = 424;
                    }


                    IsEven = false;
                }
            }
            else
            {
                if (Xlocation > (Cube.transform.localScale.x - ((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue))
                {
                    Debug.Log("reached");
                    //LatestTurbinePosition = Turbines[i].transform.position.z;
                    j = 0;
                    k++;
                    if (!FromPreviousScene.IsSameHeight)
                    {
                        FromPreviousScene.TurbineSize += 73;
                        //if (k <= 3)
                        //{
                        //    TurbineSizeY = (((30f / 1.5f) * 2f) * 8f);
                        //}
                        //else
                        //{
                        //    TurbineSizeY = ((((k * 10f) / 1.5f) * 2f) * 8f);
                        //}
                        //  TurbineSizeOdd = TurbineSizeY;
                    }
                    else
                    {
                        FromPreviousScene.TurbineSize = 424;
                        // TurbineSizeY = (((80f / 1.5f) * 2f) * 8f);
                        // TurbineSizeOdd = TurbineSizeY;
                    }
                    scale += 0.5f;
                    IsEven = true;
                }
            }
            if (k + 1 < 8 && (!FromPreviousScene.IsSameHeight))
            {
                Turbines[i].transform.localScale = new Vector3(scale, scale, scale);
            }
            else
            {
                if (FromPreviousScene.IsSameHeight)
                {
                    scale = 4;
                }
                else
                {
                    scale = 4;
                }
                Turbines[i].transform.localScale = new Vector3(scale, scale, scale);
            }
            //    Turbines[i].transform.Find("Cone").transform.localScale = new Vector3(1f,FromPreviousScene.Radius,FromPreviousScene.Radius);
            //    Turbines[i].transform.Find("Cone.2").transform.localScale = new Vector3(1f, FromPreviousScene.Radius, FromPreviousScene.Radius);
            //    Turbines[i].transform.Find("Cone.3").transform.localScale = new Vector3(1f, FromPreviousScene.Radius, FromPreviousScene.Radius);
            Turbines[i].GetComponent <canvasLook>().TurbineRow = k + 1;

            if (k != lastScale)
            {
                lastScale = k;
                if (FromPreviousScene.IsGrid)
                {
                    Xlocation  = 0f;// ((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue;
                    ZLocation += ((getTrubineHeight((int)(k)) / 1.5f) * 2) * PopulateGrid.XDiaValue;
                }
                else
                {
                    if ((k + 1) % 2 == 0)
                    {
                        Xlocation  = 0f;
                        ZLocation += ((getTrubineHeight((int)(k)) / 1.5f) * 2) * (PopulateGrid.YDiaValue);
                    }
                    else
                    {
                        Xlocation  = ((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue;
                        ZLocation += ((getTrubineHeight((int)(k)) / 1.5f) * 2) * (PopulateGrid.YDiaValue);
                    }
                }
            }
            if (FromPreviousScene.IsGrid)
            {
                Xlocation += ((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue;
            }
            else
            {
                if ((k + 1) % 2 != 0)
                {
                    Xlocation += ((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue;
                }
                else
                {
                    Xlocation += ((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * (PopulateGrid.XDiaValue);
                }
            }


            if (FromPreviousScene.IsGrid)
            {
                Turbines[i].transform.position = new Vector3(Xlocation, 0f, (ZLocation));
            }
            else
            {
                if (IsEven)
                {
                    // Debug.Log("K " + k);
                    if (k == 0)
                    {
                        //  Turbines[i].transform.position = new Vector3(((j * FromPreviousScene.TurbineSize) + (FromPreviousScene.TurbineSize / 2.0f)), 0, (ZLocation));
                        Turbines[i].transform.position = new Vector3(Xlocation - ((((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue) / 2), 0, (ZLocation));
                    }
                    else
                    {
                        // Turbines[i].transform.position = new Vector3(((j * FromPreviousScene.TurbineSize) + (FromPreviousScene.TurbineSize / 2.0f)), 0, ( ZLocation));
                        Turbines[i].transform.position = new Vector3(Xlocation - ((((getTrubineHeight((int)(k + 1)) / 1.5f) * 2) * PopulateGrid.XDiaValue) / 2), 0, (ZLocation));
                    }
                }
                else
                {
                    //   Debug.Log("K " + k);
                    //    Turbines[i].transform.position = new Vector3(((j * FromPreviousScene.TurbineSize) + (FromPreviousScene.TurbineSize)), 0f, (ZLocation));
                    Turbines[i].transform.position = new Vector3(Xlocation, 0f, (ZLocation));
                }
            }
            j++;
            //   Debug.Log(Cube.transform.localScale.x / 10);
            //  Point.transform.position = new Vector2( ((Cube.transform.localScale.x/10)) , (Turbines[i].transform.position.z/10f));
            //            Point.rectTransform.localPosition = new Vector3((Turbines[i].transform.position.x/10) - ((Cube.transform.localScale.x/10)/2), -((Turbines[i].transform.position.z / 10) - ((Cube.transform.localScale.z / 10) / 2)), 0);

            float pointx = (Turbines[i].transform.position.x / 10) - ((Cube.transform.localScale.x / 10) / 2);
            float pointy = -((Turbines[i].transform.position.z / 10) - ((Cube.transform.localScale.z / 10) / 2));
            Point.rectTransform.localPosition = new Vector3(pointx, pointy, 0);
            if (k == 0)
            {
                GridLineY = Instantiate(GridLineY, panel.transform);
                GridLineY.rectTransform.localPosition = new Vector3(Point.rectTransform.localPosition.x + 2f, Point.rectTransform.localPosition.y);
//                GridLine.rectTransform.localScale = new Vector3(GridLine.rectTransform.localPosition.x, Cube.transform.localScale.z / 10f);
                GridLineY.rectTransform.sizeDelta = new Vector2(GridLineY.rectTransform.sizeDelta.x, Cube.transform.localScale.z / 10f);
                GridLineHeight     = (int)(GridLineY.rectTransform.localPosition.y - GridLineY.rectTransform.sizeDelta.y);
                FirstPointPosition = (int)(Point.rectTransform.localPosition.y);
            }

            if (FirstPointPosition >= GridLineHeight)
            {
                GridLineHorizontal = k;
                GridLineX          = Instantiate(GridLineX, panel.transform);
                if (RotateGridForFirst == 0)
                {
                    //GridLineX.rectTransform.Rotate(0f, 0f, 90f);
                    RotateGridForFirst = 1;
                }
                GridLineX.rectTransform.sizeDelta     = new Vector2(Cube.transform.localScale.x / 10f, GridLineX.rectTransform.sizeDelta.y);
                GridLineX.rectTransform.localPosition = new Vector3(-((Cube.transform.localScale.x / 10) / 2), FirstPointPosition);
                if (FromPreviousScene.IsSameHeight)
                {
                    FirstPointPosition = (int)-((Turbines[i].transform.position.z / 10) - ((Cube.transform.localScale.z / 10) / 2));
                }
                else
                {
                    FirstPointPosition -= (int)(((YDiaValue * getTrubineHeight((int)(1))) / 10)) + (YDiaValue * 2);
                }
            }
            Point.rectTransform.localPosition = new Vector3(pointx, pointy, 0);
            //if ((k % 2 == 0) && (j % 2 == 0) && i!=0)
            //{
            //    Turbines[i].SetActive(false);
            //}
            //if (((k % 2) != 0) && ((j % 2) != 0) &&i!=0)
            //{
            //    Turbines[i].SetActive(false);
            //}
            //  newObj.GetComponentInChildren<Text>().text = i.ToString();
            // newObj.GetComponent<Button>().onClick.AddListener(() => Turbines[i].GetComponent<canvasLook>().Update());
            //Transform obj = Turbines[i].transform.Find("head");

            //AllSmokes[i].transform.localPosition= new Vector3(obj.position.x, obj.position.y, obj.position.z);
            if (Turbines[i].transform.position.z > Cube.transform.localScale.z)
            {
                Destroy(Turbines[i]);
                TurbineCount--;
                //Destroy(AllSmokes[i]);
                Destroy(Point);
                GeneratedPowerSet[k + 1, 3]--;
                break;
            }
            else
            {
                // Debug.Log("X:"+Xlocation+":Y:"+ZLocation);
                Lines.Add("X:" + Xlocation + ":Y:" + ZLocation);
            }
        }
        using (System.IO.StreamWriter file =
                   new System.IO.StreamWriter(@"D:\\Coordinates.txt"))
        {
            foreach (string line in Lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                file.WriteLine(line);
            }
        }


        //  Grid.GetComponent<GridButtons>().OnclickButton();
        // Debug.Log("reached");

        //  Debug.Log(this.transform.parent.parent.gameObject.name);
        //this.transform.parent.parent.gameObject.SetActive(false);
    }
    public void Begin()
    {
        prevSectionLife = characterController.currentLife;
        numbSegsMade    = 0;
        segmentsPassed  = 0;

        keysPressed                      = new int[2];
        trippedThisSegment               = false;
        sectionStartCoinScore            = 0;
        numCoinsPerSection               = new List <int> ();
        segmentIDs                       = new List <int> ();
        previousCoinCollectionPercentage = 1f;
        prevSectionLife                  = 3;

        currentGame++;
        playerID   = idText.text == "" ? 999 : int.Parse(idText.text);
        gameType   = adaptiveText.text == "" ? 1 : int.Parse(adaptiveText.text);
        isAdaptive = gameType != 0;

        allDataOut     = playerID + "_" + gameType + "_all.csv";
        summaryDataOut = playerID + "_" + gameType + "_summary.csv";

        if (currentGame == 1)
        {
            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter((summaryDataOut), true)) {
                file.WriteLine("Game, Section, Current_Section_ID, PCG_Section_ID, PCG_NextID, UCTScore, ExploitScore, ExploreScore, Joy, Fear, Disgust, Sadness,Anger, Suprise, Contempt, Valence, Engagement, Game Score\n");
            }
            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter((allDataOut), true)) {
                file.WriteLine("Game, Section, Current_Section_ID, Joy, Fear, Disgust, Sadness,Anger, Suprise, Contempt, Valence, Engagement\n");
            }
        }


        if (!m_Rerun)
        {
            if (m_TrackSeed != -1)
            {
                Random.InitState(m_TrackSeed);
            }
            else
            {
                Random.InitState((int)System.DateTime.Now.Ticks);
            }

            // Since this is not a rerun, init the whole system (on rerun we want to keep the states we had on death)
            m_CurrentSegmentDistance = k_StartingSegmentDistance;
            m_TotalWorldDistance     = 0.0f;

            characterController.gameObject.SetActive(true);

            // Spawn the player
            Character player = Instantiate(characterPreFab, Vector3.zero, Quaternion.identity);
            player.transform.SetParent(characterController.characterCollider.transform, false);
            Camera.main.transform.SetParent(characterController.transform, true);

            characterController.character    = player;
            characterController.trackManager = this;

            characterController.Init();
            characterController.CheatInvincible(invincible);

            m_CurrentThemeData    = theme;
            m_CurrentZone         = 0;
            m_CurrentZoneDistance = 0;

            skyMeshFilter.sharedMesh = m_CurrentThemeData.skyMesh;
            RenderSettings.fogColor  = m_CurrentThemeData.fogColor;
            RenderSettings.fog       = true;

            gameObject.SetActive(true);
            characterController.gameObject.SetActive(true);
            characterController.coins   = 0;
            characterController.premium = 0;

            m_Score      = 0;
            m_ScoreAccum = 0;

            m_SafeSegementLeft = k_StartingSafeSegments;

            Coin.coinPool = new Pooler(currentTheme.collectiblePrefab, k_StartingCoinPoolSize);
        }

        characterController.Begin();
        StartCoroutine(WaitToStart());
    }
Esempio n. 38
0
    public static string HandleDynamicCrittercismSetup(string applicationID)
    {
        string iphoneDataPath    = UnityEditor.EditorApplication.applicationContentsPath + "/PlaybackEngines/iPhonePlayer/iPhone-Trampoline/";
        string appControllerPath = null;

        try
        {
            string[] files = System.IO.Directory.GetFiles(iphoneDataPath, "*.mm", System.IO.SearchOption.AllDirectories);
            for (int nItter = 0; nItter < files.Length; nItter++)
            {
                if (files[nItter].Contains("AppController.mm"))
                {
                    appControllerPath = files[nItter];
                    break;
                }
            }
        }
        catch (System.Exception e)
        { return(e.Message); }

        if (string.IsNullOrEmpty(appControllerPath))
        {
            return("Failed To Locate IOS App Controller");
        }

        try
        {
            string writePath = GetIOSPluginsFolder() + "/AppController.mm";
            System.IO.StreamReader readFile  = new System.IO.StreamReader(appControllerPath);
            System.IO.StreamWriter writeFile = new System.IO.StreamWriter(writePath);

            bool   applicationIDWasWritten = false;
            bool   hasWritenExtern         = false;
            string lineData = null;
            while ((lineData = readFile.ReadLine()) != null)
            {
                if (!applicationIDWasWritten)
                {
                    if (!hasWritenExtern)
                    {
                        if (lineData.Contains("//"))
                        {
                            writeFile.Write("const char* kCrittercism_App	= \""+ applicationID + "\";\n");
                            writeFile.Write("extern \"C\" void Crittercism_EnableWithAppID(const char* appID);\n\n");
                            hasWritenExtern = true;
                        }
                    }
                    else
                    {
                        if (lineData.Contains("-"))
                        {
                            if (lineData.Contains("didFinishLaunchingWithOptions:"))
                            {
                                writeFile.Write(lineData + "\n");
                                lineData = readFile.ReadLine();
                                if (lineData.Contains("{") && !lineData.Contains("if"))
                                {
                                    writeFile.Write(lineData + "\n");
                                    lineData = readFile.ReadLine();
                                }
                                writeFile.Write("	Crittercism_EnableWithAppID(kCrittercism_App);\n\n");
                                applicationIDWasWritten = true;
                            }
                        }
                    }
                }

                writeFile.Write(lineData + "\n");
            }

            readFile.Close();
            readFile = null;
            writeFile.Flush();
            writeFile.Close();
            writeFile = null;
        }catch
        { return("Unable to finish writting file data."); }

        return(null);
    }
Esempio n. 39
0
    static public void UpdateUnitStats()
    {
        string[] FileLines = System.IO.File.ReadAllLines(@"..\" + filePath);
        int      NumLines  = FileLines.Length;

        string[][] TokenArray = new string[NumLines][];
        for (int i = 0; i < NumLines; ++i)
        {
            TokenArray[i] = Tokenize(FileLines[i], '\t');
        }

        System.IO.File.Create(@"..\" + newScriptPath).Close();
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"..\" + newScriptPath))
        {
            file.Write("/*This file was auto-generated. Any changes that are made will be overwritten*/\n");
            file.Write("/*Written By: Taylor Riviera*/\n");
            file.Write("/*Version 0.1*/\n");
            file.Write("using UnityEngine;\nusing System.Collections;\n\n");

            //Enum with unit types
            file.Write("public enum UnitType {");
            for (int i = 1; i < NumLines - 1; ++i)
            {
                file.Write(" " + StripQuotes(TokenArray[i][0]) + ",");
            }
            file.Write(" " + StripQuotes(TokenArray[NumLines - 1][0]) + ", Length };\n\n");

            //Class Starts Here
            file.WriteLine("[System.Serializable]");
            file.Write("public static class StatsReference\n {\n");
            //Unit Stats Structure
            file.Write("\n\t [System.Serializable]\n");
            file.Write("\tpublic struct UnitStats {\n");

            for (int i = 1; i < TokenArray[0].Length; ++i)
            {
                file.Write("\t\tpublic " + ReadTokenTypeAsString(TokenArray[1][i]) + " " + StripQuotes(TokenArray[0][i]) + ";\n");
            }

            file.Write("\n\t\tpublic UnitStats(");
            for (int i = 1; i < TokenArray[0].Length; ++i)
            {
                file.Write(ReadTokenTypeAsString(TokenArray[1][i]) + " " + StripQuotes(TokenArray[0][i]) + "_");
                if (i < TokenArray[0].Length - 1)
                {
                    file.Write(", ");
                }
            }
            file.Write(")\n\t\t{");
            for (int i = 1; i < TokenArray[0].Length; ++i)
            {
                file.Write("\n\t\t\t" + StripQuotes(TokenArray[0][i]) + " = " + StripQuotes(TokenArray[0][i]) + "_;");
            }
            file.Write("\n\t\t}\n\t}\n");
            //End of Unit stats struct
            //Start Array Declaration
            file.Write("\tpublic static UnitStats[] UnitStatsArray = new UnitStats[] {");
            for (int i = 1; i < TokenArray.Length; ++i)
            {
                file.Write("\n\t\tnew UnitStats(");
                for (int j = 1; j < TokenArray[i].Length; ++j)
                {
                    if (ReadTokenType(TokenArray[i][j]) == TokenType.Bool)
                    {
                        if (TokenArray[i][j][0] == 'T')
                        {
                            file.Write("true");
                        }
                        else
                        {
                            file.Write("false");
                        }
                    }
                    else
                    {
                        file.Write(TokenArray[i][j]);
                    }

                    if (ReadTokenType(TokenArray[i][j]) == TokenType.Float)
                    {
                        file.Write("f ");
                    }
                    else
                    {
                        file.Write(" ");
                    }

                    if (j < TokenArray[i].Length - 1)
                    {
                        file.Write(", ");
                    }
                }
                file.Write("),");
            }
            file.Write("\n\t};");
            file.Write("\n" + serializeFunction(1, TokenArray[0]));
            file.Write("\n" + isEqualFunction(1, TokenArray[0]));
            //End of File
            file.Write("\n}");
            //file.Write();
        }
        //  print("File Written Successfully!");
    }
Esempio n. 40
0
    public static string HandleHardcodedCrittercismSetup(string applicationID)
    {
        string acFile = "AppController";

#if UNITY_3_4
        acFile += "3.4.0";
#elif UNITY_3_5 && !UNITY_3_5_7
        acFile += "3.5.6";
#elif UNITY_3_5_7
        acFile += "3.5.7";
#elif UNITY_4_0 || UNITY_4_0_1
        acFile += "4.0.1";
#elif UNITY_4_1
        acFile += "4.1";
#else
        UnityEditor.EditorUtility.DisplayDialog("Error", "Unknown Version of Unity!", "Close");
        return;
#endif

        string writePath = GetIOSPluginsFolder() + "/AppController.mm";
        acFile = Application.dataPath + "/Editor/Crittercism/" + acFile + ".mm";
        try
        {
            if (!System.IO.File.Exists(acFile))
            {
                throw new System.Exception("Invalid File Path For AppController:\n" + acFile);
            }

            if (System.IO.File.Exists(writePath))
            {
                try
                {
                    System.IO.File.Delete(writePath);
                }catch
                { throw new System.Exception("Failed to Delete File For AppController:\n" + writePath); }
            }
        }catch (System.Exception e)
        { return(e.Message); }

        try
        {
            System.IO.StreamReader readFile  = new System.IO.StreamReader(acFile);
            System.IO.StreamWriter writeFile = new System.IO.StreamWriter(writePath);

            bool   applicationIDWasWritten = false;
            string lineData = null;
            while ((lineData = readFile.ReadLine()) != null)
            {
                if (!applicationIDWasWritten)
                {
                    if (lineData.Contains("\"CRITTERCISM_APP_ID\""))
                    {
                        lineData = lineData.Replace("CRITTERCISM_APP_ID", applicationID);
                        applicationIDWasWritten = true;
                    }
                }

                writeFile.Write(lineData + "\n");
            }

            readFile.Close();
            readFile = null;
            writeFile.Flush();
            writeFile.Close();
            writeFile = null;
        }catch
        { return("Unable to finish writting file data."); }

        return(null);
    }
Esempio n. 41
0
    public static void TestPrediction()
    {
        Debug.Log("Prediction.TestPrediction");

        string[] lines = System.IO.File.ReadAllLines("prediction_deltas.txt");

        string prediction_filename = "prediction.txt";

        using (System.IO.StreamWriter file = new System.IO.StreamWriter(prediction_filename))
        {
            foreach (string line in lines)
            {
                string[] stringValues = line.Split(',');

                int[] intValues = new int[stringValues.Length];

                for (int i = 0; i < stringValues.Length; ++i)
                {
                    intValues[i] = Int32.Parse(stringValues[i]);
                }

                int current_sequence  = intValues[0];
                int baseline_sequence = intValues[1];

                int baseline_position_x = intValues[15];
                int baseline_position_y = intValues[16];
                int baseline_position_z = intValues[17];

                int baseline_linear_velocity_x = intValues[22];
                int baseline_linear_velocity_y = intValues[23];
                int baseline_linear_velocity_z = intValues[24];

                int current_position_x = intValues[29];
                int current_position_y = intValues[30];
                int current_position_z = intValues[31];

                int current_linear_velocity_x = intValues[36];
                int current_linear_velocity_y = intValues[37];
                int current_linear_velocity_z = intValues[38];

                int baseline_angular_velocity_x = intValues[25];
                int baseline_angular_velocity_y = intValues[26];
                int baseline_angular_velocity_z = intValues[27];

                int current_angular_velocity_x = intValues[39];
                int current_angular_velocity_y = intValues[40];
                int current_angular_velocity_z = intValues[41];

                if (current_sequence < baseline_sequence)
                {
                    current_sequence += 65536;
                }

                int numFrames = current_sequence - baseline_sequence;

                int predicted_position_x;
                int predicted_position_y;
                int predicted_position_z;

                int predicted_linear_velocity_x;
                int predicted_linear_velocity_y;
                int predicted_linear_velocity_z;

                int predicted_angular_velocity_x;
                int predicted_angular_velocity_y;
                int predicted_angular_velocity_z;

                PredictBallistic(numFrames,
                                 baseline_position_x, baseline_position_y, baseline_position_z,
                                 baseline_linear_velocity_x, baseline_linear_velocity_y, baseline_linear_velocity_z,
                                 baseline_angular_velocity_x, baseline_angular_velocity_y, baseline_angular_velocity_z,
                                 out predicted_position_x, out predicted_position_y, out predicted_position_z,
                                 out predicted_linear_velocity_x, out predicted_linear_velocity_y, out predicted_linear_velocity_z,
                                 out predicted_angular_velocity_x, out predicted_angular_velocity_y, out predicted_angular_velocity_z);

                int position_error_x = predicted_position_x - current_position_x;
                int position_error_y = predicted_position_y - current_position_y;
                int position_error_z = predicted_position_z - current_position_z;

                int linear_velocity_error_x = predicted_linear_velocity_x - current_linear_velocity_x;
                int linear_velocity_error_y = predicted_linear_velocity_y - current_linear_velocity_y;
                int linear_velocity_error_z = predicted_linear_velocity_z - current_linear_velocity_z;

                int angular_velocity_error_x = predicted_angular_velocity_x - current_angular_velocity_x;
                int angular_velocity_error_y = predicted_angular_velocity_y - current_angular_velocity_y;
                int angular_velocity_error_z = predicted_angular_velocity_z - current_angular_velocity_z;

                file.WriteLine(numFrames + "," +
                               position_error_x + "," +
                               position_error_y + "," +
                               position_error_z + "," +
                               linear_velocity_error_x + "," +
                               linear_velocity_error_y + "," +
                               linear_velocity_error_z + "," +
                               angular_velocity_error_x + "," +
                               angular_velocity_error_y + "," +
                               angular_velocity_error_z);
            }
        }

        Debug.Log("Updated " + prediction_filename);
    }
Esempio n. 42
0
 public void AppendOneSeqToFile(GeneSeq seq)
 {
     System.IO.StreamWriter writeFile = new System.IO.StreamWriter("Strategy_Pool/strategy", append: true);
     writeFile.WriteLine(seq.Serialize());
     writeFile.Close();
 }
Esempio n. 43
0
    static void Main(string[] args)
    {
        Debug.Assert(CCopasiRootContainer.getRoot() != null);
        // create a new datamodel
        CCopasiDataModel dataModel = CCopasiRootContainer.addDatamodel();

        Debug.Assert(CCopasiRootContainer.getDatamodelList().size() == 1);
        // first we load a simple model
        try
        {
            // load the model
            dataModel.importSBMLFromString(MODEL_STRING);
        }
        catch
        {
            System.Console.Error.WriteLine("Error while importing the model.");
            System.Environment.Exit(1);
        }

        // now we need to run some time course simulation to get data to fit
        // against

        // get the trajectory task object
        CTrajectoryTask trajectoryTask = (CTrajectoryTask)dataModel.getTask("Time-Course");

        // run a deterministic time course
        trajectoryTask.setMethodType(CTaskEnum.deterministic);

        // pass a pointer of the model to the problem
        trajectoryTask.getProblem().setModel(dataModel.getModel());

        // activate the task so that it will be run when the model is saved
        // and passed to CopasiSE
        trajectoryTask.setScheduled(true);

        // get the problem for the task to set some parameters
        CTrajectoryProblem problem = (CTrajectoryProblem)trajectoryTask.getProblem();

        // simulate 4000 steps
        problem.setStepNumber(4000);
        // start at time 0
        dataModel.getModel().setInitialTime(0.0);
        // simulate a duration of 400 time units
        problem.setDuration(400);
        // tell the problem to actually generate time series data
        problem.setTimeSeriesRequested(true);

        // set some parameters for the LSODA method through the method
        // Currently we don't use the method to set anything
        //CTrajectoryMethod method = (CTrajectoryMethod)trajectoryTask.getMethod();

        bool result = true;

        try
        {
            // now we run the actual trajectory
            result = trajectoryTask.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Running the time course simulation failed.");
            String lastErrors = trajectoryTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }
        if (result == false)
        {
            System.Console.Error.WriteLine("An error occured while running the time course simulation.");
            String lastErrors = trajectoryTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }
            System.Environment.Exit(1);
        }

        // we write the data to a file and add some noise to it
        // This is necessary since COPASI can only read experimental data from
        // file.
        CTimeSeries timeSeries = trajectoryTask.getTimeSeries();

        // we simulated 100 steps, including the initial state, this should be
        // 101 step in the timeseries
        Debug.Assert(timeSeries.getRecordedSteps() == 4001);
        uint i;
        uint iMax = (uint)timeSeries.getNumVariables();

        // there should be four variables, the three metabolites and time
        Debug.Assert(iMax == 5);
        uint lastIndex = (uint)timeSeries.getRecordedSteps() - 1;
        // open the file
        // we need to remember in which order the variables are written to file
        // since we need to specify this later in the parameter fitting task
        List <uint>   indexSet    = new List <uint>();
        List <CMetab> metabVector = new List <CMetab>();

        // write the header
        // the first variable in a time series is a always time, for the rest
        // of the variables, we use the SBML id in the header
        double random = 0.0;

        System.Random rand_gen = new System.Random();
        try
        {
            System.IO.StreamWriter os = new System.IO.StreamWriter("fakedata_example6.txt");
            os.Write("# time ");
            CKeyFactory keyFactory = CCopasiRootContainer.getKeyFactory();
            Debug.Assert(keyFactory != null);
            for (i = 1; i < iMax; ++i)
            {
                string        key = timeSeries.getKey(i);
                CCopasiObject obj = keyFactory.get(key);
                Debug.Assert(obj != null);
                // only write header data or metabolites
                System.Type type = obj.GetType();
                if (type.FullName.Equals("org.COPASI.CMetab"))
                {
                    os.Write(", ");
                    os.Write(timeSeries.getSBMLId(i, dataModel));
                    CMetab m = (CMetab)obj;
                    indexSet.Add(i);
                    metabVector.Add(m);
                }
            }
            os.Write("\n");
            double data = 0.0;
            for (i = 0; i < lastIndex; ++i)
            {
                uint   j;
                string s = "";
                for (j = 0; j < iMax; ++j)
                {
                    // we only want to  write the data for metabolites
                    // the compartment does not interest us here
                    if (j == 0 || indexSet.Contains(j))
                    {
                        // write the data with some noise (+-5% max)
                        random = rand_gen.NextDouble();
                        data   = timeSeries.getConcentrationData(i, j);
                        // don't add noise to the time
                        if (j != 0)
                        {
                            data += data * (random * 0.1 - 0.05);
                        }
                        s = s + (System.Convert.ToString(data));
                        s = s + ", ";
                    }
                }
                // remove the last two characters again
                os.Write(s.Substring(0, s.Length - 2));
                os.Write("\n");
            }
            os.Close();
        }
        catch (System.ApplicationException e)
        {
            System.Console.Error.WriteLine("Error. Could not write time course data to file.");
            System.Console.WriteLine(e.Message);
            System.Environment.Exit(1);
        }

        // now we change the parameter values to see if the parameter fitting
        // can really find the original values
        random = rand_gen.NextDouble() * 10;
        CReaction reaction = dataModel.getModel().getReaction(0);

        // we know that it is an irreversible mass action, so there is one
        // parameter
        Debug.Assert(reaction.getParameters().size() == 1);
        Debug.Assert(reaction.isLocalParameter(0));
        // the parameter of a irreversible mass action is called k1
        reaction.setParameterValue("k1", random);

        reaction = dataModel.getModel().getReaction(1);
        // we know that it is an irreversible mass action, so there is one
        // parameter
        Debug.Assert(reaction.getParameters().size() == 1);
        Debug.Assert(reaction.isLocalParameter(0));
        reaction.setParameterValue("k1", random);

        CFitTask fitTask = (CFitTask)dataModel.addTask(CTaskEnum.parameterFitting);

        Debug.Assert(fitTask != null);
        // the method in a fit task is an instance of COptMethod or a subclass of
        // it.
        COptMethod fitMethod = (COptMethod)fitTask.getMethod();

        Debug.Assert(fitMethod != null);
        // the object must be an instance of COptMethod or a subclass thereof
        // (CFitMethod)
        CFitProblem fitProblem = (CFitProblem)fitTask.getProblem();

        Debug.Assert(fitProblem != null);

        CExperimentSet experimentSet = (CExperimentSet)fitProblem.getParameter("Experiment Set");

        Debug.Assert(experimentSet != null);

        // first experiment (we only have one here)
        CExperiment experiment = new CExperiment(dataModel);

        Debug.Assert(experiment != null);
        // tell COPASI where to find the data
        // reading data from string is not possible with the current C++ API
        experiment.setFileName("fakedata_example6.txt");
        // we have to tell COPASI that the data for the experiment is a komma
        // separated list (the default is TAB separated)
        experiment.setSeparator(",");
        // the data start in row 1 and goes to row 4001
        experiment.setFirstRow(1);
        Debug.Assert(experiment.getFirstRow() == 1);
        experiment.setLastRow(4001);
        Debug.Assert(experiment.getLastRow() == 4001);
        experiment.setHeaderRow(1);
        Debug.Assert(experiment.getHeaderRow() == 1);
        experiment.setExperimentType(CTaskEnum.timeCourse);
        Debug.Assert(experiment.getExperimentType() == CTaskEnum.timeCourse);
        experiment.setNumColumns(4);
        Debug.Assert(experiment.getNumColumns() == 4);
        CExperimentObjectMap objectMap = experiment.getObjectMap();

        Debug.Assert(objectMap != null);
        result = objectMap.setNumCols(4);
        Debug.Assert(result == true);
        result = objectMap.setRole(0, CExperiment.time);
        Debug.Assert(result == true);
        Debug.Assert(objectMap.getRole(0) == CExperiment.time);

        CModel model = dataModel.getModel();

        Debug.Assert(model != null);
        CCopasiObject timeReference = model.getValueReference();

        Debug.Assert(timeReference != null);
        objectMap.setObjectCN(0, timeReference.getCN().getString());

        // now we tell COPASI which column contain the concentrations of
        // metabolites and belong to dependent variables
        objectMap.setRole(1, CExperiment.dependent);
        CMetab metab = metabVector[0];

        Debug.Assert(metab != null);
        CCopasiObject particleReference = metab.getConcentrationReference();

        Debug.Assert(particleReference != null);
        objectMap.setObjectCN(1, particleReference.getCN().getString());

        objectMap.setRole(2, CExperiment.dependent);
        metab = metabVector[1];
        Debug.Assert(metab != null);
        particleReference = metab.getConcentrationReference();
        Debug.Assert(particleReference != null);
        objectMap.setObjectCN(2, particleReference.getCN().getString());

        objectMap.setRole(3, CExperiment.dependent);
        metab = metabVector[2];
        Debug.Assert(metab != null);
        particleReference = metab.getConcentrationReference();
        Debug.Assert(particleReference != null);
        objectMap.setObjectCN(3, particleReference.getCN().getString());

        experimentSet.addExperiment(experiment);
        Debug.Assert(experimentSet.getExperimentCount() == 1);
        // addExperiment makes a copy, so we need to get the added experiment
        // again
        experiment = experimentSet.getExperiment(0);
        Debug.Assert(experiment != null);

        // now we have to define the two fit items for the two local parameters
        // of the two reactions
        reaction = model.getReaction(0);
        Debug.Assert(reaction != null);
        Debug.Assert(reaction.isLocalParameter(0) == true);
        CCopasiParameter parameter = reaction.getParameters().getParameter(0);

        Debug.Assert(parameter != null);

        // define a CFitItem
        CCopasiObject parameterReference = parameter.getValueReference();

        Debug.Assert(parameterReference != null);
        CFitItem fitItem1 = new CFitItem(dataModel);

        Debug.Assert(fitItem1 != null);
        fitItem1.setObjectCN(parameterReference.getCN());
        fitItem1.setStartValue(4.0);
        fitItem1.setLowerBound(new CCopasiObjectName("0.00001"));
        fitItem1.setUpperBound(new CCopasiObjectName("10"));
        // add the fit item to the correct parameter group
        CCopasiParameterGroup optimizationItemGroup = (CCopasiParameterGroup)fitProblem.getParameter("OptimizationItemList");

        Debug.Assert(optimizationItemGroup != null);
        optimizationItemGroup.addParameter(fitItem1);

        reaction = model.getReaction(1);
        Debug.Assert(reaction != null);
        Debug.Assert(reaction.isLocalParameter(0) == true);
        parameter = reaction.getParameters().getParameter(0);
        Debug.Assert(parameter != null);

        // define a CFitItem
        parameterReference = parameter.getValueReference();
        Debug.Assert(parameterReference != null);
        CFitItem fitItem2 = new CFitItem(dataModel);

        Debug.Assert(fitItem2 != null);
        fitItem2.setObjectCN(parameterReference.getCN());
        fitItem2.setStartValue(4.0);
        fitItem2.setLowerBound(new CCopasiObjectName("0.00001"));
        fitItem2.setUpperBound(new CCopasiObjectName("10"));
        // add the fit item to the correct parameter group
        optimizationItemGroup.addParameter(fitItem2);

        result = true;
        try
        {
            // running the task for this example will probably take some time
            System.Console.WriteLine("This can take some time...");
            result = fitTask.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Parameter fitting failed.");
            String lastErrors = fitTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }

        Debug.Assert(result == true);
        // assert that there are two optimization items
        Debug.Assert(fitProblem.getOptItemList().Count == 2);
        // the order should be the order in whih we added the items above
        COptItem optItem1 = fitProblem.getOptItemList()[0];
        COptItem optItem2 = fitProblem.getOptItemList()[1];

        // the actual results are stored in the fit problem
        Debug.Assert(fitProblem.getSolutionVariables().size() == 2);
        System.Console.WriteLine("value for " + optItem1.getObject().getCN().getString() + ": " + fitProblem.getSolutionVariables().get(0));
        System.Console.WriteLine("value for " + optItem2.getObject().getCN().getString() + ": " + fitProblem.getSolutionVariables().get(1));
        // depending on the noise, the fit can be quite bad, so we are a litle
        // relaxed here (we should be within 3% of the original values)
        Debug.Assert((System.Math.Abs(fitProblem.getSolutionVariables().get(0) - 0.03) / 0.03) < 3e-2);
        Debug.Assert((System.Math.Abs(fitProblem.getSolutionVariables().get(1) - 0.004) / 0.004) < 3e-2);
    }
 public static void Writelogstream(string _str)
 {
     System.IO.StreamWriter _sw = new System.IO.StreamWriter(System.Windows.Forms.Application.StartupPath + @"\Reminder.log", true);
     _sw.WriteLine(_str);
     _sw.Close();
 }
Esempio n. 45
0
    //بدنه مربوط به ذخیره فایل و یا صفحه
    #region SavePages_btnSave_Click(object sender, EventArgs e)

    /// <summary>
    /// متد ذخیره فایل صفحه توسط ادمین
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //تریم کردن تکست باکس
        txtFileName.Text =
            txtFileName.Text.Trim();

        //اگر تکست باکس خالی بود
        if (txtFileName.Text == string.Empty)
        {
            //نمایش پیغام خطا
            string strErrorMessage =
                string.Format(Resources.Messages.ErrorMessage003);
            DisplayErrorMessage(strErrorMessage);
            return;
        }
        //در غیر اینصورت مراحل مسیر نسبی و تبدیل به مسیر فیزیکی
        string strFileName             = txtFileName.Text;
        string strRootRelativePath     = "~/App_Data/PageContents";
        string strRootRelativePathName =
            string.Format("{0}/{1}", strRootRelativePath, strFileName);

        string strPathName = Server.MapPath(strRootRelativePathName);

        //ایجاد یک شی از کلاس استریم رایتر
        System.IO.StreamWriter oStreamWriter = null;

        try
        {
            //نیو کردن استریم رایتر
            oStreamWriter = new System.IO.StreamWriter
                                (strPathName, false, System.Text.Encoding.UTF8);
            oStreamWriter.Write(txtEditContent.Text);

            //اگر فایل وجود نداشت
            if (System.IO.File.Exists(strPathName) == false)
            {
                //نمایش پیغام خطا
                string strErrorMessage =
                    string.Format(Resources.Messages.ErrorMessage004, txtFileName.Text);
                DisplayErrorMessage(strErrorMessage);
                return;
            }

            //در غیر اینصورت نمایش پیغام موفقیت در عملیات
            string strInformationMessage =
                string.Format(Resources.Messages.InformationMessage002, txtFileName.Text);
            DisplayInformationMessage(strInformationMessage);


            //تکست باکس فایل نیم را نمایان میکنیم
            txtFileName.Visible = true;
            //لینک گذر از این مرحله را فعال میکنیم
            lnbCancel.Visible = true;
            //دراب دان لیست فایل نیم را غیر فعال میکنیم
            DropDownList1.Enabled = false;
        }

        //در صورتی که عملیات ترای با خطا مواجه گردد
        catch (Exception ex)
        {
            //نمایش خطای ایجاد شده
            string strErrorMessage =
                Resources.Messages.ErrorMessage006;
            DisplayErrorMessage(strErrorMessage);

            System.Collections.Hashtable oHashtable =
                new System.Collections.Hashtable();

            //اگر در داخل یک تابع غیر استاتیک  این تابع رو صدا میزنیم از دیس تا گت تایپ استفاده میکنیم
            //در غیر اینصورت از این روش استفاده میکنیم یعنی تایپ اف نام کلاس
            //پارامتر دوم مجموعه ای از اطلاعاتی که میتونه کمک کنه رو هم لاگ میکنیم
            //پارامتر سوم هم که ای ایکس هست رو لاگ میکنیم

            return;
        }

        finally
        {
            //بستن استریم رایتر
            if (oStreamWriter != null)
            {
                oStreamWriter.Dispose();
                oStreamWriter = null;
            }
        }
    }
Esempio n. 46
0
    void calcScores()
    {
        float goals    = 0;
        float touches  = 0;
        float scoresum = 0;

        for (int i = 0; i < populationSize / 2; i++)
        {
            BallScorer bs = population[i].transform.GetChild(0).GetComponent <BallScorer>();
            goals    += bs.t1Goals + bs.t2Goals;
            touches  += bs.t1Touches + bs.t2Touches;
            scoresum += 2f * bs.t1Goals + 0.5f * bs.t1Touches - 0.01f * (bs.mint1p1 + bs.mint1p2 + bs.mint1p3) + 2f * bs.t2Goals + 0.5f * bs.t2Touches - 0.01f * (bs.mint2p1 + bs.mint2p2 + bs.mint2p3);

            if (2 * bs.t1Goals + 0.5 * bs.t1Touches - 0.01 * (bs.mint1p1 + bs.mint1p2 + bs.mint1p3) >= 2 * bs.t2Goals + 0.5 * bs.t2Touches - 0.01 * (bs.mint2p1 + bs.mint2p2 + bs.mint2p3))
            {
                winners[i] = 0;
            }
            else
            {
                winners[i] = 1;
            }

            if (i == 0)
            {
                //Debug.Log((bs.mint1p1 + bs.mint1p2 + bs.mint1p3).ToString() + " : " + (bs.mint2p1 + bs.mint2p2 + bs.mint2p3).ToString());
                //Debug.Log((0.01 * (bs.mint1p1 + bs.mint1p2 + bs.mint1p3)).ToString());
                Debug.Log("P1: " + (2 * bs.t1Goals + 0.5 * bs.t1Touches - 0.01 * (bs.mint1p1 + bs.mint1p2 + bs.mint1p3)).ToString());
            }
        }

        goals    /= populationSize;
        touches  /= populationSize;
        scoresum /= populationSize;

        string str = generationNum.ToString() + " : " + goals.ToString() + " : " + touches.ToString() + " : " + scoresum.ToString();

        Debug.Log(generationNum.ToString() + " : " + goals.ToString() + " : " + touches.ToString() + " : " + scoresum.ToString());
        System.IO.StreamWriter file = new System.IO.StreamWriter("Assets/Data/" + "teamTrain.txt", append: true);
        file.WriteLine(str);
        file.Close();


        //for (int i = 0; i < populationSize / 2; i++)
        //{
        //    BallScorer bs = population[i].transform.GetChild(0).GetComponent<BallScorer>();

        //    if (bs.mint1p1 + bs.mint1p2 + bs.mint1p3 <= bs.mint2p1 + bs.mint2p2 + bs.mint2p3)
        //    {
        //        winners[i] = 0;
        //    }
        //    else
        //    {
        //        winners[i] = 1;
        //    }

        //    if(i==0)
        //    {
        //        Debug.Log((bs.mint1p1 + bs.mint1p2 + bs.mint1p3).ToString() + " : " + (bs.mint2p1 + bs.mint2p2 + bs.mint2p3).ToString());
        //    }
        //}
    }
    private void ProcessFrame(VideoFrame frame)
    {
        if (HasTextureConflict(frame))
        {
            if (texture != null)
            {
                Destroy(texture);
            }

            using (var p = frame.Profile) {
                bool linear = (QualitySettings.activeColorSpace != ColorSpace.Linear) ||
                              (p.Stream != Stream.Color && p.Stream != Stream.Infrared);
                texture = new Texture2D(frame.Width, frame.Height, Convert(p.Format), false, linear)
                {
                    wrapMode   = TextureWrapMode.Clamp,
                    filterMode = filterMode
                };
            }

            textureBinding.Invoke(texture);
        }


        texture.LoadRawTextureData(frame.Data, frame.Stride * frame.Height);

        if (useFilter)
        {
            var colors = texture.GetPixels();
            Color[,] rawImage2D = new Color[texture.height, texture.width];

            for (int i = 0; i < colors.Length; i++)
            {
                int row = (int)Math.Floor(i / (float)texture.width);
                int col = i - (row * texture.width);

                rawImage2D[row, col] = colors[i];
            }


            Color[,] aArray = new Color[texture.height, texture.width];

            for (int i = 0; i < colors.Length; i++)
            {
                int row = (int)Math.Floor(i / (float)texture.width);
                int col = i - (row * texture.width);

                aArray[row, col] = colors[i];
            }



            Color[] filteredColors = new Color[colors.Length];
            int     index          = 0;
            //print 2d color array only once
            for (int i = 0; i < texture.height; i++)
            {
                for (int j = 0; j < texture.width; j++)
                {
                    if ((rawImage2D[i, j].r >= redMin) && (rawImage2D[i, j].g >= greenMin) && (rawImage2D[i, j].b >= blueMin) &&
                        (rawImage2D[i, j].r <= redMax) && (rawImage2D[i, j].g <= greenMax) && (rawImage2D[i, j].b <= blueMax))
                    ////if ((rawImage2D[i, j].r > redMin) && (rawImage2D[i, j].r < redMax))
                    ////{
                    //if (rawImage2D[i,j].r >= redMin)
                    {
                        filteredColors[index] = rawImage2D[i, j];
                        aArray[i, j]          = rawImage2D[i, j];
                    }
                    else
                    {
                        filteredColors[index] = new Color(0, 0, 0);
                        aArray[i, j]          = new Color(0, 0, 0);
                    }
                    index++;
                }
            }


            if (once == true)
            {
                //System.IO.File.WriteAllLines("WriteLines.txt",
                //rawImage2D.Select(ri => (double.Parse(ri.Text)).ToString()));

                //System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", );



                System.IO.StreamWriter streamWriter = new System.IO.StreamWriter("bird.txt");
                string output = "";
                for (int g = 0; g < texture.height; g++)
                {
                    for (int j = 0; j < texture.width; j++)
                    {
                        output += aArray[g, j].ToString();
                    }
                    streamWriter.WriteLine(output);
                    output = "";
                }
                streamWriter.Close();


                once = false;

                /*
                 *
                 * int k = 0;
                 * System.IO.StreamWriter streamWriter = new System.IO.StreamWriter("bird.txt");
                 * string output = "";
                 * for (int g = 0; g < filteredColors.GetUpperBound(0); g++)
                 * {
                 *
                 *  //for (int j = 0; j < aArray.GetUpperBound(1); j++)
                 *  //{
                 *  output += filteredColors[g].ToString();
                 *  //}
                 *  streamWriter.Write(output);
                 *  output = "";
                 *
                 *  if (k >= 640)
                 *  {
                 *      streamWriter.WriteLine("");
                 *  }
                 *  k++;
                 *
                 * }
                 *  streamWriter.Close();
                 *
                 *
                 *  once = false;
                 */
            }


            texture.SetPixels(filteredColors);



            int [,] a = new int[585, 700];
            for (int w = 1; w < 480; w++)
            {
                for (int q = 1; q < 640; q++)
                {
                    if ((aArray[w, q].g >= greenMin) && (aArray[w, q].b >= blueMin) &&
                        (aArray[w, q].g <= greenMax) && (aArray[w, q].b <= blueMax))
                    {
                        if ((aArray[w - 1, q].g >= greenMin) && (aArray[w - 1, q].b <= blueMin) &&
                            (aArray[w - 1, q].g >= greenMax) && (aArray[w - 1, q].b >= blueMax))
                        {
                            aArray[w - 1, q] = new Color(1, 0, 0);
                        }
                    }
                }
            }
        }
        texture.Apply();
    }
Esempio n. 48
0
    public void guardarPartida()
    {
        string json = JsonUtility.ToJson(this);

        System.IO.StreamWriter file = new System.IO.StreamWriter(ruta);
    }
Esempio n. 49
0
    // The run method
    void run()
    {
        foreach (Transform child in panel.transform) // for each block on the main panel
        {
            print("Block Name: " + child);           // prints the block name

            switch (child.name)                      // switch is used instead of a bunch of if-else statments
            {
            case "PlaceHolder":                      // placeHolder is an invisible block added to make the blocks lineup work
                break;

            case "Speak":

                addSpeak(child.GetComponent <Speak>().getText());

                print("Speak: " + child.GetComponent <Speak>().getText());

                break;

            case "MoveForward":     //TO DO: For abstraction, get numbers from MoveForward object

                float dist = 0;
                float sped = 0;
                float.TryParse(child.Find("DistanceInput").GetComponent <InputField>().text, out dist);
                float.TryParse(child.Find("SpeedInput").GetComponent <InputField>().text, out sped);

                addMoveForward(child.GetComponent <MoveForward>().getDistance(), child.GetComponent <MoveForward>().getSpeed());

                print("MoveForward: " + child.GetComponent <MoveForward>().getDistance() + ":" + child.GetComponent <MoveForward>().getSpeed());

                break;

            case "liftUp":

                addLiftUp();

                print("LiftUp");

                break;

            case "liftDown":

                addLiftDown();

                print("LiftDown");

                break;

            case "TurnInPlace":    // TO DO: For abstraction, get degrees from Turn in place object

                float degrees = 0;

                float.TryParse(child.Find("DegreesInput").GetComponent <InputField>().text, out degrees);



                addTurn(degrees);

                print("turn in place:" + degrees);

                break;

            default:
                break;
            }
        }//foreach


        Command[] runCommands = new Command[commands.Count]; // creates array the size of the commands list

        runCommands = commands.Cast <Command>().ToArray();   //adds all of the commands from the list into an array

        // Starts the command promp
        Process cmd = new Process();

        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.RedirectStandardInput  = true;
        cmd.StartInfo.RedirectStandardOutput = false;
        cmd.StartInfo.CreateNoWindow         = true;
        cmd.StartInfo.UseShellExecute        = false;
        cmd.Start();

        // stream writer writes to the command prompt
        System.IO.StreamWriter myStream = new System.IO.StreamWriter(cmd.StandardInput.BaseStream, Encoding.ASCII);


        myStream.WriteLine("py"); // py starts python3

        // imports for cozmo
        myStream.WriteLine("import time");
        myStream.WriteLine("import cozmo");
        myStream.WriteLine("import asyncio");
        myStream.WriteLine("from cozmo.util import degrees, distance_mm, speed_mmps");

        //starts cozmo function
        myStream.WriteLine("def cozmo_program(robot: cozmo.robot.Robot):");



        String rnCmd = "";

        for (int i = 0; i < runCommands.Length; i++) //loops through all commands
        {
            rnCmd = runCommands[i].getType();        // gets command type i.e "speak", "moveforward", ect

            switch (rnCmd)                           // for each block, the command object gets output which is the python code to run the command
            {                                        // numIndents is the number of tabs the python uses instad of {}
            case "speak":

                myStream.WriteLine(runCommands[i].getOutput(numIndents));
                UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));     // prints out command to debug log

                break;

            case "forward":

                myStream.WriteLine(runCommands[i].getOutput(numIndents));
                UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));

                break;

            case "turn":

                myStream.WriteLine(runCommands[i].getOutput(numIndents));
                UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));

                break;


            case "setLiftHeight":

                myStream.WriteLine(runCommands[i].getOutput(numIndents));
                UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));

                break;

            default:
                break;
            }//switch

            myStream.WriteLine(""); // blank string to get out of the function (one less indent)
            myStream.WriteLine("cozmo.run_program(cozmo_program)"); // runs cozmo function
            myStream.Close();                                       // closes streamn writer

            //closes command prompt
            cmd.StandardInput.Flush();
            cmd.WaitForExit();



            // obsolete code replaced by switch statment

            /*if (runCommands[i].getType() == "speak")
             * {
             *
             *  myStream.WriteLine(runCommands[i].getOutput(numIndents));
             *  UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));
             *
             * }//if
             *
             * else if (runCommands[i].getType() == "forward")
             * {
             *
             *  myStream.WriteLine(runCommands[i].getOutput(numIndents));
             *  UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));
             *
             * }//else if
             * else if (runCommands[i].getType() == "for")
             * {
             *
             *  myStream.WriteLine(runCommands[i].getOutput(numIndents));
             *  UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));
             *  numIndents++;
             *
             * }//else if
             * else if (runCommands[i].getType() == "forEnd")
             * {
             *
             *  myStream.WriteLine(runCommands[i].getOutput(numIndents));
             *  UnityEngine.Debug.Log(runCommands[i].getOutput(numIndents));
             *  numIndents--;
             *
             *
             * }//else if*/
        }//for



        //commands.Clear();
    }//run
Esempio n. 50
0
    /** Exports the INavmesh graph to a file */
    public void ExportToFile(NavGraph target)
    {
        INavmesh graph = (INavmesh)target;

        if (graph == null)
        {
            return;
        }

        Int3[] vertices = graph.vertices;

        if (vertices == null || target.nodes == null)
        {
            if (EditorUtility.DisplayDialog("Scan graph before exporting?", "The graph does not contain any mesh data. Do you want to scan it?", "Ok", "Cancel"))
            {
                AstarPath.MenuScan();
            }
            else
            {
                return;
            }
        }

        vertices = graph.vertices;

        if (vertices == null || target.nodes == null)
        {
            Debug.LogError("Graph still does not contain any nodes or vertices. Canceling");
            return;
        }

        string path = EditorUtility.SaveFilePanel("Export .obj", "", "navmesh.obj", "obj");

        if (path == "")
        {
            return;
        }

        //Generate .obj
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        string name = System.IO.Path.GetFileNameWithoutExtension(path);

        sb.Append("g ").Append(name).AppendLine();

        //Write vertices
        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 v = (Vector3)vertices[i];
            sb.Append(string.Format("v {0} {1} {2}\n", -v.x, v.y, v.z));
        }

        //Define single texture coordinate to zero
        sb.Append("vt 0\n");

        //Write triangles
        for (int i = 0; i < target.nodes.Length; i++)
        {
            MeshNode node = target.nodes[i] as MeshNode;
            if (node == null)
            {
                Debug.LogError("Node could not be casted to MeshNode. Node was null or no MeshNode");
                return;
            }
            sb.Append(string.Format("f {0}/0 {1}/0 {2}/0\n", node.v1 + 1, node.v2 + 1, node.v3 + 1));
        }

        string obj = sb.ToString();

        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path))
        {
            sw.Write(obj);
        }
    }
Esempio n. 51
0
 // Schreibt Text in eine Datei (Append-Modus)
 static void WriteFileAppend(string sFilename, string sLines)
 {
     System.IO.StreamWriter myFile = new System.IO.StreamWriter(sFilename, true, System.Text.Encoding.UTF8);
     myFile.Write(sLines);
     myFile.Close();
 }
Esempio n. 52
0
    void Start()
    {
        file = new System.IO.StreamWriter(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\GameLog.txt", true);

        file.WriteLine(System.DateTime.Now.ToString("hh:mm:ss") + "  level Loaded: " + Application.loadedLevelName);
    }
Esempio n. 53
0
    public static void Main()
    {
        /*
         * FPGA Read Write Process
         *  - load bytes into local bytes array
         *  - stream to FPGA using port.write()
         *  - read in serial input buffer using ReadAvailable()
         */

        // Variables for loading in the input byte stream
        string inputFileName = @"uart_input_bytes.txt";

        string[] hexBytes   = System.IO.File.ReadAllText(inputFileName).Split('\n');
        Byte[]   fpgaStream = new Byte [hexBytes.Length];
        int      i          = 0;

        //Variables for the serial port reading/writing
        string fpgaBytesRead;
        string portName     = "COM4";
        int    baudRate     = 6000000;
        int    dataBits     = 8;
        int    readInterval = 1;
        var    stopBit      = System.IO.Ports.StopBits.One;
        var    parity       = System.IO.Ports.Parity.None;

        SerialPort fpgaComPort = new SerialPort(portName, baudRate, parity, dataBits, stopBit);
        // fpgaComPort.Handshake = System.IO.Ports.Handshake.RequestToSend;

        // Helper Variables for serial r/w byte counting
        int numOutputsExpected = 518 * 518 * 2;
        int numOutputsRecieved = 0;
        int bytesRemaining     = 0;

        string outputFileName = @"fpgaOut.txt";

        System.IO.StreamWriter outputFile = new System.IO.StreamWriter(outputFileName);
        System.IO.StreamWriter testFile   = new System.IO.StreamWriter("test.txt");

        /* Load all FPGA Input Bytes into a Byte[] struct */
        int numFPGAStreamElements = 0;

        for (i = 0; i < hexBytes.Length; i++)
        {
            try
            {
                Byte hexValue = Convert.ToByte(hexBytes[i]);
                fpgaStream[i] = hexValue;
            }
            catch (Exception) { Console.WriteLine("Conversion Failed!"); }
            numFPGAStreamElements++;
        }

        Console.WriteLine("Loaded Input Bytes!");

        /* Send/Recieve Bytes from FPGA COM Ports */
        fpgaComPort.Open();
        // fpgaComPort.Write("\n");

        // Clean up the input/output buffers
        fpgaComPort.DiscardInBuffer();
        fpgaComPort.DiscardOutBuffer();
        fpgaComPort.BaseStream.Flush();

        Stopwatch timer = new Stopwatch();

        timer.Start();

        foreach (Byte outputByte in fpgaStream)
        {
            Byte[]  writeByte      = new byte [1];
            Byte [] outputFileByte = new byte [1];
            string  hexStr;

            writeByte[0] = outputByte;

            fpgaComPort.Write(writeByte, 0, 1);

            /* Allow 1ms to let Serial Input buffer fill with data */
            //System.Threading.Thread.Sleep(readInterval);

            Byte[] bufData = new byte [fpgaComPort.BytesToRead];
            fpgaComPort.Read(bufData, 0, bufData.Length);

            Console.WriteLine("Number of Bytes Recieved: {0}", bufData.Length);

            for (int j = 0; j < bufData.Length; j++)
            {
                outputFileByte[0] = bufData[j];
                hexStr            = BitConverter.ToString(outputFileByte).Replace("-", string.Empty);
                outputFile.WriteLine(hexStr);
            }

            numOutputsRecieved += bufData.Length;
            Console.WriteLine("Total FPGA Outputs Recieved = {0}", numOutputsRecieved);
        }

        /* Read the leftover FPGA Data */
        bytesRemaining = numOutputsExpected - numOutputsRecieved;

        for (int p = 0; p < bytesRemaining; p++)
        {
            //System.Threading.Thread.Sleep(readInterval);

            Byte[] bufData = new byte [fpgaComPort.BytesToRead];
            Byte[] thing   = new byte[1];

            string hexStr;
            fpgaComPort.Read(bufData, 0, bufData.Length);

            Console.WriteLine("Number of Bytes Recieved: {0}", bufData.Length);

            for (int s = 0; s < bufData.Length; s++)
            {
                thing[0] = bufData[s];

                hexStr = BitConverter.ToString(thing).Replace("-", string.Empty);
                outputFile.WriteLine(hexStr);
            }

            numOutputsRecieved += bufData.Length;
            Console.WriteLine("Total FPGA Outputs Recieved = {0}", numOutputsRecieved);
        }
        fpgaComPort.Close();

        timer.Stop();
        Console.WriteLine("Execution Time: {0} ms", timer.ElapsedMilliseconds);

        return;
    }
Esempio n. 54
0
    static int Main()
    {
        //testing the Jacobi dia..

        WriteLine("Part A:");
        WriteLine("i) Test of Jacobi diagonalization with cyclic sweeps:");
        WriteLine("In the file test.txt the implementation is tested for a random sysmetic matrix.");

        var    test = new System.IO.StreamWriter("test.txt");
        int    nm   = 4;                      //matrix size
        matrix A1   = randmatrix_sym(nm, nm); //random matrix

        jac_dia ja = new jac_dia(A1);         //diagonalization

        matrix A = ja.A;
        matrix D = new matrix(A.size1, A.size2);
        vector e = ja.e;

        for (int n = 0; n < A.size1; n++)
        {
            D[n, n] = e[n];
        }
        matrix V    = ja.V;
        matrix vdvt = V * D * V.T;
        matrix vtav = V.T * A1 * V;


        test.WriteLine("Test ofJacobi diagonalization with cyclic sweeps.");
        test.WriteLine($"");
        test.WriteLine("Random symmetric matrix A:");
        for (int n1 = 0; n1 < A.size1; n1++)
        {
            for (int n2 = 0; n2 < A.size1; n2++)
            {
                test.Write($"{A1[n1,n2]}	");
            }
            test.Write("\n \n");
        }


        test.WriteLine("Reduced matrix A:");
        for (int n1 = 0; n1 < A.size1; n1++)
        {
            for (int n2 = 0; n2 < A.size1; n2++)
            {
                test.Write($"{A[n1,n2]}	");
            }
            test.Write("\n \n");
        }
        test.WriteLine("the Diagonal matrix with the corresponding eigenvaluesmatrix D:");
        for (int n1 = 0; n1 < A.size1; n1++)
        {
            for (int n2 = 0; n2 < A.size1; n2++)
            {
                test.Write($"{D[n1,n2]}	");
            }
            test.Write("\n \n");
        }
        test.WriteLine("The orthogonal matrix of eigenvectorsmatrix V:");
        for (int n1 = 0; n1 < A.size1; n1++)
        {
            for (int n2 = 0; n2 < A.size1; n2++)
            {
                test.Write($"{V[n1,n2]}	");
            }
            test.Write("\n \n");
        }
        test.WriteLine("Test VDVT=A... VDVT is given as:");
        for (int n1 = 0; n1 < A.size1; n1++)
        {
            for (int n2 = 0; n2 < A.size1; n2++)
            {
                test.Write($"{vdvt[n1,n2]}	");
            }
            test.Write("\n \n");
        }
        test.WriteLine("Test VTAV=D... VTAV is given as:");
        for (int n1 = 0; n1 < A.size1; n1++)
        {
            for (int n2 = 0; n2 < A.size1; n2++)
            {
                test.Write($"{vtav[n1,n2]}	");
            }
            test.Write("\n");
        }
        test.Close();

        //particle in box:
        //build H
        int    nh = 50;
        double s  = 1.0 / (nh + 1);
        matrix H  = new matrix(nh, nh);

        for (int i = 0; i < nh - 1; i++)
        {
            matrix.set(H, i, i, -2);
            matrix.set(H, i, i + 1, 1);
            matrix.set(H, i + 1, i, 1);
        }        //end for
        matrix.set(H, nh - 1, nh - 1, -2);
        matrix.scale(H, -1 / s / s);

        //diagonalize H

        jac_dia jah = new jac_dia(H);
        //matrix H_dia=jah.A;
        vector eh = jah.e;
        matrix Vh = jah.V;

        WriteLine("ii) Particle in a box.");
        WriteLine("The following is a comparison between the first 5 the caculated and exact energies:");
        WriteLine("Number:	Calculated: 	Exact:");
        //check energies
        for (int n1 = 0; n1 < 5; n1++)
        {
            double exact = Pow(PI * (n1 + 1), 2);
            WriteLine($"{n1}	{eh[n1]}		{exact}");
        }        //end for

        WriteLine("");
        WriteLine("In plotA.svg the 5 lowest eigenfunctions are plotted. The result have same form as the analytic result.");

        var data = new System.IO.StreamWriter("data.txt");


        for (int k = 0; k < (5 + 1); k++)
        {
            data.Write($"{0}  ");
        }        //end for
        data.Write("\n");
        for (int j = 0; j < nh; j++)
        {
            data.Write($"{(j+1.0)/(nh+1)}  ");
            for (int k = 0; k < 5; k++)
            {
                data.Write($"{matrix.get(Vh,j,k)}  ");
            }    //end for
            data.Write("\n");
        }        // end for
        data.Write($"{1} ");
        for (int k = 0; k < (5); k++)
        {
            data.Write($"{0}  ");
        }        //end for
        data.Close();


        return(0);
    }
Esempio n. 55
0
    static void Main(string[] args)
    {
        string corpus_path = "";
        string dict_path   = "";
        string data_folder = "";

        for (int iarg = 0; iarg < args.Length; ++iarg)
        {
            string cmd = args[iarg].Substring(1);
            if (cmd == "corpus")
            {
                corpus_path = args[iarg + 1];
                iarg++;
            }
            else if (cmd == "dict")
            {
                dict_path = args[iarg + 1];
                iarg++;
            }
            else if (cmd == "workdir")
            {
                data_folder = args[iarg + 1];
                iarg++;
            }
            else if (cmd == "window")
            {
                window = int.Parse(args[iarg + 1]);
                iarg++;
            }
            else if (cmd == "emit_shingles")
            {
                emit_shingles = bool.Parse(args[iarg + 1]);
                iarg++;
            }
            else if (cmd == "emit_morphtags")
            {
                emit_morphtags = bool.Parse(args[iarg + 1]);
                iarg++;
            }
            else
            {
                throw new ApplicationException($"Unknown option [{args[iarg]}]");
            }
        }



        string train_path       = System.IO.Path.Combine(data_folder, "chunker_train.dat");
        string test_path        = System.IO.Path.Combine(data_folder, "chunker_test.dat");
        string test_result_path = System.IO.Path.Combine(data_folder, "chunker_eval.txt");

        Console.WriteLine("Loading dictionary from {0}...", dict_path);
        SolarixGrammarEngineNET.GrammarEngine2 gren;
        gren = new SolarixGrammarEngineNET.GrammarEngine2();
        gren.Load(dict_path, true);

        int counter   = 0;
        int MAX_COUNT = 10000000;

        string[] bin_corpora = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(corpus_path), System.IO.Path.GetFileName(corpus_path));

        System.IO.StreamWriter wrt_train = new System.IO.StreamWriter(train_path);
        System.IO.StreamWriter wrt_test  = new System.IO.StreamWriter(test_path);

        foreach (string path1 in bin_corpora)
        {
            Console.WriteLine("Reading corpus {0}...", path1);

            IntPtr hCorpus = SolarixGrammarEngineNET.GrammarEngine.sol_OpenCorpusStorage8(gren.GetEngineHandle(), path1, false);
            if (hCorpus == IntPtr.Zero)
            {
                throw new ApplicationException(string.Format("Can not open corpus {0}", path1));
            }

            while (true)
            {
                IntPtr hSample1 = SolarixGrammarEngineNET.GrammarEngine.sol_LoadSyntaxTree(gren.GetEngineHandle(), hCorpus);
                if (hSample1 == IntPtr.Zero)
                {
                    break;
                }

                IntPtr hSample2 = SolarixGrammarEngineNET.GrammarEngine.sol_LoadSyntaxTree(gren.GetEngineHandle(), hCorpus);
                IntPtr hSample3 = SolarixGrammarEngineNET.GrammarEngine.sol_LoadSyntaxTree(gren.GetEngineHandle(), hCorpus);

                if (counter >= MAX_COUNT)
                {
                    break;
                }

                string sample       = SolarixGrammarEngineNET.GrammarEngine.sol_GetSentenceW(hSample1);
                var    morphology   = new SolarixGrammarEngineNET.AnalysisResults(gren, SolarixGrammarEngineNET.GrammarEngine.sol_GetTreeHandle(hSample1), false);
                var    tokenization = new SolarixGrammarEngineNET.AnalysisResults(gren, SolarixGrammarEngineNET.GrammarEngine.sol_GetTreeHandle(hSample2), false);
                var    syntax_tree  = new SolarixGrammarEngineNET.AnalysisResults(gren, SolarixGrammarEngineNET.GrammarEngine.sol_GetTreeHandle(hSample3), false);

                counter++;
                Console.WriteLine("0.{1}: {0}", sample, counter);

                bool test_sample = false, train_sample = true;
                if ((counter % 10) == 0)
                {
                    test_sample  = true;
                    train_sample = false;
                }

                if (syntax_tree.Count == 3)
                {
                    System.IO.StreamWriter wrt = train_sample ? wrt_train : wrt_test;


                    // Получаем список слов с прикрепленными к ним номерами чанков.
                    Dictionary <int /*word_index*/, int /*chunk_index*/> labels = new Dictionary <int, int>();
                    FindChunks(syntax_tree, labels);

                    // Вставим специальный чанк для фиктивного слова слева от первого, чтобы первое слово
                    // автоматом пометилось как начало чанка.
                    labels[-1] = -1;

                    for (int i = 1; i < morphology.Count - 1; ++i)
                    {
                        int label = 0;

                        int word_index = i - 1;

                        // Если слово начинает новый чанк, то есть слева было слово из другого чанка,
                        // то метка будет 1.
                        try
                        {
                            if (labels[word_index - 1] != labels[word_index])
                            {
                                label = 1;
                            }
                        }
                        catch (KeyNotFoundException ex)
                        {
                            Console.WriteLine("Missing word {0} in syntax tree for sample {1}", morphology[i].GetWord(), sample);
                        }


                        string features = GetFeatures(gren, morphology, i);
                        wrt.WriteLine("{0}\t{1}", label, features);
                    }

                    wrt.WriteLine("");
                    wrt.Flush();
                }

                SolarixGrammarEngineNET.GrammarEngine.sol_FreeSyntaxTree(hSample1);
                SolarixGrammarEngineNET.GrammarEngine.sol_FreeSyntaxTree(hSample2);
                SolarixGrammarEngineNET.GrammarEngine.sol_FreeSyntaxTree(hSample3);
            }

            SolarixGrammarEngineNET.GrammarEngine.sol_CloseCorpusStorage(gren.GetEngineHandle(), hCorpus);
        }

        wrt_train.Close();
        wrt_test.Close();


        // Сохраним информацию о кодировке фич, чтобы потом в C++ коде формировать данные для разбора.
        string codebook_path = System.IO.Path.Combine(data_folder, "chunker.codebook");

        Console.WriteLine("Writing feature codebook to {0}", codebook_path);
        if (System.IO.File.Exists(codebook_path))
        {
            System.IO.File.Delete(codebook_path);
        }

        using (System.IO.BinaryWriter wr = new System.IO.BinaryWriter(System.IO.File.OpenWrite(codebook_path)))
        {
            wr.Write(0);

            wr.Write(window);
            wr.Write(shingle_len);
            wr.Write(emit_shingles);
            wr.Write(emit_morphtags);

            wr.Write(shingle2index.Count);
            foreach (var k in shingle2index)
            {
                byte[] l8 = System.Text.Encoding.UTF8.GetBytes(k.Key);
                wr.Write(l8.Length);
                wr.Write(l8);
                wr.Write(k.Value);
            }
        }


        Console.WriteLine("Start training with CRFSuite on {0}...", train_path);
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.Arguments = train_path + " " + data_folder;
        p.StartInfo.FileName  = string.Format("{0}\\chunker_train.cmd", System.IO.Directory.GetCurrentDirectory());

        Console.WriteLine("Executing {0} {1}", p.StartInfo.FileName, p.StartInfo.Arguments);
        bool r = false;

        r = p.Start();
        p.WaitForExit();

        // Оценка точности
        p = new System.Diagnostics.Process();
        p.StartInfo.Arguments = test_path + " " + test_result_path + " " + data_folder;
        p.StartInfo.FileName  = string.Format("{0}\\chunker_test.cmd", System.IO.Directory.GetCurrentDirectory());

        Console.WriteLine("Executing {0} {1}", p.StartInfo.FileName, p.StartInfo.Arguments);
        r = p.Start();
        p.WaitForExit();

        int nb_instance_errors = 0;
        int nb_word_errors     = 0;
        int nb_instances       = 0;
        int nb_words           = 0;

        using (System.IO.StreamReader rdr = new System.IO.StreamReader(test_result_path))
        {
            bool instance_ok = true;
            while (!rdr.EndOfStream)
            {
                string line = rdr.ReadLine();
                if (line == null)
                {
                    break;
                }

                if (line == "")
                {
                    nb_instances++;
                    if (!instance_ok)
                    {
                        nb_instance_errors++;
                    }

                    instance_ok = true;
                }
                else
                {
                    nb_words++;
                    string[] tx = line.Split('\t');
                    if (tx[0] != tx[1])
                    {
                        instance_ok = false;
                        nb_word_errors++;
                    }
                }
            }
        }

        Console.WriteLine("Per word accuracy={0}", ((float)(nb_words - nb_word_errors)) / nb_words);
        Console.WriteLine("Per instance accuracy={0}", ((float)(nb_instances - nb_instance_errors)) / nb_instances);

        return;
    }
    public int getNextSegment()
    {
        if (numbSegsMade < k_DesiredSegmentCount)
        {
            return(Random.Range(0, m_CurrentThemeData.zones [m_CurrentZone].prefabList.Length));
        }
        int totalExplore = 0;

        for (int i = 0; i < m_CurrentThemeData.zones[m_CurrentZone].prefabList.Length; i++)
        {
            totalExplore += exploreWeights[segmentIDs [segmentIDs.Count - 1], i];
        }

        List <int> possibleIndexs = new List <int>();
        float      bestScore      = -0f;
        List <int> unvisited      = new List <int> ();

        for (int i = 0; i < m_CurrentThemeData.zones[m_CurrentZone].prefabList.Length; i++)
        {
            float score = exploitWeights[segmentIDs [segmentIDs.Count - 1], i] + (Mathf.Sqrt(2) * Mathf.Sqrt(Mathf.Log(totalExplore) / exploreWeights[segmentIDs [segmentIDs.Count - 1], i] + Mathf.Epsilon));
            if (exploreWeights [segmentIDs [segmentIDs.Count - 1], i] == 0)
            {
                unvisited.Add(i);                  //If we have not explored this we want to
            }
            if (score > bestScore)
            {
                bestScore = score;
                possibleIndexs.Clear();
                possibleIndexs.Add(i);
            }
            else if (score == bestScore)
            {
                possibleIndexs.Add(i);
            }
        }

        int nextSegment = unvisited.Count == 0 ? possibleIndexs [Random.Range(0, possibleIndexs.Count)] : unvisited [Random.Range(0, unvisited.Count)];

        //print ("Current segement " + currentSegmentID +  " Best next segment: " + nextSegment + " with score of: " + bestScore);
        string outString = currentGame + "," + (segmentsPassed) + "," + segmentIDs [0] + "," + segmentIDs [segmentIDs.Count - 1] + "," + nextSegment + "," + bestScore + "," + exploitWeights [segmentIDs [segmentIDs.Count - 1], nextSegment] + "," + (Mathf.Sqrt(Mathf.Log(totalExplore) / ((float)exploreWeights[segmentIDs [segmentIDs.Count - 1], nextSegment] + Mathf.Epsilon))) + ",";

        foreach (List <float> emotions in currentSectionEmotionValues)
        {
            float total = 0f;
            foreach (float emotion in emotions)
            {
                total += emotion;
            }
            total     /= emotions.Count;
            outString += total + ",";
        }
        outString += score + "\n";

        if (segmentsPassed != 0)
        {
            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter((summaryDataOut), true)) {
                file.WriteLine(outString);
            }
        }


        if (!isAdaptive)
        {
            return(Random.Range(0, m_CurrentThemeData.zones [m_CurrentZone].prefabList.Length));
        }
        return(nextSegment);       //return a random best index
    }
Esempio n. 57
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (!locker)
            {
                fileName   = "BlockData" + deneme + ".txt";
                folderName = @"C:\Users\admin\Desktop\Blocks";
                System.IO.Directory.CreateDirectory(folderName);
                folderName = System.IO.Path.Combine(folderName, fileName);
                locker     = true;
                deneme++;
            }
            else
            {
                locker = false;
            }
            if (Time.timeScale == 0)
            {
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
            }
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            locker = false;
        }

        if (locker)
        {
            using (System.IO.StreamWriter fs = System.IO.File.AppendText(folderName))
            {
                Vector3 posData  = (temp[0].transform.position);
                Vector3 posData1 = (temp[1].transform.position);

                float anglex = temp[0].transform.localEulerAngles.x;
                anglex = (anglex > 180) ? anglex - 360 : anglex;

                float angley = temp[0].transform.localEulerAngles.y;
                angley = (angley > 180) ? angley - 360 : angley;

                float anglez = temp[0].transform.localEulerAngles.z;
                anglez = (anglez > 180) ? anglez - 360 : anglez;

                float anglex1 = temp[1].transform.localEulerAngles.x;
                anglex1 = (anglex1 > 180) ? anglex1 - 360 : anglex1;

                float angley1 = temp[1].transform.localEulerAngles.y;
                angley1 = (angley1 > 180) ? angley1 - 360 : angley1;

                float anglez1 = temp[1].transform.localEulerAngles.z;
                anglez1 = (anglez > 180) ? anglez1 - 360 : anglez1;

                // fs.WriteLine(posData.x + "," + posData.y + "," + posData.z + "," + anglex + "," + angley + "," + anglez);
                //  fs.WriteLine(posData1.x + "," + posData1.y + "," + posData1.z + "," + anglex1 + "," + angley1 + "," + anglez1 + "," + "1");



                if (write == 1)
                {
                    fs.WriteLine(posData.x + "," + posData.y + "," + posData.z + "," + anglex + "," + angley + "," + anglez);
                    write = 2;
                }

                if (write == 2)
                {
                    fs.Write(posData.x + "," + posData.y + "," + posData.z + "," + anglex + "," + angley + "," + anglez + ",");
                    write = 1;
                }

                if (write == 3)
                {
                    fs.WriteLine("X,Y,Z,Rotx,Roty,Rotz," + "preX,preY,preZ,preRotx,preRoty,preRotz");
                    fs.Write(posData.x + "," + posData.y + "," + posData.z + "," + anglex + "," + angley + "," + anglez + ",");
                }

                write = 1;
            }
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            locker = false;
            for (int i = 0; i < startCount; i++)
            {
                Destroy(temp[i]);
            }
            count = startCount;
            temp.Clear();
            pos.y = 1;
            RandomCreater();
            Spawn();
        }
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow))
        {
            keysPressed [1]++;
        }
        //Update the full frame by frame emotion values
        for (int i = 0; i < 9; i++)
        {
            if (emotionListener.currentEmotions.ContainsKey((Emotions)i))
            {
                currentSectionEmotionValues [i].Add(emotionListener.currentEmotions [(Emotions)i]);
            }
            else
            {
                currentSectionEmotionValues [i].Add(-1);
            }
        }

        int    currentSeg = segmentIDs.Count > 0 ? segmentIDs [0] : -1;
        string outString  = currentGame + "," + (segmentsPassed + 1) + "," + currentSeg + ",";

        foreach (var emotion in emotionListener.currentEmotions)
        {
            outString += emotion.Value + ",";
        }
        outString += "\n";

        using (System.IO.StreamWriter file =
                   new System.IO.StreamWriter((allDataOut), true)) {
            file.WriteLine(outString);
        }

        while (m_Segments.Count < k_DesiredSegmentCount)
        {
            SpawnNewSegment();
        }

        if (parallaxRoot != null && currentTheme.cloudPrefabs.Length > 0)
        {
            while (parallaxRoot.childCount < currentTheme.cloudNumber)
            {
                float lastZ = parallaxRoot.childCount == 0 ? 0 : parallaxRoot.GetChild(parallaxRoot.childCount - 1).position.z + currentTheme.cloudMinimumDistance.z;

                GameObject obj = Instantiate(currentTheme.cloudPrefabs[Random.Range(0, currentTheme.cloudPrefabs.Length)]);
                obj.transform.SetParent(parallaxRoot, false);

                obj.transform.localPosition =
                    Vector3.up * (currentTheme.cloudMinimumDistance.y + (Random.value - 0.5f) * currentTheme.cloudSpread.y)
                    + Vector3.forward * (lastZ + (Random.value - 0.5f) * currentTheme.cloudSpread.z)
                    + Vector3.right * (currentTheme.cloudMinimumDistance.x + (Random.value - 0.5f) * currentTheme.cloudSpread.x);

                obj.transform.localScale    = obj.transform.localScale * (1.0f + (Random.value - 0.5f) * 0.5f);
                obj.transform.localRotation = Quaternion.AngleAxis(Random.value * 360.0f, Vector3.up);
            }
        }

        if (!m_IsMoving)
        {
            return;
        }

        float scaledSpeed = m_Speed * Time.deltaTime;

        m_ScoreAccum          += scaledSpeed;
        m_CurrentZoneDistance += scaledSpeed;

        int intScore = Mathf.FloorToInt(m_ScoreAccum);

        if (intScore != 0)
        {
            AddScore(intScore);
        }
        m_ScoreAccum -= intScore;

        m_TotalWorldDistance     += scaledSpeed;
        m_CurrentSegmentDistance += scaledSpeed;

        if (m_CurrentSegmentDistance > m_Segments[0].worldLength)
        {
            m_CurrentSegmentDistance -= m_Segments[0].worldLength;
            segmentsPassed++;
            // m_PastSegments are segment we already passed, we keep them to move them and destroy them later
            // but they aren't part of the game anymore

            updateExploitScoreForSegement();

            sectionStartCoinScore = characterController.coins;


            m_PreviousSegment = segmentIDs[0];
            segmentIDs.RemoveAt(0);

            keysPressed [0] = keysPressed [1];
            keysPressed [1] = 0;
            m_PastSegments.Add(m_Segments[0]);


            m_Segments.RemoveAt(0);
        }

        Vector3    currentPos;
        Quaternion currentRot;
        Transform  characterTransform = characterController.transform;

        m_Segments[0].GetPointAtInWorldUnit(m_CurrentSegmentDistance, out currentPos, out currentRot);


        // Floating origin implementation
        // Move the whole world back to 0,0,0 when we get too far away.
        bool needRecenter = currentPos.sqrMagnitude > k_FloatingOriginThreshold;

        // Parallax Handling
        if (parallaxRoot != null)
        {
            Vector3 difference = (currentPos - characterTransform.position) * parallaxRatio;;
            int     count      = parallaxRoot.childCount;
            for (int i = 0; i < count; i++)
            {
                Transform cloud = parallaxRoot.GetChild(i);
                cloud.position += difference - (needRecenter ? currentPos : Vector3.zero);
            }
        }

        if (needRecenter)
        {
            int count = m_Segments.Count;
            for (int i = 0; i < count; i++)
            {
                m_Segments[i].transform.position -= currentPos;
            }

            count = m_PastSegments.Count;
            for (int i = 0; i < count; i++)
            {
                m_PastSegments[i].transform.position -= currentPos;
            }

            // Recalculate current world position based on the moved world
            m_Segments[0].GetPointAtInWorldUnit(m_CurrentSegmentDistance, out currentPos, out currentRot);
        }

        characterTransform.rotation = currentRot;
        characterTransform.position = currentPos;

        if (parallaxRoot != null && currentTheme.cloudPrefabs.Length > 0)
        {
            for (int i = 0; i < parallaxRoot.childCount; ++i)
            {
                Transform child = parallaxRoot.GetChild(i);

                // Destroy unneeded clouds
                if ((child.localPosition - currentPos).z < -50)
                {
                    Destroy(child.gameObject);
                }
            }
        }

        // Still move past segment until they aren't visible anymore.
        for (int i = 0; i < m_PastSegments.Count; ++i)
        {
            if ((m_PastSegments[i].transform.position - currentPos).z < k_SegmentRemovalDistance)
            {
                m_PastSegments[i].Cleanup();
                m_PastSegments.RemoveAt(i);
                i--;
            }
        }

        PowerupSpawnUpdate();

        if (m_Speed < maxSpeed)
        {
            m_Speed += k_Acceleration * Time.deltaTime;
        }
        else
        {
            m_Speed = maxSpeed;
        }

        m_Multiplier = 1 + Mathf.FloorToInt((m_Speed - minSpeed) / (maxSpeed - minSpeed) * speedStep);

        if (modifyMultiply != null)
        {
            foreach (MultiplierModifier part in modifyMultiply.GetInvocationList())
            {
                m_Multiplier = part(m_Multiplier);
            }
        }

        MusicPlayer.instance.UpdateVolumes(speedRatio);
    }
Esempio n. 59
0
    static void Main()
    {
        WriteLine("\n----------------------------------------------------------------");

        WriteLine("\nProblem 7B\n");

        // starting and end points
        double ra = 0.001; double rb = 20;
        vector fa = new vector(ra - ra * ra, 1 - 2 * ra); // starting f and f' conditions
        vector fb = new vector(0, Double.NaN);            // expected result at f(b), f'(b) is unknown

        // ODE conditions
        double h = 1e-3; double oeps = 1e-6; double oacc = 1e-6;

        // Auxiliary function to rootf on
        Func <vector, vector> M = delegate(vector epsilon)
        {        // energy epsilon
            Func <double, vector, vector> seq = makeSEQ(epsilon[0]);
            (List <double> xvals, List <vector> yvals) = ode.rk45(seq, ra, fa, rb, h: h);
            vector Fb = yvals[yvals.Count - 1];
            return(new vector(Fb[0] - fb[0]));
        };

        // Shooting method by root finding of M(epsilon)
        vector x0               = new vector(-0.47);
        double racc             = 1e-3;
        vector groot            = rootf.newton(M, x0, eps: racc);
        double energy           = groot[0];

        // Write results
        WriteLine($"Shooting method of hydrogen SEQ ODE by rootfinding of auxiliary func M");
        WriteLine($"Initial ODE step:                   	{h}");
        WriteLine($"ODE accuracy goal:			{oacc}");
        WriteLine($"ODE relative accuracy goal:		{oeps}");
        WriteLine($"ODE starting x:				{ra}");
        WriteLine($"ODE end x:				{rb}");
        WriteLine($"rootf started at epsilon:		{x0[0]}");
        WriteLine($"rootf accuracy goal:			{racc}");
        WriteLine($"Found root of M(epsilon):           	{energy}");
        WriteLine($"Value of M at root:		        {M(groot)[0]}");
        WriteLine($"Analytical root:			{-0.5}");
        WriteLine($"Deviation from analytical result:	{-0.5-energy}");

        // Solve differential equation with found solution and export
        Func <double, vector, vector> seq_sol = makeSEQ(energy);

        (List <double> rvals, List <vector> fvals) = ode.rk45(seq_sol, ra, fa, rb, h: h);

        var writer = new System.IO.StreamWriter("out.func.txt");

        for (int i = 0; i < rvals.Count; i++)
        {
            if (rvals[i] > 8)
            {
                break;
            }
            writer.WriteLine($"{rvals[i]} {fvals[i][0]} {fvals[i][1]}");
        }

        // Write analytical solution
        writer.Write("\n\n");
        for (double r = 0; r <= 8; r += 0.05)
        {
            writer.WriteLine($"{r} {r*Exp(-r)}");
        }
        writer.Close();

        WriteLine($"\n\nSee PlotB.svg for plot of solution and analytical function");
        WriteLine("\n----------------------------------------------------------------\n");
    }
Esempio n. 60
0
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        int     CouplePackage = Convert.ToInt16(ddl_CouplePackage.SelectedValue);
        int     SinglePackage = Convert.ToInt16(ddl_SinglePackage.SelectedValue);
        int     TeensPackage  = Convert.ToInt16(ddl_TeensPackage.SelectedValue);
        int     KidsPackage   = Convert.ToInt16(ddl_KidsPackage.SelectedValue);
        decimal CoupleAmount  = Convert.ToDecimal(CouplePackage * Convert.ToInt32(pricecouple.Text));
        decimal SingleAmount  = Convert.ToDecimal(SinglePackage * Convert.ToInt32(pricesingle.Text));
        decimal TeensAmount   = Convert.ToDecimal(TeensPackage * Convert.ToInt32(priceteen.Text));
        decimal KidsAmount    = Convert.ToDecimal(KidsPackage * Convert.ToInt32(pricekids.Text));
        decimal TotalAmount   = CoupleAmount + SingleAmount + TeensAmount + KidsAmount;
        //Session["Quantity"] = Quantity;
        //string[] arrCat = Package.Split(',');
        //Session["Package"] = arrCat[0];
        // decimal TotalAmount = Convert.ToDecimal(Quantity) * Convert.ToDecimal(arrCat[1]);
        //Session["CouplePackage"] = CouplePackage;
        //Session["SinglePackage"] = SinglePackage;
        //Session["TeensPackage"] = TeensPackage;
        //Session["KidsPackage"] = KidsPackage;
        //Session["TotalAmount"] = TotalAmount;
        //Session["Name"] = txtName.Text;
        //Session["Email"] = txtEmail.Text;
        //Session["ContactNo"] = txtContact.Text;
        DateTime DateofBooking = DateTime.Now.Date;
        string   ISDCode       = "91";
        // string BookingId = "KODNY00000"; //for the First TIme
        TransactionRecord tr = new TransactionRecord();

        tr.NYBookingID = GTICKBOL.NewYearBooking_Max();
        //Session["BookingID"] = tr.NYBookingID;
        //tr.QntyCouple = Convert.ToInt16(Session["CouplePackage"]);
        //tr.QntySingle = Convert.ToInt16(Session["SinglePackage"]);
        //tr.QntyTeens = Convert.ToInt16(Session["TeensPackage"]);
        //tr.QntyKids = Convert.ToInt16(Session["KidsPackage"]);
        //tr.NYTotalAmount = Convert.ToDecimal(Session["TotalAmount"].ToString());
        tr.QntyCouple    = Convert.ToInt16(CouplePackage);
        tr.QntySingle    = Convert.ToInt16(SinglePackage);
        tr.QntyTeens     = Convert.ToInt16(TeensPackage);
        tr.QntyKids      = Convert.ToInt16(KidsPackage);
        tr.NYTotalAmount = Convert.ToDecimal(TotalAmount.ToString());

        string nybookingid = MaxBookingId(tr.NYBookingID.ToString());

        tr.NYBookingID = nybookingid;

        //GTICKV.LogEntry(Session["BookingID"].ToString(), "Sending to HDFC Payment Gateway", "8");
        //GTICKBOL.NewYearBooking_Details(Convert.ToInt16(CouplePackage), Convert.ToInt16(SinglePackage), Convert.ToInt16(TeensPackage), Convert.ToInt16(KidsPackage), Convert.ToDecimal(TotalAmount.ToString()), DateofBooking, tr.NYBookingID.ToString(), txtName.Text, txtEmail.Text, txtContact.Text, false, "");
        GTICKBOL.NewYearBooking_Details(Convert.ToInt16(CouplePackage), Convert.ToInt16(SinglePackage), Convert.ToInt16(TeensPackage), Convert.ToInt16(KidsPackage), Convert.ToDecimal(TotalAmount.ToString()), DateofBooking, tr.NYBookingID.ToString(), txtName.Text, txtEmail.Text, txtContact.Text, false, "", textroyalinfo.Text);

        //Payment Gateway Flow

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(tr.NYBookingID.ToString() + "Sending to HDFC Payment Gateway");
        //GTICKV.LogEntry(tr.NYBookingID.ToString(), "Sending to HDFC Payment Gateway", "8", "");
        string trackId, amount;
        string URL = "";

        trackId = tr.NYBookingID;
        // Session["trackId"] = trackId;
        amount = TotalAmount.ToString();
        // Session["amount"] = amount;

        String ErrorUrl    = KoDTicketingIPAddress + "NewYearPackages/HDFC/Error.aspx";
        String ResponseUrl = KoDTicketingIPAddress + "NewYearPackages/HDFC/ReturnReceipt.aspx";

        //string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + Server.UrlEncode(amount)
        //    + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
        //    + "&trackid=" + trackId
        //    + "&udf1=TicketBooking&udf2=" + Server.UrlEncode(txtEmailAddress.Text.Trim())
        //    + "&udf3=" + Server.UrlEncode(txtISDCode.Text + txtContactNo.Text) + "&udf4=" + Server.UrlEncode(txtAddress.Text.Trim()) + "&udf5=" + tr.BookingID;

        string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + amount
                        + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                        + "&trackid=" + trackId
                        + "&udf1=TicketBooking&udf2=" + txtEmail.Text.Trim()
                        + "&udf3=" + Server.UrlEncode(ISDCode.ToString().TrimStart('+') + txtContact.Text) + "&udf4=" + Server.UrlEncode(txtName.Text.Trim()) + "&udf5=" + tr.BookingID.ToString();

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Preparing for HDFC Payment..." + qrystr);

        //Writefile_new("\n***************Initial Request********************", Server.MapPath("~"));
        //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + qrystr, Server.MapPath("~"));

        System.IO.StreamWriter requestWriter = null;
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Redirecting for HDFC Payment..." + HDFCTransUrl);
        System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HDFCTransUrl);   //create a SSL connection object server-to-server
        objRequest.Method          = "POST";
        objRequest.ContentLength   = qrystr.Length;
        objRequest.ContentType     = "application/x-www-form-urlencoded";
        objRequest.CookieContainer = new System.Net.CookieContainer();
        try
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Processing request for HDFC Payment...");
            requestWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());  // here the request is sent to payment gateway
            requestWriter.Write(qrystr);
        }
        catch (Exception ex)
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Excetion while processing HDFC payment: " + trackId + ex.Message);
        }

        if (requestWriter != null)
        {
            requestWriter.Close();
        }

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Review validation response from HDFC Payment Gateway...");
        System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

        //System.Net.CookieContainer responseCookiesContainer = new System.Net.CookieContainer();
        //foreach (System.Net.Cookie cook in objResponse.Cookies)
        //{
        //    responseCookiesContainer.Add(cook);
        //}

        using (System.IO.StreamReader sr =
                   new System.IO.StreamReader(objResponse.GetResponseStream()))
        {
            String NSDLval = sr.ReadToEnd();
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Response: " + NSDLval);
            if (NSDLval.Contains("Invalid User Defined Field"))
            {
                lblMess.Text = "The information submitted contains some invalid character, please avoid using [+,-,#] etc.";
                return;
            }

            //Writefile_new("\n***************Initial Response********************", Server.MapPath("~"));
            //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + NSDLval, Server.MapPath("~"));
            if (NSDLval.IndexOf("http") == -1)
            {
                lblMess.Text = "Payment cannot be processed with information provided.";
                return;
            }

            // gb.HDFCLog(transid.ToString(), "", trackId, "***Initial Response*** : " + NSDLval);
            string strPmtId  = NSDLval.Substring(0, NSDLval.IndexOf(":http"));  // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
            string strPmtUrl = NSDLval.Substring(NSDLval.IndexOf("http"));
            if (strPmtId != String.Empty && strPmtUrl != String.Empty)
            {
                URL = strPmtUrl.ToString() + "?PaymentID=" + strPmtId;
            }
            else
            {
                lblMess.Text = "Invalid Response!";
            }
            sr.Close();
        }
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Payment Redirection: " + URL);
        Response.Redirect(URL, false);
    }