Exemplo n.º 1
0
    // Use this for initialization
    void Start()
    {
        credits = new List<string>();
        positionRect = new List<Rect>();

        // Create reader & open file
        try{
            tr = new StreamReader(path);
            string temp;
            int count = 0;
            while((temp = tr.ReadLine()) != null)
            {
                credits.Add(temp);
                positionRect.Add(new Rect(Screen.width/4 - Screen.width/8, (float)(Screen.height * 0.07 * count + Screen.height), (float)(Screen.width/2 + Screen.width/4), (float)(Screen.height * 0.5)));
                count++;
            }

            // Close the stream
            tr.Close();
        }
        catch(FileLoadException e) {
            Debug.LogException(e);
            credits.Add("Error while loading credits file.");
        }
    }
Exemplo n.º 2
0
        public override void Close()
        {
            atEof = true;

            endRead = startRead;

            reader?.Close();
        }
Exemplo n.º 3
0
 public void Dispose()
 {
     if (!closeStream)
     {
         return;
     }
     textReader?.Close();
     textReader?.Dispose();
 }
Exemplo n.º 4
0
 public override void Close()
 {
     if (_closeSource)
     {
         _source?.Close();
         _source?.Dispose();
     }
     _source = null;
     base.Close();
 }
Exemplo n.º 5
0
        private void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            reader?.Close();
            reader?.Dispose();
            reader = null;
        }
Exemplo n.º 6
0
 public static void CloseFileStreamers(params object[] streams)
 {
     foreach (object item in streams)
     {
         Stream     s  = null;
         TextWriter sw = null;
         TextReader sr = null;
         if ((s = item as Stream) is Stream ||
             (sw = item as TextWriter) is TextWriter ||
             (sr = item as TextReader) is TextReader)
         {
             s?.Close();
             sw?.Close();
             sr?.Close();
         }
     }
 }
Exemplo n.º 7
0
        //po załadowaniu bloków jezeli wczesniej jakiś zaznaczylismy załadowane bloki czasami są zaznaczone (czesto)
        private void OpenFile()
        {
            OpenFileDialog openfile = new OpenFileDialog();

            openfile.FileName = ".xml";
            openfile.Filter   = "XML (*.xml)|*.xml";
            if (openfile.ShowDialog() == DialogResult.OK)
            {
                ActualFilePath = openfile.FileName;
                TextReader reader = null;
                try
                {
                    openfile.FileName = openfile.FileName.Substring(0, openfile.FileName.Count() - 3) + "hab";
                    if (openfile.CheckFileExists)
                    {
                        reader?.Close();
                        var serializer = new XmlSerializer(typeof(ListCanvasBlocks));
                        reader         = new StreamReader(openfile.FileName);
                        Canvas.CanvObj = (ListCanvasBlocks)serializer.Deserialize(reader);
                        canvas1?.Invalidate();
                    }
                    else
                    {
                        MessageBox.Show("Plik przechowujący informacje o blokach nie został znaleziony");
                    }
                    openfile.FileName = openfile.FileName.Substring(0, openfile.FileName.Count() - 3) + "hal";
                    if (openfile.CheckFileExists)
                    {
                        reader?.Close();
                        var serializer = new XmlSerializer(typeof(ListCanvasLines));
                        reader           = new StreamReader(openfile.FileName);
                        Canvas.CanvLines = (ListCanvasLines)serializer.Deserialize(reader);
                        canvas1?.Invalidate();
                    }
                    else
                    {
                        MessageBox.Show("Plik przechowujący połączenia bloków nie został znaleziony");
                    }
                }
                finally
                {
                    reader?.Close();
                }
            }
        }
Exemplo n.º 8
0
        public static bool IsFileInUse(this string file)
        {
            TextReader textReader = null;

            try
            { textReader = File.OpenText(file); }
            catch (FileNotFoundException fileNotFoundException)
            { return(false); }
            catch (IOException ioException)
            { return(true); }
            catch (Exception exception)
            {
                LogWriter.LogError($"Unable to determine if '{Path.GetFileName(file)}' is in use.");
                throw exception;
            }
            finally
            { textReader?.Close(); }
            return(false);
        }
        /// <summary>
        /// Load an instance of <see typeref="T" />.
        /// </summary>
        /// <typeparam name="T">The type to load</typeparam>
        /// <param name="func">Function to provide a <see cref="StreamReader" /></param>
        /// <returns>Instance of T.</returns>
        public static T LoadXmlDocument <T>(Func <TextReader> func)
        {
            var        serializer = new XmlSerializer(typeof(T));
            TextReader reader     = null;

            try
            {
                reader = func();
                return((T)serializer.Deserialize(reader));
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw;
            }
            finally
            {
                reader?.Close();
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Call this method to perform the actual generation 
        /// </summary>
        public void Generate(TextReader readerTemplateStream, TextWriter writerStream, bool keepLegacyExceptions)
        {
            _zwFrameCollectionMacroCounter = 0;
            Sr = readerTemplateStream;
            Sw = writerStream;
            try
            {
                string line;
                string controlField = null;
                while ((line = Sr.ReadLine()) != null)
                {
                    if (LineIsComment(line))
                    {
                    }
                    else if (LineHasControlField(ref controlField, line))
                    {
                        switch (controlField)
                        {
                            case "GENERATING_INFO":
                                Generate_Info();
                                break;
                            case "GENERATING_VERSION":
                                Generate_Version(Version);
                                break;
                            case "FRAME_MACRO_EX":
                                {
                                    for (int i = 0; i < _zwFrameCollectionMacroCounter; i++)
                                    {
                                        Sw.WriteLine("ZW_FRAME_COLLECTION_MACRO" + i);
                                    }
                                }
                                break;
                            case "FRAME_MACRO":
                                {
                                    IList<string> frameLines = Generate_Frame_Macro();

                                    for (int i = 0; i < frameLines.Count; i++)
                                    {
                                        if (i % 400 == 0)
                                        {
                                            Sw.WriteLine("");
                                            Sw.WriteLine(@"#define ZW_FRAME_COLLECTION_MACRO" +
                                                         _zwFrameCollectionMacroCounter + @"\");
                                            if (_zwFrameCollectionMacroCounter == 0)
                                                Sw.WriteLine(
                                                    @"   ZW_COMMON_FRAME                                       ZW_Common;\");

                                            _zwFrameCollectionMacroCounter++;
                                        }
                                        //if (((i + 1) % 400) == 0)
                                        //{
                                        //    sw.WriteLine(frameLines[i].Replace(@";\", ";"));
                                        //}
                                        //else
                                        //{
                                        Sw.WriteLine(frameLines[i]);
                                        //}
                                    }
                                }
                                break;
                            case "BASIC_DEVICE_DEF":
                                Generate_Defines(BasicDeviceList);
                                break;
                            case "GEN_SPEC_DEVICE_DEF":
                                Generate_SpecificDevice();
                                break;
                            case "COMMAND_CLASS_DEF":
                                Generate_Defines(CommandClassList);
                                break;
                            case "COMMAND_DEF":
                                Generate_Command_Def(keepLegacyExceptions);
                                break;
                            case "COMMAND_STRUCTS":
                                Generate_Command_Structs();
                                break;
                        }
                    }
                    else
                    {
                        Sw.WriteLine(line);
                    }
                }
                Sr.Close();
                Sw.Close();
            }
            catch (IOException)
            {
                try
                {
                    Sr.Close();
                }
                catch (IOException)
                {
                }
                try
                {
                    Sw.Close();
                }
                catch (IOException)
                {
                }
                throw;
            }
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            /////////////////////////////////////// Looking for a file  ///////////////////////////////////////
            int m = 0, n;

            //Learning the value of m(Number of training examples) and n(number of atributes)
            using (TextReader reader = File.OpenText("C:/Users/larissa/Desktop/ex2data2.txt"))
            {
                string   linha = reader.ReadLine();
                string[] temp  = linha.Split(',');
                n = temp.Length - 1;
                while (linha != null)
                {
                    m++;
                    linha = reader.ReadLine();
                }
                reader.Close();
            }

            double[,] X     = new double[m, n + 1];
            double[,] y     = new double[m, 1];
            double[,] theta = new double[n + 1, 1];

            //filling out the matrix X, the vector y, and the vector theta
            using (TextReader reader = File.OpenText("C:/Users/larissa/Desktop/ex2data2.txt"))
            {
                int    i     = 0;
                string linha = reader.ReadLine();
                while (linha != null)
                {
                    string[] temp = linha.Split(',');
                    X[i, 0] = 1;
                    for (int j = 1; j < n + 1; j++)
                    {
                        //Console.Write(temp[j - 1]);
                        X[i, j] = Convert.ToDouble(temp[j - 1]);
                    }
                    y[i, 0] = Convert.ToDouble(temp[n]);
                    linha   = reader.ReadLine();
                    i++;
                }
                reader.Close();
            }
            for (int i = 0; i < n + 1; i++)
            {
                theta[i, 0] = 0;
            }


            ////////////////////////////////////////////// PRINT ////////////////////////////////////////////////
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n + 1; j++)
                {
                    Console.Write("X[{0}][{1}] = {2} ", i, j, X[i, j]);
                }
                Console.Write("\n");
            }

            for (int i = 0; i < m; i++)
            {
                Console.Write("y[{0}] = {1}\n", i, y[i, 0]);
            }

            for (int i = 0; i < n + 1; i++)
            {
                Console.Write("theta[{0}] = {1}\n", i, theta[i, 0]);
            }

            Console.ReadLine();


            ////////////////////////////////////////////Matlab calculations/////////////////////////////////////////////

            // Create the MATLAB instance
            MLApp.MLApp matlab = new MLApp.MLApp();


            // Change to the directory where the function is located
            matlab.Execute(@"cd C:\Users\larissa\Desktop");

            // Define the output
            object result      = null;

            // Call the MATLAB function myfunc
            matlab.Execute("clear all");
            double lambda = 1;

            matlab.Feval("costFunctionReg", 2, out result, theta, X, y, lambda);

            // Display result [cost, grad] = costFunctionReg(initial_theta, X, y, lambda);
            object[] res = result as object[];


            Console.WriteLine("Computing the cost J = " + res[0]);
            // Closing the matblab window
            //matlab.Quit();
            // Wait until fisnih
            Console.ReadLine();
        }
Exemplo n.º 12
0
 public override void Close()
 {
     _baseReader.Close();
 }
Exemplo n.º 13
0
        /// <summary>
        /// Add Localization messages from the specified TextReader
        /// (which hopefully points at a .po file)
        /// Doesn't initialize the collection, so it can be called from
        /// a loop if needed.
        /// </summary>
        /// <param name="reader"></param>
        public void LoadFromReader(TextReader reader)
        {
            Regex re = new Regex(@"""(.*)""", RegexOptions.Compiled);

            string  line;
            bool    parsingMsgID = true;
            Message message      = new Message();

            while (null != (line = reader.ReadLine()))
            {
                if (String.IsNullOrEmpty(line))
                {
                    // new message block
                    if (message.MsgID != "")
                    {
                        if (!Messages.ContainsKey(message.MsgID))
                        {
                            Messages.Add(message.MsgID, message);
                        }
                        if (!MessagesByAutoID.ContainsKey(message.AutoID))
                        {
                            MessagesByAutoID.Add(message.AutoID, message);
                        }
                    }
                    message = new Message();
                    continue;
                }
                if (line.StartsWith("#:") && LoadComments)
                {
                    // context
                    message.Contexts.Add(line.Replace("#: ", ""));
                }
                if (line.StartsWith("#") && LoadComments)
                {
                    // comment
                    message.Comments.Add(line);
                    continue;
                }
                if (line.StartsWith("msgid"))
                {
                    // text we find from here out is part of the MessageID
                    parsingMsgID = true;
                }
                else if (line.StartsWith("msgstr"))
                {
                    // text we find from here on out is part of the Message String
                    parsingMsgID = false;
                }

                Match m = re.Match(line);
                if (m.Success)
                {
                    string token = m.Groups[1].Value;

                    if (parsingMsgID)
                    {
                        message.MsgID += token;
                    }
                    else
                    {
                        if (!line.StartsWith("msgstr"))
                        {
                            message.MsgStr += Environment.NewLine;
                        }
                        message.MsgStr += token;
                    }
                }
            }

            // put away the last one
            if (message.MsgID != "")
            {
                Messages.Add(message.MsgID, message);
            }

            reader.Close();
        }
 public override void Close()
 {
     _reader.Close();
 }
Exemplo n.º 15
0
        /// <summary>
        /// Laad het bestand uit de reader in. Noteer voor functies in welk bestand ze zaten.
        /// Let op niet nog een keer hetzelfde bestand te gaan laden. Voor je het weet zit je in een loop.
        /// En een loop mag niet.
        /// Een includefile mag geen code opleveren. Alleen: lege regels, regels met commentaar, en regels met alleen een enkele '@'
        /// </summary>
        /// <param name="filename">Naam van de file die we nu doen</param>
        /// <param name="reader">De textlezer</param>
        /// <param name="loadedfiles">Lijst files die we al gehad hebben, inclusief de 'filename'</param>
        /// <param name="functioninfo">Lijst te vullen functies</param>
        /// <param name="includefile">Als deze true is gaat het om een includefile</param>
        /// <param name="conceptname">Als geen includefile, dan is conceptname gevuld met de naam van het type waarvoor gegenereerd is.
        /// De file zelf kan hergebruikt worden in principe meerdere concepten, mits ze gelijke gegevens gebruiken natuurlijk</param>
        /// <returns>De programmacode die niet in functies zat, elke regel voorafgegaan door het regelnummer</returns>
        private StringCollection LoadSourceFromReader(String filename, TextReader reader, StringCollection loadedfiles, Hashtable functioninfo, bool includefile, string conceptname)
        {
            StringCollection sc = new StringCollection();
            int    linenr       = 1;                      //linenr update
            string s            = reader.ReadLine();

            while (s != null)
            {
                if (s.TrimStart().StartsWith("@"))
                {
                    string sLineTrim = s.TrimStart().Substring(1).TrimStart();
                    if (sLineTrim.StartsWith("Function "))
                    {
                        SourceCodeContext fncontext = new SourceCodeContext(conceptname, filename, linenr++);
                        FunctionInfo      fi        = new FunctionInfo(fncontext, s);
                        s = reader.ReadLine();
                        while (s != null) // of bij EndFunction eruit gebroken...
                        {
                            sLineTrim = s.TrimStart();
                            if (sLineTrim.StartsWith("@"))
                            {
                                sLineTrim = sLineTrim.Substring(1).TrimStart() + " ";
                                if (sLineTrim.StartsWith("EndFunction "))
                                {
                                    linenr++;
                                    break;
                                }
                            }
                            fi.Add(linenr++.ToString() + ":" + s);
                            s = reader.ReadLine();
                        }
                        if (s == null)
                        {
                            throw new EndFunctionMissingException(fncontext, fi.Name);
                        }
                        if (functioninfo.Contains(fi.Name))
                        {
                            FunctionInfo otherone = functioninfo[fi.Name] as FunctionInfo;
                            throw new DuplicateFunctionDefinitionException(fncontext, fi.Name, otherone.DeclaredAt);
                        }
                        functioninfo.Add(fi.Name, fi);
                        s = reader.ReadLine();
                        continue;
                    }
                    if (sLineTrim.StartsWith("Include "))
                    {
                        // Verzamel eerst de handel in het aangegeven bestand.
                        // Merge de resultaten met de functioninfo van 'ons'.(check dat er geen dubbele functies in zitten.
                        // En ga verder met de rest.
                        String includefilename = sLineTrim.Substring(8).Trim();
                        if (loadedfiles.Contains(includefilename))
                        {
                            throw new IncludeFileLoopException(new SourceCodeContext(conceptname, filename, linenr), includefilename);
                        }

                        String includefilepath = TemplateUtil.Instance().CombineAndCompact(Path.GetDirectoryName(filename), includefilename);
                        if (!File.Exists(includefilepath))
                        {
                            throw new IncludeFileNotFoundException(new SourceCodeContext(conceptname, filename, linenr), includefilepath);
                        }

                        TextReader r = new StreamReader(includefilepath);
                        loadedfiles.Add(includefilename);
                        StringCollection files = new StringCollection();
                        foreach (string s1 in loadedfiles)
                        {
                            files.Add(s1);
                        }
                        Hashtable includedfncs = new Hashtable();
                        LoadSourceFromReader(includefilename, r, files, includedfncs, true, "");
                        // Neem nu de gelezen functies over in onze eigen lijst, check op dubbelen.
                        foreach (FunctionInfo fi in includedfncs.Values)
                        {
                            if (functioninfo.ContainsKey(fi.Name))
                            {
                                FunctionInfo otherone = functioninfo[fi.Name] as FunctionInfo;
                                throw new DuplicateFunctionDefinitionException(fi.DeclaredAt, fi.Name, otherone.DeclaredAt);
                            }
                            functioninfo.Add(fi.Name, fi);
                        }
                        //.. en alweer klaar.
                        linenr++;
                        s = reader.ReadLine();
                        continue;
                    }
                    if (sLineTrim.StartsWith("--") || sLineTrim == "")
                    {
                        linenr++;
                        s = reader.ReadLine();
                        continue;
                    }
                }
                if (includefile)
                {
                    if (s.Trim() != "")
                    {
                        throw new IncludeFilesCanOnlyContainFunctionsException(new SourceCodeContext(conceptname, filename, linenr));
                    }
                }

                sc.Add(linenr.ToString() + ":" + s);
                s = reader.ReadLine();
                linenr++;
            }
            reader.Close();
            return(sc);
        }
Exemplo n.º 16
0
        ///**
        // * Skips characters.
        // *
        // * @exception  IOException  If an I/O error occurs
        // */

        //public long Skip(long n) {
        //    return inp.Skip(n);
        //}

        ///**
        // * Tells whether this stream is ready to be read.
        // *
        // * @exception  IOException  If an I/O error occurs
        // */

        //public bool Ready() {
        //    return inp.Ready();
        //}

        ///**
        // * Tells whether this stream supports the Mark() operation.
        // */

        //public bool MarkSupported() {
        //    return inp.MarkSupported();
        //}

        ///**
        // * Marks the present position inp the stream.
        // *
        // * @exception  IOException  If an I/O error occurs
        // */

        //public void Mark(int readAheadLimit) {
        //    inp.Mark(readAheadLimit);
        //}

        ///**
        // * Resets the stream.
        // *
        // * @exception  IOException  If an I/O error occurs
        // */

        //public void Reset() {
        //    inp.Reset();
        //}

        override public void Close()
        {
            inp.Close();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Load the settings from local file
        /// </summary>
        public bool LoadSettings()
        {
            bool oldAutoSave = AutoSave;

            AutoSave = false;
            try
            {
                if (string.IsNullOrEmpty(SettingsFile))
                {
                    return(false);
                }

                using (TextReader reader = File.OpenText(SettingsFile))
                {
                    string       currentGroupId = string.Empty;
                    SettingGroup currentGroup   = null;
                    string       buffer;
                    while ((buffer = reader.ReadLine()) != null)
                    {
                        buffer = buffer.Trim();
                        if (string.IsNullOrEmpty(buffer) || buffer.StartsWith("#"))
                        {
                            continue;
                        }

                        string[] parts = buffer.Split(SettingValueDelimiter);
                        if (parts.Length > 0)
                        {
                            string key   = parts[0].Trim();
                            string value = null;
                            if (parts.Length > 1)
                            {
                                value = parts[1].Trim();
                            }
                            if (string.Equals("group", key, StringComparison.OrdinalIgnoreCase))
                            {
                                // assign a GUID as group ID
                                if (string.IsNullOrEmpty(value))
                                {
                                    value = Guid.NewGuid().ToString();
                                }
                                currentGroupId = value;
                                currentGroup   = new SettingGroup()
                                {
                                    Id = value
                                };
                                GroupsDictionary.Add(value, currentGroup);
                                // adding ID to both dictionaries
                                currentGroup.SetSetting("Id", value);
                                SetSetting(currentGroupId + ".Id", value);
                            }
                            else if (string.Equals("endgroup", key, StringComparison.OrdinalIgnoreCase))
                            {
                                currentGroupId = null;
                                currentGroup   = null;
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(currentGroupId))
                                {
                                    SetSetting(key, value);
                                }
                                else
                                {
                                    string fullName = currentGroupId + "." + key;
                                    SetSetting(fullName, value);
                                    currentGroup.SetSetting(key, value);
                                }
                            }
                        }
                    }
                    reader.Close();
                }
                return(true);
            }
            catch (Exception err)
            {
                // todo
            }
            AutoSave = oldAutoSave;
            return(false);
        }
Exemplo n.º 18
0
 public clsGestorBD()
 {
     tr.Close();
     tr.Dispose();
 }
Exemplo n.º 19
0
        /// <summary>
        /// Loads a RDF Dataset from the NQuads input using a RDF Handler
        /// </summary>
        /// <param name="handler">RDF Handler to use</param>
        /// <param name="parameters">Parameters indicating the Stream to read from</param>
        public void Load(IRdfHandler handler, IStoreParams parameters)
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler", "Cannot parse an RDF Dataset using a null RDF Handler");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters", "Cannot parse an RDF Dataset using null Parameters");
            }

            //Try and get the Input from the parameters
            TextReader input = null;

            if (parameters is StreamParams)
            {
                //Get Input Stream
                input = ((StreamParams)parameters).StreamReader;

#if !SILVERLIGHT
                //Issue a Warning if the Encoding of the Stream is not ASCII
                if (!((StreamReader)input).CurrentEncoding.Equals(Encoding.ASCII))
                {
                    this.RaiseWarning("Expected Input Stream to be encoded as ASCII but got a Stream encoded as " + ((StreamReader)input).CurrentEncoding.EncodingName + " - Please be aware that parsing errors may occur as a result");
                }
#endif
            }
            else if (parameters is TextReaderParams)
            {
                input = ((TextReaderParams)parameters).TextReader;
            }

            if (input != null)
            {
                try
                {
                    //Setup Token Queue and Tokeniser
                    NTriplesTokeniser tokeniser = new NTriplesTokeniser(input);
                    tokeniser.NQuadsMode = true;
                    TokenQueue tokens = new TokenQueue();
                    tokens.Tokeniser = tokeniser;
                    tokens.Tracing   = this._tracetokeniser;
                    tokens.InitialiseBuffer();

                    //Invoke the Parser
                    this.Parse(handler, tokens);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    try
                    {
                        input.Close();
                    }
                    catch
                    {
                        //No catch actions - just cleaning up
                    }
                }
            }
            else
            {
                throw new RdfStorageException("Parameters for the NQuadsParser must be of the type StreamParams/TextReaderParams");
            }
        }
Exemplo n.º 20
0
            /// <summary>
            /// Carga una cadena de Texto con formato RTF.
            /// </summary>
            /// <param name="text">Cadena de Texto que contiene el documento.</param>
            /// <returns>Se devuelve el valor 0 en caso de no producirse ningún error en la carga del documento.
            /// En caso contrario se devuelve el valor -1.</returns>
            public int LoadRtfText(string text)
            {
                //Resultado de la carga
                int res = 0;

                //Se abre el fichero de entrada
                rtf = new StringReader(text);

                //Se crea el analizador léxico para RTF
                lex = new RtfLex(rtf);

                //Se carga el árbol con el contenido del documento RTF
                res = parseRtfTree();

                //Se cierra el stream
                rtf.Close();

                //Se devuelve el resultado de la carga
                return res;
            }
Exemplo n.º 21
0
    void Awake()
    {
        if (Application.loadedLevelName == "MainMenu" || Application.loadedLevelName == "Options" || Application.loadedLevelName == "PlanetSelector" || Application.loadedLevelName == "ProfileSelector")
        {
            isMenu = true;
        }
        entities = new Dictionary<Vector3Int, GameEntity> (new Vector3EqualityComparer ());
        sensorSpaces = new Dictionary<Vector3Int, List<BasicSensor>> (new Vector3EqualityComparer ());
        images[0] = Resources.Load("Art/Textures/GUI/button_exit") as Texture2D;
        images[1] = Resources.Load("Art/Textures/GUI/button_hint") as Texture2D;
        images[2] = Resources.Load("Art/Textures/GUI/button_restart") as Texture2D;
        skin = 		Resources.Load("Art/Textures/GUI/ingame_skin") as GUISkin;
        foreach (GameObject go in FindObjectsOfType(typeof(GameObject))){
            if (go.name == "Camera"){
                CameraDecubeLevel c = go.GetComponent<CameraDecubeLevel>();
                levelCamera = c;
                break;
            }
        }
        hints = new List<string>();
        path = "Assets/Resources/Txt/hints.txt";
        try{
            tr = new StreamReader(path);
            string temp;
            while((temp = tr.ReadLine()) != null)
            {
                if(hints.Count == 12){
                    hints.Add(temp);
                }
                hints.Add(temp);
            }

            // Close the stream
            tr.Close();
        }
        catch(FileLoadException e) {
            Debug.LogException(e);
        }
    }
 public void Close() => input.Close();
Exemplo n.º 23
0
        internal void Process(string fileArg)
        {
            GetNames(fileArg);
            // check for file exists
            OpenSource();
            // parse source file
            if (inputFile != null)
            {
                DateTime start = DateTime.Now;
                try
                {
                    handler        = new ErrorHandler();
                    scanner        = new QUT.Gplex.Lexer.Scanner(inputFile);
                    parser         = new QUT.Gplex.Parser.Parser(scanner);
                    scanner.yyhdlr = handler;
                    parser.Initialize(this, scanner, handler, new OptionParser2(ParseOption));
                    aast = parser.Aast;
                    parser.Parse();
                    // aast.DiagnosticDump();
                    if (verbose)
                    {
                        Status(start);
                    }
                    CheckOptions();
                    if (!Errors && !ParseOnly)
                    {   // build NFSA
                        if (ChrClasses)
                        {
                            DateTime t0 = DateTime.Now;
                            partition = new Partition(TargetSymCardinality, this);
                            partition.FindClasses(aast);
                            partition.FixMap();
                            if (verbose)
                            {
                                ClassStatus(t0, partition.Length);
                            }
                        }
                        else
                        {
                            CharRange.Init(TargetSymCardinality);
                        }
                        nfsa = new NFSA(this);
                        nfsa.Build(aast);
                        if (!Errors)
                        {       // convert to DFSA
                            dfsa = new DFSA(this);
                            dfsa.Convert(nfsa);
                            if (!Errors)
                            {   // minimize automaton
                                if (minimize)
                                {
                                    dfsa.Minimize();
                                }
                                if (!Errors && !checkOnly)
                                {   // emit the scanner to output file
                                    TextReader frameRdr   = FrameReader();
                                    TextWriter outputWrtr = OutputWriter();
                                    dfsa.EmitScanner(frameRdr, outputWrtr);

                                    if (!embedBuffers)
                                    {
                                        CopyBufferCode();
                                    }
                                    // Clean up!
                                    if (frameRdr != null)
                                    {
                                        frameRdr.Close();
                                    }
                                    if (outputWrtr != null)
                                    {
                                        outputWrtr.Close();
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string str = ex.Message;
                    handler.AddError(str, aast.AtStart);
                    throw;
                }
            }
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            //Variables
            List <string> parameters = new List <string>(); //Holds the command line arguments
            List <string> textFile   = new List <string>(); //Hold the text file line by line


            #region Reading Command Line Arguments
            for (int i = 0; i < args.Length; i++)
            {
                parameters.Add(Convert.ToString(args[i]));
                // Console.WriteLine(parameters[i]);
            }
            #endregion

            #region Reading txt document into list(line by line)
            ////Source: https://stackoverflow.com/questions/12771347/how-to-read-from-file-in-command-line-arguments-otherwise-standard-in-emulate
            if (args.Any())
            {
                var path = parameters[0];//This holds the txt file path.
                if (File.Exists(path))
                {
                    input = File.OpenText(path);
                }
            }
            for (string line; (line = input.ReadLine()) != null;)//Display the txt file line by line.
            {
                //Console.WriteLine(line);
                textFile.Add(line);
            }

            //Close the textfile to save resources
            input.Close();

            #endregion

            //Display their original text file
            Console.WriteLine("Your task are:");
            foreach (var word in textFile)
            {
                Console.WriteLine(word);
            }

            #region Formatting task so they are one element per row/column

            //Console.WriteLine("BEGIN EDITINGONS");
            string[] removeThis = { " ", "  " };

            List <string> editedFiles = new List <string>();//Does not contain the frist line
            //editedFiles.Add("-");

            //Parsing the First Line
            List <string> firstLine = new List <string>();
            var           lineaUno  = textFile[0].Split(removeThis, System.StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < lineaUno.Length; i++)
            {
                firstLine.Add(lineaUno[i]);
            }
            //Ending parsing first line

            for (int a = 1; a < textFile.Count; a++)//The a = 1 makes it so first line is not included
            {
                var allvalues = textFile[a].Split(removeThis, System.StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < allvalues.Length; i++)
                {
                    editedFiles.Add(allvalues[i]);
                }
                editedFiles.Add("-");
            }



            //foreach (var VARIABLE in editedFiles)
            //{
            //    Console.WriteLine(VARIABLE);
            //}
            //Console.WriteLine(editedFiles.Count);
            #endregion


            if (parameters.Count == 3)
            {
                //See if they want EDF or RM
                if (parameters[1].Equals("EDF") && parameters[2].Equals("EE"))
                {
                    Console.WriteLine("You want EDF W/ EE");
                    EDF(editedFiles, parameters[2]);
                }
                else if (parameters[1].Equals("RM") && parameters[2].Equals("EE"))
                {
                    Console.WriteLine("You want RM W/ EE");
                    RM(editedFiles, firstLine, parameters[2]);
                }
                else if (parameters[1].Equals("EDF"))
                {
                    Console.WriteLine("You want EDF");
                    EDF(editedFiles);
                }
                else if (parameters[1].Equals("RM"))
                {
                    Console.WriteLine("You want RM");
                    RM(editedFiles, firstLine);
                }
                else
                {
                    Console.WriteLine("ERROR");
                }
            }
            else if (parameters.Count == 2)
            {
                if (parameters[1].Equals("EDF"))
                {
                    Console.WriteLine("You want EDF");
                    EDF(editedFiles);
                    // foreach (var param in parameters) { Console.WriteLine(param); }
                }
                else if (parameters[1].Equals("RM"))
                {
                    Console.WriteLine("You want RM");
                    RM(editedFiles, firstLine);
                }
                else
                {
                    Console.WriteLine("ERROR");
                }
            }
            else
            {
                Console.WriteLine("Please enter EDF or RM & optionally EE in format inputfile.txt EDF EE");
            }

            Console.ReadKey();
        }
Exemplo n.º 25
0
        /// <summary>
        /// Reads a <see cref="Matrix{TDataType}"/> from the given <see cref="TextReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="TextReader"/> to read the matrix from.</param>
        /// <param name="sparse">Whether the returned matrix should be constructed as sparse (true) or dense (false). Default: false.</param>
        /// <param name="delimiter">Number delimiter between numbers of the same line. Supports Regex groups. Default: "\s" (white space).</param>
        /// <param name="hasHeaders">Whether the first row contains column headers or not. Default: false.</param>
        /// <param name="formatProvider">The culture to use. Default: null.</param>
        /// <param name="missingValue">The value to represent missing values. Default: NaN.</param>
        /// <returns>A matrix containing the data from the <see cref="TextReader"/>.</returns>
        /// <typeparam name="T">The data type of the Matrix. It can be either: double, float, Complex, or Complex32.</typeparam>
        public static Matrix <T> Read <T>(TextReader reader, bool sparse = false, string delimiter = @"\s", bool hasHeaders = false, IFormatProvider formatProvider = null, T?missingValue = null)
            where T : struct, IEquatable <T>, IFormattable
        {
            delimiter = CleanDelimiter(delimiter);
            var mv    = missingValue ?? (sparse ? Zero <T>() : NaN <T>());
            var mvStr = mv.ToString("G", formatProvider);

            var regex = delimiter == @"\s" ?
                        RegexCache.GetOrAdd(delimiter, d => new Regex(WhiteSpaceRegexTemplate, RegexOptions.Compiled)) :
                        RegexCache.GetOrAdd(delimiter, d => new Regex(string.Format(RegexTemplate, d), RegexOptions.Compiled));

            var parse = CreateParser <T>(formatProvider);
            var data  = new List <T[]>();

            // max is used to supports files like:
            // 1,2
            // 3,4,5,6
            // 7
            // this creates a 3x4 matrix:
            // 1, 2, MISSING, MISSING
            // 3, 4, 5, 6
            // 7, MISSING, MISSING, MISSING
            var max = -1;

            var line = reader.ReadLine();

            if (hasHeaders)
            {
                line = reader.ReadLine();
            }

            while (line != null)
            {
                line = line.Trim();

                if (line.Length > 0)
                {
                    var matches = regex.Matches(line);

                    if (delimiter == @"\s")
                    {
                        var row = (from Match match in matches where match.Length > 0 select parse(match.Value.StripOffQuotes())).ToArray();
                        max = Math.Max(max, row.Length);
                        data.Add(row);
                    }
                    else
                    {
                        var offset = 0;
                        var row    = new List <T>();

                        foreach (var value in (from Match match in matches where match.Length > 0 select match.Value))
                        {
                            var delimterCount = value.StartsWith(delimiter) ? value.CountDelimiters(delimiter) : 0;

                            if (delimterCount > 0)
                            {
                                for (var i = offset; i < delimterCount; i++)
                                {
                                    row.Add(parse(mvStr.StripOffQuotes()));
                                }
                            }
                            else
                            {
                                row.Add(parse((string.IsNullOrWhiteSpace(value) ? mvStr : value).StripOffQuotes()));
                            }
                            offset = 1;
                        }

                        max = Math.Max(max, row.Count);
                        data.Add(row.ToArray());
                    }
                }
                line = reader.ReadLine();
            }

            var matrix = sparse ? Matrix <T> .Build.Sparse(data.Count, max, mv) : Matrix <T> .Build.Dense(data.Count, max, mv);

            var storage = matrix.Storage;

            for (var i = 0; i < data.Count; i++)
            {
                var row = data[i];
                for (var j = 0; j < row.Length; j++)
                {
                    var value = row[j];
                    storage.At(i, j, value);
                }
            }

            reader.Close();
            reader.Dispose();

            return(matrix);
        }
 /// <summary>
 /// Close the reader
 /// </summary>
 public void Close()
 {
     mReader.Close();
 }
Exemplo n.º 27
0
 public override void Close() => _in.Close();
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            int num_jobs_init;
            int num_users_init;
            int num_features;
            int user_number = 1;

            //Reading the file to get the size of lines and columns of R and Y,
            //which will be used in training colloborative filtering.
            using (TextReader readerR = File.OpenText("C:/Users/larissaf/Desktop/files/Y.txt"))
            {
                num_jobs_init = 0;
                string   line = readerR.ReadLine();
                string[] temp = line.Split('\t');
                num_users_init = temp.Length;
                while (line != null)
                {
                    line = readerR.ReadLine();
                    num_jobs_init++;
                }
                readerR.Close();
            }

            //File that is going to be written with the Top ten jobs and ratings and similarity for all users
            StreamWriter writetext = new StreamWriter("results.txt");

            //Dictionary that contains a list of top ten jobs compared with other jobs for each user
            Dictionary <int, List <MyData> > finalList = new Dictionary <int, List <MyData> >();

            //consider that we have 100 users (we can ask how may and change the while-condition)
            while (user_number <= 100)
            {
                //Now we read R and Y from theirs files (-1 because I will remove the chosen user from the matrixes)
                double[,] Y = new double[num_jobs_init, num_users_init - 1];
                double[,] R = new double[num_jobs_init, num_users_init - 1];

                // Movie rating file for a user
                double[,] my_ratings = new double[num_jobs_init, 1];

                //reading Y_training
                using (TextReader readerY = File.OpenText("C:/Users/larissaf/Desktop/files/Y.txt"))
                {
                    int    i    = 0;
                    string line = readerY.ReadLine();
                    while (line != null)
                    {
                        string[] temp = line.Split('\t');
                        int      k    = 0;
                        for (int j = 0; j < num_users_init; j++)
                        {
                            if (j != (user_number - 1))
                            {
                                Y[i, k] = Convert.ToDouble(temp[j]);
                                k++;
                            }
                            else
                            {
                                my_ratings[i, 0] = Convert.ToDouble(temp[j]);
                            }
                        }
                        line = readerY.ReadLine();
                        i++;
                    }
                    readerY.Close();
                }
                //reading R_training
                using (TextReader readerR = File.OpenText("C:/Users/larissaf/Desktop/files/R.txt"))
                {
                    int    i    = 0;
                    string line = readerR.ReadLine();
                    while (line != null)
                    {
                        string[] temp = line.Split('\t');
                        int      k    = 0;
                        for (int j = 0; j < num_users_init; j++)
                        {
                            if (j != (user_number - 1))
                            {
                                R[i, k] = Convert.ToDouble(temp[j]);
                                k++;
                            }
                        }
                        line = readerR.ReadLine();
                        i++;
                    }
                    readerR.Close();
                }

                //reading X to get the number of features
                using (TextReader readerX = File.OpenText("C:/Users/larissaf/Desktop/files/X.txt"))
                {
                    num_features = 0;
                    string line = readerX.ReadLine();
                    if (line != null)
                    {
                        string[] temp = line.Split('\t');
                        num_features = temp.Length;
                    }
                    readerX.Close();
                }

                //allocating the X matriz
                double[,] X = new double[num_jobs_init, num_features];

                //reading X_training
                using (TextReader readerX = File.OpenText("C:/Users/larissaf/Desktop/files/X.txt"))
                {
                    int    i    = 0;
                    string line = readerX.ReadLine();
                    while (line != null)
                    {
                        string[] temp = line.Split('\t');
                        for (int j = 0; j < num_features; j++)
                        {
                            X[i, j] = Convert.ToDouble(temp[j]);
                        }
                        line = readerX.ReadLine();
                        i++;
                    }
                    readerX.Close();
                }

                /*
                 * using (TextReader reader_movies_ratings = File.OpenText("C:/Users/larissaf/Desktop/files/one_user_rating.txt"))
                 * {
                 *  int i = 0;
                 *  string line = reader_movies_ratings.ReadLine();
                 *  while (line != null)
                 *  {
                 *      string[] temp = line.Split('\t');
                 *      my_ratings[Convert.ToInt32(temp[0]) - 1, 0] = Convert.ToInt32(temp[1]);
                 *
                 *      line = reader_movies_ratings.ReadLine();
                 *      i++;
                 *  }
                 *  reader_movies_ratings.Close();
                 * }*/

                // Job names
                string[] job_list = new string[num_jobs_init];
                using (TextReader reader_movie_list = File.OpenText("C:/Users/larissaf/Desktop/files/job_names.txt"))
                {
                    string line = reader_movie_list.ReadLine();
                    int    i    = 0;
                    while (line != null)
                    {
                        job_list[i] = line;
                        line        = reader_movie_list.ReadLine();
                        i++;
                    }
                    reader_movie_list.Close();
                }

                ////////////////////////////////////////////Matlab calculations///////////////////////////////////////////

                // Create the MATLAB instance
                MLApp.MLApp matlab = new MLApp.MLApp();

                //this is used to do not show the matlab window
                //matlab.Visible = 0;

                // Change to the directory where the functions are located --- always use the desktop to make tests to avoid problems with pathway
                matlab.Execute(@"cd C:\Users\larissaf\Desktop\files");

                // Define the output to print the final result
                object result_movies_search = null;

                matlab.Execute("my_ratings");


                // Movie erecommendations script
                matlab.Feval("scriptGeneration", 6, out result_movies_search, my_ratings, job_list, Y, R, X, num_features);
                object[] res = result_movies_search as object[];

                int len = ((double[, ])res[0]).Length;


                //for each one of the users, we will have a list containg all the comparassions between the top ten jobs for him, and
                //the other jobs (that had similarity >= 70%)
                List <MyData> mylist = new List <MyData>();
                MyData        aux;

                for (int i = 0; i < len; i++)
                {
                    //adding a new element in the list for each user.
                    aux = new MyData(job_list[(int)(((double[, ])res[0])[i, 0]) - 1], (((double[, ])res[1])[i, 0]), job_list[(int)(((double[, ])res[2])[i, 0]) - 1], (((double[, ])res[3])[i, 0]), (((double[, ])res[4])[i, 0]));
                    mylist.Add(aux);

                    writetext.Write(job_list[(int)(((double[, ])res[0])[i, 0]) - 1] + "\t");
                    writetext.Write((((double[, ])res[1])[i, 0]) + "\t");
                    writetext.Write(job_list[(int)(((double[, ])res[2])[i, 0]) - 1] + "\t");
                    writetext.Write((((double[, ])res[3])[i, 0]) + "\t");
                    writetext.Write((((double[, ])res[4])[i, 0]) + "\t");
                    writetext.Write(user_number + "\n");
                }

                //adding the list at the Dictionary for each user
                finalList.Add(user_number, mylist);


                user_number++;
            } // while ends



            writetext.Close();

            //creating a instance of an object for user 1: (maybe send null)
            dataResult avgs = new dataResult(null, 10);

            avgs.WriteInAFile(finalList);


            Console.WriteLine("DONE");

            // Wait until fisnih
            Console.ReadLine();
        }
Exemplo n.º 29
0
 public CUEToolsSourceFile(string _path, TextReader reader)
 {
     path     = _path;
     contents = reader.ReadToEnd();
     reader.Close();
 }
Exemplo n.º 30
0
 public void Close()
 {
     _baseReader.Close();
 }
Exemplo n.º 31
0
        //----< closes filestream >------------------------------------------

        public void close()
        {
            ts.Close();
        }
Exemplo n.º 32
0
 public void Close()
 {
     _reader.Close();
 }
Exemplo n.º 33
0
        } // DoParse

        // ----------------------------------------------------------------------
        private void ParseRtf(TextReader reader)
        {
            curText = new StringBuilder();

            unicodeSkipCountStack.Clear();
            codePageStack.Clear();
            unicodeSkipCount         = 1;
            level                    = 0;
            tagCountAtLastGroupStart = 0;
            tagCount                 = 0;
            fontTableStartLevel      = -1;
            targetFont               = null;
            expectingThemeFont       = false;
            fontToCodePageMapping.Clear();
            hexDecodingBuffer.SetLength(0);
            UpdateEncoding(RtfSpec.AnsiCodePage);
            int       groupCount = 0;
            const int eof        = -1;
            int       nextChar   = PeekNextChar(reader, false);
            bool      backslashAlreadyConsumed = false;

            while (nextChar != eof)
            {
                int  peekChar      = 0;
                bool peekCharValid = false;
                switch (nextChar)
                {
                case '\\':
                    if (!backslashAlreadyConsumed)
                    {
                        reader.Read(); // must still consume the 'peek'ed char
                    }
                    int secondChar = PeekNextChar(reader, true);
                    switch (secondChar)
                    {
                    case '\\':
                    case '{':
                    case '}':
                        curText.Append(ReadOneChar(reader)); // must still consume the 'peek'ed char
                        break;

                    case '\n':
                    case '\r':
                        reader.Read(); // must still consume the 'peek'ed char
                        // must be treated as a 'par' tag if preceded by a backslash
                        // (see RTF spec page 144)
                        HandleTag(reader, new RtfTag(RtfSpec.TagParagraph));
                        break;

                    case '\'':
                        reader.Read(); // must still consume the 'peek'ed char
                        char hex1 = (char)ReadOneByte(reader);
                        char hex2 = (char)ReadOneByte(reader);
                        if (!IsHexDigit(hex1))
                        {
                            throw new RtfHexEncodingException(Strings.InvalidFirstHexDigit(hex1));
                        }
                        if (!IsHexDigit(hex2))
                        {
                            throw new RtfHexEncodingException(Strings.InvalidSecondHexDigit(hex2));
                        }
                        int decodedByte = Int32.Parse("" + hex1 + hex2, NumberStyles.HexNumber);
                        hexDecodingBuffer.WriteByte((byte)decodedByte);
                        peekChar      = PeekNextChar(reader, false);
                        peekCharValid = true;
                        bool mustFlushHexContent = true;
                        if (peekChar == '\\')
                        {
                            reader.Read();
                            backslashAlreadyConsumed = true;
                            int continuationChar = PeekNextChar(reader, false);
                            if (continuationChar == '\'')
                            {
                                mustFlushHexContent = false;
                            }
                        }
                        if (mustFlushHexContent)
                        {
                            // we may _NOT_ handle hex content in a character-by-character way as
                            // this results in invalid text for japanese/chinese content ...
                            // -> we wait until the following content is non-hex and then flush the
                            //    pending data. ugly but necessary with our decoding model.
                            DecodeCurrentHexBuffer();
                        }
                        break;

                    case '|':
                    case '~':
                    case '-':
                    case '_':
                    case ':':
                    case '*':
                        HandleTag(reader, new RtfTag("" + ReadOneChar(reader))); // must still consume the 'peek'ed char
                        break;

                    default:
                        ParseTag(reader);
                        break;
                    }
                    break;

                case '\n':
                case '\r':
                    reader.Read(); // must still consume the 'peek'ed char
                    break;

                case '\t':
                    reader.Read(); // must still consume the 'peek'ed char
                    // should be treated as a 'tab' tag (see RTF spec page 144)
                    HandleTag(reader, new RtfTag(RtfSpec.TagTabulator));
                    break;

                case '{':
                    reader.Read(); // must still consume the 'peek'ed char
                    FlushText();
                    NotifyGroupBegin();
                    tagCountAtLastGroupStart = tagCount;
                    unicodeSkipCountStack.Push(unicodeSkipCount);
                    codePageStack.Push(encoding == null ? 0 : _encodings[encoding.WebName]);
                    level++;
                    break;

                case '}':
                    reader.Read(); // must still consume the 'peek'ed char
                    FlushText();
                    if (level > 0)
                    {
                        unicodeSkipCount = (int)unicodeSkipCountStack.Pop();
                        if (fontTableStartLevel == level)
                        {
                            fontTableStartLevel = -1;
                            targetFont          = null;
                            expectingThemeFont  = false;
                        }
                        UpdateEncoding((int)codePageStack.Pop());
                        level--;
                        NotifyGroupEnd();
                        groupCount++;
                    }
                    else
                    {
                        throw new RtfBraceNestingException(Strings.ToManyBraces);
                    }
                    break;

                default:
                    curText.Append(ReadOneChar(reader)); // must still consume the 'peek'ed char
                    break;
                }
                if (level == 0 && IgnoreContentAfterRootGroup)
                {
                    break;
                }
                if (peekCharValid)
                {
                    nextChar = peekChar;
                }
                else
                {
                    nextChar = PeekNextChar(reader, false);
                    backslashAlreadyConsumed = false;
                }
            }
            FlushText();
#if READERCLOSE
            reader.Close();
#endif

            if (level > 0)
            {
                throw new RtfBraceNestingException(Strings.ToFewBraces);
            }
            if (groupCount == 0)
            {
                throw new RtfEmptyDocumentException(Strings.NoRtfContent);
            }
            curText = null;
        } // ParseRtf