SubstringSpecial() static private method

static private SubstringSpecial ( this self, int start, int end ) : string
self this
start int
end int
return string
Example #1
0
        /// <summary>
        /// Converts a string in JDBC time escape format to a <code>Time</code> value.
        /// </summary>
        /// <param name="s"> time in format "hh:mm:ss" </param>
        /// <returns> a corresponding <code>Time</code> object </returns>
        public static Time ValueOf(String s)
        {
            int hour;
            int minute;
            int second;
            int firstColon;
            int secondColon;

            if (s == null)
            {
                throw new System.ArgumentException();
            }

            firstColon  = s.IndexOf(':');
            secondColon = s.IndexOf(':', firstColon + 1);
            if ((firstColon > 0) & (secondColon > 0) & (secondColon < s.Length() - 1))
            {
                hour   = Convert.ToInt32(s.Substring(0, firstColon));
                minute = Convert.ToInt32(StringHelperClass.SubstringSpecial(s, firstColon + 1, secondColon));
                second = Convert.ToInt32(s.Substring(secondColon + 1));
            }
            else
            {
                throw new System.ArgumentException();
            }

            return(new Time(hour, minute, second));
        }
Example #2
0
        public override void onItemClick <T1>(AdapterView <T1> parent, View view, int position, long id)
        {
            string device = ((TextView)view).Text.ToString();

            logicalName = device.Substring(0, device.IndexOf(DEVICE_ADDRESS_START, StringComparison.Ordinal));

            string address = StringHelperClass.SubstringSpecial(device, device.IndexOf(DEVICE_ADDRESS_START, StringComparison.Ordinal) + DEVICE_ADDRESS_START.Length, device.IndexOf(DEVICE_ADDRESS_END, StringComparison.Ordinal));

            try
            {
                foreach (object entry in bxlConfigLoader.Entries)
                {
                    JposEntry jposEntry = (JposEntry)entry;
                    bxlConfigLoader.removeEntry(jposEntry.LogicalName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            try
            {
                bxlConfigLoader.addEntry(logicalName, BXLConfigLoader.DEVICE_CATEGORY_POS_PRINTER, logicalName, BXLConfigLoader.DEVICE_BUS_BLUETOOTH, address);

                bxlConfigLoader.saveFile();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
        }
Example #3
0
        // LUCENE-3642: normalize BMP->SMP and check that offsets are correct
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testCrossPlaneNormalization2() throws java.io.IOException
        public virtual void testCrossPlaneNormalization2()
        {
            Analyzer analyzer = new AnalyzerAnonymousInnerClassHelper2(this);
            int      num      = 1000 * RANDOM_MULTIPLIER;

            for (int i = 0; i < num; i++)
            {
                string      s  = TestUtil.randomUnicodeString(random());
                TokenStream ts = analyzer.tokenStream("foo", s);
                try
                {
                    ts.reset();
                    OffsetAttribute offsetAtt = ts.addAttribute(typeof(OffsetAttribute));
                    while (ts.incrementToken())
                    {
                        string highlightedText = StringHelperClass.SubstringSpecial(s, offsetAtt.startOffset(), offsetAtt.endOffset());
                        for (int j = 0, cp = 0; j < highlightedText.Length; j += char.charCount(cp))
                        {
                            cp = char.ConvertToUtf32(highlightedText, j);
                            assertTrue("non-letter:" + cp.ToString("x"), char.IsLetter(cp));
                        }
                    }
                    ts.end();
                }
                finally
                {
                    IOUtils.closeWhileHandlingException(ts);
                }
            }
            // just for fun
            checkRandomData(random(), analyzer, num);
        }
 public virtual bool accept(File dir, string name)
 {
     if (name.Length > 4)
     {
         string fileExtension = StringHelperClass.SubstringSpecial(name, name.Length - 4, name.Length);
         return(".jpg".Equals(fileExtension, StringComparison.CurrentCultureIgnoreCase) || ".png".Equals(fileExtension, StringComparison.CurrentCultureIgnoreCase));
     }
     return(false);
 }
    public virtual string replaceVariables(string expression)
    {
        int openIndex = expression.IndexOf(EvaluationConstants.OPEN_VARIABLE, StringComparison.Ordinal);

        if (openIndex < 0)
        {
            return(expression);
        }

        string replacedExpression = expression;

        while (openIndex >= 0)
        {
            int closedIndex = -1;
            if (openIndex >= 0)
            {
                closedIndex = replacedExpression.IndexOf(EvaluationConstants.CLOSED_VARIABLE, openIndex + 1, StringComparison.Ordinal);
                if (closedIndex > openIndex)
                {
                    string variableName = StringHelperClass.SubstringSpecial(replacedExpression, openIndex + EvaluationConstants.OPEN_VARIABLE.Length, closedIndex);

                    // Validate that the variable name is valid.
                    try
                    {
                        isValidName(variableName);
                    }
                    catch (System.ArgumentException iae)
                    {
                        throw new EvaluationException("Invalid variable name of \"" + variableName + "\".", iae);
                    }

                    string variableValue = getVariableValue(variableName);

                    string variableString = EvaluationConstants.OPEN_VARIABLE + variableName + EvaluationConstants.CLOSED_VARIABLE;

                    replacedExpression = EvaluationHelper.replaceAll(replacedExpression, variableString, variableValue);
                }
                else
                {
                    break;
                }
            }


            openIndex = replacedExpression.IndexOf(EvaluationConstants.OPEN_VARIABLE, StringComparison.Ordinal);
        }

        // If an open brace is left over, then a variable could not be replaced.
        int openBraceIndex = replacedExpression.IndexOf(EvaluationConstants.OPEN_VARIABLE, StringComparison.Ordinal);

        if (openBraceIndex > -1)
        {
            throw new EvaluationException("A variable has not been closed (index=" + openBraceIndex + ").");
        }

        return(replacedExpression);
    }
Example #6
0
        }         // equals()

        /// <summary>
        /// A routine for parsing the MIME type out of a String.
        /// </summary>
        /// <exception cref="NullPointerException"> if <code>rawdata</code> is null </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void parse(String rawdata) throws MimeTypeParseException
        private void Parse(String rawdata)
        {
            int slashIndex = rawdata.IndexOf('/');
            int semIndex   = rawdata.IndexOf(';');

            if ((slashIndex < 0) && (semIndex < 0))
            {
                //    neither character is present, so treat it
                //    as an error
                throw new MimeTypeParseException("Unable to find a sub type.");
            }
            else if ((slashIndex < 0) && (semIndex >= 0))
            {
                //    we have a ';' (and therefore a parameter list),
                //    but no '/' indicating a sub type is present
                throw new MimeTypeParseException("Unable to find a sub type.");
            }
            else if ((slashIndex >= 0) && (semIndex < 0))
            {
                //    we have a primary and sub type but no parameter list
                PrimaryType_Renamed = rawdata.Substring(0, slashIndex).Trim().ToLowerCase(Locale.ENGLISH);
                SubType_Renamed     = rawdata.Substring(slashIndex + 1).Trim().ToLowerCase(Locale.ENGLISH);
                Parameters_Renamed  = new MimeTypeParameterList();
            }
            else if (slashIndex < semIndex)
            {
                //    we have all three items in the proper sequence
                PrimaryType_Renamed = rawdata.Substring(0, slashIndex).Trim().ToLowerCase(Locale.ENGLISH);
                SubType_Renamed     = StringHelperClass.SubstringSpecial(rawdata, slashIndex + 1, semIndex).Trim().ToLowerCase(Locale.ENGLISH);
                Parameters_Renamed  = new MimeTypeParameterList(rawdata.Substring(semIndex));
            }
            else
            {
                //    we have a ';' lexically before a '/' which means we have a primary type
                //    & a parameter list but no sub type
                throw new MimeTypeParseException("Unable to find a sub type.");
            }

            //    now validate the primary and sub types

            //    check to see if primary is valid
            if (!IsValidToken(PrimaryType_Renamed))
            {
                throw new MimeTypeParseException("Primary type is invalid.");
            }

            //    check to see if sub is valid
            if (!IsValidToken(SubType_Renamed))
            {
                throw new MimeTypeParseException("Sub type is invalid.");
            }
        }
Example #7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private final int findLastEntry(PatternEntry entry, StringBuffer excessChars) throws ParseException
        private int FindLastEntry(PatternEntry entry, StringBuffer excessChars)
        {
            if (entry == null)
            {
                return(0);
            }

            if (entry.Strength_Renamed != PatternEntry.RESET)
            {
                // Search backwards for string that contains this one;
                // most likely entry is last one

                int oldIndex = -1;
                if ((entry.Chars_Renamed.length() == 1))
                {
                    int index = entry.Chars_Renamed.charAt(0) >> BYTEPOWER;
                    if ((StatusArray[index] & (BITARRAYMASK << (entry.Chars_Renamed.charAt(0) & BYTEMASK))) != 0)
                    {
                        oldIndex = Patterns.LastIndexOf(entry);
                    }
                }
                else
                {
                    oldIndex = Patterns.LastIndexOf(entry);
                }
                if ((oldIndex == -1))
                {
                    throw new ParseException("couldn't find last entry: " + entry, oldIndex);
                }
                return(oldIndex + 1);
            }
            else
            {
                int i;
                for (i = Patterns.Count - 1; i >= 0; --i)
                {
                    PatternEntry e = Patterns[i];
                    if (e.Chars_Renamed.regionMatches(0, entry.Chars_Renamed, 0, e.Chars_Renamed.length()))
                    {
                        excessChars.Append(StringHelperClass.SubstringSpecial(entry.Chars_Renamed, e.Chars_Renamed.length(), entry.Chars_Renamed.length()));
                        break;
                    }
                }
                if (i == -1)
                {
                    throw new ParseException("couldn't find: " + entry, i);
                }
                return(i + 1);
            }
        }
Example #8
0
 /// <summary>
 /// Does some optimizations on the term. This optimisations are
 /// contextual.
 /// </summary>
 private void optimize(StringBuilder buffer)
 {
     // Additional step for female plurals of professions and inhabitants.
     if (buffer.Length > 5 && StringHelperClass.SubstringSpecial(buffer, buffer.Length - 5, buffer.Length).Equals("erin*"))
     {
         buffer.Remove(buffer.Length - 1, 1);
         strip(buffer);
     }
     // Additional step for irregular plural nouns like "Matrizen -> Matrix".
     // NOTE: this length constraint is probably not a great value, its just to prevent AIOOBE on empty terms
     if (buffer.Length > 0 && buffer[buffer.Length - 1] == ('z'))
     {
         buffer[buffer.Length - 1] = 'x';
     }
 }
        private void permutation(string prefix, string str)
        {
            int n = str.Length;

            if (n == 0)
            {
                SymmetrySet.GetOrAdd(swapIfNeeded(prefix), 0);
            }
            else
            {
                for (int i = 0; i < n; i++)
                {
                    permutation(prefix + str[i], str.Substring(0, i) + StringHelperClass.SubstringSpecial(str, i + 1, n));
                }
            }
        }
Example #10
0
        /// <summary>
        /// undouble vowel
        /// If the words ends CVD, where C is a non-vowel, D is a non-vowel other than I, and V is double a, e, o or u, remove one of the vowels from V (for example, maan -> man, brood -> brod).
        /// </summary>
        /// <param name="sb"> String being stemmed </param>
        private void step4(StringBuilder sb)
        {
            if (sb.Length < 4)
            {
                return;
            }
            string end = StringHelperClass.SubstringSpecial(sb, sb.Length - 4, sb.Length);
            char   c   = end[0];
            char   v1  = end[1];
            char   v2  = end[2];
            char   d   = end[3];

            if (v1 == v2 && d != 'I' && v1 != 'i' && isVowel(v1) && !isVowel(d) && !isVowel(c))
            {
                sb.Remove(sb.Length - 2, sb.Length - 1 - sb.Length - 2);
            }
        }
Example #11
0
 public virtual void onClick(DialogInterface arg0, int arg1)
 {
     outerInstance.outerInstance.mAlert.dismiss();
     try
     {
         string receiveFileName = StringHelperClass.SubstringSpecial(outerInstance.outerInstance.mFilePath, outerInstance.outerInstance.mFilePath.LastIndexOf("/", StringComparison.Ordinal), outerInstance.outerInstance.mFilePath.Length);
         outerInstance.outerInstance.mReceiverService.receiveFile(outerInstance.outerInstance.mTransId, DEST_DIRECTORY + receiveFileName, true);
         Log.i(TAG, "Transfer accepted");
         outerInstance.outerInstance.showQuitDialog();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         Console.Write(e.StackTrace);
         Toast.makeText(outerInstance.outerInstance.mCtxt, "IllegalArgumentException", Toast.LENGTH_SHORT).show();
     }
 }
Example #12
0
        /// <summary>
        /// Converts a string in JDBC date escape format to
        /// a <code>Date</code> value.
        /// </summary>
        /// <param name="s"> a <code>String</code> object representing a date in
        ///        in the format "yyyy-[m]m-[d]d". The leading zero for <code>mm</code>
        /// and <code>dd</code> may also be omitted. </param>
        /// <returns> a <code>java.sql.Date</code> object representing the
        ///         given date </returns>
        /// <exception cref="IllegalArgumentException"> if the date given is not in the
        ///         JDBC date escape format (yyyy-[m]m-[d]d) </exception>
        public static Date ValueOf(String s)
        {
            const int YEAR_LENGTH  = 4;
            const int MONTH_LENGTH = 2;
            const int DAY_LENGTH   = 2;
            const int MAX_MONTH    = 12;
            const int MAX_DAY      = 31;
            int       firstDash;
            int       secondDash;
            Date      d = null;

            if (s == null)
            {
                throw new System.ArgumentException();
            }

            firstDash  = s.IndexOf('-');
            secondDash = s.IndexOf('-', firstDash + 1);

            if ((firstDash > 0) && (secondDash > 0) && (secondDash < s.Length() - 1))
            {
                String yyyy = s.Substring(0, firstDash);
                String mm   = StringHelperClass.SubstringSpecial(s, firstDash + 1, secondDash);
                String dd   = s.Substring(secondDash + 1);
                if (yyyy.Length() == YEAR_LENGTH && (mm.Length() >= 1 && mm.Length() <= MONTH_LENGTH) && (dd.Length() >= 1 && dd.Length() <= DAY_LENGTH))
                {
                    int year  = Convert.ToInt32(yyyy);
                    int month = Convert.ToInt32(mm);
                    int day   = Convert.ToInt32(dd);

                    if ((month >= 1 && month <= MAX_MONTH) && (day >= 1 && day <= MAX_DAY))
                    {
                        d = new Date(year - 1900, month - 1, day);
                    }
                }
            }
            if (d == null)
            {
                throw new System.ArgumentException();
            }

            return(d);
        }
Example #13
0
        /// <summary>
        /// suffix stripping (stemming) on the current term. The stripping is reduced
        /// to the seven "base" suffixes "e", "s", "n", "t", "em", "er" and * "nd",
        /// from which all regular suffixes are build of. The simplification causes
        /// some overstemming, and way more irregular stems, but still provides unique.
        /// discriminators in the most of those cases.
        /// The algorithm is context free, except of the length restrictions.
        /// </summary>
        private void strip(StringBuilder buffer)
        {
            bool doMore = true;

            while (doMore && buffer.Length > 3)
            {
                if ((buffer.Length + substCount > 5) && StringHelperClass.SubstringSpecial(buffer, buffer.Length - 2, buffer.Length).Equals("nd"))
                {
                    buffer.Remove(buffer.Length - 2, buffer.Length - buffer.Length - 2);
                }
                else if ((buffer.Length + substCount > 4) && StringHelperClass.SubstringSpecial(buffer, buffer.Length - 2, buffer.Length).Equals("em"))
                {
                    buffer.Remove(buffer.Length - 2, buffer.Length - buffer.Length - 2);
                }
                else if ((buffer.Length + substCount > 4) && StringHelperClass.SubstringSpecial(buffer, buffer.Length - 2, buffer.Length).Equals("er"))
                {
                    buffer.Remove(buffer.Length - 2, buffer.Length - buffer.Length - 2);
                }
                else if (buffer[buffer.Length - 1] == 'e')
                {
                    buffer.Remove(buffer.Length - 1, 1);
                }
                else if (buffer[buffer.Length - 1] == 's')
                {
                    buffer.Remove(buffer.Length - 1, 1);
                }
                else if (buffer[buffer.Length - 1] == 'n')
                {
                    buffer.Remove(buffer.Length - 1, 1);
                }
                // "t" occurs only as suffix of verbs.
                else if (buffer[buffer.Length - 1] == 't')
                {
                    buffer.Remove(buffer.Length - 1, 1);
                }
                else
                {
                    doMore = false;
                }
            }
        }
Example #14
0
        private Wrapper WrapperOrNullFromDescriptor(String desc)
        {
            if (!desc.StartsWith(WRAPPER_PREFIX))
            {
                // Not a class type (array or method), so not a boxed type
                // or not in the right package
                return(null);
            }
            // Pare it down to the simple class name
            String cname = StringHelperClass.SubstringSpecial(desc, WRAPPER_PREFIX.Length(), desc.Length() - 1);
            // Hash to a Wrapper
            Wrapper w = FROM_WRAPPER_NAME[HashWrapperName(cname)];

            if (w == null || w.wrapperSimpleName().Equals(cname))
            {
                return(w);
            }
            else
            {
                return(null);
            }
        }
Example #15
0
        /// <summary>
        /// Retrieve the "R zone" (1 or 2 depending on the buffer) and return the corresponding string<br>
        /// "R is the region after the first non-vowel following a vowel
        /// or is the null region at the end of the word if there is no such non-vowel"<br> </summary>
        /// <param name="buffer"> java.lang.StringBuilder - the in buffer </param>
        /// <returns> java.lang.String - the resulting string </returns>
        private string retrieveR(StringBuilder buffer)
        {
            int len = buffer.Length;
            int pos = -1;

            for (int c = 0; c < len; c++)
            {
                if (isVowel(buffer[c]))
                {
                    pos = c;
                    break;
                }
            }
            if (pos > -1)
            {
                int consonne = -1;
                for (int c = pos; c < len; c++)
                {
                    if (!isVowel(buffer[c]))
                    {
                        consonne = c;
                        break;
                    }
                }
                if (consonne > -1 && (consonne + 1) < len)
                {
                    return(StringHelperClass.SubstringSpecial(buffer, consonne + 1, len));
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Example #16
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private String doReplacement(String filesRootLoc, String link, String pre, String post, String content) throws Exception
        private string doReplacement(string filesRootLoc, string link, string pre, string post, string content)
        {
            int len = link.Length;
            int pos = content.IndexOf(link, StringComparison.Ordinal);

            if (pos < 0)
            {
                return(content);
            }
            string part1 = content.Substring(0, pos - 1);
            string part2 = content.Substring(pos + len);

            string pattern = "href=\"";
            int    sPos    = link.IndexOf(pattern, StringComparison.Ordinal);

            if (sPos == -1)
            {
                pattern = "src=\"";
                sPos    = link.IndexOf(pattern, StringComparison.Ordinal);
            }
            if (sPos == -1)
            {
                return(content);
            }
            int    ePos     = link.IndexOf("\"", sPos + 1 + pattern.Length);
            string resName  = StringHelperClass.SubstringSpecial(link, sPos + pattern.Length, ePos);
            string fileName = filesRootLoc + resName;

            string resContent = readFile(fileName);

            if (resContent.IndexOf("@import url", StringComparison.Ordinal) >= 0)
            {
                // looks like there's a css with some import to be resolved
                resContent = resolveImport(filesRootLoc, resContent);
            }

            return(part1 + pre + resContent + post + part2);
        }
Example #17
0
        static ProcessEnvironment()
        {
            NameComparator             = new NameComparator();
            EntryComparator            = new EntryComparator();
            TheEnvironment             = new ProcessEnvironment();
            TheUnmodifiableEnvironment = Collections.UnmodifiableMap(TheEnvironment);

            String envblock = environmentBlock();
            int    beg, end, eql;

            for (beg = 0; ((end = envblock.IndexOf('\u0000', beg)) != -1 && (eql = envblock.IndexOf('=', beg + 1)) != -1); beg = end + 1)
            {
                // An initial `=' indicates a magic Windows variable name -- OK
                // Ignore corrupted environment strings.
                if (eql < end)
                {
                    TheEnvironment.Put(envblock.Substring(beg, eql - beg), StringHelperClass.SubstringSpecial(envblock, eql + 1, end));
                }
            }

            TheCaseInsensitiveEnvironment = new TreeMap <>(NameComparator);
            TheCaseInsensitiveEnvironment.PutAll(TheEnvironment);
        }
Example #18
0
        /// <summary>
        /// Retrieve the "RV zone" from a buffer an return the corresponding string<br>
        /// "If the word begins with two vowels, RV is the region after the third letter,
        /// otherwise the region after the first vowel not at the beginning of the word,
        /// or the end of the word if these positions cannot be found."<br> </summary>
        /// <param name="buffer"> java.lang.StringBuilder - the in buffer </param>
        /// <returns> java.lang.String - the resulting string </returns>
        private string retrieveRV(StringBuilder buffer)
        {
            int len = buffer.Length;

            if (buffer.Length > 3)
            {
                if (isVowel(buffer[0]) && isVowel(buffer[1]))
                {
                    return(buffer.Substring(3, len - 3));
                }
                else
                {
                    int pos = 0;
                    for (int c = 1; c < len; c++)
                    {
                        if (isVowel(buffer[c]))
                        {
                            pos = c;
                            break;
                        }
                    }
                    if (pos + 1 < len)
                    {
                        return(StringHelperClass.SubstringSpecial(buffer, pos + 1, len));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            else
            {
                return(null);
            }
        }
Example #19
0
        /// <summary>
        /// Parses the string representation of a {@code URL} into a
        /// {@code URL} object.
        /// <para>
        /// If there is any inherited context, then it has already been
        /// copied into the {@code URL} argument.
        /// </para>
        /// <para>
        /// The {@code parseURL} method of {@code URLStreamHandler}
        /// parses the string representation as if it were an
        /// {@code http} specification. Most URL protocol families have a
        /// similar parsing. A stream protocol handler for a protocol that has
        /// a different syntax must override this routine.
        ///
        /// </para>
        /// </summary>
        /// <param name="u">       the {@code URL} to receive the result of parsing
        ///                  the spec. </param>
        /// <param name="spec">    the {@code String} representing the URL that
        ///                  must be parsed. </param>
        /// <param name="start">   the character index at which to begin parsing. This is
        ///                  just past the '{@code :}' (if there is one) that
        ///                  specifies the determination of the protocol name. </param>
        /// <param name="limit">   the character position to stop parsing at. This is the
        ///                  end of the string or the position of the
        ///                  "{@code #}" character, if present. All information
        ///                  after the sharp sign indicates an anchor. </param>
        protected internal virtual void ParseURL(URL u, String spec, int start, int limit)
        {
            // These fields may receive context content if this was relative URL
            String protocol  = u.Protocol;
            String authority = u.Authority;
            String userInfo  = u.UserInfo;
            String host      = u.Host;
            int    port      = u.Port;
            String path      = u.Path;
            String query     = u.Query;

            // This field has already been parsed
            String @ref = u.Ref;

            bool isRelPath = false;
            bool queryOnly = false;

            // FIX: should not assume query if opaque
            // Strip off the query part
            if (start < limit)
            {
                int queryStart = spec.IndexOf('?');
                queryOnly = queryStart == start;
                if ((queryStart != -1) && (queryStart < limit))
                {
                    query = StringHelperClass.SubstringSpecial(spec, queryStart + 1, limit);
                    if (limit > queryStart)
                    {
                        limit = queryStart;
                    }
                    spec = spec.Substring(0, queryStart);
                }
            }

            int i = 0;
            // Parse the authority part if any
            bool isUNCName = (start <= limit - 4) && (spec.CharAt(start) == '/') && (spec.CharAt(start + 1) == '/') && (spec.CharAt(start + 2) == '/') && (spec.CharAt(start + 3) == '/');

            if (!isUNCName && (start <= limit - 2) && (spec.CharAt(start) == '/') && (spec.CharAt(start + 1) == '/'))
            {
                start += 2;
                i      = spec.IndexOf('/', start);
                if (i < 0)
                {
                    i = spec.IndexOf('?', start);
                    if (i < 0)
                    {
                        i = limit;
                    }
                }

                host = authority = spec.Substring(start, i - start);

                int ind = authority.IndexOf('@');
                if (ind != -1)
                {
                    userInfo = authority.Substring(0, ind);
                    host     = authority.Substring(ind + 1);
                }
                else
                {
                    userInfo = null;
                }
                if (host != null)
                {
                    // If the host is surrounded by [ and ] then its an IPv6
                    // literal address as specified in RFC2732
                    if (host.Length() > 0 && (host.CharAt(0) == '['))
                    {
                        if ((ind = host.IndexOf(']')) > 2)
                        {
                            String nhost = host;
                            host = nhost.Substring(0, ind + 1);
                            if (!IPAddressUtil.isIPv6LiteralAddress(host.Substring(1, ind - 1)))
                            {
                                throw new IllegalArgumentException("Invalid host: " + host);
                            }

                            port = -1;
                            if (nhost.Length() > ind + 1)
                            {
                                if (nhost.CharAt(ind + 1) == ':')
                                {
                                    ++ind;
                                    // port can be null according to RFC2396
                                    if (nhost.Length() > (ind + 1))
                                    {
                                        port = Convert.ToInt32(nhost.Substring(ind + 1));
                                    }
                                }
                                else
                                {
                                    throw new IllegalArgumentException("Invalid authority field: " + authority);
                                }
                            }
                        }
                        else
                        {
                            throw new IllegalArgumentException("Invalid authority field: " + authority);
                        }
                    }
                    else
                    {
                        ind  = host.IndexOf(':');
                        port = -1;
                        if (ind >= 0)
                        {
                            // port can be null according to RFC2396
                            if (host.Length() > (ind + 1))
                            {
                                port = Convert.ToInt32(host.Substring(ind + 1));
                            }
                            host = host.Substring(0, ind);
                        }
                    }
                }
                else
                {
                    host = "";
                }
                if (port < -1)
                {
                    throw new IllegalArgumentException("Invalid port number :" + port);
                }
                start = i;
                // If the authority is defined then the path is defined by the
                // spec only; See RFC 2396 Section 5.2.4.
                if (authority != null && authority.Length() > 0)
                {
                    path = "";
                }
            }

            if (host == null)
            {
                host = "";
            }

            // Parse the file path if any
            if (start < limit)
            {
                if (spec.CharAt(start) == '/')
                {
                    path = spec.Substring(start, limit - start);
                }
                else if (path != null && path.Length() > 0)
                {
                    isRelPath = true;
                    int    ind       = path.LastIndexOf('/');
                    String seperator = "";
                    if (ind == -1 && authority != null)
                    {
                        seperator = "/";
                    }
                    path = path.Substring(0, ind + 1) + seperator + spec.Substring(start, limit - start);
                }
                else
                {
                    String seperator = (authority != null) ? "/" : "";
                    path = seperator + spec.Substring(start, limit - start);
                }
            }
            else if (queryOnly && path != null)
            {
                int ind = path.LastIndexOf('/');
                if (ind < 0)
                {
                    ind = 0;
                }
                path = path.Substring(0, ind) + "/";
            }
            if (path == null)
            {
                path = "";
            }

            if (isRelPath)
            {
                // Remove embedded /./
                while ((i = path.IndexOf("/./")) >= 0)
                {
                    path = path.Substring(0, i) + path.Substring(i + 2);
                }
                // Remove embedded /../ if possible
                i = 0;
                while ((i = path.IndexOf("/../", i)) >= 0)
                {
                    /*
                     * A "/../" will cancel the previous segment and itself,
                     * unless that segment is a "/../" itself
                     * i.e. "/a/b/../c" becomes "/a/c"
                     * but "/../../a" should stay unchanged
                     */
                    if (i > 0 && (limit = path.LastIndexOf('/', i - 1)) >= 0 && (path.IndexOf("/../", limit) != 0))
                    {
                        path = path.Substring(0, limit) + path.Substring(i + 3);
                        i    = 0;
                    }
                    else
                    {
                        i = i + 3;
                    }
                }
                // Remove trailing .. if possible
                while (path.EndsWith("/.."))
                {
                    i = path.IndexOf("/..");
                    if ((limit = path.LastIndexOf('/', i - 1)) >= 0)
                    {
                        path = path.Substring(0, limit + 1);
                    }
                    else
                    {
                        break;
                    }
                }
                // Remove starting .
                if (path.StartsWith("./") && path.Length() > 2)
                {
                    path = path.Substring(2);
                }

                // Remove trailing .
                if (path.EndsWith("/."))
                {
                    path = path.Substring(0, path.Length() - 1);
                }
            }

            SetURL(u, protocol, host, port, authority, userInfo, path, query, @ref);
        }
Example #20
0
        /// <summary>
        /// Decodes a {@code application/x-www-form-urlencoded} string using a specific
        /// encoding scheme.
        /// The supplied encoding is used to determine
        /// what characters are represented by any consecutive sequences of the
        /// form "<i>{@code %xy}</i>".
        /// <para>
        /// <em><strong>Note:</strong> The <a href=
        /// "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
        /// World Wide Web Consortium Recommendation</a> states that
        /// UTF-8 should be used. Not doing so may introduce
        /// incompatibilities.</em>
        ///
        /// </para>
        /// </summary>
        /// <param name="s"> the {@code String} to decode </param>
        /// <param name="enc">   The name of a supported
        ///    <a href="../lang/package-summary.html#charenc">character
        ///    encoding</a>. </param>
        /// <returns> the newly decoded {@code String} </returns>
        /// <exception cref="UnsupportedEncodingException">
        ///             If character encoding needs to be consulted, but
        ///             named character encoding is not supported </exception>
        /// <seealso cref= URLEncoder#encode(java.lang.String, java.lang.String)
        /// @since 1.4 </seealso>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static String decode(String s, String enc) throws UnsupportedEncodingException
        public static String Decode(String s, String enc)
        {
            bool         needToChange = false;
            int          numChars     = s.Length();
            StringBuffer sb           = new StringBuffer(numChars > 500 ? numChars / 2 : numChars);
            int          i            = 0;

            if (enc.Length() == 0)
            {
                throw new UnsupportedEncodingException("URLDecoder: empty string enc parameter");
            }

            char c;

            sbyte[] bytes = null;
            while (i < numChars)
            {
                c = s.CharAt(i);
                switch (c)
                {
                case '+':
                    sb.Append(' ');
                    i++;
                    needToChange = true;
                    break;

                case '%':
                    /*
                     * Starting with this instance of %, process all
                     * consecutive substrings of the form %xy. Each
                     * substring %xy will yield a byte. Convert all
                     * consecutive  bytes obtained this way to whatever
                     * character(s) they represent in the provided
                     * encoding.
                     */

                    try
                    {
                        // (numChars-i)/3 is an upper bound for the number
                        // of remaining bytes
                        if (bytes == null)
                        {
                            bytes = new sbyte[(numChars - i) / 3];
                        }
                        int pos = 0;

                        while (((i + 2) < numChars) && (c == '%'))
                        {
                            int v = Convert.ToInt32(StringHelperClass.SubstringSpecial(s, i + 1, i + 3), 16);
                            if (v < 0)
                            {
                                throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value");
                            }
                            bytes[pos++] = (sbyte)v;
                            i           += 3;
                            if (i < numChars)
                            {
                                c = s.CharAt(i);
                            }
                        }

                        // A trailing, incomplete byte encoding such as
                        // "%x" will cause an exception to be thrown

                        if ((i < numChars) && (c == '%'))
                        {
                            throw new IllegalArgumentException("URLDecoder: Incomplete trailing escape (%) pattern");
                        }

                        sb.Append(StringHelperClass.NewString(bytes, 0, pos, enc));
                    }
                    catch (NumberFormatException e)
                    {
                        throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - " + e.Message);
                    }
                    needToChange = true;
                    break;

                default:
                    sb.Append(c);
                    i++;
                    break;
                }
            }

            return(needToChange? sb.ToString() : s);
        }
Example #21
0
        /// <summary>
        /// Converts a <code>String</code> object in JDBC timestamp escape format to a
        /// <code>Timestamp</code> value.
        /// </summary>
        /// <param name="s"> timestamp in format <code>yyyy-[m]m-[d]d hh:mm:ss[.f...]</code>.  The
        /// fractional seconds may be omitted. The leading zero for <code>mm</code>
        /// and <code>dd</code> may also be omitted.
        /// </param>
        /// <returns> corresponding <code>Timestamp</code> value </returns>
        /// <exception cref="java.lang.IllegalArgumentException"> if the given argument
        /// does not have the format <code>yyyy-[m]m-[d]d hh:mm:ss[.f...]</code> </exception>
        public static Timestamp ValueOf(String s)
        {
            const int YEAR_LENGTH  = 4;
            const int MONTH_LENGTH = 2;
            const int DAY_LENGTH   = 2;
            const int MAX_MONTH    = 12;
            const int MAX_DAY      = 31;
            String    date_s;
            String    time_s;
            String    nanos_s;
            int       year  = 0;
            int       month = 0;
            int       day   = 0;
            int       hour;
            int       minute;
            int       second;
            int       a_nanos = 0;
            int       firstDash;
            int       secondDash;
            int       dividingSpace;
            int       firstColon    = 0;
            int       secondColon   = 0;
            int       period        = 0;
            String    formatError   = "Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]";
            String    zeros         = "000000000";
            String    delimiterDate = "-";
            String    delimiterTime = ":";

            if (s == null)
            {
                throw new System.ArgumentException("null string");
            }

            // Split the string into date and time components
            s             = s.Trim();
            dividingSpace = s.IndexOf(' ');
            if (dividingSpace > 0)
            {
                date_s = s.Substring(0, dividingSpace);
                time_s = s.Substring(dividingSpace + 1);
            }
            else
            {
                throw new System.ArgumentException(formatError);
            }

            // Parse the date
            firstDash  = date_s.IndexOf('-');
            secondDash = date_s.IndexOf('-', firstDash + 1);

            // Parse the time
            if (time_s == null)
            {
                throw new System.ArgumentException(formatError);
            }
            firstColon  = time_s.IndexOf(':');
            secondColon = time_s.IndexOf(':', firstColon + 1);
            period      = time_s.IndexOf('.', secondColon + 1);

            // Convert the date
            bool parsedDate = false;

            if ((firstDash > 0) && (secondDash > 0) && (secondDash < date_s.Length() - 1))
            {
                String yyyy = date_s.Substring(0, firstDash);
                String mm   = StringHelperClass.SubstringSpecial(date_s, firstDash + 1, secondDash);
                String dd   = date_s.Substring(secondDash + 1);
                if (yyyy.Length() == YEAR_LENGTH && (mm.Length() >= 1 && mm.Length() <= MONTH_LENGTH) && (dd.Length() >= 1 && dd.Length() <= DAY_LENGTH))
                {
                    year  = Convert.ToInt32(yyyy);
                    month = Convert.ToInt32(mm);
                    day   = Convert.ToInt32(dd);

                    if ((month >= 1 && month <= MAX_MONTH) && (day >= 1 && day <= MAX_DAY))
                    {
                        parsedDate = true;
                    }
                }
            }
            if (!parsedDate)
            {
                throw new System.ArgumentException(formatError);
            }

            // Convert the time; default missing nanos
            if ((firstColon > 0) & (secondColon > 0) & (secondColon < time_s.Length() - 1))
            {
                hour   = Convert.ToInt32(time_s.Substring(0, firstColon));
                minute = Convert.ToInt32(StringHelperClass.SubstringSpecial(time_s, firstColon + 1, secondColon));
                if ((period > 0) & (period < time_s.Length() - 1))
                {
                    second  = Convert.ToInt32(StringHelperClass.SubstringSpecial(time_s, secondColon + 1, period));
                    nanos_s = time_s.Substring(period + 1);
                    if (nanos_s.Length() > 9)
                    {
                        throw new System.ArgumentException(formatError);
                    }
                    if (!char.IsDigit(nanos_s.CharAt(0)))
                    {
                        throw new System.ArgumentException(formatError);
                    }
                    nanos_s = nanos_s + zeros.Substring(0, 9 - nanos_s.Length());
                    a_nanos = Convert.ToInt32(nanos_s);
                }
                else if (period > 0)
                {
                    throw new System.ArgumentException(formatError);
                }
                else
                {
                    second = Convert.ToInt32(time_s.Substring(secondColon + 1));
                }
            }
            else
            {
                throw new System.ArgumentException(formatError);
            }

            return(new Timestamp(year - 1900, month - 1, day, hour, minute, second, a_nanos));
        }
Example #22
0
 internal sealed override String ToString(int start, int end)
 {
     return(StringHelperClass.SubstringSpecial(Str.ToString(), start + Offset, end + Offset));
 }
Example #23
0
        public virtual float GetDistance(string source, string target)
        {
            int sl = source.Length;
            int tl = target.Length;

            if (sl == 0 || tl == 0)
            {
                if (sl == tl)
                {
                    return(1);
                }
                else
                {
                    return(0);
                }
            }

            int cost = 0;

            if (sl < n || tl < n)
            {
                for (int i = 0, ni = Math.Min(sl, tl); i < ni; i++)
                {
                    if (source[i] == target[i])
                    {
                        cost++;
                    }
                }
                return((float)cost / Math.Max(sl, tl));
            }

            char[]  sa = new char[sl + n - 1];
            float[] p;  //'previous' cost array, horizontally
            float[] d;  // cost array, horizontally
            float[] _d; //placeholder to assist in swapping p and d

            //construct sa with prefix
            for (int i = 0; i < sa.Length; i++)
            {
                if (i < n - 1)
                {
                    sa[i] = (char)0; //add prefix
                }
                else
                {
                    sa[i] = source[i - n + 1];
                }
            }
            p = new float[sl + 1];
            d = new float[sl + 1];

            // indexes into strings s and t
            int i;                    // iterates through source
            int j;                    // iterates through target

            char[] t_j = new char[n]; // jth n-gram of t

            for (i = 0; i <= sl; i++)
            {
                p[i] = i;
            }

            for (j = 1; j <= tl; j++)
            {
                //construct t_j n-gram
                if (j < n)
                {
                    for (int ti = 0; ti < n - j; ti++)
                    {
                        t_j[ti] = (char)0; //add prefix
                    }
                    for (int ti = n - j; ti < n; ti++)
                    {
                        t_j[ti] = target[ti - (n - j)];
                    }
                }
                else
                {
                    t_j = StringHelperClass.SubstringSpecial(target, j - n, j).ToCharArray();
                }
                d[0] = j;
                for (i = 1; i <= sl; i++)
                {
                    cost = 0;
                    int tn = n;
                    //compare sa to t_j
                    for (int ni = 0; ni < n; ni++)
                    {
                        if (sa[i - 1 + ni] != t_j[ni])
                        {
                            cost++;
                        }
                        else if (sa[i - 1 + ni] == 0) //discount matches on prefix
                        {
                            tn--;
                        }
                    }
                    float ec = (float)cost / tn;
                    // minimum of cell to the left+1, to the top+1, diagonally left and up +cost
                    d[i] = Math.Min(Math.Min(d[i - 1] + 1, p[i] + 1), p[i - 1] + ec);
                }
                // copy current distance counts to 'previous row' distance counts
                _d = p;
                p  = d;
                d  = _d;
            }

            // our last action in the above loop was to switch d and p, so p now
            // actually has the most recent cost counts
            return(1.0f - (p[sl] / Math.Max(tl, sl)));
        }
Example #24
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public String lex(String str) throws java.io.IOException
    public virtual string lex(string str)
    {
//		System.out.println("in lex function");
        string str1 = null; string[] array;

        if (str.Trim().Length > 0)
        {
            // remove extra spaces
            //StringTokenizer st = new StringTokenizer(str, " ");
            StringBuilder sb = new StringBuilder();
            //while (st.hasMoreElements())
            //{
            //	sb.Append(st.nextElement()).Append(" ");
            //}
            //str = sb.ToString().Trim();
            // remove tabs or new line
            //str = str.replaceAll("\t", "");
            //str1 = str.replaceAll("\n", "");

            var tokens = str.Split(' ');
            foreach (var tok in tokens)
            {
                sb.Append(tok + " ");
                str  = sb.ToString().Trim();
                str  = str.Replace("\t", "");
                str  = str.Replace("\r", "");
                str  = str.Replace("\n", "");
                str1 = str;
            }
            // check for single line comment
            if (str1.Contains("//"))
            {
//				System.out.println("\n" + str1);
//				System.out.println("\nSingle line comment");
                int ind = str1.IndexOf("//", StringComparison.Ordinal);
                str1 = str1.Substring(0, ind);
//				System.out.println("New String " + str1);
            }

            // check for multiple line comment
            if (str1.Contains("/*"))
            {
//				System.out.println("\nMultiple line comment");
//				System.out.println(str1);
                str1 = StringHelperClass.SubstringSpecial(str1, str1.IndexOf("/*", StringComparison.Ordinal), str1.Length);
                while (!str1.Contains("*/"))
                {
                    str1 = br.ReadLine();
//					System.out.println(str1);
                    str1.Replace(str1, "");
                }
                int a = str1.IndexOf("*/", StringComparison.Ordinal);
                str1 = StringHelperClass.SubstringSpecial(str1, a + 2, str1.Length);
            }

            // split with spaces
            array = str1.Split(" ", true);
//			System.out.println("\n" + str1 + "\n");
            // readOneLine=0;
            for (int i = 0; i < array.Length; i++)
            {
                if ((i == (array.Length - 1)) && (readOneLine == 1))
                {
                    readLastChar = 1;
                }
                if (checkKeyword(array[i]))
                {
//					System.out.println("Keyword : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else if (checkAriOperator(array[i]))
                {
//					System.out.println("Arithmatic operator : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else if (checkRelOp(array[i]))
                {
//					System.out.println("Relational operator : " + array[i]);
                    syntax("relop", array[i]);
                }
                else if (array[i].Equals("="))
                {
//					System.out.println("Assignment Operator : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else if ((array[i].Equals("{")) || (array[i].Equals("}")) || (array[i].Equals("(")) || (array[i].Equals(")")))
                {
//					System.out.println("Brackets : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else if ((array[i].Equals("||")) || (array[i].Equals("&&")))
                {
//					System.out.println("Logical Operators : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else if ((array[i].Equals(";")) || (array[i].Equals(",")))
                {
//					System.out.println("Delimitor : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else if (!char.IsDigit(array[i][0]))
                {
//					System.out.println("Identifier : " + array[i]);
                    syntax("id", array[i]);
                }
                else if (checkNumber(array[i]))
                {
//					System.out.println("Integer Number : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else if (checkNumber1(array[i]))
                {
//					System.out.println("Float Number : " + array[i]);
                    syntax(array[i], array[i]);
                }
                else
                {
//					System.out.println("Invalid identifier!!!!! : " + array[i]);
                }
            }
//			System.out.println("Read one line  and readOneLine = "
//					+ readOneLine);
            readOneLine = 1;
        }
        return(null);
    }