コード例 #1
0
 public void ReadAgeOrRange_RangePercentage()
 {
     StringReader reader = new StringReader("30-75(10%)");
     int index;
     eventHandlerCalled = false;
     expectedRange = new AgeRange(30, 75);
     expectedPercentage = Percentage.Parse("10%");
     InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
     Assert.IsTrue(eventHandlerCalled);
     Assert.AreEqual(0, index);
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #2
0
 public void ReadAgeOrRange_RangeWhitespacePercentage()
 {
     StringReader reader = new StringReader(" 1-100 (22.2%)Hi");
     int index;
     eventHandlerCalled = false;
     expectedRange = new AgeRange(1, 100);
     expectedPercentage = Percentage.Parse("22.2%");
     InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
     Assert.IsTrue(eventHandlerCalled);
     Assert.AreEqual(1, index);
     Assert.AreEqual('H', reader.Peek());
 }
コード例 #3
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Reads a percentage for partial thinning of a cohort age or age
        /// range.
        /// </summary>
        /// <remarks>
        /// The percentage is bracketed by parentheses.
        /// </remarks>
        public static InputValue<Percentage> ReadPercentage(StringReader reader,
                                                            out int      index)
        {
            TextReader.SkipWhitespace(reader);
            index = reader.Index;

            //  Read left parenthesis
            int nextChar = reader.Peek();
            if (nextChar == -1)
                throw new InputValueException();  // Missing value
            if (nextChar != '(')
                throw MakeInputValueException(TextReader.ReadWord(reader),
                                              "Value does not start with \"(\"");
            StringBuilder valueAsStr = new StringBuilder();
            valueAsStr.Append((char) (reader.Read()));

            //  Read whitespace between '(' and percentage
            valueAsStr.Append(ReadWhitespace(reader));

            //  Read percentage
            string word = ReadWord(reader, ')');
            if (word == "")
                throw MakeInputValueException(valueAsStr.ToString(),
                                              "No percentage after \"(\"");
            valueAsStr.Append(word);
            Percentage percentage;
            try {
                percentage = Percentage.Parse(word);
            }
            catch (System.FormatException exc) {
                throw MakeInputValueException(valueAsStr.ToString(),
                                              exc.Message);
            }
            if (percentage < 0.0 || percentage > 1.0)
                throw MakeInputValueException(valueAsStr.ToString(),
                                              string.Format("{0} is not between 0% and 100%", word));

            //  Read whitespace and ')'
            valueAsStr.Append(ReadWhitespace(reader));
            char? ch = TextReader.ReadChar(reader);
            if (! ch.HasValue)
                throw MakeInputValueException(valueAsStr.ToString(),
                                              "Missing \")\"");
            valueAsStr.Append(ch.Value);
            if (ch != ')')
                throw MakeInputValueException(valueAsStr.ToString(),
                                              string.Format("Value ends with \"{0}\" instead of \")\"", ch));

            return new InputValue<Percentage>(percentage, valueAsStr.ToString());
        }
コード例 #4
0
 public void NonEmptyString()
 {
     string str = "Hello World!";
     StringReader reader = new StringReader(str);
     int expectedIndex = 0;
     foreach (char expectedCh in str) {
         Assert.AreEqual(expectedIndex, reader.Index);
         int i = reader.Read();
         Assert.IsTrue(i != -1);
         Assert.AreEqual(expectedCh, (char) i);
         expectedIndex++;
     }
     Assert.AreEqual(expectedIndex, reader.Index);
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #5
0
        public void ReadBlock()
        {
            string str = "Four score and seven years ago ...";
            StringReader reader = new StringReader(str);
            char[] buffer = new char[str.Length];
            int blockSize = 5;

            for (int bufferIndex = 0; bufferIndex < buffer.Length; bufferIndex += blockSize) {
                Assert.AreEqual(bufferIndex, reader.Index);
                int countToRead;
                if (bufferIndex + blockSize > buffer.Length)
                    countToRead = buffer.Length - bufferIndex;
                else
                    countToRead = blockSize;
                Assert.AreEqual(countToRead, reader.Read(buffer, bufferIndex,
                                                         countToRead));
            }
            Assert.AreEqual(str.Length, reader.Index);
            Assert.AreEqual(-1, reader.Peek());
            Assert.AreEqual(str, new string(buffer));
        }
コード例 #6
0
 public void EmptyString()
 {
     StringReader reader = new StringReader("");
     Assert.AreEqual(0, reader.Index);
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #7
0
 //---------------------------------------------------------------------
 /// <summary>
 /// Reads whitespace from a string reader.
 /// </summary>
 public static string ReadWhitespace(StringReader reader)
 {
     StringBuilder whitespace = new StringBuilder();
     int i = reader.Peek();
     while (i != -1 && char.IsWhiteSpace((char) i)) {
         whitespace.Append((char) reader.Read());
         i = reader.Peek();
     }
     return whitespace.ToString();
 }
        //----------------------------------------------------------------------

        //  Need to include a copy of this method because it modifies an
        //  instance member "rankingMethod" in the original version.  Bad
        //  design; the ranking method should be passed as a parameter.
        
        protected void ReadForestTypeTable(IStandRankingMethod rankingMethod)
        {
            int optionalStatements = 0;
            
            //check if this is the ForestTypeTable
            if (CurrentName == Names.ForestTypeTable) {
                ReadName(Names.ForestTypeTable);

                //fresh input variables for table
                InputVar<string> inclusionRule = new InputVar<string>("Inclusion Rule");
                InputVar<AgeRange> age_range = new InputVar<AgeRange>("Age Range", ParseAgeOrRange);
                InputVar<string> percentOfCells = new InputVar<string>("PercentOfCells");  //as a string so it can include keyword 'highest'
                InputVar<string> speciesName = new InputVar<string>("Species");
                
                
                //list for each rule- each line is a separate rule
                List<InclusionRule> rule_list = new List<InclusionRule>();              
                //keep reading until no longer in the ForestTypeTable
                while (! AtEndOfInput && !namesThatFollowForestType.Contains(CurrentName)) {
                    StringReader currentLine = new StringReader(CurrentLine);

                    //  inclusionRule column
                    ReadValue(inclusionRule, currentLine);

                    //verify inclusion rule = 'optional', 'required', or 'forbidden'
                    if (inclusionRule.Value.Actual != "Optional" && inclusionRule.Value.Actual != "Required"
                                    && inclusionRule.Value.Actual != "Forbidden") {
                        string[] ic_list = new string[]{"Valid Inclusion Rules:",
                                                                           "    Optional",
                                                                           "    Required",
                                                                           "    Forbidden"};
                        throw new InputValueException(CurrentName, CurrentName + " is not a valid inclusion rule.",
                                                  new MultiLineText(ic_list));
                    }

                    if (inclusionRule.Value.Actual == "Optional")
                        optionalStatements++;
                    
                    
                    TextReader.SkipWhitespace(currentLine);
                    ReadValue(age_range, currentLine);

                    //percentage column
                    TextReader.SkipWhitespace(currentLine);
                    ReadValue(percentOfCells, currentLine);
                    //PlugIn.ModelCore.UI.WriteLine("percentOfCells = {0}", percentOfCells.Value.String);
                    //cannot validate until parsing is done.  will do this in the inclusionRule constructor

                    //a list in case there are multiple species on this line
                    List<string> species_list = new List<string>();
                    //add each species to this rule's species list
                    TextReader.SkipWhitespace(currentLine);
                    while (currentLine.Peek() != -1) {
                        //species column (build list)
                        
                        ReadValue(speciesName, currentLine);
                        string name = speciesName.Value.String;
                        
                        ISpecies species = GetSpecies(new InputValue<string>(name, speciesName.Value.String));
                        if (species_list.Contains(species.Name))
                            throw NewParseException("The species {0} appears more than once.", species.Name);
                        species_list.Add(species.Name);

                        //species_list.Add(species.Value.String);
                        TextReader.SkipWhitespace(currentLine);
                    }

                    //add this new inclusion rule (by parameters)  to the requirement
                    rule_list.Add(new InclusionRule(inclusionRule.Value.String,
                                                    age_range.Value.Actual,
                                                    percentOfCells.Value.String,
                                                    species_list));
                    
                    GetNextLine();
                }
                //create a new requirement with this list of rules
                IRequirement inclusionRequirement = new InclusionRequirement(rule_list);
                //add this requirement to the ranking method
                rankingMethod.AddRequirement(inclusionRequirement);
            }
            
            if(optionalStatements > 0 && optionalStatements < 2)
                throw new InputValueException(CurrentName, "If there are optional statements, there must be more than one",
                                                  "ForestTypeTable");
            
        }
 public void Read_MultipleWords()
 {
     string[] words = new string[] { "987.01", ".'.", "x-y*z^2", @"C:\some\Path\to\a\file.ext" };
     StringReader reader = new StringReader(string.Join(" ", words));
     foreach (string word in words) {
         strVar.ReadValue(reader);
         Assert.AreEqual(word, strVar.Value.Actual);
     }
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #10
0
 public void GetReadMethod_Byte_StringOfBytes()
 {
     StringReader reader = new StringReader(valuesAsStr);
     int prevIndex = -1;
     foreach (byte b in values) {
         int index;
         InputValue<byte> result = byteReadMethod(reader, out index);
         Assert.AreEqual(b, result.Actual);
         Assert.IsTrue(index > prevIndex);
         prevIndex = index;
     }
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #11
0
 public void ReadAgeOrRange_AgeWhitespacePercentage()
 {
     StringReader reader = new StringReader("66 ( 50% )\t");
     int index;
     eventHandlerCalled = false;
     expectedRange = new AgeRange(66, 66);
     expectedPercentage = Percentage.Parse("50%");
     InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
     Assert.IsTrue(eventHandlerCalled);
     Assert.AreEqual(0, index);
     Assert.AreEqual('\t', reader.Peek());
 }
コード例 #12
0
 public void ReadWord_Empty()
 {
     StringReader reader = new StringReader("");
     string word = PartialThinning.ReadWord(reader, '(');
     Assert.AreEqual("", word);
     Assert.AreEqual(-1, reader.Peek());
     Assert.AreEqual(0, reader.Index);
 }
コード例 #13
0
 public void ReadPercentage_Whitespace()
 {
     StringReader reader = new StringReader("( 55.5%\t)");
     int index;
     InputValue<Percentage> percentage = PartialThinning.ReadPercentage(reader, out index);
     Assert.IsNotNull(percentage);
     Assert.AreEqual("( 55.5%\t)", percentage.String);
     Assert.AreEqual(0.555, (double) (percentage.Actual));
     Assert.AreEqual(0, index);
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #14
0
 public void ReadPercentage_WhitespaceAfterLParen()
 {
     StringReader reader = new StringReader("( 8%)a");
     int index;
     InputValue<Percentage> percentage = PartialThinning.ReadPercentage(reader, out index);
     Assert.IsNotNull(percentage);
     Assert.AreEqual("( 8%)", percentage.String);
     Assert.AreEqual(0.08, (double) (percentage.Actual));
     Assert.AreEqual(0, index);
     Assert.AreEqual('a', reader.Peek());
 }
コード例 #15
0
 //---------------------------------------------------------------------
 private void CheckReadResults(string readerInitVal,
     string expectedReadResult)
 {
     StringReader reader = new StringReader(readerInitVal);
     int index;
     InputValue<string> val = String.Read(reader, out index);
     Assert.AreEqual(expectedReadResult, val.Actual);
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #16
0
 public void Read_MultipleWords()
 {
     string[] words = new string[] { "987.01", ".'.", "x-y*z^2", @"C:\some\Path\to\a\file.ext" };
     StringReader reader = new StringReader(string.Join(" ", words));
     foreach (string word in words) {
         int index;
         InputValue<string> str = String.Read(reader, out index);
         Assert.AreEqual(word, str.Actual);
         Assert.AreEqual(index + word.Length, reader.Index);
     }
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #17
0
 public void ReadWord_AgeWhiteSpace()
 {
     StringReader reader = new StringReader("70 ");
     string word = PartialThinning.ReadWord(reader, '(');
     Assert.AreEqual("70", word);
     Assert.AreEqual(' ', reader.Peek());
     Assert.AreEqual(2, reader.Index);
 }
コード例 #18
0
 public void ReadWord_AgeLeftParen()
 {
     StringReader reader = new StringReader("200(75%)");
     string word = PartialThinning.ReadWord(reader, '(');
     Assert.AreEqual("200", word);
     Assert.AreEqual('(', reader.Peek());
     Assert.AreEqual(3, reader.Index);
 }
コード例 #19
0
        public void ReadAgeOrRange_Multiple()
        {
            StringReader reader = new StringReader(" 1-40 (50%)  50(65%)\t 65-70  71-107 ( 15% )  109");
            int index;                            //0123456789_123456789_^123456789_123456789_12345678

            eventHandlerCalled = false;
            expectedRange = new AgeRange(1, 40);
            expectedPercentage = Percentage.Parse("50%");
            InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
            Assert.IsTrue(eventHandlerCalled);
            Assert.AreEqual(1, index);
            Assert.AreEqual(' ', reader.Peek());

            eventHandlerCalled = false;
            expectedRange = new AgeRange(50, 50);
            expectedPercentage = Percentage.Parse("65%");
            ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
            Assert.IsTrue(eventHandlerCalled);
            Assert.AreEqual(13, index);
            Assert.AreEqual('\t', reader.Peek());

            eventHandlerCalled = false;
            expectedRange = new AgeRange(65, 70);
            expectedPercentage = null;
            ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
            Assert.IsTrue(eventHandlerCalled);
            Assert.AreEqual(22, index);
            Assert.AreEqual('7', reader.Peek());

            eventHandlerCalled = false;
            expectedRange = new AgeRange(71, 107);
            expectedPercentage = Percentage.Parse("15%");
            ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
            Assert.IsTrue(eventHandlerCalled);
            Assert.AreEqual(29, index);
            Assert.AreEqual(' ', reader.Peek());

            eventHandlerCalled = false;
            expectedRange = new AgeRange(109, 109);
            expectedPercentage = null;
            ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
            Assert.IsTrue(eventHandlerCalled);
            Assert.AreEqual(45, index);
            Assert.AreEqual(-1, reader.Peek());
        }
コード例 #20
0
 public void ReadWord_Range()
 {
     StringReader reader = new StringReader("40-110");
     string word = PartialThinning.ReadWord(reader, '(');
     Assert.AreEqual("40-110", word);
     Assert.AreEqual(-1, reader.Peek());
     Assert.AreEqual(6, reader.Index);
 }
コード例 #21
0
        //---------------------------------------------------------------------
        /// <summary>
        /// Read a string from a StringReader.
        /// </summary>
        /// <remarks>
        /// This method reads a string from a StringReader.  The string is
        /// either an unquoted word or a quoted string.  A word is one or more
        /// adjacent non-whitespace characters.  A quoted string is zero or
        /// more characters surrounded by a pair of quotes.  The quotes may be
        /// a pair of double quotes (") or a pair of single quotes (').  A
        /// quote character can be included inside a quoted string by escaping
        /// it with a backslash (\).
        /// <example>
        /// Here are some valid strings:
        /// <code>
        ///   foo
        ///   a-brief-phrase
        ///   C:\some\path\to\a\file.ext
        ///   ""
        ///   "Four score and seven years ago ..."
        ///   "That's incredulous!"
        ///   'That\'s incredulous!'
        ///   ''
        ///   'He said "Boo."'
        ///   "He said \"Boo.\""
        /// </code>
        /// </example>
        /// Whitespace preceeding the word or the quoted string is skipped.
        /// The delimiting quotes of a quoted string are removed.
        /// </remarks>
        /// <exception cref="">System.IO.EndOfStreamException</exception>
        public static InputValue<string> Read(StringReader reader,
            out int      index)
        {
            TextReader.SkipWhitespace(reader);
            if (reader.Peek() == -1)
                throw new InputValueException();

            index = reader.Index;
            char nextChar = (char) reader.Peek();
            if (nextChar == '\'' || nextChar == '"') {
                //  Quoted string
                char startQuote = (char) reader.Read();
                StringBuilder quotedStr = new StringBuilder();
                quotedStr.Append(startQuote);
                StringBuilder actualStr = new StringBuilder();
                bool endQuoteFound = false;
                while (! endQuoteFound) {
                    char? ch = TextReader.ReadChar(reader);
                    if (! ch.HasValue)
                        throw new InputValueException(quotedStr.ToString(),
                                                      "String has no end quote: {0}",
                                                      quotedStr.ToString());
                    if (ch.Value == startQuote) {
                        endQuoteFound = true;
                        quotedStr.Append(ch.Value);
                    }
                    else {
                        if (ch.Value == '\\') {
                            //  Get the next character if it's a quote.
                            nextChar = (char) reader.Peek();
                            if (nextChar == '\'' || nextChar == '"') {
                                quotedStr.Append(ch.Value);
                                ch = TextReader.ReadChar(reader);
                            }
                        }
                        actualStr.Append(ch.Value);
                        quotedStr.Append(ch.Value);
                    }
                }
                return new InputValue<string>(actualStr.ToString(),
                                              quotedStr.ToString());
            }
            else {
                string word = TextReader.ReadWord(reader);
                return new InputValue<string>(word, word);
            }
        }
コード例 #22
0
 public void ReadWord_RangeWhitespace()
 {
     StringReader reader = new StringReader("1-35\t");
     string word = PartialThinning.ReadWord(reader, '(');
     Assert.AreEqual("1-35", word);
     Assert.AreEqual('\t', reader.Peek());
     Assert.AreEqual(4, reader.Index);
 }
 //---------------------------------------------------------------------
 private void CheckReadResults(string readerInitVal,
     string expectedReadResult)
 {
     StringReader reader = new StringReader(readerInitVal);
     strVar.ReadValue(reader);
     Assert.AreEqual(expectedReadResult, strVar.Value.Actual);
     Assert.AreEqual(-1, reader.Peek());
 }
コード例 #24
0
 public void ReadWord_RangeLeftParen()
 {
     StringReader reader = new StringReader("55-90( 10%)\t");
     string word = PartialThinning.ReadWord(reader, '(');
     Assert.AreEqual("55-90", word);
     Assert.AreEqual('(', reader.Peek());
     Assert.AreEqual(5, reader.Index);
 }
コード例 #25
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Reads a cohort age or a range of ages (format: age-age) followed
        /// by an optional percentage for partial thinning.
        /// </summary>
        /// <remarks>
        /// The optional percentage is bracketed by parenthesis.
        /// </remarks>
        public static InputValue<AgeRange> ReadAgeOrRange(StringReader reader,
                                                          out int      index)
        {
            TextReader.SkipWhitespace(reader);
            index = reader.Index;

            string word = ReadWord(reader, '(');
            if (word == "")
                throw new InputValueException();  // Missing value

            AgeRange ageRange = BaseHarvest.InputParametersParser.ParseAgeOrRange(word);

            //  Does a percentage follow?
            TextReader.SkipWhitespace(reader);
            if (reader.Peek() == '(') {
                int ignore;
                InputValue<Percentage> percentage = ReadPercentage(reader, out ignore);
                if (ReadAgeOrRangeEvent != null)
                    ReadAgeOrRangeEvent(ageRange, percentage.Actual);
            }
            else {
                if (ReadAgeOrRangeEvent != null)
                    ReadAgeOrRangeEvent(ageRange, null);
            }

            return new InputValue<AgeRange>(ageRange, word);
        }
コード例 #26
0
 public void ReadWord_PercentageRightParen()
 {
     StringReader reader = new StringReader("10.5%)\t");
     string word = PartialThinning.ReadWord(reader, ')');
     Assert.AreEqual("10.5%", word);
     Assert.AreEqual(')', reader.Peek());
     Assert.AreEqual(5, reader.Index);
 }
コード例 #27
0
        //---------------------------------------------------------------------
        /// <summary>
        /// Reads a cohort age or a range of ages (format: age-age) followed
        /// by an optional percentage for partial thinning.
        /// </summary>
        /// <remarks>
        /// The optional percentage is bracketed by parenthesis.
        /// </remarks>
        public static InputValue<AgeRange> ReadAgeOrRange(StringReader reader,
            out int      index)
        {
            TextReader.SkipWhitespace(reader);
            index = reader.Index;

            string word = ReadWord(reader, '(');
            if (word == "")
                throw new InputValueException();  // Missing value

            AgeRange ageRange = AgeRangeParsing.ParseAgeOrRange(word);

            //  Does a percentage follow?
            TextReader.SkipWhitespace(reader);
            if (reader.Peek() == '(') {
                int ignore;
                InputValue<Percentage> percentage = ReadPercentage(reader, out ignore);
                percentages[ageRange.Start] = percentage;
            }

            return new InputValue<AgeRange>(ageRange, word);
        }
コード例 #28
0
 public void ReadWord_RightParen()
 {
     StringReader reader = new StringReader(")");
     string word = PartialThinning.ReadWord(reader, ')');
     Assert.AreEqual("", word);
     Assert.AreEqual(')', reader.Peek());
     Assert.AreEqual(0, reader.Index);
 }
コード例 #29
0
 //---------------------------------------------------------------------
 /// <summary>
 /// Reads a word from a string reader.
 /// </summary>
 /// <remarks>
 /// The word is terminated by whitespace, the end of input, or a
 /// particular delimiter character.
 /// </remarks>
 public static string ReadWord(StringReader reader,
     char         delimiter)
 {
     StringBuilder word = new StringBuilder();
     int i = reader.Peek();
     while (i != -1 && ! char.IsWhiteSpace((char) i) && i != delimiter) {
         word.Append((char) reader.Read());
         i = reader.Peek();
     }
     return word.ToString();
 }
 public void IntParseWrapper_StringOfInts()
 {
     StringReader reader = new StringReader(intValuesAsStr);
     int prevIndex = -1;
     foreach (int i in intValues) {
         int index;
         InputValue<int> result = intParseWrapper.Read(reader, out index);
         Assert.AreEqual(i, result.Actual);
         Assert.IsTrue(index > prevIndex);
         prevIndex = index;
     }
     Assert.AreEqual(-1, reader.Peek());
 }