Esempio n. 1
0
File: Load.cs Progetto: orico/shogun
 public static string[] load_dna(string filename)
 {
     List<string> list = new List<string>();
     string[] result = null;
     try
     {
         FileInputStream fstream = new FileInputStream(filename);
         DataInputStream @in = new DataInputStream(fstream);
         BufferedReader buffer = new BufferedReader(new InputStreamReader(@in));
         string line;
         while((line = buffer.readLine()) != null)
         {
             list.Add(line);
         }
         @in.close();
         result = new string[list.Count];
         for (int i = 0; i < list.Count; i++)
         {
             result[i] = (string)list[i];
         }
     }
     catch(java.io.IOException e)
     {
         Console.WriteLine("Unable to create matrix from " + filename + ": " + e.Message);
         Environment.Exit(-1);
     }
     return result;
 }
Esempio n. 2
0
        private static string convertStreamToString(InputStream @is)
        {

            BufferedReader reader = new BufferedReader(new InputStreamReader(@is));
            StringBuilder sb = new StringBuilder();

            string line = null;
            try
            {
                while ((line = reader.ReadLine()) != null)
                {
                    sb.Append((line + "\n"));
                }
            }
            catch (IOException e)
            {
                Log.W("LOG", e.GetMessage());
            }
            finally
            {
                try
                {
                    @is.Close();
                }
                catch (IOException e)
                {
                    Log.W("LOG", e.GetMessage());
                }
            }
            return sb.ToString();
        }
        public string ReadFromFile(string fileName)
        {
            var ret = "";

            try
            {
                var inputStream = context.OpenFileInput(fileName);

                if (inputStream != null)
                {
                    var inputStreamReader = new InputStreamReader(inputStream);
                    var bufferedReader = new BufferedReader(inputStreamReader);
                    var receiveString = "";
                    var stringBuilder = new StringBuilder();

                    while ((receiveString = bufferedReader.ReadLine()) != null)
                    {
                        stringBuilder.Append(receiveString);
                    }

                    inputStream.Close();
                    ret = stringBuilder.ToString();
                }
            }
            catch (FileNotFoundException e)
            {
                Log.Debug("Exception", "File not found: " + e.ToString());
            }
            catch (IOException e)
            {
                Log.Debug("Exception", "Can not read file: " + e.ToString());
            }

            return ret;
        }
        private static string GetUpcomingFixturesForTeam(int teamId, bool forceRefresh = false)
        {
            var url = new URL(string.Format("http://www.football-data.org/team/{0}/fixtures/upcoming?venue=home", teamId));
            var urlConnection = (HttpURLConnection)url.OpenConnection();
            try
            {
                if (forceRefresh)
                {
                    urlConnection.AddRequestProperty("Cache-Control", "no-cache");
                }
                else
                {
                    urlConnection.AddRequestProperty("Cache-Control", "max-stale=" + 86400); //1 day
                }

                urlConnection.SetUseCaches(true);
                var reader = new BufferedReader(new InputStreamReader(urlConnection.GetInputStream()));
                var builder = new StringBuilder();
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    builder.Append(line);
                }
                return builder.ToString();
            }
            catch (Exception ex)
            {
                Log.I(Constants.Tag, "Error getting fixtures. " + ex.Message + " " + ex.StackTrace);
                return null;
            }
        }
Esempio n. 5
0
 /// <summary>
 /// Read a file with given path and return a string array with it's entire contents.
 /// </summary>
 public static string[] ReadAllLines(string path)
 {
     if (path == null)
         throw new ArgumentNullException("path");
     var file = new JFile(path);
     if (!file.Exists() || !file.IsFile())
         throw new FileNotFoundException(path);
     if (!file.CanRead())
         throw new UnauthorizedAccessException(path);
     var reader = new BufferedReader(new FileReader(file));
     try
     {
         var list = new ArrayList<string>();
         string line;
          while ((line = reader.ReadLine()) != null)
          {
              list.Add(line);
          }
         return list.ToArray(new string[list.Count]);
     }
     finally
     {
         reader.Close();
     }
 }
Esempio n. 6
0
		private static List<User> ReadUsers(FileInfo dataDirectory, List<NetflixMovie> movies)
		{
			Dictionary<int, List<Preference>> userIDPrefMap =
				new Dictionary<int, List<Preference>>(104395301, 1.0f);
				//new HashMap<Integer, List<Preference>>(15485867, 1.0f);

			int counter = 0;
			FilenameFilter filenameFilter = new FilenameFilter(
                    delegate(File dir, String filename) 
                    {
					    return filename.startsWith("mv_");
					    //return filename.startsWith("mv_000");
				    }
                );
			
			foreach (FileInfo movieFile in new File(dataDirectory, "training_set").ListFiles(filenameFilter)) 
            {
				BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(movieFile)));
				String line = reader.readLine();
				if (line == null) {
					throw new IOException("Can't read first line of file " + movieFile);
				}
				int movieID = int.parse(line.substring(0, line.length() - 1));
				NetflixMovie movie = movies.get(movieID - 1);
				if (movie == null) 
                {
					throw new ArgumentException("No such movie: " + movieID);
				}
				while ((line = reader.readLine()) != null) 
                {
					counter++;
					if (counter % 100000 == 0) 
                    {
						log.Info("Processed " + counter + " prefs");
					}
					int firstComma = line.indexOf((int) ',');
					Int32 userID = Int32.Parse(line.Substring(0, firstComma));
					int secondComma = line.IndexOf((int) ',', firstComma + 1);
					double rating = Double.Parse(line.Substring(firstComma + 1, secondComma));
					List<Preference> userPrefs = userIDPrefMap.get(userID);
					if (userPrefs == null) 
                    {
						userPrefs = new List<Preference>();
						userIDPrefMap.Add(userID, userPrefs);
					}
					userPrefs.Add(new GenericPreference(null, movie, rating));
				}
				IOUtils.quietClose(reader);
			}

			List<User> users = new List<User>(userIDPrefMap.Count);
			foreach (KeyValuePair<int, List<Preference>> entry in userIDPrefMap) 
            {
				users.Add(new GenericUser<int>(entry.Key, entry.Value));
			}
			return users;
		}
Esempio n. 7
0
	public BufferedReader readDataFile(string filename) {
		BufferedReader inputReader = null;

		try {
			inputReader = new BufferedReader(new FileReader(filename));
		} catch (FileNotFoundException ex) {
			Console.Error.WriteLine("File not found: " + filename);
		}

		return inputReader;
	}
 public static string[] readFile(string path)
 {
     BufferedReader input = new BufferedReader(new FileReader(path));
     string line = null;
     List<string> _list = new List<string>();
     while ((line = input.ReadLine()) != null) {
         line = line.Replace("@%@", ",");
         _list.Add(line);
     }
     input.Close();
     return _list.ToArray();
 }
Esempio n. 9
0
 private Annotation FindAnnotation()
 {
     if (this.reader == null)
     {
         return(null);
     }
     try
     {
         string        line;
         StringBuilder doc = new StringBuilder();
         while ((line = this.reader.ReadLine()) != null)
         {
             doc.Append(line);
             doc.Append('\n');
             //            if(line.contains("<DOC id")){
             //              log.info(line);
             //            }
             if (line.Equals("</DOC>"))
             {
                 break;
             }
             if (line.Contains("</DOC>"))
             {
                 throw new Exception(string.Format("invalid line '%s'", line));
             }
         }
         if (line == null)
         {
             this.reader.Close();
             this.reader = this.FindReader();
         }
         string xml = doc.ToString().ReplaceAll("&", "&amp;");
         if (xml == null || xml.Equals(string.Empty))
         {
             return(this.FindAnnotation());
         }
         xml = xml.ReplaceAll("num=([0-9]+) (.*)", "num=\"$1\" $2");
         xml = xml.ReplaceAll("sid=(.*)>", "sid=\"$1\">");
         xml = xml.ReplaceAll("</SENT>\n</DOC>", "</SENT>\n</TEXT>\n</DOC>");
         xml = Sharpen.Runtime.GetStringForBytes(Sharpen.Runtime.GetBytesForString(xml), "UTF8");
         //log.info("This is what goes in:\n" + xml);
         return(Edu.Stanford.Nlp.Time.ParsedGigawordReader.ToAnnotation(xml));
     }
     catch (IOException e)
     {
         throw new RuntimeIOException(e);
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Run a very simple server.
        /// </summary>
        private void RunServer()
        {
            try
            {
                Log.I("SimpleHttpServer", "Creating server socket");
                var serverSocket = new ServerSocket(PORT);
                var requestCount = 0;
                try
                {
                    while (!stop)
                    {
                        Log.I("SimpleHttpServer", "Waiting for connection");
                        var socket = serverSocket.Accept();

                        var input  = new BufferedReader(new InputStreamReader(socket.GetInputStream()));
                        var output = new BufferedWriter(new OutputStreamWriter(socket.GetOutputStream()));

                        string line;
                        Log.I("SimpleHttpServer", "Reading request");
                        while ((line = input.ReadLine()) != null)
                        {
                            Log.I("SimpleHttpServer", "Received: " + line);
                            if (line.Length == 0)
                            {
                                break;
                            }
                        }

                        Log.I("SimpleHttpServer", "Sending response");
                        output.Write("HTTP/1.1 200 OK\r\n");
                        output.Write("\r\n");
                        output.Write(string.Format("Hello world {0}\r\n", requestCount));
                        output.Flush();

                        socket.Close();
                        requestCount++;
                    }
                }
                finally
                {
                    serverSocket.Close();
                }
            }
            catch (Exception ex)
            {
                Log.E("SimpleHttpServer", "Connection error", ex);
            }
        }
        public string Read()
        {
            string data = "";

            if (socket == null || !socket.IsConnected)
            {
                return(data);
            }

            using (var stream = socket.InputStream)
                using (var reader = new BufferedReader(new InputStreamReader(stream)))
                {
                    if (reader.Ready())
                    {
                        try
                        {
                            Debug.WriteLine("TRYING TO READ DATA");

                            System.String line = "";
                            while (line != null && reader.Ready())
                            {
                                line = reader.ReadLine();
                                if (line != null)
                                {
                                    Debug.WriteLine(line);
                                    data += line;
                                }
                            }

                            if (data == null)
                            {
                                data = "";
                            }
                            Debug.WriteLine("DATA: " + data);
                        }
                        catch (Java.Lang.Exception ex)
                        {
                            Debug.WriteLine("java EXCEPTION: " + ex.Message);
                        }
                        catch (System.Exception ex)
                        {
                            Debug.WriteLine("c# EXCEPTION: " + ex.Message);
                        }
                    }
                }

            return(data);
        }
Esempio n. 12
0
        public void RewriteOptimized(BufferedWriter writer, string containerIndexPath = null, string searchIndexPath = null)
        {
            int[] map = _compressor.OptimizeIndex();

            using (BufferedReader inner = BufferedReader.FromArray(_reader.Buffer, 0, 0))
                using (ContainerIndex containerIndex = (containerIndexPath == null ? null : ContainerIndex.OpenWrite(containerIndexPath)))
                    using (SearchIndexWriter indexWriter = (searchIndexPath == null ? null : new SearchIndexWriter(searchIndexPath, map.Length, 128 * 1024)))
                    {
                        long last = 0;

                        while (this.Read())
                        {
                            int length = (int)(this.BytesRead - last);
                            writer.EnsureSpace(length);

                            if (LengthLookup[(byte)_currentMarker] >= 0)
                            {
                                // Everything but compressed text: write bytes out
                                Buffer.BlockCopy(_reader.Buffer, _reader.Index - length, writer.Buffer, writer.Index, length);
                                writer.Index += length;
                            }
                            else
                            {
                                writer.Buffer[writer.Index++] = (byte)_currentMarker;

                                // Compressed Test: Rewrite the text segment
                                inner.ReadSlice(_reader.Buffer, _reader.Index - _currentLength, _reader.Index - 1);
                                _compressor.RewriteOptimized(map, inner, writer, indexWriter);

                                writer.Buffer[writer.Index++] = (byte)BionMarker.EndValue;
                            }

                            if ((byte)_currentMarker >= (byte)BionMarker.EndArray)
                            {
                                if ((byte)_currentMarker >= (byte)BionMarker.StartArray)
                                {
                                    containerIndex?.Start(writer.BytesWritten - 1);
                                }
                                else
                                {
                                    containerIndex?.End(writer.BytesWritten);
                                }
                            }

                            last = this.BytesRead;
                        }
                    }
        }
Esempio n. 13
0
        public void RegionCanBeLinkedToDuchy()
        {
            var reader = new BufferedReader("duchies = { d_ivrea d_athens d_oppo }");
            var region = CK3Region.Parse(reader);

            var reader2 = new BufferedReader(
                "{ c_athens = { b_athens = { province = 79 } b_newbarony = { province = 56 } } }"
                );
            var duchy2 = new Title("d_athens");

            duchy2.LoadTitles(reader2);

            Assert.Null(region.Duchies["d_athens"]);             // nullptr before linking
            region.LinkDuchy(duchy2);
            Assert.NotNull(region.Duchies["d_athens"]);
        }
Esempio n. 14
0
        public void ImperatorRulerTermIsCorrectlyConverted()
        {
            var reader = new BufferedReader(
                "character = 69 " +
                "start_date = 500.2.3 " +
                "government = dictatorship"
                );
            var impRulerTerm = ImperatorToCK3.Imperator.Countries.RulerTerm.Parse(reader);
            var govReader    = new BufferedReader("link = {imp=dictatorship ck3=feudal_government }");
            var govMapper    = new GovernmentMapper(govReader);
            var ck3RulerTerm = new RulerTerm(impRulerTerm, govMapper);

            Assert.Equal("imperator69", ck3RulerTerm.CharacterId);
            Assert.Equal(new Date(500, 2, 3, AUC: true), ck3RulerTerm.StartDate);
            Assert.Equal("feudal_government", ck3RulerTerm.Government);
        }
Esempio n. 15
0
        public void CorrectRuleMatches()
        {
            var reader = new BufferedReader(
                "link = { ck3 = ck3Religion imp = impReligion }" +
                "link = { ck3 = ck3Religion2 imp = impReligion2 }"
                );
            var mapper          = new ReligionMapper(reader);
            var impRegionMapper = new ImperatorToCK3.Mappers.Region.ImperatorRegionMapper();
            var ck3RegionMapper = new ImperatorToCK3.Mappers.Region.CK3RegionMapper();

            mapper.LoadRegionMappers(impRegionMapper, ck3RegionMapper);

            var ck3Religion = mapper.Match("impReligion2", 45, 456);

            Assert.Equal("ck3Religion2", ck3Religion);
        }
Esempio n. 16
0
        public void Expand(BufferedReader reader, BufferedWriter writer)
        {
            while (!reader.EndOfStream)
            {
                int count = NumberConverter.ReadSixBitTerminatedBlock(reader, _block);
                for (int i = 0; i < count; ++i)
                {
                    int     wordIndex = (int)_block[i];
                    String8 word      = _words[wordIndex].Word;

                    writer.EnsureSpace(word.Length);
                    word.CopyTo(writer.Buffer, writer.Index);
                    writer.Index += word.Length;
                }
            }
        }
Esempio n. 17
0
        private void loadProperties()
        {
            File              file              = new File(this.location, "feat.params");
            InputStream       inputStream       = new URL(file.getPath()).openStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader    bufferedReader    = new BufferedReader(inputStreamReader);

            this.modelProperties = new Properties();
            string text;

            while ((text = bufferedReader.readLine()) != null)
            {
                string[] array = String.instancehelper_split(text, " ");
                this.modelProperties.put(array[0], array[1]);
            }
        }
Esempio n. 18
0
        public void FamiliesCanBeLoaded()
        {
            var reader = new BufferedReader(
                "= {\n" +
                "42={}\n" +
                "43={}\n" +
                "}"
                );
            var families = new ImperatorToCK3.Imperator.Families.FamilyCollection();

            families.LoadFamilies(reader);

            Assert.Collection(families,
                              item => Assert.Equal((ulong)42, item.Id),
                              item => Assert.Equal((ulong)43, item.Id));
        }
Esempio n. 19
0
        public void LinkedRegionWillFailForProvinceMismatch()
        {
            var reader = new BufferedReader("duchies = { d_ivrea d_athens d_oppo }");
            var region = CK3Region.Parse(reader);

            var reader2 = new BufferedReader(
                "{ c_athens = { b_athens = { province = 79 } b_newbarony = { province = 56 } } }"
                );
            var duchy2 = new Title("d_athens");

            duchy2.LoadTitles(reader2);

            region.LinkDuchy(duchy2);

            Assert.False(region.ContainsProvince(7));
        }
Esempio n. 20
0
        public void WrongParentLocationsReturnNullopt()
        {
            var theMapper = new ImperatorRegionMapper();

            var areaReader = new BufferedReader(
                "test_area = { provinces = { 1 2 3 } }\n"
                );
            var regionReader = new BufferedReader(
                "test_region = { areas = { test_area } }\n"
                );

            theMapper.LoadRegions(areaReader, regionReader);

            Assert.Null(theMapper.GetParentAreaName(5));
            Assert.Null(theMapper.GetParentRegionName(5));
        }
Esempio n. 21
0
    public void LinkingCountryWithoutMatchingIdIsLogged()
    {
        var reader   = new BufferedReader("= { owner = 50 }");
        var province = Province.Parse(reader, 42);

        var countryReader = new BufferedReader(string.Empty);
        var country       = Country.Parse(countryReader, 49);

        var output = new StringWriter();

        Console.SetOut(output);
        province.LinkOwnerCountry(country);
        var logStr = output.ToString();

        Assert.Contains("[WARN] Province 42: linking owner 49 that doesn't match owner from save (50)!", logStr);
    }
Esempio n. 22
0
        public static FamilyCollection ParseBloc(BufferedReader reader)
        {
            var blocParser = new Parser();
            var families   = new FamilyCollection();

            blocParser.RegisterKeyword("families", reader =>
                                       families.LoadFamilies(reader)
                                       );
            blocParser.RegisterRegex(CommonRegexes.Catchall, ParserHelpers.IgnoreAndLogItem);

            blocParser.ParseStream(reader);
            blocParser.ClearRegisteredRules();

            Logger.Debug($"Ignored Family tokens: {string.Join(", ", Family.IgnoredTokens)}");
            return(families);
        }
        /// <summary>Reads a text result from the given socket</summary>
        /// <exception cref="System.IO.IOException"/>
        private static string ReadResult(Socket socket)
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.GetInputStream(), "utf-8"));
            StringBuilder  result = new StringBuilder();
            string         line;

            while ((line = reader.ReadLine()) != null)
            {
                if (result.Length > 0)
                {
                    result.Append("\n");
                }
                result.Append(line);
            }
            return(result.ToString());
        }
Esempio n. 24
0
        /// <summary>
        /// Assumes the given reader has only tsurgeon operations (not a tregex pattern), and returns
        /// them as a String, mirroring the way the strings appear in the file.
        /// </summary>
        /// <remarks>
        /// Assumes the given reader has only tsurgeon operations (not a tregex pattern), and returns
        /// them as a String, mirroring the way the strings appear in the file. This is helpful
        /// for lazy evaluation of the operations, as in a GUI,
        /// because you do not parse the operations on load.  Comments are still excised.
        /// </remarks>
        /// <exception cref="System.IO.IOException"/>
        public static string GetTsurgeonTextFromReader(BufferedReader reader)
        {
            StringBuilder sb = new StringBuilder();

            for (string thisLine; (thisLine = reader.ReadLine()) != null;)
            {
                thisLine = RemoveComments(thisLine);
                if (emptyLinePattern.Matcher(thisLine).Matches())
                {
                    continue;
                }
                sb.Append(thisLine);
                sb.Append('\n');
            }
            return(sb.ToString());
        }
        // Note: This DocumentReaderAndWriter needs to be in core because it is
        // used in the truecasing Annotator (loaded by reflection).
        /// <summary>for test only</summary>
        /// <exception cref="System.IO.IOException"/>
        public static void Main(string[] args)
        {
            Reader reader = new BufferedReader(new FileReader(args[0]));
            TrueCasingForNISTDocumentReaderAndWriter raw = new TrueCasingForNISTDocumentReaderAndWriter();

            raw.Init(null);
            for (IEnumerator <IList <CoreLabel> > it = raw.GetIterator(reader); it.MoveNext();)
            {
                IList <CoreLabel> l = it.Current;
                foreach (CoreLabel cl in l)
                {
                    System.Console.Out.WriteLine(cl);
                }
                System.Console.Out.WriteLine("========================================");
            }
        }
Esempio n. 26
0
        public void CannotLinkCountryWithoutMatchingID()
        {
            var reader   = new BufferedReader("= { owner = 50 }");
            var province = Province.Parse(reader, 42);

            var countryReader = new BufferedReader(string.Empty);
            var country       = Country.Parse(countryReader, 49);

            var output = new StringWriter();

            Console.SetOut(output);
            province.LinkOwnerCountry(country);
            var logStr = output.ToString();

            Assert.Contains("[WARN] Province 42: cannot link country 49: wrong ID!", logStr);
        }
        public void CanLookupCK3Provinces()
        {
            var reader = new BufferedReader(
                "0.0.0.0 = {\n" +
                "	link = { ck3 = 2 ck3 = 1 imp = 2 imp = 1 }\n"+
                "}"
                );
            var mapper = new ProvinceMapper(reader);

            Assert.Equal(2, mapper.GetCK3ProvinceNumbers(1).Count);
            Assert.Equal((ulong)2, mapper.GetCK3ProvinceNumbers(1)[0]);
            Assert.Equal((ulong)1, mapper.GetCK3ProvinceNumbers(1)[1]);
            Assert.Equal(2, mapper.GetCK3ProvinceNumbers(2).Count);
            Assert.Equal((ulong)2, mapper.GetCK3ProvinceNumbers(2)[0]);
            Assert.Equal((ulong)1, mapper.GetCK3ProvinceNumbers(2)[1]);
        }
Esempio n. 28
0
 /// <summary>Constructs a new stoplist from the contents of a file.</summary>
 /// <remarks>
 /// Constructs a new stoplist from the contents of a file. It is
 /// assumed that the file contains stopwords, one on a line.
 /// The stopwords need not be in any order.
 /// </remarks>
 public StopList(File list)
 {
     wordSet = Generics.NewHashSet();
     try
     {
         BufferedReader reader = new BufferedReader(new FileReader(list));
         while (reader.Ready())
         {
             wordSet.Add(new Word(reader.ReadLine()));
         }
     }
     catch (IOException e)
     {
         throw new Exception(e);
     }
 }
Esempio n. 29
0
        public void PopsCanBeSet()
        {
            var reader = new BufferedReader(
                "=\n" +
                "{\n" +
                "\tpop=69\n" +
                "\tpop=68\n" +
                "\tpop=12213\n" +
                "\tpop=23\n" +
                "}"
                );

            var theProvince = Province.Parse(reader, 42);

            Assert.Equal(4, theProvince.GetPopCount());
        }
Esempio n. 30
0
        /// <exception cref="System.IO.IOException"/>
        public static void Main(string[] args)
        {
            Properties p = StringUtils.ArgsToProperties(args);

            if (p.Contains("input"))
            {
                FileInputStream   fis    = new FileInputStream(p.GetProperty("input"));
                InputStreamReader isr    = new InputStreamReader(fis, "UTF-8");
                BufferedReader    reader = new BufferedReader(isr);
                string            thisLine;
                while ((thisLine = reader.ReadLine()) != null)
                {
                    EncodingPrintWriter.Out.Println(Normalize(thisLine), "UTF-8");
                }
            }
        }
 public virtual void TranslateLines(BufferedReader br, BufferedWriter bw)
 {
     try
     {
         string line;
         while ((line = br.ReadLine()) != null)
         {
             bw.Write(Apply(line));
             bw.NewLine();
         }
     }
     catch (IOException e)
     {
         throw new RuntimeIOException(e);
     }
 }
Esempio n. 32
0
 public MorfetteFileIterator(string filename)
 {
     try
     {
         reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
         PrimeNext();
     }
     catch (UnsupportedEncodingException e)
     {
         Sharpen.Runtime.PrintStackTrace(e);
     }
     catch (FileNotFoundException e)
     {
         Sharpen.Runtime.PrintStackTrace(e);
     }
 }
Esempio n. 33
0
        public List <Usuario> readFile(String archivo)
        {
            Reader         lector;
            List <Usuario> datosusu = new List <Usuario>();
            bool           header   = true;

            try
            {
                lector = new FileReader(archivo);
                BufferedReader contenido = new BufferedReader(lector);
                String         linea;
                while ((linea = contenido.readLine()) != null)
                {
                    if (!header)
                    {
                        String datos[] = linea.split(",");
            /// <exception cref="System.Exception"/>
            public Void Call()
            {
                string token   = string.Empty;
                string owner   = string.Empty;
                string renewer = "renewer";
                string body    = "{\"renewer\":\"" + renewer + "\"}";
                Uri    url     = new Uri("http://localhost:8088/ws/v1/cluster/delegation-token?doAs=client2"
                                         );
                HttpURLConnection conn = (HttpURLConnection)url.OpenConnection();

                Org.Apache.Hadoop.Yarn.Server.Resourcemanager.Webapp.TestRMWebServicesDelegationTokenAuthentication
                .SetupConn(conn, "POST", MediaType.ApplicationJson, body);
                InputStream response = conn.GetInputStream();

                NUnit.Framework.Assert.AreEqual(ClientResponse.Status.Ok.GetStatusCode(), conn.GetResponseCode
                                                    ());
                BufferedReader reader = null;

                try
                {
                    reader = new BufferedReader(new InputStreamReader(response, "UTF8"));
                    for (string line; (line = reader.ReadLine()) != null;)
                    {
                        JSONObject obj = new JSONObject(line);
                        if (obj.Has("token"))
                        {
                            token = obj.GetString("token");
                        }
                        if (obj.Has("owner"))
                        {
                            owner = obj.GetString("owner");
                        }
                    }
                }
                finally
                {
                    IOUtils.CloseQuietly(reader);
                    IOUtils.CloseQuietly(response);
                }
                NUnit.Framework.Assert.AreEqual("client2", owner);
                Org.Apache.Hadoop.Security.Token.Token <RMDelegationTokenIdentifier> realToken = new
                                                                                                 Org.Apache.Hadoop.Security.Token.Token <RMDelegationTokenIdentifier>();
                realToken.DecodeFromUrlString(token);
                NUnit.Framework.Assert.AreEqual("client2", realToken.DecodeIdentifier().GetOwner(
                                                    ).ToString());
                return(null);
            }
        public string GetCPU()
        {
            if (cpu == null)
            {
                cpu = "";
                try
                {
                    var br = new BufferedReader(new FileReader("/proc/cpuinfo"));

                    string str;

                    var output = new Dictionary <string, string>();

                    try
                    {
                        while ((str = br.ReadLine()) != null)
                        {
                            var data = str.Split(":");

                            if (data.Length > 1)
                            {
                                var key = data[0].Trim().Replace(" ", "_");
                                if (key.Equals("model_name") || key.Equals("Hardware"))
                                {
                                    key = "cpu_model";
                                }

                                var value = data[1].Trim();

                                if (key.Equals("cpu_model"))
                                {
                                    cpu = value;
                                    break;
                                }
                            }
                        }
                    }
                    finally
                    {
                        br.Close();
                    }
                }
                catch {};
            }

            return(cpu);
        }
Esempio n. 36
0
            /// <exception cref="System.IO.IOException"/>
            public virtual double Read(string path)
            {
                FileSystem fs = FileSystem.Get(new Configuration());

                FileStatus[] files = fs.ListStatus(new Path(path));
                foreach (FileStatus fileStat in files)
                {
                    if (!fileStat.IsFile())
                    {
                        continue;
                    }
                    BufferedReader br = null;
                    try
                    {
                        br = new BufferedReader(new InputStreamReader(fs.Open(fileStat.GetPath())));
                        string line;
                        while ((line = br.ReadLine()) != null)
                        {
                            StringTokenizer st = new StringTokenizer(line);
                            string          word;
                            while (st.HasMoreTokens())
                            {
                                word = st.NextToken();
                                this.wordsRead++;
                                this.wordLengthsRead        += word.Length;
                                this.wordLengthsReadSquared += (long)Math.Pow(word.Length, 2.0);
                            }
                        }
                    }
                    catch (IOException e)
                    {
                        System.Console.Out.WriteLine("Output could not be read!");
                        throw;
                    }
                    finally
                    {
                        br.Close();
                    }
                }
                double mean = (((double)this.wordLengthsRead) / ((double)this.wordsRead));

                mean = Math.Pow(mean, 2.0);
                double term   = (((double)this.wordLengthsReadSquared / ((double)this.wordsRead)));
                double stddev = Math.Sqrt((term - mean));

                return(stddev);
            }
Esempio n. 37
0
        /// <exception cref="System.Exception"/>
        public virtual void _testMapReduce(bool restart)
        {
            OutputStream os = GetFileSystem().Create(new Path(GetInputDir(), "text.txt"));
            TextWriter   wr = new OutputStreamWriter(os);

            wr.Write("hello1\n");
            wr.Write("hello2\n");
            wr.Write("hello3\n");
            wr.Write("hello4\n");
            wr.Close();
            if (restart)
            {
                StopCluster();
                StartCluster(false, null);
            }
            JobConf conf = CreateJobConf();

            conf.SetJobName("mr");
            conf.SetInputFormat(typeof(TextInputFormat));
            conf.SetMapOutputKeyClass(typeof(LongWritable));
            conf.SetMapOutputValueClass(typeof(Text));
            conf.SetOutputFormat(typeof(TextOutputFormat));
            conf.SetOutputKeyClass(typeof(LongWritable));
            conf.SetOutputValueClass(typeof(Text));
            conf.SetMapperClass(typeof(IdentityMapper));
            conf.SetReducerClass(typeof(IdentityReducer));
            FileInputFormat.SetInputPaths(conf, GetInputDir());
            FileOutputFormat.SetOutputPath(conf, GetOutputDir());
            JobClient.RunJob(conf);
            Path[] outputFiles = FileUtil.Stat2Paths(GetFileSystem().ListStatus(GetOutputDir(
                                                                                    ), new Utils.OutputFileUtils.OutputFilesFilter()));
            if (outputFiles.Length > 0)
            {
                InputStream    @is     = GetFileSystem().Open(outputFiles[0]);
                BufferedReader reader  = new BufferedReader(new InputStreamReader(@is));
                string         line    = reader.ReadLine();
                int            counter = 0;
                while (line != null)
                {
                    counter++;
                    NUnit.Framework.Assert.IsTrue(line.Contains("hello"));
                    line = reader.ReadLine();
                }
                reader.Close();
                NUnit.Framework.Assert.AreEqual(4, counter);
            }
        }
Esempio n. 38
0
        /// <exception cref="System.Exception"/>
        public virtual void TestDynamicLogLevel()
        {
            string logName = typeof(TestLogLevel).FullName;

            Org.Apache.Commons.Logging.Log testlog = LogFactory.GetLog(logName);
            //only test Log4JLogger
            if (testlog is Log4JLogger)
            {
                Logger log = ((Log4JLogger)testlog).GetLogger();
                log.Debug("log.debug1");
                log.Info("log.info1");
                log.Error("log.error1");
                Assert.True(!Level.Error.Equals(log.GetEffectiveLevel()));
                HttpServer2 server = new HttpServer2.Builder().SetName("..").AddEndpoint(new URI(
                                                                                             "http://*****:*****@out.WriteLine("*** Connecting to " + url);
                URLConnection connection = url.OpenConnection();
                connection.Connect();
                BufferedReader @in = new BufferedReader(new InputStreamReader(connection.GetInputStream
                                                                                  ()));
                for (string line; (line = @in.ReadLine()) != null; @out.WriteLine(line))
                {
                }
                @in.Close();
                log.Debug("log.debug2");
                log.Info("log.info2");
                log.Error("log.error2");
                Assert.True(Level.Error.Equals(log.GetEffectiveLevel()));
                //command line
                string[] args = new string[] { "-setlevel", authority, logName, Level.Debug.ToString
                                                   () };
                LogLevel.Main(args);
                log.Debug("log.debug3");
                log.Info("log.info3");
                log.Error("log.error3");
                Assert.True(Level.Debug.Equals(log.GetEffectiveLevel()));
            }
            else
            {
                @out.WriteLine(testlog.GetType() + " not tested.");
            }
        }
Esempio n. 39
0
        /// <summary>
        /// Run a very simple server.
        /// </summary>
        private void RunServer()
        {
            try
            {
                Log.I("SimpleHttpServer", "Creating server socket");
                var serverSocket = new ServerSocket(PORT);
                var requestCount = 0;
                try
                {
                    while (!stop)
                    {
                        Log.I("SimpleHttpServer", "Waiting for connection");
                        var socket = serverSocket.Accept();

                        var input = new BufferedReader(new InputStreamReader(socket.GetInputStream()));
                        var output = new BufferedWriter(new OutputStreamWriter(socket.GetOutputStream()));

                        string line;
                        Log.I("SimpleHttpServer", "Reading request");
                        while ((line = input.ReadLine()) != null)
                        {
                            Log.I("SimpleHttpServer", "Received: " + line);
                            if (line.Length == 0)
                                break;
                        }

                        Log.I("SimpleHttpServer", "Sending response");
                        output.Write("HTTP/1.1 200 OK\r\n");
                        output.Write("\r\n");
                        output.Write(string.Format("Hello world {0}\r\n", requestCount));
                        output.Flush();

                        socket.Close();
                        requestCount++;
                    }
                }
                finally
                {
                    serverSocket.Close();
                }
            }
            catch (Exception ex)
            {
                Log.E("SimpleHttpServer", "Connection error", ex);
            }
        }
        private const int ICON_SIZE = 32; // dip

        protected override void OnCreate(Bundle b) {
            base.OnCreate(b);
            SetContentView(R.Layouts.sharing_receiver_support);

            float density = GetResources().GetDisplayMetrics().Density;
            int iconSize = (int) (ICON_SIZE * density + 0.5f);

            ShareCompat.IntentReader intentReader = ShareCompat.IntentReader.From(this);

            // The following provides attribution for the app that shared the data with us.
            TextView info = (TextView) FindViewById(R.Ids.app_info);
            Drawable d = intentReader.GetCallingActivityIcon();
            d.SetBounds(0, 0, iconSize, iconSize);
            info.SetCompoundDrawables(d, null, null, null);
            info.SetText(intentReader.GetCallingApplicationLabel());

            TextView tv = (TextView) FindViewById(R.Ids.text);
            StringBuilder txt = new StringBuilder("Received share!\nText was: ");

            txt.Append(intentReader.GetText());
            txt.Append("\n");

            txt.Append("Streams included:\n");
            int N = intentReader.GetStreamCount();
            for (int i = 0; i < N; i++) {
                Uri uri = intentReader.GetStream(i);
                txt.Append("Share included stream " + i + ": " + uri + "\n");
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            GetContentResolver().OpenInputStream(uri)));
                    try {
                        txt.Append(reader.ReadLine() + "\n");
                    } catch (IOException e) {
                        Log.E(TAG, "Reading stream threw exception", e);
                    } finally {
                        reader.Close();
                    }
                } catch (FileNotFoundException e) {
                    Log.E(TAG, "File not found from share.", e);
                } catch (IOException e) {
                    Log.D(TAG, "I/O Error", e);
                }
            }

            tv.SetText(txt.ToString());
        }
Esempio n. 41
0
        /// <summary>
        /// Converts the stream to a string.
        /// </summary>
        /// <returns>A string with the contents read from the stream.</returns>
        /// <param name="s">S.</param>
        private string convertStreamToString(Stream s)
        {
            BufferedReader br = new BufferedReader (new InputStreamReader(s));
            StringBuilder sb = new StringBuilder ();

            string line = null;
            try {
                while((line = br.ReadLine()) != null)
                    sb.AppendLine(line);
            } catch (Exception e) {
                Log.Warn ("PARSING INPUT MAP", e.Message);
            } finally {
                try {
                    s.Close();
                } catch (Exception e) {
                    Log.Warn ("CLOSING STREAM", e.Message);
                }
            }

            return sb.ToString ();
        }
Esempio n. 42
0
 public static int[,] getRandSudoku(Stream ist)
 {
     try{
         BufferedReader br = new BufferedReader(new InputStreamReader(ist));
         int count = Integer.ParseInt(br.ReadLine());
         int rand = new Random().Next(1, count);
         for (int i = 0; i < rand - 1; i++){
             br.ReadLine();
         }
         string[] sudoku = br.ReadLine().Split(' ');
         int[ ,] result = new int[9 ,9];
         for (int i = 0; i < 9; i++){
             for (int q = 0; q < 9; q++){
                 result[i ,q] = Integer.ParseInt(sudoku[i*9 + q]);
             }
         }
         return result;
     } catch (System.Exception e){
         Log.Error(typeof(SudokuFileReader).FullName, "FILE EXCEPTION", e);
     }
     return null;
 }
Esempio n. 43
0
	public ArrayList<Candidate> loadCandidateList(BufferedReader dataFile) {
		ArrayList<Candidate> toReturn = new ArrayList<Candidate>();
		try {
			string line = dataFile.readLine();
			Scanner scanLine;
			ArrayList<double?> featureVectorToAdd;
			while (line != null && !(line.equals(""))) {
				scanLine = new Scanner(line);
				featureVectorToAdd = new ArrayList<double?>();
				int intClass = -1
				featureVectorToAdd.add/* [13,27] expecting: identifier: (*/scanLine/* [13,72] expecting: ';', ',': .*//* [13,107] expecting: ';', ',': nextDouble*/()/* [13,154] expecting: '{', ';': )*/;
				featureVectorToAdd.add/* [14,27] expecting: identifier: (*/scanLine/* [14,72] expecting: ';', ',': .*//* [14,107] expecting: ';', ',': nextDouble*/()/* [14,154] expecting: '{', ';': )*/;
				featureVectorToAdd.add/* [15,27] expecting: identifier: (*/scanLine/* [15,72] expecting: ';', ',': .*//* [15,107] expecting: ';', ',': nextDouble*/()/* [15,154] expecting: '{', ';': )*/;
				featureVectorToAdd.add/* [16,27] expecting: identifier: (*/scanLine/* [16,72] expecting: ';', ',': .*//* [16,107] expecting: ';', ',': nextDouble*/()/* [16,154] expecting: '{', ';': )*/;

				String typeOfPlant = scanLine.next();
				/* [19,5] expecting: 'abstract', 'boolean', 'byte', 'char', 'class', 'double', 'enum', 'final', 'float', 'int', 'interface', 'long', 'native', 'private', 'protected', 'public', 'short', 'static', 'strictfp', 'synchronized', 'transient', 'void', 'volatile', identifier, '{', '}', ';', '<', '@': if*/ /* [19,304] expecting: 'abstract', 'boolean', 'byte', 'char', 'class', 'double', 'enum', 'final', 'float', 'int', 'interface', 'long', 'native', 'private', 'protected', 'public', 'short', 'static', 'strictfp', 'synchronized', 'transient', 'void', 'volatile', identifier, '{', '}', ';', '<', '@': (*/typeOfPlant.equals/* [19,621] expecting: identifier: (*//* [19,659] expecting: identifier: "Iris-setosa"*/)) {
					intClass = 1;
				} else if (typeOfPlant.equals("Iris-versicolor")) {
					intClass = 2;
				} else if (typeOfPlant.equals("Iris-virginica")) {
					intClass = 3;
					}
						Candidate c = new Candidate(featureVectorToAdd, intClass);
				toReturn.add/* [15,17] expecting: identifier: (*/c/* [15,55] expecting: ';', ',': )*/;
				line /* [16,10] expecting: identifier: =*/ dataFile/* [16,56] expecting: ';', ',': .*//* [16,91] expecting: ';', ',': readLine*/();
				scanLine.close/* [17,19] expecting: identifier: (*//* [17,56] expecting: identifier: )*//* [17,93] expecting: identifier: ;*/

			/* [19,4] expecting: identifier: }*/
			/* [20,4] expecting: identifier: return*/ toReturn;

		} /* [22,5] expecting: EOF: catch*/ /* [22,39] expecting: EOF: (*//* [22,69] expecting: EOF: IOException*/ /* [22,110] expecting: EOF: e*//* [22,141] expecting: EOF: )*/ /* [22,173] expecting: EOF: {*/
			// TODO Auto-generated catch block
			/* [24,4] expecting: EOF: e*//* [24,33] expecting: EOF: .*//* [24,63] expecting: EOF: printStackTrace*//* [24,107] expecting: EOF: (*/);
		}
		return null;

	}
Esempio n. 44
0
 /// <summary>
 /// Perform the low level request and return the resulting content.
 /// </summary>
 private static string PerformRequest(string iataCode)
 {
     var uri = string.Format("http://services.faa.gov/airport/status/{0}?format=application/json", iataCode);
     var client = AndroidHttpClient.NewInstance("AirportInfo");
     var request = new HttpGet(uri);
     try
     {
         var response = client.Execute(request);
         var content = response.GetEntity().GetContent();
         var reader = new BufferedReader(new InputStreamReader(content));
         var builder = new StringBuilder();
         string line;
         while ((line = reader.ReadLine()) != null)
         {
             builder.Append(line);
         }
         return builder.ToString();
     }
     catch (Exception ex)
     {
         return null;
     }
 }
Esempio n. 45
0
        public static void Main( string[] args ) {
#if DEBUG
            _hidekeys = true;
#endif
            BufferedWriter sw = null;
            try {
                sw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( "result.txt" ), "Shift_JIS" ) );
                VocaloSysUtil.init();
                string editor2 = VocaloSysUtil.getEditorPath( SynthesizerType.VOCALOID2 );
                sw.write( new string( '#', 72 ) );
                sw.newLine();
                sw.write( "VOCALOID2" );
                sw.newLine();
                SingerConfigSys sys2 = VocaloSysUtil.getSingerConfigSys( SynthesizerType.VOCALOID2 );
                write( sw, editor2, sys2 );

                sw.write( new string( '#', 72 ) );
                sw.newLine();
                sw.write( "VOCALOID1" );
                sw.newLine();
                string editor1 = VocaloSysUtil.getEditorPath( SynthesizerType.VOCALOID1 );
                SingerConfigSys sys1 = VocaloSysUtil.getSingerConfigSys( SynthesizerType.VOCALOID1 );
                write( sw, editor1, sys1 );
            } catch ( Exception ex ) {
            } finally {
                if ( sw != null ) {
                    try {
                        sw.close();
                    } catch ( Exception ex ) {
                    }
                }
            }

            if ( _hidekeys ) {
                // 一度全体を読み込み、隠す必要のあるID文字列を抽出
                BufferedReader br2 = null;
                try {
                    br2 = new BufferedReader( new InputStreamReader( new FileInputStream( "result.txt" ), "Shift_JIS" ) );
                    String line = "";
                    String[] headers = new String[]{
                        "HKLM\\SOFTWARE\\VOCALOID\\APPLICATION\\",
                        "HKLM\\SOFTWARE\\VOCALOID\\DATABASE\\EXPRESSION\\",
                        "HKLM\\SOFTWARE\\VOCALOID2\\APPLICATION\\",
                        "HKLM\\SOFTWARE\\VOCALOID2\\DATABASE\\EXPRESSION\\",
                        "HKLM\\SOFTWARE\\VOCALOID\\SKIN\\",
                        "HKLM\\SOFTWARE\\VOCALOID2\\DATABASE\\VOICE\\",
                        "HKLM\\SOFTWARE\\VOCALOID\\DATABASE\\VOICE\\", };

                    while ( (line = br2.readLine()) != null ) {
                        String[] spl = PortUtil.splitString( line, '\t' );
                        if ( spl.Length < 3 ) {
                            continue;
                        }
                        String s = spl[0];

                        // ID(?)
                        foreach( String h in headers ){
                            if( !s.StartsWith( h ) ){
                                continue;
                            }
                            String keys = "";
                            try {
                                keys = s.Substring( PortUtil.getStringLength( h ) + 17, 4 );
                            } catch ( Exception ex ) {
                                continue;
                            }
#if DEBUG
                            sout.println( "Main; keys=" + keys );
#endif
                            if( !keys.Equals( "KEYS" ) ){
                                continue;
                            }
                            String key = s.Substring( PortUtil.getStringLength( h ), 16 );
#if DEBUG
                            sout.println( "Main; key=" + key );
#endif
                            addIdMap( key );
                        }

                        // handle(?)
                        if ( spl[1] == "TIME" || spl[1] == "STANDARD" ) {
                            if( isId( spl[2] ) ){
                                addIdMap( spl[2] );
                            }
                        } else if ( spl[1] == "default" ) {
                            if ( tryParseUInt128( spl[2] ) ) {
                                addHandleMap( spl[2] );
                            }
                        } else {
                            if( isId( spl[1] ) && tryParseUInt128( spl[2] ) ){
                                addIdMap( spl[1] );
                                addHandleMap( spl[2] );
                            }
                        }
                    }
                } catch ( Exception ex ) {
                    serr.println( "Main; ex=" + ex );
                } finally {
                    if ( br2 != null ) {
                        try {
                            br2.close();
                        } catch ( Exception ex2 ) {
                            serr.println( "Main; ex2=" + ex2 );
                        }
                    }
                }
                
                String tmp = PortUtil.createTempFile();
                PortUtil.deleteFile( tmp );
                PortUtil.copyFile( "result.txt", tmp );
                PortUtil.deleteFile( "result.txt" );
                BufferedReader br = null;
                BufferedWriter bw = null;

                try {
                    br = new BufferedReader( new InputStreamReader( new FileInputStream( tmp ), "Shift_JIS" ) );
                    bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( "result.txt" ), "Shift_JIS" ) );
                    String line = "";
                    while ( (line = br.readLine()) != null ) {
                        foreach ( String from in _map_id.Keys ) {
                            String to = _map_id[from];
                            line = line.Replace( from, to );
                        }
                        bw.write( line );
                        bw.newLine();
                    }
                } catch ( Exception ex ) {
                } finally {
                    if ( br != null ) {
                        try {
                            br.close();
                        } catch ( Exception ex2 ) {
                        }
                        PortUtil.deleteFile( tmp );
                    }
                    if ( bw != null ) {
                        try {
                            bw.close();
                        } catch ( Exception ex2 ) {
                        }
                    }
                }
            }
#if DEBUG
            Console.WriteLine( "tryParseUInt128(\"403034329006c1cf2c401d4664d3492b\")=" + tryParseUInt128( "403034329006c1cf2c401d4664d3492b" ) );
            Console.Write( "hit any key to exit..." );
            Console.Read();
#endif
        }
Esempio n. 46
0
 private bool Connect(string serverAddress, int portNumber)
 {
     try {
         Socket s = new Socket(serverAddress, portNumber);
         s.KeepAlive = true;
         writer = new BufferedWriter(new OutputStreamWriter(s.OutputStream));
         reader = new BufferedReader(new InputStreamReader(s.InputStream));
         new ReceivingThread(this).Start();
         new KeepAliveThread(this).Start();
         return true;
     } catch(Exception e) {
         System.Diagnostics.Debug.WriteLine("Failed to connect to TCP server. Error: " + e.GetBaseException().Message);
         return false;
     }
 }
Esempio n. 47
0
        private void ParseItemNano(int rectype, int recnum, byte[] data)
        {
            this.BR = new BufferedReader(rectype, recnum, data, this.Tracing);
            bool flag;
            flag = !Output.ItemNano_Begin(XR.RecordNum, XR.RecordType == 1040005, CS);
            if (flag)
            {
                return;
            }

            br.SkipBytes(16, "Pre-Attr");
            int num = br.ReadCNum("AttrCount");
            Plugin.ItemNanoInfo info = default(Plugin.ItemNanoInfo);
            List<Plugin.ItemNanoKeyVal> list = new List<Plugin.ItemNanoKeyVal>();
            bool flag2 = false;
            int arg_C0_0 = 0;
            short num5;
            short num6;
            checked
            {
                int num2 = num - 1;
                int num3 = arg_C0_0;
                while (true)
                {
                    int arg_1C2_0 = num3;
                    int num4 = num2;
                    if (arg_1C2_0 > num4)
                    {
                        break;
                    }
                    Plugin.ItemNanoKeyVal item = default(Plugin.ItemNanoKeyVal);
                    item.AttrKey = br.ReadInt32("AttrKey" + Conversions.ToString(num3));
                    item.AttrVal = br.ReadInt32("AttrVal" + Conversions.ToString(num3));
                    list.Add(item);
                    int attrKey = item.AttrKey;
                    flag = (attrKey == 54);
                    if (flag)
                    {
                        info.QL = item.AttrVal;
                    }
                    else
                    {
                        flag = (attrKey == 76);
                        if (flag)
                        {
                            info.EquipPage = item.AttrVal;
                        }
                        else
                        {
                            flag = (attrKey == 88);
                            if (flag)
                            {
                                info.DefaultSlot = item.AttrVal;
                            }
                            else
                            {
                                flag = (attrKey == 298);
                                if (flag)
                                {
                                    info.EquipSlots = item.AttrVal;
                                }
                                else
                                {
                                    flag = (attrKey == 388);
                                    if (flag)
                                    {
                                        flag2 = true;
                                    }
                                }
                            }
                        }
                    }
                    num3++;
                }
                br.SkipBytes(8, "Post-Attr");
                num5 = br.ReadInt16("NameLen");
                num6 = br.ReadInt16("DescLen");
            }
            bool arg_222_0;
            if (num5 >= 0 && num6 >= 0)
            {
                if (num5 <= 4095L)
                {
                    if (num6 <= 4095L)
                    {
                        arg_222_0 = false;
                        goto IL_222;
                    }
                }
            }
            arg_222_0 = true;
        IL_222:
            flag = arg_222_0;
            if (flag)
            {
                br.DebugDump("NameLen or DescLen is invalid", ParserReturns.Failed);
            }
            flag = (num5 > 0);
            if (flag)
            {
                info.Name = br.ReadString((int)num5, "Name");
            }
            else
            {
                info.Name = "";
            }
            flag = (num6 > 0);
            if (flag)
            {
                info.Description = br.ReadString((int)num6, "Description");
            }
            else
            {
                info.Description = "";
            }
            BitManipulation bitManipulation = new BitManipulation();
            info.Type = info.EquipPage;
            flag = (Strings.InStr(info.Name, "_", CompareMethod.Binary) != 0
                    || Strings.InStr(Strings.UCase(info.Name), "BOSS", CompareMethod.Binary) != 0);
            if (flag)
            {
                info.Type = 4;
            }
            else
            {
                flag = flag2;
                if (flag)
                {
                    info.Type = 7;
                }
                else
                {
                    flag = (info.EquipPage == 1);
                    if (flag)
                    {
                        bool flag3 = bitManipulation.CheckBit((long)info.EquipSlots, 6)
                                     || bitManipulation.CheckBit((long)info.EquipSlots, 8);
                        if (flag3)
                        {
                            info.Type = 1;
                        }
                        else
                        {
                            info.Type = 6;
                        }
                    }
                }
            }
            try
            {
                Output.ItemNano(info, list.ToArray());
            }
            catch (SQLiteException expr_371)
            {
                ProjectData.SetProjectError(expr_371);
                ReturnCode = ParserReturns.Crashed;
                ProjectData.ClearProjectError();
            }
            catch (Exception expr_387)
            {
                ProjectData.SetProjectError(expr_387);
                Exception ex3 = expr_387;
                CustomException ex4 = new CustomException(ex3.ToString(), "Plugin Error");
                ReturnCode = ParserReturns.Crashed;
                ProjectData.ClearProjectError();
            }
            bool flag4 = true;
            checked
            {
                while (br.Ptr < br.Buffer.Length - 8 && flag4)
                {
                    switch (br.ReadInt32("ParseSetsKeyNum"))
                    {
                        case 2:
                            this.ParseFunctionSet(ref flag4);
                            break;
                        case 3:
                        case 5:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 21:
                            goto IL_4BF;
                        case 4:
                            this.ParseAtkDefSet(ref flag4);
                            break;
                        case 6:
                            {
                                br.SkipBytes(4, "Pre-SkipSet");
                                int count = br.ReadCNum("SkipSet") * 8;
                                br.SkipBytes(count, "Post-SkipSet");
                                break;
                            }
                        case 14:
                            this.ParseAnimSoundSet(1, ref flag4);
                            break;
                        case 20:
                            this.ParseAnimSoundSet(2, ref flag4);
                            break;
                        case 22:
                            this.ParseActionSet(ref flag4);
                            break;
                        case 23:
                            this.ParseShopHash(ref flag4);
                            break;
                        default:
                            goto IL_4BF;
                    }
                    continue;
                IL_4BF:
                    flag4 = this.CritError("Invalid KeyNum");
                }
                try
                {
                    Output.ItemNano_End();
                }
                catch (SQLiteException expr_50A)
                {
                    ProjectData.SetProjectError(expr_50A);
                    ReturnCode = ParserReturns.Crashed;
                    ProjectData.ClearProjectError();
                }
                catch (Exception expr_520)
                {
                    ProjectData.SetProjectError(expr_520);
                    Exception ex5 = expr_520;
                    CustomException ex6 = new CustomException(ex5.ToString(), "Plugin Error");
                    ReturnCode = ParserReturns.Crashed;
                    ProjectData.ClearProjectError();
                }
            }
        }
Esempio n. 48
0
        private static string convertStreamTostring(InputStream inputStream)
        {
            /*
             * To convert the InputStream to string we use the BufferedReader.readLine()
             * method. We iterate until the BufferedReader return null which means
             * there's no more data to read. Each line will appended to a stringBuilder
             * and returned as string.
             */
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();

            string line = null;
            try {
                while ((line = reader.ReadLine()) != null) {
                    sb.Append(line + "\n");
                }
            } catch (IOException e) {
                e.PrintStackTrace();
            } finally {
                try {
                    inputStream.Close();
                } catch (IOException e) {
                    e.PrintStackTrace();
                }
            }

            return sb.ToString();
        }
		/// <summary> </summary>
		/// <param name="fontBuilder">FontBuilder
		/// </param>
		/// <param name="height">double
		/// </param>
		/// <param name="text">String
		/// </param>
		/// <param name="color">Color
		/// </param>
		/// <param name="xOffset">int
		/// </param>
		/// <param name="yOffset">int
		/// </param>
		/// <throws>  IOException </throws>
		/// <summary> add text</summary>
		//UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
		public virtual void  add(FontBuilder fontBuilder, double height, System.String text, ref System.Drawing.Color color, int xOffset, int yOffset)
		{
			fontBuilders.Add(fontBuilder);
			
			//UPGRADE_ISSUE: Constructor 'java.io.BufferedReader.BufferedReader' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioBufferedReaderBufferedReader_javaioReader'"
			System.IO.StreamReader reader = new BufferedReader(new System.IO.StringReader(text));
			System.String line;
			char[] chars;
			int yCount = 0;
			double t_width = 0.0f;
			double t_height = 0.0f;
			while (true)
			{
				line = reader.ReadLine();
				// Make sure we don't create empty TextRecords
				// A empty textRecord will crash Flash Player. Player Bug#57644
				if ((line == null) || (line.Length == 0))
					break;
				
				//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
				//UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
				TextRecord tr = getStyleRecord(fontBuilder, height, ref color, xOffset, (int) (yOffset + yCount * height * flash.swf.SwfConstants_Fields.TWIPS_PER_PIXEL));
				
				chars = line.ToCharArray();
				tr.entries = new GlyphEntry[chars.Length];
				double w = 0;
				for (int i = 0; i < chars.Length; i++)
				{
					char c = chars[i];
					// preilly: According to Sherman Gong, we need to clone the font GlyphEntry, so
					// that the advance value can be mapped from the font's logical scale to the
					// text's physical scale.
					GlyphEntry ge = (GlyphEntry) fontBuilder.getGlyph(c).Clone();
					//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
					ge.advance = (int) ((ge.advance / 1024f) * tr.height);
					tr.entries[i] = ge;
					w += ge.advance;
				}
				if (w > t_width)
					t_width = w;
				tag.records.Add(tr);
				yCount++;
			}
			t_height = yCount * height;
			
			double x1 = 0;
			double y1 = 0;
			double x2 = x1 + t_width;
			double y2 = y1 + t_height;
			x1 = x1 * flash.swf.SwfConstants_Fields.TWIPS_PER_PIXEL;
			x2 = x2 * flash.swf.SwfConstants_Fields.TWIPS_PER_PIXEL;
			y1 = y1 * flash.swf.SwfConstants_Fields.TWIPS_PER_PIXEL;
			y2 = y2 * flash.swf.SwfConstants_Fields.TWIPS_PER_PIXEL;
			/**
			*  If the values are greater than Max_value, then
			*  the results are not to be trusted.
			*/
			if (x1 > System.Int32.MaxValue)
				x1 = 0;
			if (x2 > System.Int32.MaxValue)
				x2 = 0;
			if (y1 > System.Int32.MaxValue)
				y1 = 0;
			if (y2 > System.Int32.MaxValue)
				y2 = 0;
			
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			tag.bounds = new Rect((int) x1, (int) x2, (int) y1, (int) y2);
		}
Esempio n. 50
0
		private static List<NetflixMovie> readMovies(File dataDirectory) 
		{
			List<NetflixMovie> movies = new List<NetflixMovie>(17770);
			BufferedReader reader =
				new BufferedReader(new InputStreamReader(new FileStream(new File(dataDirectory, "movie_titles.txt"))));
			String line;
			while ((line = reader.readLine()) != null) 
			{
				int firstComma = line.indexOf((int) ',');
				int id = Integer.valueOf(line.substring(0, firstComma));
				int secondComma = line.indexOf((int) ',', firstComma + 1);
				String title = line.substring(secondComma + 1);
				movies.Add(new NetflixMovie(id, title));
			}
			IOUtils.quietClose(reader);
			return movies;
		}
Esempio n. 51
0
 /// <summary>
 /// Creates a dictionary based on a reader.
 /// </summary>
 public PlainTextDictionary(Reader reader)
 {
     @in = new BufferedReader(reader);
 }
Esempio n. 52
0
 /// <summary>
 /// Creates a dictionary based on an inputstream.
 /// Using <code>fieldDelimiter</code> to seperate out the
 /// fields in a line.
 /// <para>
 /// NOTE: content is treated as UTF-8
 /// </para>
 /// </summary>
 public FileDictionary(InputStream dictFile, string fieldDelimiter)
 {
     @in = new BufferedReader(IOUtils.GetDecodingReader(dictFile, StandardCharsets.UTF_8));
     this.fieldDelimiter = fieldDelimiter;
 }
Esempio n. 53
0
        /// <summary>
        /// The parse item.
        /// </summary>
        /// <param name="rectype">
        /// The rectype.
        /// </param>
        /// <param name="recnum">
        /// The recnum.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="itemNamesSqlList">
        /// </param>
        /// <returns>
        /// The <see cref="AOItem"/>.
        /// </returns>
        public ItemTemplate ParseItem(Extractor.RecordType recordType, int recnum, byte[] data, List<string> itemNamesSqlList)
        {
            int rectype = (int)recordType;
            this.br = new BufferedReader(rectype, recnum, data);
            ItemTemplate aoi = new ItemTemplate();

            aoi.ID = recnum;
            this.br.Skip(16);

            int num = this.br.Read3F1();
            int argc0 = 0;

            int num2 = num - 1;
            int num3 = argc0;

            while (true)
            {
                int arg1c2 = num3;
                int num4 = num2;
                if (arg1c2 > num4)
                {
                    break;
                }

                int attrkey = this.br.ReadInt32();
                int attrval = this.br.ReadInt32();
                if (attrkey == 54)
                {
                    aoi.Quality = attrval;
                }
                else
                {
                    aoi.Stats.Add(attrkey, attrval);
                }

                num3++;
            }

            this.br.Skip(8);

            short num5 = this.br.ReadInt16();
            short num6 = this.br.ReadInt16();
            string itemname = string.Empty;
            if (num5 > 0)
            {
                itemname = this.br.ReadString(num5);
            }

            if (itemNamesSqlList != null)
            {
                itemNamesSqlList.Add(string.Format("( {0} , '{1}' , '{2}', '{3}' ) ",
                    recnum,
                    itemname.Replace("'", "''"),
                    Enum.GetName(typeof(Extractor.RecordType), recordType),
                    aoi.getItemAttribute(79)));
            }

            if (num6 > 0)
            {
                this.br.ReadString(num6); // Read and discard Description
            }

            bool flag4 = true;
            checked
            {
                while (this.br.Ptr < this.br.Buffer.Length - 8 && flag4)
                {
                    switch (this.br.ReadInt32()) // what are these ints ?
                    {
                        case 2:
                            this.ParseFunctionSet(aoi.Events);
                            break;
                        case 3:
                        case 5:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 21:
                            goto IL_4BF;
                        case 4:
                            this.ParseAtkDefSet(aoi.Attack, aoi.Defend);
                            break;
                        case 6:
                            {
                                this.br.Skip(4);
                                int count = this.br.Read3F1() * 8;
                                this.br.Skip(count);
                                break;
                            }

                        case 14:
                            this.ParseAnimSoundSet(1, aoi);
                            break;
                        case 20:
                            this.ParseAnimSoundSet(2, aoi);
                            break;
                        case 22:
                            this.ParseActionSet(aoi.Actions);
                            break;
                        case 23:
                            this.ParseShopHash(aoi.Events);
                            break;
                        default:
                            goto IL_4BF;
                    }

                    continue;
                IL_4BF:
                    flag4 = false;
                }
            }

            return aoi;
        }
Esempio n. 54
0
        /// <summary>
        /// The parse nano.
        /// </summary>
        /// <param name="rectype">
        /// The rectype.
        /// </param>
        /// <param name="recnum">
        /// The recnum.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="sqlFile">
        /// The sql file.
        /// </param>
        /// <returns>
        /// The <see cref="AONanos"/>.
        /// </returns>
        public NanoFormula ParseNano(int recnum, byte[] data, string sqlFile)
        {
            this.br = new BufferedReader((int)Extractor.RecordType.Nano, recnum, data);
            NanoFormula aon = new NanoFormula();
            aon.ID = recnum;
            this.br.Skip(16);

            int numberOfAttributes = this.br.Read3F1() - 1;
            int counter = 0;

            while (true)
            {
                if (counter > numberOfAttributes)
                {
                    break;
                }

                int attrkey = this.br.ReadInt32();
                int attrval = this.br.ReadInt32();
                if (attrkey == 54)
                {
                    aon.Stats.Add(attrkey, attrval);
                }
                else
                {
                    aon.Stats.Add(attrkey, attrval);
                }

                counter++;
            }

            this.br.Skip(8);

            short nameLength = this.br.ReadInt16();
            short descriptionLength = this.br.ReadInt16();
            if (nameLength > 0)
            {
                this.br.ReadString(nameLength);
            }

            if (descriptionLength > 0)
            {
                this.br.ReadString(descriptionLength); // Read and discard Description
            }

            bool flag4 = true;
            checked
            {
                while (this.br.Ptr < this.br.Buffer.Length - 8 && flag4)
                {
                    switch (this.br.ReadInt32())
                    {
                        case 2:
                            this.ParseFunctionSet(aon.Events);
                            break;
                        case 3:
                        case 5:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 21:
                            goto IL_4BF;
                        case 4:
                            this.ParseAtkDefSet(aon.Attack, aon.Defend);
                            break;
                        case 6:
                            {
                                this.br.Skip(4);
                                int count = this.br.Read3F1() * 8;
                                this.br.Skip(count);
                                break;
                            }

                        case 14:
                            this.ParseAnimSoundSet(1, null);
                            break;
                        case 20:
                            this.ParseAnimSoundSet(2, null);
                            break;
                        case 22:
                            this.ParseActionSet(aon.Actions);
                            break;
                        case 23:
                            this.ParseShopHash(aon.Events);
                            break;
                        default:
                            goto IL_4BF;
                    }

                    continue;
                IL_4BF:
                    flag4 = false;
                }
            }

            return aon;
        }
Esempio n. 55
0
 /// <summary>
 /// Creates a dictionary based on a File.
 /// <para>
 /// NOTE: content is treated as UTF-8
 /// </para>
 /// </summary>
 public PlainTextDictionary(File file)
 {
     @in = new BufferedReader(IOUtils.getDecodingReader(file, StandardCharsets.UTF_8));
 }
Esempio n. 56
0
		protected void reader_BufferFullCallback(BufferedReader<Lex, char> sender, Lex[] buffer)
		{
			Lexes.Add(buffer[0]);
		}
Esempio n. 57
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void addInternal(java.io.BufferedReader in) throws java.io.IOException
	  private void addInternal(BufferedReader @in)
	  {
		string line = null;
		while ((line = @in.readLine()) != null)
		{
		  if (line.Length == 0 || line[0] == '#')
		  {
			continue; // ignore empty lines and comments
		  }

		  CharsRef[] inputs;
		  CharsRef[] outputs;

		  // TODO: we could process this more efficiently.
		  string[] sides = Split(line, "=>");
		  if (sides.Length > 1) // explicit mapping
		  {
			if (sides.Length != 2)
			{
			  throw new System.ArgumentException("more than one explicit mapping specified on the same line");
			}
			string[] inputStrings = Split(sides[0], ",");
			inputs = new CharsRef[inputStrings.Length];
			for (int i = 0; i < inputs.Length; i++)
			{
			  inputs[i] = analyze(unescape(inputStrings[i]).Trim(), new CharsRef());
			}

			string[] outputStrings = Split(sides[1], ",");
			outputs = new CharsRef[outputStrings.Length];
			for (int i = 0; i < outputs.Length; i++)
			{
			  outputs[i] = analyze(unescape(outputStrings[i]).Trim(), new CharsRef());
			}
		  }
		  else
		  {
			string[] inputStrings = Split(line, ",");
			inputs = new CharsRef[inputStrings.Length];
			for (int i = 0; i < inputs.Length; i++)
			{
			  inputs[i] = analyze(unescape(inputStrings[i]).Trim(), new CharsRef());
			}
			if (expand)
			{
			  outputs = inputs;
			}
			else
			{
			  outputs = new CharsRef[1];
			  outputs[0] = inputs[0];
			}
		  }

		  // currently we include the term itself in the map,
		  // and use includeOrig = false always.
		  // this is how the existing filter does it, but its actually a bug,
		  // especially if combined with ignoreCase = true
		  for (int i = 0; i < inputs.Length; i++)
		  {
			for (int j = 0; j < outputs.Length; j++)
			{
			  add(inputs[i], outputs[j], false);
			}
		  }
		}
	  }
Esempio n. 58
0
 /// <summary>
 /// Creates a dictionary based on an inputstream.
 /// <para>
 /// NOTE: content is treated as UTF-8
 /// </para>
 /// </summary>
 public PlainTextDictionary(InputStream dictFile)
 {
     @in = new BufferedReader(IOUtils.getDecodingReader(dictFile, StandardCharsets.UTF_8));
 }
Esempio n. 59
0
 private void SendStoredMessages()
 {
     if (HasInternetConnection)
       {
     try
     {
       using (File dir = Context.GetDir("RaygunIO", FileCreationMode.Private))
       {
     File[] files = dir.ListFiles();
     foreach (File file in files)
     {
       if (file.Name.StartsWith("RaygunErrorMessage"))
       {
         using (FileInputStream stream = new FileInputStream(file))
         {
           using (InputStreamInvoker isi = new InputStreamInvoker(stream))
           {
             using (InputStreamReader streamReader = new Java.IO.InputStreamReader(isi))
             {
               using (BufferedReader bufferedReader = new BufferedReader(streamReader))
               {
                 StringBuilder stringBuilder = new StringBuilder();
                 string line;
                 while ((line = bufferedReader.ReadLine()) != null)
                 {
                   stringBuilder.Append(line);
                 }
                 bool success = SendMessage(stringBuilder.ToString());
                 // If just one message fails to send, then don't delete the message, and don't attempt sending anymore until later.
                 if (!success)
                 {
                   return;
                 }
                 System.Diagnostics.Debug.WriteLine("Sent " + file.Name);
               }
             }
           }
         }
         file.Delete();
       }
     }
     if (dir.List().Length == 0)
     {
       if (files.Length > 0)
       {
         System.Diagnostics.Debug.WriteLine("Successfully sent all pending messages");
       }
       dir.Delete();
     }
       }
     }
     catch (Exception ex)
     {
       System.Diagnostics.Debug.WriteLine(string.Format("Error sending stored messages to Raygun.io {0}", ex.Message));
     }
       }
 }
Esempio n. 60
0
 /// <summary>
 /// Creates a dictionary based on a reader. 
 /// Using <code>fieldDelimiter</code> to seperate out the
 /// fields in a line.
 /// </summary>
 public FileDictionary(Reader reader, string fieldDelimiter)
 {
     @in = new BufferedReader(reader);
     this.fieldDelimiter = fieldDelimiter;
 }