Example #1
0
        public static JValue Parse(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                throw new ArgumentNullException("text");

            var chars = new CharEnumerator(text);
            var result = chars.ReadValue(true);

            if(chars.MoveToNoWhite())
                throw new FormatException(string.Format("unexpected symbols '{0}' in the reading of end", chars.Tail));

            return result;
        }
Example #2
0
        private static string FormatImpl(string format,
                                         IFormatProvider provider, StringFormatTokenBindingHandler binder, params object[] args)
        {
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }

            Debug.Assert(binder != null);

            //
            // Following is a slightly modified version of the parser from
            // Henri Weichers that was presented at:
            // http://haacked.com/archive/2009/01/14/named-formats-redux.aspx
            // See also the following comment about the modifications:
            // http://haacked.com/archive/2009/01/14/named-formats-redux.aspx#70485
            //

            StringBuilder result = new StringBuilder(format.Length * 2);
            StringBuilder token  = new StringBuilder();

            CharEnumerator e = format.GetEnumerator();

            while (e.MoveNext())
            {
                char ch = e.Current;
                if (ch == '{')
                {
                    while (true)
                    {
                        if (!e.MoveNext())
                        {
                            throw new FormatException();
                        }

                        ch = e.Current;
                        if (ch == '}')
                        {
                            if (token.Length == 0)
                            {
                                throw new FormatException();
                            }

                            result.Append(binder(token.ToString(), args, provider));
                            token.Length = 0;
                            break;
                        }
                        if (ch == '{')
                        {
                            result.Append(ch);
                            break;
                        }
                        token.Append(ch);
                    }
                }
                else if (ch == '}')
                {
                    if (!e.MoveNext() || e.Current != '}')
                    {
                        throw new FormatException();
                    }
                    result.Append('}');
                }
                else
                {
                    result.Append(ch);
                }
            }

            return(result.ToString());
        }
Example #3
0
        private static ToleranceEntry ParseToleranceEntry(string line)
        {
            string[] values = Regex.Split(line, "%%v");

            ToleranceGeometricSymbol geom = ToleranceGeometricSymbol.None;
            ToleranceValue           t1   = null;
            ToleranceValue           t2   = null;
            DatumReferenceValue      d1   = null;
            DatumReferenceValue      d2   = null;
            DatumReferenceValue      d3   = null;

            if (!string.IsNullOrEmpty(values[0]))
            {
                if (values[0].StartsWith("{"))
                {
                    // geometric symbol
                    CharEnumerator chars  = values[0].GetEnumerator();
                    char           symbol = Symbol(chars);
                    geom = ParseGeometricSymbol(symbol);
                }
            }

            for (int i = 1; i < values.Length; i++)
            {
                string value = values[i];

                switch (i)
                {
                case 1:
                    t1 = ParseToleranceValue(value);
                    break;

                case 2:
                    t2 = ParseToleranceValue(value);
                    break;

                case 3:
                    d1 = ParseDatumReferenceValue(value);
                    break;

                case 4:
                    d2 = ParseDatumReferenceValue(value);
                    break;

                case 5:
                    d3 = ParseDatumReferenceValue(value);
                    break;

                default:
                    throw new FormatException("The tolerance string representation is not well formatted");
                }
            }

            ToleranceEntry t = new ToleranceEntry
            {
                GeometricSymbol = geom,
                Tolerance1      = t1,
                Tolerance2      = t2,
                Datum1          = d1,
                Datum2          = d2,
                Datum3          = d3
            };

            return(t);
        }
Example #4
0
 /// <summary>
 /// A tokenizer is always constructed on a single string.  Create one tokenizer per string.
 /// </summary>
 /// <param name="s">string to tokenize</param>
 public Tokenizer(string s)
 {
     _En = s.GetEnumerator();
     MoveNext();
 }
Example #5
0
        /// <summary>
        /// Obtains the MText text value without the formatting codes, control characters like tab '\t' will be preserved in the result,
        /// the new paragraph command "\P" will be converted to new line feed '\r\n'.
        /// </summary>
        /// <returns>MText text value without the formatting codes.</returns>
        public string PlainText()
        {
            if (string.IsNullOrEmpty(this.text))
            {
                return(string.Empty);
            }

            string txt = this.text;

            //text = text.Replace("%%c", "Ø");
            //text = text.Replace("%%d", "°");
            //text = text.Replace("%%p", "±");

            StringBuilder rawText = new StringBuilder();

            using (CharEnumerator chars = txt.GetEnumerator())
            {
                while (chars.MoveNext())
                {
                    char token = chars.Current;
                    if (token == '\\') // is a formatting command
                    {
                        if (chars.MoveNext())
                        {
                            token = chars.Current;
                        }
                        else
                        {
                            return(rawText.ToString());                  // premature end of text
                        }
                        if (token == '\\' | token == '{' | token == '}') // escape chars
                        {
                            rawText.Append(token);
                        }
                        else if (token == 'L' | token == 'l' | token == 'O' | token == 'o' | token == 'K' | token == 'k')
                        {
                            /* discard one char commands */
                        }
                        else if (token == 'P' | token == 'X')
                        {
                            rawText.Append(Environment.NewLine); // replace the end paragraph command with the standard new line, carriage return code "\r\n".
                        }
                        else if (token == 'S')
                        {
                            if (chars.MoveNext())
                            {
                                token = chars.Current;
                            }
                            else
                            {
                                return(rawText.ToString()); // premature end of text
                            }
                            // we want to preserve the text under the stacking command
                            StringBuilder data = new StringBuilder();

                            while (token != ';')
                            {
                                if (token == '\\')
                                {
                                    if (chars.MoveNext())
                                    {
                                        token = chars.Current;
                                    }
                                    else
                                    {
                                        return(rawText.ToString()); // premature end of text
                                    }
                                    data.Append(token);
                                }
                                else if (token == '^')
                                {
                                    if (chars.MoveNext())
                                    {
                                        token = chars.Current;
                                    }
                                    else
                                    {
                                        return(rawText.ToString()); // premature end of text
                                    }
                                    // discard the code "^ " that defines super and subscript texts
                                    if (token != ' ')
                                    {
                                        data.Append("^" + token);
                                    }
                                }
                                else
                                {
                                    // replace the '#' stacking command by '/'
                                    // non command characters '#' are written as '\#'
                                    data.Append(token == '#' ? '/' : token);
                                }

                                if (chars.MoveNext())
                                {
                                    token = chars.Current;
                                }
                                else
                                {
                                    return(rawText.ToString()); // premature end of text
                                }
                            }

                            rawText.Append(data);
                        }
                        else
                        {
                            // formatting commands of more than one character always terminate in ';'
                            // discard all information
                            while (token != ';')
                            {
                                if (chars.MoveNext())
                                {
                                    token = chars.Current;
                                }
                                else
                                {
                                    return(rawText.ToString()); // premature end of text
                                }
                            }
                        }
                    }
                    else if (token == '{' | token == '}')
                    {
                        /* discard group markers */
                    }
                    else // char is what it is, a character
                    {
                        rawText.Append(token);
                    }
                }
            }

            return(rawText.ToString());
        }
Example #6
0
 public string ExecuteOperation(CharEnumerator candidate, int startIdx, int len, bool isReversed)
 {
     throw new NotImplementedException();
 }
Example #7
0
 public ParsedText(CharEnumerator charEnumerator)
 => Text = GetText(charEnumerator);
Example #8
0
        /// <summary>
        /// Like node parser from character class
        /// </summary>
        ILikeNode ParseCharClass(CharEnumerator chars, char?escapeCharacter)
        {
            if (!chars.MoveNext())
            {
                return(null);
            }

            bool negate = false;

            if (chars.Current == '^')
            {
                negate = true;
                if (!chars.MoveNext())
                {
                    return(null);
                }

                if (chars.Current == ']')
                {
                    return(new LikeString("^"));
                }
            }

            string insides = string.Empty;
            var    escaped = new List <bool>();

            while (true)
            {
                if (escapeCharacter.HasValue && escapeCharacter.Value == chars.Current)
                {
                    if (!chars.MoveNext())
                    {
                        return(null);
                    }

                    insides += chars.Current;
                    escaped.Add(true);
                }
                else
                {
                    if (chars.Current == ']')
                    {
                        break;
                    }

                    insides += chars.Current;
                    escaped.Add(false);
                }

                if (!chars.MoveNext())
                {
                    return(null);
                }
            }

            if (insides.Length == 3 && insides[1] == '-' && !escaped[1])
            {
                return(new LikeCharRange(insides[0], insides[2], negate));
            }
            else
            {
                var filteredChars = insides
                                    .Select((character, index) => new { character, index })
                                    .Zip(escaped, (x, isEscaped) => new { x.character, x.index, isEscaped })
                                    .Where(x => x.character != '-' || x.isEscaped || x.index == 0 || x.index == insides.Length - 1)
                                    .Select(x => x.character);

                return(new LikeCharSet(filteredChars, negate));
            }
        }
Example #9
0
 string Parse(CharEnumerator e, string name = null)
 {
     return(ParseMethod(e, name) ?? ParsePrimitive(e, name) ?? ParseArray(e, name) ?? ParseClass(e, name));
 }
Example #10
0
        void interpret(string lin)
        {
            this.cpu.DebugLog("Line: {0}, currently at PC=0x{1:X}", lin, cpu.PC);
            if (!check_crc(lin))
            {
                // WRONG CRC
                this.cpu.DebugLog("Line: {0}", lin);
                this.cpu.DebugLog("WRONG CRC!!!");
                terminal.SendByte((byte)'-'); // send '-' (WRONG CRC)
                return;
            }
            terminal.SendByte((byte)'+');                               // send '+' (ACK)
            string cmd = lin.Split('#')[0].Split('$')[1].Split(':')[0]; // TODO: this is shitty, but should work here.

            if (cmd[0] != 'X')
            {
                this.cpu.DebugLog("cmd is {0}", cmd);
            }
            string cmd_data = cmd.Substring(1);

            if (cmd[0] == 'X')
            {
                // WRITE BYTES
                uint addr = Convert.ToUInt32(cmd_data.Split(',')[0], 16);
                uint size = Convert.ToUInt32(cmd_data.Split(',')[1], 16);
                if (size > 0)
                {
                    this.cpu.DebugLog("We have {0} data to write @ {1:X}.", size, addr);
                    int    i       = 0;
                    int    delta   = cmd.Length + 1 + 1;// cmd len + "$" + ":"
                    int    written = 0;
                    bool   escape  = false;
                    byte[] buf     = new byte[size];
                    while (written < size)
                    {
                        if (escape)
                        {
                            buf[written] = (byte)(lin[delta + i] ^ 0x20);
                            //machine.SystemBus.WriteByte(addr + written, (byte)(lin[delta + i] ^ 0x20));
                            escape = false;
                            written++;
                        }
                        else if (lin[delta + i] != 0x7D)
                        {
                            buf[written] = (byte)lin[delta + i];
                            //machine.SystemBus.WriteByte(addr + written, lin[delta + i]);
                            written++;
                        }
                        else
                        {
                            escape = true;
                        }
                        i++;
                    }

                    /*  for (i = 0; i < size / 4; i+=4) {
                     *  uint val = BitConverter.ToUInt32(buf,i);
                     *  machine.SystemBus.WriteDoubleWord(addr+i, swapEndianness(val));
                     * }*/
                    machine.SystemBus.WriteBytes(buf, addr);
                }
                send_command("OK");
            }
            else if (cmd[0] == 'q')
            {
                //Console.WriteLine("query : {0}",cmd_data);
                // QUERY
                string query_cmd = cmd_data.Split(',')[0];
                this.cpu.DebugLog("query_cmd: {0}", query_cmd);
                if (query_cmd == "Supported")
                {
                    send_command(string.Format("PacketSize={0:x4}", 4096));
                }
                else if (query_cmd == "Attached")
                {
                    send_command("0");
                }
                else if (query_cmd == "Rcmd")
                {
                    if (this.OnMonitor == null)
                    {
                        send_command(""); // not supported
                    }
                    else
                    {
                        // mon
                        string         str            = cmd_data.Split(',')[1];
                        CharEnumerator charEnum       = str.GetEnumerator();
                        var            string_builder = new StringBuilder();
                        while (charEnum.MoveNext())
                        {
                            string hex = string.Format("{0}", charEnum.Current);
                            charEnum.MoveNext();
                            hex = hex + string.Format("{0}", charEnum.Current);
                            byte val = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                            string_builder.Append((char)val);
                        }
                        string mon_cmd = string_builder.ToString();
                        this.cpu.DebugLog("mon_cmd = {0}", mon_cmd);
                        this.OnMonitor(mon_cmd);
                        send_command("OK");
                    }
                }
                else if (query_cmd == "C")
                {
                    send_command("QC0");
                }
                else
                {
                    send_command(""); // empty
                }
            }
            else if (cmd == "?")
            {
                if (machine.IsPaused)
                {
                    send_command("S05");
                }
                else
                {
                    send_command("OK");
                }
            }
            else if (cmd[0] == 'H')
            {
                if (cmd == "Hc-1")
                { // future step/continue on all threads
                    send_command("OK");
                }
                else
                {
                    send_command("");
                }
            }
            else if (cmd == "g")
            {
                this.cpu.DebugLog("read registers...");
                int    i;
                string registers = "";
                for (i = 0; i < 16; i++)
                {
                    char[] reg = string.Format("{0:x8}", cpu.GetRegisterUnsafe(i)).ToCharArray();
                    Array.Reverse(reg);
                    int j;
                    for (j = 0; j < 8; j += 2)
                    {
                        registers = registers + string.Format("{0:c}{1:c}", reg[j + 1], reg[j]);
                    }
                }
                this.cpu.DebugLog("sending registers...");
                send_command(registers); // send registers
            }
            else if (cmd[0] == 'm')
            { // read memory
                string[] data   = cmd.Split('m')[1].Split(',');
                uint     offset = Convert.ToUInt32(data[0], 16);
                uint     size   = Convert.ToUInt32(data[1], 16);
                //Console.WriteLine("Trying to read @ {0:X} size {1}", offset, size);
                uint result = 0;
                if (size == 4)
                {
                    result = machine.SystemBus.ReadDoubleWord(offset); // TODO: should support diffrent sizes than 4
                    byte[] temp = BitConverter.GetBytes(result);
                    Array.Reverse(temp);
                    result = System.BitConverter.ToUInt32(temp, 0);
                    send_command(string.Format("{0:x8}", result));
                }
                else if (size == 1)
                {
                    result = machine.SystemBus.ReadByte(offset);
                    send_command(string.Format("{0:x2}", result));
                }
                else if (size == 2)
                {
                    result = machine.SystemBus.ReadWord(offset); // TODO: Endian conversion
                    send_command(string.Format("{0:x4}", result));
                }
                else
                {
                    // multibyte read
                    var    res = machine.SystemBus.ReadBytes((long)offset, (int)size);
                    string s   = "";
                    for (int i = 0; i < size; i++)
                    {
                        s = s + string.Format("{0:x2}", res[i]);
                    }
                    send_command(s);
                }
            }
            else if (cmd[0] == 'p')
            { // read register ?
                uint reg_no = Convert.ToUInt32(cmd.Split('p')[1]);
                if (reg_no == 19)
                {
                    send_command(string.Format("{0:x8}", cpu.GetRegisterUnsafe(15)));
                }
            }
            else if (cmd[0] == 'P')
            {
                if (cmd_data[0] == 'f')
                {
                    string addr_s = cmd_data.Split('=')[1];
                    uint   addr   = Convert.ToUInt32(addr_s, 16);
                    byte[] temp   = BitConverter.GetBytes(addr);
                    Array.Reverse(temp);
                    addr = System.BitConverter.ToUInt32(temp, 0);
                    this.cpu.DebugLog("Setting PC to {0:X}", addr);
                    cpu.PC = addr;
                    cpu.Reset();
                    cpu.PC = addr;
                }
                send_command("OK");
            }
            else if (cmd[0] == 'z')
            {
                string[] data = cmd_data.Split(',');
                cpu.DebugLog("Remove breakpoint_{0} to {1} size {2}", data[0], data[1], data[2]);
                uint addr = Convert.ToUInt32(data[1], 16);
                cpu.RemoveBreakpoint(addr);
                send_command("OK");
            }
            else if (cmd[0] == 'Z')
            { // TODO
                string[] data = cmd_data.Split(',');
                cpu.DebugLog("Set breakpoint_{0} to {1} size {2}", data[0], data[1], data[2]);
                uint addr = Convert.ToUInt32(data[1], 16);
                cpu.AddBreakpoint(addr);
                send_command("OK");
            }
            else if (cmd[0] == 'v')
            {
                // if 's' : Cont? and then Cont;s
                // if 'c' : Cont? and then Cont;c
                if (cmd_data == "Cont;s")
                {
                    cpu.DebugLog("Single stepping...");
                    if (cpu.InSingleStep())
                    {
                        cpu.DebugLog("already in singlestep, doing another step...");
                        cpu.SingleStep();
                    }
                    else
                    {
                        cpu.SetSingleStepMode(true);
                        machine.Start();
                    }
                    cpu.DebugLog("Waiting for step done");
                }
                else if (cmd_data == "Cont;c")
                {
                    cpu.DebugLog("GDB: We're going to continue @ PC=0x{0:X}", cpu.PC);
                    cpu.SetSingleStepMode(false);
                    machine.Start();
                    cpu.DebugLog("Waiting for breakpoint");
                }
                else
                {
                    send_command("OK");
                }
            }
        }
        private void MakeValue(CharEnumerator format, int flags)
        {
            for (;;)
            {
                int n;
                switch (PopChar(format))
                {
                case '(':
                    n = CountFormat(format, ')');
                    MakeList(format, ')', n, flags);
                    return;

                case '[':
                    n = CountFormat(format, ']');
                    MakeList(format, ']', n, flags);
                    return;

                case '{':
                    n = CountFormat(format, '}');
                    MakeList(format, '}', n, flags);
                    return;

                case 'b':
                case 'B':
                case 'h':
                case 'i':
                    ArgumentTypes.Add(dtInt);
                    return;

                case 'H':
                case 'I':
                    ArgumentTypes.Add(dtUInt);
                    return;

                case 'n':
                    ArgumentTypes.Add(dtPySize);
                    return;

                case 'l':
                    ArgumentTypes.Add(dtLong);
                    return;

                case 'k':
                    ArgumentTypes.Add(dtULong);
                    return;

                case 'L':
                    ArgumentTypes.Add(dtLongLong);
                    return;

                case 'K':
                    ArgumentTypes.Add(dtULongLong);
                    return;

                case 'u':

                    ArgumentTypes.Add(ptrPyUnicode);
                    if (format.Current == '#')
                    {
                        format.MoveNext();
                        if ((flags & FLAG_SIZE_T) != 0)
                        {
                            ArgumentTypes.Add(dtPySize);
                        }
                        else
                        {
                            ArgumentTypes.Add(dtInt);
                        }
                    }
                    return;

                case 'f':
                case 'd':
                    ArgumentTypes.Add(dtDouble);
                    return;

                case 'D':
                    ArgumentTypes.Add(ptrPyComplex);
                    return;

                case 'c':
                    ArgumentTypes.Add(dtInt);
                    return;

                case 's':
                case 'z':
                    ArgumentTypes.Add(ptrChar);
                    if (format.Current == '#')
                    {
                        format.MoveNext();
                        if ((flags & FLAG_SIZE_T) != 0)
                        {
                            ArgumentTypes.Add(dtPySize);
                        }
                        else
                        {
                            ArgumentTypes.Add(dtInt);
                        }
                    }
                    return;

                case 'N':
                case 'S':
                case 'O':
                    if (format.Current == '&')
                    {
                        ArgumentTypes.Add(ptrPyConverter);
                        ArgumentTypes.Add(ptrVoid);
                        format.MoveNext();
                    }
                    else
                    {
                        ArgumentTypes.Add(ptrPyObject);
                    }
                    return;

                case ':':
                case ',':
                case ' ':
                case '\t':
                    break;

                default:
                    throw new ApplicationException(
                              "Bad format char passed to Py_BuildValue");
                }
            }
        }
Example #12
0
        /// <summary>
        /// 解析并创建选择器对象
        /// </summary>
        /// <param name="enumerator">用于读取选择器表达式的枚举器</param>
        /// <returns>选择器对象</returns>
        private static ISelector ParseSelector(CharEnumerator enumerator)
        {
            var selectorList = new List <ISelector>();

            ISelector selector = null;

            selector = ParseElementSelector(enumerator);

            while (true)
            {
                SkipWhiteSpace(enumerator);

                if (enumerator.Current == char.MinValue)
                {
                    if (selectorList.Any())
                    {
                        if (selector == null)
                        {
                            throw FormatError(enumerator);
                        }

                        selectorList.Add(selector);
                        return(new CssMultipleSelector(selectorList.ToArray()));
                    }

                    else
                    {
                        return(selector);
                    }
                }

                var ch = enumerator.Current;
                if (ch == '>' || ch == '+' || ch == '~')
                {
                    EnsureNext(enumerator);
                    SkipWhiteSpace(enumerator);

                    var right = ParseElementSelector(enumerator);
                    if (right == null)
                    {
                        throw FormatError(enumerator);
                    }

                    selector = CreateCasecadingSelector(selector, ch, right);
                }
                else if (ch == ',')
                {
                    EnsureNext(enumerator);
                    SkipWhiteSpace(enumerator);

                    selectorList.Add(selector);
                    selector = ParseElementSelector(enumerator);
                }
                else
                {
                    var right = ParseElementSelector(enumerator);
                    if (right == null)
                    {
                        throw FormatError(enumerator);
                    }

                    selector = CreateCasecadingSelector(selector, ' ', right);
                }
            }
        }
Example #13
0
        /// <summary>
        /// 解析属性选择器
        /// </summary>
        /// <param name="enumerator">字符枚举器</param>
        /// <returns>属性选择器</returns>
        private static CssAttributeSelector ParseAttributeSelector(CharEnumerator enumerator)
        {
            if (enumerator.Current != '[')
            {
                return(null);
            }

            EnsureNext(enumerator);

            var attriuteName = ParseName(enumerator);

            if (attriuteName.IsNullOrEmpty())
            {
                throw FormatError(enumerator);
            }

            var ch = enumerator.Current;

            if (ch == ']')
            {
                enumerator.MoveNext();
                return(CreateAttributeSelector(attriuteName));
            }


            string compare;

            if (ch == '=')
            {
                compare = "=";
            }

            else if (ch == '^' || ch == '$' || ch == '~' || ch == '*' || ch == '!')
            {
                if (EnsureNext(enumerator) != '=')//比较符不正确
                {
                    throw FormatError(enumerator, '=');
                }

                compare = ch + "=";
            }

            else
            {
                throw FormatError(enumerator);
            }


            EnsureNext(enumerator);                 //比较符后面没有字符

            var value = ParseQuoteText(enumerator); //尝试解析引用字符串

            if (value == null)
            {
                var offset = enumerator.Offset;

                while (true)
                {
                    if (enumerator.Current == ']')//遇到结束符
                    {
                        break;
                    }

                    EnsureNext(enumerator);//遇到结束符前结束
                }

                value = enumerator.SubString(offset, enumerator.Offset - offset);
            }

            else if (enumerator.Current != ']')//引用字符串结束位置不是结束符
            {
                throw FormatError(enumerator, ']');
            }


            enumerator.MoveNext();
            return(CreateAttributeSelector(attriuteName, compare, value));
        }
Example #14
0
        /// <summary>
        /// 解析元素选择器
        /// </summary>
        /// <param name="enumerator">字符枚举器</param>
        /// <returns>解析好的元素选择器</returns>
        private static CssElementSelector ParseElementSelector(CharEnumerator enumerator)
        {
            var elementName = ParseName(enumerator);

            if (elementName.IsNullOrEmpty() && enumerator.Current == '*')
            {
                enumerator.MoveNext();
                elementName = "*";
            }

            var attributeSelectors  = new List <CssAttributeSelector>();
            var psedoclassSelectors = new List <ICssPseudoClassSelector>();

            while (true)//解析ID和类选择符
            {
                if (enumerator.Current == '#')
                {
                    EnsureNext(enumerator);
                    attributeSelectors.Add(CreateAttributeSelector("id", "=", ParseName(enumerator)));
                }

                else if (enumerator.Current == '.')
                {
                    EnsureNext(enumerator);
                    attributeSelectors.Add(CreateAttributeSelector("class", "~=", ParseName(enumerator)));
                }

                else
                {
                    break;
                }
            }

            while (true)//解析属性选择符
            {
                if (enumerator.Current == '[')
                {
                    attributeSelectors.Add(ParseAttributeSelector(enumerator));
                }

                else
                {
                    break;
                }
            }

            while (true)//解析伪类选择符
            {
                if (enumerator.Current == ':')
                {
                    psedoclassSelectors.Add(ParsePsedoclassSelector(enumerator));
                }

                else
                {
                    break;
                }
            }


            if (elementName != null || attributeSelectors.Any() || psedoclassSelectors.Any())
            {
                return(CreateElementSelector(elementName, attributeSelectors.ToArray(), psedoclassSelectors.ToArray()));
            }

            else
            {
                return(null);
            }
        }
Example #15
0
 private static FormatException FormatError(CharEnumerator enumerator, char desired)
 {
     return(new FormatException(string.Format(CultureInfo.InvariantCulture, "意外的字符 '{0}' ,在分析CSS选择器表达式 \"{1}\" 第 {2} 字符处,期望的字符为 '{3}' 。", enumerator.Current, enumerator.ToString(), enumerator.Offset, desired)));
 }
Example #16
0
 private bool InternalValidate(CharEnumerator password) {
     while(password.MoveNext()){
         for (int i = 0; i < m_Validators.Length; i++) {
             m_Validators[i].InspectChar(password.Current);
         }
     }
     bool result = true;
     m_LastStrength = 0;
     for (int i = 0; i < m_Validators.Length; i++) {
         result &= m_Validators[i].IsValidated();
         m_LastStrength += m_Validators[i].PasswordStrength;
         m_Validators[i].Reset();
     }
     m_LastStrength /= m_Validators.Length;
     return result;
 }
Example #17
0
        /// <summary>
        /// Like node parser from string
        /// </summary>
        ILikeNode ParseString(CharEnumerator chars, char?escapeCharacter)
        {
            List <ILikeNode> nodes         = new List <ILikeNode>();
            List <char>      currentString = null;

            Action <ILikeNode> appendNonCharNode = n =>
            {
                if (currentString != null)
                {
                    nodes.Add(new LikeString(currentString));
                    currentString = null;
                }

                nodes.Add(n);
            };

            Action <char> appendCharNode = c =>
            {
                if (currentString == null)
                {
                    currentString = new List <char>();
                }

                currentString.Add(c);
            };

            while (chars.MoveNext())
            {
                switch (chars.Current)
                {
                case '%':
                    appendNonCharNode(new LikeWildcard());
                    break;

                case '_':
                    appendNonCharNode(new LikeAny());
                    break;

                case '[':
                    var classNode = this.ParseCharClass(chars, escapeCharacter);
                    if (classNode == null)
                    {
                        // Match the behavior of ScopeLikeUtil in ScopeContainers.h
                        return(new LikeFalse());
                    }

                    appendNonCharNode(classNode);
                    break;

                default:
                    if (escapeCharacter.HasValue && escapeCharacter.Value == chars.Current)
                    {
                        // Match the behavior of ScopeLikeUtil in ScopeContainers.h
                        if (!chars.MoveNext())
                        {
                            return(new LikeFalse());
                        }
                    }

                    appendCharNode(chars.Current);
                    break;
                }
            }

            if (currentString != null)
            {
                nodes.Add(new LikeString(currentString));
                currentString = null;
            }

            return(new LikeRoot(nodes));
        }
Example #18
0
        private Packet ReadPacket(CharEnumerator text)
        {
            Packet packet;
            int    version;
            int    typeId;

            try
            {
                version = (int)ReadBits(text, 3);
                typeId  = (int)ReadBits(text, 3);
            }
            catch (InvalidOperationException)
            {
                return(null);
            }
            if (typeId == 4)
            {
                // literal value;
                var  buffer = new List <byte>();
                bool last;
                do
                {
                    last = ReadBits(text, 1) == 0;
                    buffer.Add((byte)ReadBits(text, 4));
                } while (last == false);

                packet = new Literal {
                    Version = version, Value = buffer
                };
            }
            else
            {
                // this an operator
                var mode = ReadBits(text, 1) == 0;
                var subs = new List <Packet>();
                packet = new Operator {
                    Version = version, Type = typeId, SubPackets = subs
                };
                if (mode)
                {
                    var length    = (int)ReadBits(text, 15);
                    var subString = new StringBuilder(length);
                    for (var i = 0; i < length; i++)
                    {
                        subString.Append(text.Current);
                        text.MoveNext();
                    }

                    var sub = subString.ToString().GetEnumerator();
                    sub.MoveNext();
                    for (;;)
                    {
                        var readPacket = ReadPacket(sub);
                        if (readPacket == null)
                        {
                            break;
                        }
                        subs.Add(readPacket);
                    }
                }
                else
                {
                    var count = ReadBits(text, 11);
                    for (var i = 0; i < count; i++)
                    {
                        subs.Add(ReadPacket(text));
                    }
                }
            }

            return(packet);
        }
Example #19
0
 public double Evaluate(string expression, CharEnumerator enumerator)
 {
     return(GetSummands(expression, enumerator).Sum());
 }
Example #20
0
        /// <summary>
        /// Parsuje templejt do podglądu, nie pobiera jako argument tagów - na sztywno wpisuje
        /// </summary>
        /// <param name="template">schemat templejta</param>
        /// <param name="definitions">definicje zmiennych/keywordów (struktura)</param>
        /// <returns>Zparsowany templejt wypełnionymi danymi z tags</returns>
        static public string parseTemplate(string template, varNames definitions)
        {
            string afterRepl   = "";
            bool   endOfString = false;
            string tArtist     = "David Bovie";
            string tAlbum      = "Beautifull story";
            string tGuest      = "Carter";
            string tNum        = "1";
            string tTrack      = "New Life";

            string templejt = template;

            //ustawienie enumeratorów - będą chodzić po stringu
            CharEnumerator enumerator = templejt.GetEnumerator();
            CharEnumerator drugiEnum  = templejt.GetEnumerator();

            //jezeli pusty nie zaczynaj
            if (templejt.Equals(""))
            {
                return(afterRepl);
            }

            //1 krok na 1 znak
            enumerator.MoveNext();


            for (int i = 0; i < templejt.Length; i++)
            {
                while (i < templejt.Length)
                {
                    if (enumerator.Current.Equals('$'))
                    {
                        while (!(enumerator.Current.Equals(' ')))
                        {
                            //wpisano $ zliczaj dalsze znaki zeby skumac czy to keyword
                            buffer += enumerator.Current;
                            i++;
                            if (i < templejt.Length)
                            {
                                enumerator.MoveNext();
                            }
                            else
                            {
                                endOfString = true;
                                break;
                            }
                        }

                        switch (buffer)
                        {
                        case "$artist":
                            afterRepl += tArtist;
                            break;

                        case "$album":
                            afterRepl += tAlbum;
                            break;

                        case "$guest":
                            afterRepl += tGuest;
                            break;

                        case "$num":
                            afterRepl += tNum;
                            break;

                        case "$track":
                            afterRepl += tTrack;
                            break;

                        default:
                            afterRepl += buffer;

                            break;
                        }
                        i++;
                        flush();
                    }
                    else
                    {
                        afterRepl += enumerator.Current;

                        enumerator.MoveNext();
                        i++;
                    }
                }
            }

            return(afterRepl);
        }
Example #21
0
 public FunCharEnumerator(CharEnumerator enumerator)
 {
     _enumerator = enumerator;
 }
Example #22
0
        public override string Encrypt(string text, string key = null)
        {
            string result = "";

            if (string.IsNullOrEmpty(key))
            {
                throw new Exception("Введите ключ");
            }
            string alphabet = "";

            key = key.ToLower();

            key = key.Replace("j", "i");
            key = key.Replace("ё", "е");

            if (key.All(symb => _rusAlphabet.Contains(symb)))
            {
                alphabet = _rusAlphabet;
            }
            else if (key.All(symb => _engAlphabet.Contains(symb)))
            {
                alphabet = _engAlphabet;
            }
            else
            {
                throw new Exception("Ключ должен состоять из символов одного алфавита");
            }

            string tempKey = String.Join("", key.Distinct());

            foreach (var item in tempKey)
            {
                alphabet = alphabet.Replace(item.ToString(), "");
            }

            alphabet = tempKey + alphabet;


            string tempText = ""; // tempText will contain only alphabet letters

            List <int> ptrs = new List <int>();

            // choose correct letters from open text
            for (int i = 0; i < text.Length; i++)
            {
                if (alphabet.Contains(char.ToLower(text[i])))
                {
                    ptrs.Add(i);
                    tempText += text[i];
                }
            }

            // for every bigram do rule
            for (int i = 0; i < tempText.Length; i += 2)
            {
                string bigram = "" + tempText[i];
                if (i + 1 < tempText.Length)
                {
                    bigram += tempText[i + 1];
                }
                result += doRule(bigram, alphabet);
            }

            StringBuilder  stringBuilder = new StringBuilder(text);
            CharEnumerator iter          = result.GetEnumerator();

            foreach (var ptr in ptrs)
            {
                iter.MoveNext();
                stringBuilder[ptr] = iter.Current;
            }

            return(stringBuilder.ToString());
        }
Example #23
0
        /// <summary>
        /// Obtains the MText text value without the formatting codes, control characters like tab '\t' will be preserved in the result,
        /// the new paragraph command "\P" will be converted to new line feed '\r\n'.
        /// </summary>
        /// <returns>MText text value without the formatting codes.</returns>
        public string PlainText()
        {
            if (string.IsNullOrEmpty(this.value))
            {
                return(string.Empty);
            }

            string text = this.value;

            //text = text.Replace("%%c", "Ø");
            //text = text.Replace("%%d", "°");
            //text = text.Replace("%%p", "±");

            StringBuilder  rawText = new StringBuilder();
            CharEnumerator chars   = text.GetEnumerator();

            while (chars.MoveNext())
            {
                char token = chars.Current;
                if (token == '\\') // is a formatting command
                {
                    if (chars.MoveNext())
                    {
                        token = chars.Current;
                    }
                    else
                    {
                        return(rawText.ToString());                  // premature end of text
                    }
                    if (token == '\\' | token == '{' | token == '}') // escape chars
                    {
                        rawText.Append(token);
                    }
                    else if (token == 'L' | token == 'l' | token == 'O' | token == 'o' | token == 'K' | token == 'k' | token == 'P' | token == 'X') // one char commands
                    {
                        if (token == 'P')
                        {
                            rawText.Append(Environment.NewLine);
                        }
                        else
                        {
                        }        // discard other commands
                    }
                    else // formatting commands of more than one character always terminate in ';'
                    {
                        bool stacking = token == 'S'; // we want to preserve the text under the stacking command
                        while (token != ';')
                        {
                            if (chars.MoveNext())
                            {
                                token = chars.Current;
                            }
                            else
                            {
                                return(rawText.ToString()); // premature end of text
                            }
                            if (stacking && token != ';')
                            {
                                rawText.Append(token); // append user data of stacking command
                            }
                        }
                    }
                }
                else if (token == '{' | token == '}')
                {
                    // discard group markers
                }
                else // char is what it is, a character
                {
                    rawText.Append(token);
                }
            }
            return(rawText.ToString());
        }
Example #24
0
 public PathDataReader(string input)
 {
     this.input = input;
     iterator   = input.GetEnumerator();
 }
Example #25
0
        //check ty le PH ck
        public static bool checkReleaseRate(string p_strReleaseRate)
        {
            try
            {
                bool           _ck             = false;
                int            _dau2cham_cout  = 0;
                int            _dau2cham_vitri = 0;
                int            counter         = 0;
                int            convertedPw;
                CharEnumerator charEnum = p_strReleaseRate.GetEnumerator();

                if (Convert.ToInt32(p_strReleaseRate[0]) == 32 || Convert.ToInt32(p_strReleaseRate[0]) == 48 || Convert.ToInt32(p_strReleaseRate[0]) == 58 || Convert.ToInt32(p_strReleaseRate[counter]) == 58)
                {
                    return(false);
                }
                else
                {
                    #region check chuoi neu ktu dau va cuoi ko phai la dau 2 cham, ky tu dau tien ko phai la so 0 hoac khoang trang
                    while (charEnum.MoveNext())
                    {
                        convertedPw = Convert.ToInt32(p_strReleaseRate[counter]);
                        // dangtq sửa theo index bug 48108
                        //if ((convertedPw >= 48) && (convertedPw <= 57))
                        //{   //ky tu so
                        //    _ck = true;
                        //}

                        // new
                        if (((convertedPw >= 48) && (convertedPw <= 57)) || (convertedPw == 46))
                        {   //ky tu so hoac la dau . phan cach thap phan
                            _ck = true;
                        }
                        else if (convertedPw == 58 && _dau2cham_cout < 2)
                        {
                            _dau2cham_vitri = counter;
                            _dau2cham_cout += 1;
                            _ck             = true;
                        }
                        else
                        {
                            _ck = false;
                            break;
                        }

                        counter++;
                    }
                    #endregion
                }

                if (_ck == true)
                {
                    //check xem dau 2 cham o vi tri dau tien hay cuoi cung
                    if (_dau2cham_cout == 0 || Convert.ToInt32(p_strReleaseRate[_dau2cham_vitri + 1]) == 48)
                    {
                        _ck = false;
                    }
                }
                return(_ck);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #26
0
        private int CountFormat(CharEnumerator format)
        {
            int count  = 0;
            int level  = 0;
            int endfmt = 0;

            while (endfmt == 0)
            {
                var c = PopChar(format);
                switch (c)
                {
                case '(':
                    if (level == 0)
                    {
                        count++;
                    }
                    level++;
                    break;

                case ')':
                    if (level == 0)
                    {
                        throw new ApplicationException(
                                  "Excess ')' in getargs format");
                    }
                    else
                    {
                        level--;
                    }
                    break;

                case '\0':
                    endfmt = 1;
                    break;

                case ':':
                    endfmt = 1;
                    break;

                case ';':
                    endfmt = 1;
                    break;

                default:
                    if (level == 0)
                    {
                        if (char.IsLetter(c))
                        {
                            if (c != 'e')     /* skip encoded */
                            {
                                count++;
                            }
                        }
                    }
                    break;
                }
            }

            if (level != 0)
            {
                throw new ApplicationException(
                          "Missing ')' in getargs format");
            }
            return(count);
        }
Example #27
0
        /// <summary>
        /// Converts the string representation of a tolerance to its tolerance entity equivalent.
        /// </summary>
        /// <param name="s">A string that represents a tolerance to convert.</param>
        /// <returns>The Tolerance entity equivalent to the tolerance contained in s.</returns>
        public static Tolerance ParseStringRepresentation(string s)
        {
            string[] lines = Regex.Split(s, "\\^J");

            ToleranceEntry t1              = null;
            ToleranceEntry t2              = null;
            string         projValue       = string.Empty;
            bool           showProjSymbol  = false;
            string         datumIdentifier = string.Empty;

            for (int i = 0; i < lines.Length; i++)
            {
                string line = lines[i];
                if (line.StartsWith("{") || line.StartsWith("%%v"))
                {
                    switch (i)
                    {
                    case 0:
                        t1 = ParseToleranceEntry(line);
                        break;

                    case 1:
                        t2 = ParseToleranceEntry(line);
                        break;
                    }
                }
                else
                {
                    if (i == lines.Length - 1)
                    {
                        datumIdentifier = line;
                    }
                    else
                    {
                        StringBuilder value = new StringBuilder();

                        CharEnumerator chars = line.GetEnumerator();
                        while (chars.MoveNext())
                        {
                            char token = chars.Current;
                            if (token == '{')
                            {
                                char symbol = Symbol(chars);
                                if (symbol == 'p')
                                {
                                    showProjSymbol = true;
                                }
                            }
                            else
                            {
                                value.Append(token);
                            }
                        }
                        projValue = value.ToString();
                    }
                }
            }

            Tolerance tolerance = new Tolerance
            {
                Entry1 = t1,
                Entry2 = t2,
                ProjectedToleranceZoneValue      = projValue,
                ShowProjectedToleranceZoneSymbol = showProjSymbol,
                DatumIdentifier = datumIdentifier
            };

            return(tolerance);
        }
Example #28
0
        private void ConvertSimple(CharEnumerator format, int flags)
        {
            switch (PopChar(format))
            {
            case 'b':     /* unsigned byte -- very short int */
            case 'B':     /* byte sized bitfield - both signed and unsigned
                           * values allowed */
                ArgumentTypes.Add(ptrChar);
                break;

            case 'h':     /* signed short int */
                ArgumentTypes.Add(Ptr(dtShort));
                break;

            case 'H':     /* short int sized bitfield, both signed and
                           * unsigned allowed */
                ArgumentTypes.Add(Ptr(dtUShort));
                break;

            case 'i':     /* signed int */
                ArgumentTypes.Add(Ptr(dtInt));
                break;

            case 'I':     /* int sized bitfield, both signed and
                           * unsigned allowed */
                ArgumentTypes.Add(Ptr(dtUInt));
                break;

            case 'n':     /* Py_ssize_t */
                ArgumentTypes.Add(Ptr(dtPySize));
                break;

            case 'l':     /* long int */
                ArgumentTypes.Add(Ptr(dtLong));
                break;

            case 'k':     /* long sized bitfield */
                ArgumentTypes.Add(Ptr(dtULong));
                break;

            case 'L':     /* PY_LONG_LONG */
                ArgumentTypes.Add(Ptr(dtLongLong));
                break;

            case 'K':     /* long long sized bitfield */
                ArgumentTypes.Add(Ptr(dtULongLong));
                break;

            case 'f':     /* float */
                ArgumentTypes.Add(Ptr(dtFloat));
                break;

            case 'd':     /* double */
                ArgumentTypes.Add(Ptr(dtDouble));
                break;

            case 'D':     /* complex double */
                ArgumentTypes.Add(ptrPyComplex);
                break;

            case 'c':     /* char */
                ArgumentTypes.Add(ptrChar);
                break;

            case 's':     /* string */
            case 'z':     /* string, may be NULL (None) */
                if (format.Current == '*')
                {
                    ArgumentTypes.Add(ptrPyBuffer);
                    format.MoveNext();
                }
                else if (format.Current == '#')
                {
                    ArgumentTypes.Add(Ptr(ptrChar));
                    if ((flags & FLAG_SIZE_T) != 0)
                    {
                        ArgumentTypes.Add(Ptr(dtPySize));
                    }
                    else
                    {
                        ArgumentTypes.Add(Ptr(dtInt));
                    }

                    format.MoveNext();
                }
                else
                {
                    ArgumentTypes.Add(Ptr(ptrChar));
                }
                break;

            case 'e':     /* encoded string */
                ArgumentTypes.Add(ptrChar);

                /* Get output buffer parameter:
                 * 's' (recode all objects via Unicode) or
                 * 't' (only recode non-string objects)
                 */
                if (format.Current != 's' && format.Current == 't')
                {
                    throw new ApplicationException(
                              "Unknown parser marker combination");
                }
                ArgumentTypes.Add(Ptr(ptrChar));
                format.MoveNext();

                if (format.Current == '#')
                {
                    /* Using buffer length parameter '#' */
                    if ((flags & FLAG_SIZE_T) != 0)
                    {
                        ArgumentTypes.Add(Ptr(dtPySize));
                    }
                    else
                    {
                        ArgumentTypes.Add(Ptr(dtInt));
                    }

                    format.MoveNext();
                }
                break;

            case 'u':     /* raw unicode buffer (Py_UNICODE *) */
                if (format.Current == '#')
                {
                    ArgumentTypes.Add(Ptr(ptrChar));
                    if ((flags & FLAG_SIZE_T) != 0)
                    {
                        ArgumentTypes.Add(Ptr(dtPySize));
                    }
                    else
                    {
                        ArgumentTypes.Add(Ptr(dtInt));
                    }
                    format.MoveNext();
                }
                else
                {
                    ArgumentTypes.Add(Ptr(ptrPyUnicode));
                }
                break;

            case 'S':     /* string object */
            case 'U':     /* Unicode object */
                ArgumentTypes.Add(Ptr(ptrPyObject));
                break;

            case 'O':     /* object */
                if (format.Current == '!')
                {
                    ArgumentTypes.Add(ptrPyTypeObject);
                    ArgumentTypes.Add(Ptr(ptrPyObject));
                    format.MoveNext();
                }
                else if (format.Current == '?')
                {
                    ArgumentTypes.Add(ptrPyInquiry);
                    ArgumentTypes.Add(Ptr(ptrPyObject));
                    format.MoveNext();
                }
                else if (format.Current == '&')
                {
                    ArgumentTypes.Add(ptrPyConverter);
                    ArgumentTypes.Add(ptrVoid);
                    format.MoveNext();
                }
                else
                {
                    ArgumentTypes.Add(Ptr(ptrPyObject));
                }
                break;

            case 'w':     /* memory buffer, read-write access */
                ArgumentTypes.Add(Ptr(ptrVoid));

                if (format.Current == '*')
                {
                    format.MoveNext();
                }
                else if (format.Current == '#')
                {
                    if ((flags & FLAG_SIZE_T) != 0)
                    {
                        ArgumentTypes.Add(Ptr(dtPySize));
                    }
                    else
                    {
                        ArgumentTypes.Add(Ptr(dtInt));
                    }
                    format.MoveNext();
                }
                break;

            case 't':     /* 8-bit character buffer, read-only access */
                ArgumentTypes.Add(Ptr(ptrChar));

                if (format.Current != '#')
                {
                    throw new ApplicationException(
                              "Invalid use of 't' format character");
                }

                format.MoveNext();

                if ((flags & FLAG_SIZE_T) != 0)
                {
                    ArgumentTypes.Add(Ptr(dtPySize));
                }
                else
                {
                    ArgumentTypes.Add(Ptr(dtInt));
                }

                break;

            default:
                throw new ApplicationException("Bad format char");
            }
        }
Example #29
0
        private object fCreateLisEnum(string aString, Type aType)
        {
            object[] flagsAttribs = aType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false);
            if ((int)flagsAttribs.LongLength > 0)
            {
                string      inputString     = string.Empty;
                string      enumStringValue = null;
                int         i      = 0;
                FieldInfo[] fields = aType.GetFields();
                if (fields != null)
                {
                    for (; i < (int)fields.LongLength; i++)
                    {
                        FieldInfo          fi      = fields[i];
                        LisEnumAttribute[] attribs = fi.GetCustomAttributes(typeof(LisEnumAttribute), inherit: false) as LisEnumAttribute[];
                        if ((int)attribs.LongLength > 0)
                        {
                            enumStringValue = attribs[0].LisID;
                        }
                        if (aString == null)
                        {
                            continue;
                        }
                        CharEnumerator enumerator = aString.GetEnumerator();
                        if (enumerator == null)
                        {
                            continue;
                        }
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                char ch = enumerator.Current;
                                if (string.Compare(enumStringValue, new string(ch, 1), ignoreCase: true) == 0)
                                {
                                    inputString = inputString + fi.Name + ",";
                                }
                            }
                        }
                        finally
                        {
                            enumerator.Dispose();
                        }
                    }
                }
                if (inputString.Length > 0)
                {
                    inputString = inputString.Remove(inputString.Length - 1, 1);
                    return(Enum.Parse(aType, inputString));
                }
            }
            else
            {
                string      inputString = null;
                int         i           = 0;
                FieldInfo[] fields      = aType.GetFields();
                if (fields != null)
                {
                    for (; i < (int)fields.LongLength; i++)
                    {
                        FieldInfo          fi      = fields[i];
                        LisEnumAttribute[] attribs = fi.GetCustomAttributes(typeof(LisEnumAttribute), inherit: false) as LisEnumAttribute[];
                        if ((int)attribs.LongLength > 0)
                        {
                            inputString = attribs[0].LisID;
                        }
                        if (string.Compare(inputString, aString, ignoreCase: true) == 0)
                        {
                            return(Enum.Parse(aType, fi.Name));
                        }
                    }
                }
            }
            object Result = default(object);

            return(Result);
        }
Example #30
0
 public CharIterator(String str)
 {
     fEn    = str.GetEnumerator();
     fValid = true;
     MoveNext();
 }
Example #31
0
        public static object unpack(String jsonstr)
        {
            object    _out   = null;
            Hashtable _table = null;
            ArrayList _array = null;

            String         key   = "";
            String         value = "";
            CharEnumerator c     = jsonstr.GetEnumerator();

            Stack s = new Stack();

            Func <String, String> parsekey = (String _c) => {
                key += _c;
                return(key);
            };

            Func <String, String> parsevalue = (String _c) =>
            {
                value += _c;
                return(value);
            };

            Func <String, String> parsesys = parsekey;

            Func <String, String> parsemap = (String _c) =>
            {
                parsesys = parsekey;

                if (value == "" || key == "")
                {
                    return(_c);
                }

                value = value.Trim();
                while (value[0] == '\n' || value[0] == '\t' || value[0] == '\0')
                {
                    value = value.Substring(1, value.Length - 1);
                }
                String v = value;
                key = key.Trim();
                while (key[0] == '\n' || key[0] == '\t' || key[0] == '\0')
                {
                    key = key.Substring(1, key.Length - 1);
                }
                key = key.Substring(1, key.Length - 2);

                if (v == "true")
                {
                    _table[key] = true;
                }
                else if (v == "false")
                {
                    _table[key] = false;
                }
                else if (v == "null")
                {
                    _table[key] = null;
                }
                else
                {
                    if (v[0] == '\"' && v[v.Length - 1] == '\"')
                    {
                        v           = v.Substring(1, v.Length - 2);
                        _table[key] = v;
                    }
                    else
                    {
                        int status = 0;

                        foreach (char _ch in v)
                        {
                            if ((_ch < '0' || _ch > '9') && _ch != '.')
                            {
                                throw new Exception("format error");
                            }

                            if (_ch == '.')
                            {
                                status++;
                            }
                        }

                        if (status == 0)
                        {
                            _table[key] = Convert.ToInt64(v);
                        }
                        else if (status == 1)
                        {
                            _table[key] = Convert.ToDouble(v);
                        }
                        else
                        {
                            throw new Exception("format error");
                        }
                    }
                }

                key   = "";
                value = "";

                return(_c);
            };

            Func <String, String> parsearray = (String _c) =>
            {
                value = value.Trim();

                if (value == "")
                {
                    return(_c);
                }

                while (value[0] == '\n' || value[0] == '\t' || value[0] == '\0')
                {
                    value = value.Substring(1, value.Length - 1);
                }
                String v = value;

                if (v.ToLower() == "true")
                {
                    _array.Add(true);
                }
                else if (v.ToLower() == "false")
                {
                    _array.Add(false);
                }
                else if (v.ToLower() == "null")
                {
                    _array.Add(null);
                }
                else
                {
                    if (v[0] == '\"' && v[v.Length - 1] == '\"')
                    {
                        v = v.Substring(1, v.Length - 2);
                        _array.Add(v);
                    }
                    else
                    {
                        int status = 0;

                        foreach (char _ch in v)
                        {
                            if ((_ch < '0' || _ch > '9') && _ch != '.')
                            {
                                throw new Exception("format error");
                            }

                            if (_ch == '.')
                            {
                                status++;
                            }
                        }

                        if (status == 0)
                        {
                            _array.Add(Convert.ToInt64(v));
                        }
                        else if (status == 1)
                        {
                            _array.Add(Convert.ToDouble(v));
                        }
                        else
                        {
                            throw new Exception("format error");
                        }
                    }
                }

                key   = "";
                value = "";

                return(_c);
            };

            Func <String, String> parseenum = parsemap;

            Func <object, object> parsepop = (object o) => {
                if (typeof(Hashtable).IsInstanceOfType(o))
                {
                    _table = (Hashtable)o;

                    parsesys  = parsekey;
                    parseenum = parsemap;
                }
                else if (typeof(ArrayList).IsInstanceOfType(o))
                {
                    _array = (ArrayList)o;

                    parsesys  = parsevalue;
                    parseenum = parsearray;
                }

                return(o);
            };

            int count  = 0;
            int escape = 0;

            while (c.MoveNext())
            {
                if (c.Current.ToString() == "\\")
                {
                    escape = 1;
                }
                else
                {
                    escape = 0;
                }

                if (c.Current.ToString() == "\"" && escape != 1)
                {
                    if (count == 0)
                    {
                        count++;
                    }
                    else
                    {
                        count = 0;
                    }
                }

                if (count == 0)
                {
                    if (c.Current.ToString() == "{")
                    {
                        parsesys  = parsekey;
                        parseenum = parsemap;

                        Hashtable _newtable = new Hashtable();
                        if (_table != null)
                        {
                            key = key.Trim();
                            while (key[0] == '\n' || key[0] == '\t' || key[0] == '\0')
                            {
                                key = key.Substring(1, key.Length - 1);
                            }
                            s.Push(_table);
                            key         = key.Substring(1, key.Length - 2);
                            _table[key] = _newtable;
                            _table      = null;
                            key         = "";
                        }
                        else if (_array != null)
                        {
                            s.Push(_array);
                            _array.Add(_newtable);
                            _array = null;
                        }
                        _table = _newtable;

                        continue;
                    }

                    if (c.Current.ToString() == "}")
                    {
                        parseenum(c.Current.ToString());

                        if (s.Count > 0)
                        {
                            parsepop(s.Pop());
                        }

                        continue;
                    }

                    if (c.Current.ToString() == "[")
                    {
                        parsesys  = parsevalue;
                        parseenum = parsearray;

                        ArrayList _newarray = new ArrayList();
                        if (_table != null)
                        {
                            s.Push(_table);
                            key = key.Trim();
                            while (key[0] == '\n' || key[0] == '\t' || key[0] == '\0')
                            {
                                key = key.Substring(1, key.Length - 1);
                            }
                            key         = key.Substring(1, key.Length - 2);
                            _table[key] = _newarray;
                            _table      = null;
                            key         = "";
                        }
                        else if (_array != null)
                        {
                            s.Push(_array);
                            _array.Add(_newarray);
                            _array = null;
                        }
                        _array = _newarray;

                        continue;
                    }

                    if (c.Current.ToString() == "]")
                    {
                        parseenum(c.Current.ToString());

                        if (s.Count > 0)
                        {
                            parsepop(s.Pop());
                        }

                        continue;
                    }

                    if (c.Current.ToString() == ",")
                    {
                        parseenum(c.Current.ToString());
                        continue;
                    }

                    if (c.Current.ToString() == ":")
                    {
                        parsesys = parsevalue;
                        continue;
                    }
                }

                parsesys(c.Current.ToString());
            }

            if (_table != null)
            {
                _out = _table;
            }
            else if (_array != null)
            {
                _out = _array;
            }

            return(_out);
        }
Example #32
0
        /// <summary>
        /// dang tq check so số thập phân
        /// </summary>
        /// <param name="strnewAcc"></param>
        /// <returns></returns>
        public static bool CheckSoThapPhan(string strnewAcc, int p_number_afer_cham)
        {
            try
            {
                //32,454.454000
                bool           _ck     = false;
                int            counter = 0;
                int            convertedPw;
                CharEnumerator charEnum       = strnewAcc.GetEnumerator();
                int            count          = 0;
                int            count_after_46 = 0;
                bool           _is_46         = false;
                while (charEnum.MoveNext())
                {
                    convertedPw = Convert.ToInt32(strnewAcc[counter]);

                    if ((convertedPw >= 48) && (convertedPw <= 57))
                    {
                        _ck = true;
                        if (_is_46)
                        {
                            count_after_46++;
                            // không chỉ cho ấn
                            if (count_after_46 > p_number_afer_cham)
                            {
                                _ck = false;
                                break;
                            }
                        }
                    }
                    else if (convertedPw == 46 || convertedPw == 44)//dau phay va dau cham
                    {
                        _ck = true;
                        if (convertedPw == 46) // dấu .
                        {
                            count++;
                            _is_46 = true;
                            // không cho ấn 2 dấu .
                            if (count > 1)
                            {
                                _ck = false;
                                break;
                            }
                        }
                        else
                        {
                            // nếu có dấu . rồi mà ấn thêm dấu , thì ko cho ấn
                            if (_is_46)
                            {
                                _ck = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        _ck = false;
                        break;
                    }
                    counter++;
                }

                return(_ck);
            }
            catch (Exception)
            {
                return(false);
            }
        }