Example #1
0
        private void Scan(String E)
        {
            ErTokens = new LinkedList <ErroresTokens>
                           ();
            Estado         = 0;
            TokensA        = new LinkedList <Tokens>();
            Thomson        = new LinkedList <Nodo>();
            contadorLexico = "";
            Char c;

            for (int i = 0; i <= E.Length - 1; i++)
            {
                c = E.ElementAt(i);

                switch (Estado)
                {
                case 0:

                    if (Char.IsLetter(c))
                    {
                        contadorLexico += c;
                        columna++;

                        Estado = 1;
                    }
                    else if (Char.IsDigit(c))
                    {
                        contadorLexico += c;
                        columna++;

                        Estado = 2;
                    }

                    else if (c == ('\u0022'))
                    {
                        columna++;
                        Estado = 3;
                    }

                    else if (Char.IsWhiteSpace(c))
                    {
                        columna++;
                    }
                    else if (c.Equals('\n'))
                    {
                        fila++;
                        MessageBox.Show("salto");
                        columna = 0;
                    }
                    else if (c.Equals('\t'))

                    {
                        columna++;
                    }

                    else if (c == '-')
                    {
                        contadorLexico += c;
                        columna++;

                        Estado = 9;
                    }
                    else if (c == '%')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 3;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Porcentaje);
                    }
                    else if (c == '_')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 4;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Guio);
                    }
                    else if (c == '$')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 5;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Dollar);
                    }

                    else if (c == '!')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 6;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Diferente);
                    }
                    else if (c == '#')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 7;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Numeral);
                    }
                    else if (c == '&')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 8;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Y);
                    }

                    else if (c == '(')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 9;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.ParentesisAbierto);
                    }
                    else if (c == '|')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 9;
                        AgregarNodo(contadorLexico, Nodo.TipoNodo.OR);

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.OR);
                    }
                    else if (c == ')')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 10;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.ParentesisCerrado);
                    }
                    else if ((c == (Char)39))
                    {
                        columna++;

                        Estado = 4;
                    }

                    else if (c == '+')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 11;
                        AgregarNodo(contadorLexico, Nodo.TipoNodo.CerraduraP);

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Mas);
                    }


                    else if (c == '.')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 12;
                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Concatenacion);

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Concatenacion);
                    }
                    else if (c == '/')
                    {
                        columna++;
                        Estado = 5;
                    }

                    else if (c == ':')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 14;

                        AgregarToken2(contadorLexico, columna, fila, idtoken, Tokens.Tipo.DosPuntos);
                        Estado = 1;
                    }
                    else if (c == ';')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 15;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.PuntoYComa);
                    }
                    else if (c == '<')
                    {
                        columna++;
                        Estado = 7;
                    }
                    else if (c == '=')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 16;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Igual);
                    }
                    else if (c == '?')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 16;
                        AgregarNodo(contadorLexico, Nodo.TipoNodo.CerraduraI);

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Interroga);
                    }
                    else if (c == '@')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 17;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Arroba);
                    }
                    else if (c == '^')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 18;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Elevado);
                    }
                    else if (c == '*')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 19;
                        AgregarNodo(contadorLexico, Nodo.TipoNodo.CerraduraA);

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Asterisco);
                    }

                    else if (c == '%')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 20;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Porcentaje);
                    }

                    else if (c == '{')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 23;

                        AgregarToken2(contadorLexico, columna, fila, idtoken, Tokens.Tipo.LLaveAbierta);
                        Estado = 1;
                    }

                    else if (c == '}')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 25;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.LlaveCerrada);
                    }

                    else if (c == ',')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 29;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Coma);
                    }
                    else if (c == '~')
                    {
                        contadorLexico += c;
                        columna++;

                        idtoken = 29;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.ConjuntoT);
                    }
                    else
                    {
                        contadorLexico += c;
                        ErToken(contadorLexico, "Simbolo no reconocido por el sistema", columna, fila);
                    }
                    break;

                case 1:


                    if (Char.IsLetter(c))
                    {
                        Estado          = 1;
                        contadorLexico += c;

                        columna++;
                    }
                    else if (c == '~')
                    {
                        contadorLexico += c;

                        Estado = 10;
                    }
                    else if (Expresion.ToLower().Equals(contadorLexico.ToLower()))
                    {
                        if (Char.IsDigit(c))
                        {
                            contadorLexico += c;
                            idtoken         = 20;
                            AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Expresion);
                            i--;
                        }
                        else
                        {
                            contadorLexico += c;
                            ErToken(contadorLexico, "se esperaba digito", columna, fila);
                        }
                    }
                    else if (operaciones.Equals(contadorLexico.ToLower()))
                    {
                        contadorLexico += c;
                        idtoken         = 22;
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Operaciones);
                        i--;
                    }



                    else if (CONJ.ToLower().Equals(contadorLexico.ToLower()))
                    {
                        contadorLexico += c;


                        idtoken = 21;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Conjunto);
                        i--;
                    }

                    else if (c == '}')
                    {
                        AgregarToken3(c.ToString(), columna, fila, idtoken, Tokens.Tipo.LlaveCerrada);

                        columna++;

                        idtoken = 26;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);


                        Estado         = 0;
                        contadorLexico = "";
                    }
                    else if (c == ' ')
                    {
                        idtoken = 29;

                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Terminal);
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);

                        Estado         = 0;
                        contadorLexico = "";
                    }
                    else if (c == ',')
                    {
                        columna++;

                        idtoken = 29;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);
                    }
                    else if (c == '+')
                    {
                        AgregarToken3(c.ToString(), columna, fila, idtoken, Tokens.Tipo.Mas);
                        AgregarNodo(c.ToString(), Nodo.TipoNodo.CerraduraP);
                        columna++;

                        idtoken = 29;

                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Terminal);
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);
                    }
                    else if (c == '|')
                    {
                        AgregarToken3(c.ToString(), columna, fila, idtoken, Tokens.Tipo.OR);
                        AgregarNodo(c.ToString(), Nodo.TipoNodo.OR);

                        columna++;

                        idtoken = 29;
                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Terminal);
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);
                    }
                    else if (c == '*')
                    {
                        AgregarToken3(c.ToString(), columna, fila, idtoken, Tokens.Tipo.Asterisco);
                        AgregarNodo(c.ToString(), Nodo.TipoNodo.CerraduraA);


                        idtoken = 29;

                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Terminal);
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);
                    }
                    else if (c == '.')
                    {
                        AgregarToken3(c.ToString(), columna, fila, idtoken, Tokens.Tipo.Punto);
                        AgregarNodo(c.ToString(), Nodo.TipoNodo.Concatenacion);


                        idtoken = 29;

                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Terminal);
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);
                    }
                    else if (c == '?')
                    {
                        AgregarToken3(c.ToString(), columna, fila, idtoken, Tokens.Tipo.Interroga);
                        AgregarNodo(c.ToString(), Nodo.TipoNodo.CerraduraI);


                        idtoken = 29;

                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Terminal);
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Id);
                    }


                    else
                    {
                        contadorLexico += c;
                        ErToken(contadorLexico, "no van letras aca", columna, fila);
                    }
                    break;

                case 2:



                    if (char.IsDigit(c))
                    {
                        contadorLexico += c;



                        Estado = 2;
                    }



                    else
                    {
                        idtoken = 27;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Digito);
                        i--;
                    }
                    break;


                case 3:

                    if ((c == ('\u0022')) && contadorLexico.Length >= 1)
                    {
                        idtoken = 28;
                        AgregarNodo(contadorLexico, Nodo.TipoNodo.Terminal);
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Comillas);
                        contadorLexico = "";
                        Estado         = 0;
                    }
                    else
                    {
                        contadorLexico += c;
                        columna++;
                        Estado = 3;
                    }


                    break;


                case 4:
                    if ((c == (Char)39) && contadorLexico.Length > 1)

                    {
                        idtoken = 29;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.ComillasSimples);
                    }
                    else
                    {
                        contadorLexico += c;
                    }
                    break;

                case 5:
                    if (c == '/')
                    {
                        Estado = 6;
                    }
                    else
                    {
                        MessageBox.Show("error");
                    }
                    break;

                case 6:

                    if (c == '\n')
                    {
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.ComentarioDeLinea);
                    }
                    else
                    {
                        contadorLexico += c;

                        Estado = 6;
                        columna++;
                    }
                    break;

                case 7:

                    if (c == '!')
                    {
                        Estado = 8;
                    }
                    else
                    {
                        ErToken("!", "falto terminal !", columna, fila);
                    }


                    break;

                case 8:
                    if (c == '!')
                    {
                        Estado = 8;
                    }

                    else if (c == '>')

                    {
                        MessageBox.Show("si");
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Comentario);
                    }
                    else
                    {
                        contadorLexico += c;
                        columna++;
                        Estado = 8;
                    }
                    break;


                case 9:
                    if (c == '>')
                    {
                        idtoken = 30;

                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.Flecha);
                        Estado         = 0;
                        contadorLexico = "";
                    }
                    break;

                case 10:
                    if (Char.IsLetter(c))
                    {
                        contadorLexico += c;
                        AgregarToken(contadorLexico, columna, fila, idtoken, Tokens.Tipo.ConjuntoT);
                    }
                    break;
                }
            }
            XML(TokensA);
            ErrorXML(ErTokens);
        }
Example #2
0
 public BoolWord(Char value, EBoolCharStyle charStyle = EBoolCharStyle.Yn)
 {
     _value   = value.Equals(charStyle.GetAlternateValue()[0]);
     _default = false;
     _style   = (EBoolWordStyle)charStyle;
 }
Example #3
0
        private String removeLastCharacter(String str)
        {
            int idxEnd = 0;

            for (int i = str.Length - 2; i >= 0; i--)
            {
                if (Char.IsNumber(str.ElementAt(i)) || this.listPattern.Contains(str.ElementAt(i)) || Char.Equals(str.ElementAt(i), '(') ||
                    Char.Equals(str.ElementAt(i), ')'))
                {
                    idxEnd = i + 1;
                    break;
                }
            }

            return(str.Substring(0, idxEnd));
        }
Example #4
0
        private TokenType NextTokenAny()
        {
            var chars = new char[1];

            currentToken     = "";
            currentTokenType = TokenType.Eof;
            int finished = reader.Read(chars, 0, 1);

            bool isNumber = false;
            bool isWord   = false;

            while (finished != 0)
            {
                // convert int to char
                var ba    = (char)reader.Peek();
                var ascii = new[] { ba };

                Char currentCharacter = chars[0];
                Char nextCharacter    = ascii[0];
                currentTokenType = GetType(currentCharacter);
                TokenType nextTokenType = GetType(nextCharacter);

                // handling of words with _
                if (isWord && currentCharacter == '_')
                {
                    currentTokenType = TokenType.Word;
                }
                // handing of words ending in numbers
                if (isWord && currentTokenType == TokenType.Number)
                {
                    currentTokenType = TokenType.Word;
                }

                if (currentTokenType == TokenType.Word && nextCharacter == '_')
                {
                    //enable words with _ inbetween
                    nextTokenType = TokenType.Word;
                    isWord        = true;
                }
                if (currentTokenType == TokenType.Word && nextTokenType == TokenType.Number)
                {
                    //enable words ending with numbers
                    nextTokenType = TokenType.Word;
                    isWord        = true;
                }

                // handle negative numbers
                if (currentCharacter == '-' && nextTokenType == TokenType.Number) // && isNumber == false)
                {
                    currentTokenType = TokenType.Number;
                    nextTokenType    = TokenType.Number;
                    //isNumber = true;
                }

                // this handles numbers with exponential values
                if (isNumber && (nextCharacter.Equals('E') || nextCharacter.Equals('e')))
                {
                    nextTokenType = TokenType.Number;
                }

                if (isNumber && (currentCharacter.Equals('E') || currentCharacter.Equals('e')) && (nextTokenType == TokenType.Number || nextTokenType == TokenType.Symbol))
                {
                    currentTokenType = TokenType.Number;
                    nextTokenType    = TokenType.Number;
                }


                // this handles numbers with a decimal point
                if (isNumber && nextTokenType == TokenType.Number && currentCharacter == '.')
                {
                    currentTokenType = TokenType.Number;
                }
                if (currentTokenType == TokenType.Number && nextCharacter == '.' && isNumber == false)
                {
                    nextTokenType = TokenType.Number;
                    isNumber      = true;
                }


                Column++;
                if (currentTokenType == TokenType.Eol)
                {
                    LineNumber++;
                    Column = 1;
                }

                currentToken = currentToken + currentCharacter;
                //if (_currentTokenType==TokenType.Word && nextCharacter=='_')
                //{
                // enable words with _ inbetween
                //	finished = _reader.Read(chars,0,1);
                //}
                if (currentTokenType != nextTokenType)
                {
                    finished = 0;
                }
                else if (currentTokenType == TokenType.Symbol && currentCharacter != '-')
                {
                    finished = 0;
                }
                else
                {
                    finished = reader.Read(chars, 0, 1);
                }
            }
            return(currentTokenType);
        }
Example #5
0
        static void Main(string[] args)
        {
            String[] nomesParaNovasRegras = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "X", "W", "Y", "Z" };
            List <GramaticaRegular>   gramaticasRegulares = new List <GramaticaRegular>();
            List <String>             tokens              = new List <String>();
            List <Char>               alfabeto            = new List <Char>();
            List <String>             nomesEstados        = new List <String>();
            List <Regra>              regras              = new List <Regra>();
            List <ItemRegraAdicionar> transicoesAdicionar = new List <ItemRegraAdicionar>();
            List <ContadorTransicao>  contadorTransicoes  = new List <ContadorTransicao>();

            String estadoInicial = "S";

            //===== Leitura do arquivo

            string[] linhasArquivo = System.IO.File.ReadAllLines(@"Entrada.txt");

            //====== Define os tokens
            {
                foreach (String linha in linhasArquivo)
                {
                    if ((linha.Length > 0) && (!linha.Contains("<")))
                    {
                        tokens.Add(linha);
                    }
                }
            }
            //====== Define os Estados
            {
                foreach (String linha in linhasArquivo)
                {
                    if (linha.Length > 0)
                    {
                        if ((linha.Contains("<")) && (linha.Contains(">")))
                        {
                            GramaticaRegular gramaticaRegular = new GramaticaRegular();
                            gramaticaRegular.linhaInteira = linha;

                            String estado   = "";
                            int    read     = 0;
                            int    primeiro = 1;
                            foreach (char caractere in linha)
                            {
                                switch (caractere)
                                {
                                case '<':
                                    read   = 1;
                                    estado = "";
                                    break;

                                case '>':
                                    if (!nomesEstados.Contains(estado))
                                    {
                                        nomesEstados.Add(estado);
                                    }
                                    if (primeiro == 1)
                                    {
                                        gramaticaRegular.nomeEstado = estado;
                                    }
                                    primeiro = 0;
                                    read     = 0;
                                    break;

                                default:
                                    if (read == 1)
                                    {
                                        estado += caractere;
                                    }
                                    break;
                                }
                            }
                            gramaticasRegulares.Add(gramaticaRegular);
                        }
                    }
                }
                /// Definir Estado
            }
            //====== Define o alfabeto
            {
                foreach (String linha in linhasArquivo)
                {
                    if (linha.Length > 0)
                    {
                        if ((linha.Contains("<")) && (linha.Contains(">")))
                        {
                            int read = 0;
                            foreach (char caractere in linha)
                            {
                                switch (caractere)
                                {
                                case '|':
                                    read = 1;
                                    break;

                                case '=':
                                    read = 1;
                                    break;

                                case '<':
                                    read = 0;
                                    break;

                                case ' ':
                                    break;

                                default:
                                    if ((read == 1) && (!alfabeto.Contains(caractere)))
                                    {
                                        alfabeto.Add(caractere);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }

                foreach (string token in tokens)
                {
                    foreach (char caractere in token)
                    {
                        if (!alfabeto.Contains(caractere))
                        {
                            alfabeto.Add(caractere);
                        }
                        ;
                    }
                }
            }
            //====== Debug Estados e Alfabeto
            {
                Console.WriteLine("Estados");
                foreach (string estado in nomesEstados)
                {
                    Console.WriteLine('*' + estado + '*');
                }

                Console.WriteLine("Alfabeto");
                foreach (char letra in alfabeto)
                {
                    Console.WriteLine(letra.ToString() + ' ');
                }
            }
            //====== Define as Regras pelas gramáticas informadas no arquivo
            {
                foreach (String estado in nomesEstados)
                {
                    Regra regra = new Regra();
                    regra.nomeRegra = estado;
                    regras.Add(regra);
                }

                foreach (GramaticaRegular gramatica in gramaticasRegulares)
                {
                    int    read           = 0;
                    int    comecarLeitura = 0;
                    Char   simbolo        = ' ';
                    String transicao      = "";
                    foreach (char caractere in gramatica.linhaInteira)
                    {
                        /* READ = 1: Lendo terminal
                         * READ = 2: Lendo Não-terminal
                         * READ = 3: Adicionar a produção à regra
                         */

                        switch (caractere)
                        {
                        case '=':
                            read           = 1;
                            comecarLeitura = 1;
                            break;

                        case '|':
                            if (transicao.Length > 0 || !simbolo.Equals('\0'))
                            {
                                read = 3;
                            }
                            else
                            {
                                read = 1;
                            }

                            break;

                        case '<':
                            if (comecarLeitura == 1)
                            {
                                read = 2;
                            }
                            break;

                        case '>':
                            if (read == 2)
                            {
                                read = 3;
                            }
                            break;

                        default:
                            if ((read == 1) && !caractere.Equals(' '))
                            {
                                simbolo = caractere;
                            }
                            if ((read == 2) && !caractere.Equals(' '))
                            {
                                transicao += caractere;
                            }
                            if (read == 3)
                            {
                                ItemRegra itemRegra = new ItemRegra();
                                itemRegra.simbolo        = simbolo;
                                itemRegra.regraTransicao = transicao;

                                foreach (Regra regra in regras)
                                {
                                    if (regra.nomeRegra.Equals(gramatica.nomeEstado))
                                    {
                                        if (transicao == "")
                                        {
                                            regra.final = true;
                                        }

                                        try
                                        {
                                            regra.transicoes.Add(itemRegra);
                                        }
                                        catch
                                        {
                                            regra.transicoes.Insert(0, itemRegra);
                                        }
                                    }
                                }
                                read      = 1;
                                transicao = "";
                                simbolo   = '\0';
                            }
                            break;
                        }
                    }
                    // Tratar última produção quando ainda não tratada
                    if (read == 3)
                    {
                        ItemRegra itemRegra = new ItemRegra();
                        itemRegra.simbolo        = simbolo;
                        itemRegra.regraTransicao = transicao;

                        foreach (Regra regra in regras)
                        {
                            if (regra.nomeRegra.Equals(gramatica.nomeEstado))
                            {
                                try
                                {
                                    regra.transicoes.Add(itemRegra);
                                }
                                catch
                                {
                                    regra.transicoes.Insert(0, itemRegra);
                                }
                            }
                        }
                        read      = 0;
                        transicao = "";
                    }
                }
            }
            //====== Define as Regras pelos tokens
            {
                var estadoAtual = "S";
                var temRegra    = 0;
                foreach (var token in tokens)
                {
                    estadoAtual = "S";
                    foreach (var caractere in token)
                    {
                        var    adicionarRegra  = 0;
                        String novoNomeExterno = "";
                        foreach (var regra in regras)
                        {
                            if (regra.nomeRegra.Equals(estadoAtual))
                            {
                                foreach (var novoNome in nomesParaNovasRegras)
                                {
                                    temRegra = 0;
                                    foreach (var regraTeste in regras)
                                    {
                                        if (regraTeste.nomeRegra == novoNome)
                                        {
                                            temRegra = 1;
                                            continue;
                                        }
                                    }
                                    if (temRegra == 0)
                                    {
                                        adicionarRegra  = 1;
                                        novoNomeExterno = novoNome;
                                        estadoAtual     = novoNome;

                                        ItemRegra itemRegra = new ItemRegra();
                                        itemRegra.regraTransicao = novoNome;
                                        itemRegra.simbolo        = caractere;
                                        regra.transicoes.Add(itemRegra);

                                        break;
                                    }
                                }
                            }
                        }
                        if (adicionarRegra == 1)
                        {
                            if (!nomesEstados.Contains(novoNomeExterno))
                            {
                                nomesEstados.Add(novoNomeExterno);
                            }

                            Regra novaRegra = new Regra
                            {
                                transicoes = new List <ItemRegra>(),
                                nomeRegra  = novoNomeExterno
                            };
                            regras.Add(novaRegra);
                        }
                    }
                }
            }
            //====== Identificar estados finais e epsilon transições
            {
                ItemRegra itemRegra = null;
                foreach (var regra in regras)
                {
                    if (regra.transicoes.Count == 0)
                    {
                        regra.final = true;

                        itemRegra                = new ItemRegra();
                        itemRegra.simbolo        = '&';
                        itemRegra.regraTransicao = "X";
                        regra.transicoes.Add(itemRegra);
                    }
                    foreach (var transicao in regra.transicoes)
                    {
                        if (transicao.regraTransicao.Length == 0)
                        {
                            transicao.regraTransicao = "X";
                        }
                        if (transicao.simbolo.Equals('\0'))
                        {
                            if (!alfabeto.Contains('&'))
                            {
                                alfabeto.Add('&');
                            }
                            transicao.simbolo = '&';
                        }
                        if (transicao.simbolo.Equals('&'))
                        {
                            regra.final = true;
                        }
                    }
                }
            }
            //====== Imprimir regras
            {
                ImprimirRegras(regras);
                ImprimirCSV(regras, alfabeto, nomesEstados, "AutomatoFinitoOriginal.csv");
            }
            //====== Remover Epsilon Transições
            {
                foreach (var regra in regras)
                {
                    foreach (var transicao in regra.transicoes)
                    {
                        if (transicao.simbolo.Equals('\0') || transicao.simbolo.Equals('&'))
                        {
                            var nomeRegraDestino = transicao.regraTransicao;
                            foreach (var regraDestino in regras)
                            {
                                if (regraDestino.nomeRegra == nomeRegraDestino)
                                {
                                    foreach (var transicaoRegraDestino in regraDestino.transicoes)
                                    {
                                        ItemRegraAdicionar transicaoAdicionar = new ItemRegraAdicionar
                                        {
                                            final          = regraDestino.final,
                                            nomeRegra      = regra.nomeRegra,
                                            regraTransicao = transicaoRegraDestino.regraTransicao,
                                            simbolo        = transicaoRegraDestino.simbolo
                                        };
                                        transicoesAdicionar.Add(transicaoAdicionar);
                                    }
                                }
                            }
                            transicao.valida = false;
                        }
                    }
                }
                foreach (var transicao in transicoesAdicionar)
                {
                    ItemRegra novaTransicao = new ItemRegra
                    {
                        regraTransicao = transicao.regraTransicao,
                        simbolo        = transicao.simbolo
                    };

                    Regra regra = BuscarRegra(regras, transicao.nomeRegra);
                    if (!VerificaExistenciaTransicaoRegra(regra, novaTransicao))
                    {
                        regra.transicoes.Add(novaTransicao);
                        if (transicao.final)
                        {
                            regra.final = true;
                        }
                    }
                }
                ImprimirRegras(regras);
                ImprimirCSV(regras, alfabeto, nomesEstados, "AutomatoFinitoSemEspilonTransicoes.csv");
            }
            //====== Determinização
            {
                Console.WriteLine("Determinização: ");


                bool alterou = true;


                while (alterou)
                {
                    contadorTransicoes.Clear();
                    alterou = false;
                    foreach (var regra in regras)
                    {
                        if (regra.valida)
                        {
                            foreach (var transicao in regra.transicoes)
                            {
                                if (transicao.valida)
                                {
                                    var achou = 0;
                                    foreach (var contador in contadorTransicoes)
                                    {
                                        if (transicao.simbolo.Equals(contador.simbolo) && regra.nomeRegra == contador.regraAssociada)
                                        {
                                            achou = 1;
                                            contador.quantidade++;
                                            contador.regras.Add(transicao.regraTransicao);
                                        }
                                    }
                                    if (achou == 0)
                                    {
                                        ContadorTransicao novoContador = new ContadorTransicao
                                        {
                                            regraAssociada = regra.nomeRegra,
                                            simbolo        = transicao.simbolo,
                                            quantidade     = 1
                                        };
                                        novoContador.regras.Insert(0, transicao.regraTransicao);
                                        contadorTransicoes.Add(novoContador);
                                    }
                                }
                            }
                        }
                    }


                    foreach (var contador in contadorTransicoes)
                    {
                        Console.WriteLine("Regra: " + contador.regraAssociada + " simbolo: " + contador.simbolo);
                        foreach (String regra in contador.regras)
                        {
                            Console.Write(" <" + regra + "> ");
                        }
                        Console.WriteLine("");
                    }

                    foreach (var contador in contadorTransicoes)
                    {
                        if (contador.quantidade > 1)
                        {
                            alterou = true;
                            String nomeNovaRegra = "";
                            foreach (String s in contador.regras)
                            {
                                nomeNovaRegra += s;
                            }
                            if (!nomesEstados.Contains(nomeNovaRegra))
                            {
                                nomesEstados.Add(nomeNovaRegra);


                                Regra novaRegra = new Regra();
                                novaRegra.nomeRegra = nomeNovaRegra;
                                foreach (String s in contador.regras)
                                {
                                    foreach (var regra in regras)
                                    {
                                        if (regra.nomeRegra == s)
                                        {
                                            if (regra.final)
                                            {
                                                novaRegra.final = true;
                                            }

                                            foreach (var transicao in regra.transicoes)
                                            {
                                                if (!VerificaExistenciaTransicaoRegra(novaRegra, transicao))
                                                {
                                                    ItemRegra novaTransicao = new ItemRegra()
                                                    {
                                                        simbolo        = transicao.simbolo,
                                                        valida         = transicao.valida,
                                                        regraTransicao = transicao.regraTransicao
                                                    };
                                                    novaRegra.transicoes.Add(novaTransicao);
                                                }
                                            }
                                        }
                                    }
                                }

                                regras.Add(novaRegra);
                            }
                            else
                            {
                                foreach (var regraExistente in regras)
                                {
                                    if (regraExistente.nomeRegra == nomeNovaRegra && regraExistente.valida)
                                    {
                                        foreach (String s in contador.regras)
                                        {
                                            foreach (var regra in regras)
                                            {
                                                if (regra.nomeRegra == s)
                                                {
                                                    if (regra.final)
                                                    {
                                                        regraExistente.final = true;
                                                    }

                                                    foreach (var transicao in regra.transicoes)
                                                    {
                                                        if (!VerificaExistenciaTransicaoRegra(regraExistente, transicao))
                                                        {
                                                            ItemRegra novaTransicao = new ItemRegra()
                                                            {
                                                                simbolo        = transicao.simbolo,
                                                                valida         = transicao.valida,
                                                                regraTransicao = transicao.regraTransicao
                                                            };
                                                            regraExistente.transicoes.Add(novaTransicao);
                                                        }
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            //==== Adiciona o novo estado nas transicoes e invalida as transições que foram agrupadas.
                            foreach (var regra in regras)
                            {
                                if (contador.regraAssociada == regra.nomeRegra)
                                {
                                    ItemRegra novaTransicao = new ItemRegra();
                                    novaTransicao.regraTransicao = nomeNovaRegra;
                                    novaTransicao.simbolo        = contador.simbolo;
                                    if (!VerificaExistenciaTransicaoRegra(regra, novaTransicao))
                                    {
                                        regra.transicoes.Add(novaTransicao);
                                    }

                                    foreach (var transicao in regra.transicoes)
                                    {
                                        if (transicao.simbolo == contador.simbolo && transicao.regraTransicao != nomeNovaRegra)
                                        {
                                            transicao.valida = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }



                ImprimirRegras(regras);
                ImprimirCSV(regras, alfabeto, nomesEstados, "AutomatoFinitoDeterminizado.csv");
            }

            //====== Remover estados inalcançáveis
            {
                foreach (var regraChamada in regras)
                {
                    int chamada = 0;
                    foreach (var outraRegra in regras)
                    {
                        if (regraChamada.nomeRegra != outraRegra.nomeRegra)
                        {
                            if (outraRegra.valida)
                            {
                                foreach (var transicao in outraRegra.transicoes)
                                {
                                    if (transicao.regraTransicao == regraChamada.nomeRegra && transicao.valida)
                                    {
                                        chamada = 1;
                                    }
                                }
                            }
                        }
                    }
                    if (chamada == 0 && regraChamada.nomeRegra != estadoInicial)
                    {
                        regraChamada.valida = false;
                    }
                }
            }

            //====== Remover Estados Mortos
            {
                foreach (var estado in nomesEstados)
                {
                    foreach (var regra in regras)
                    {
                        if (regra.valida)
                        {
                            if (regra.nomeRegra == estado)
                            {
                                if (regra.final)
                                {
                                    continue;
                                }

                                regra.valida = PercorreRegra(estado, regra, regras);
                            }
                            if (!regra.valida)
                            {
                                foreach (var outrasRegras in regras)
                                {
                                    foreach (var transicao in outrasRegras.transicoes)
                                    {
                                        if (transicao.regraTransicao == regra.nomeRegra)
                                        {
                                            transicao.valida = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                ImprimirRegras(regras);
                ImprimirCSV(regras, alfabeto, nomesEstados, "AutomatoFinitoMinimizado.csv");
            }

            //====== Estado de erro
            {
                var deveCriarEstadoErro = 0;
                foreach (var letra in alfabeto)
                {
                    foreach (var regra in regras)
                    {
                        var achou = 0;
                        foreach (var transicao in regra.transicoes)
                        {
                            if ((transicao.simbolo.Equals(letra) && transicao.valida) || (letra.Equals('&') && regra.final))
                            {
                                achou = 1;
                                break;
                            }
                        }
                        if (achou == 0)
                        {
                            ItemRegra transacaoErro = new ItemRegra()
                            {
                                simbolo        = letra,
                                valida         = true,
                                regraTransicao = "!"
                            };
                            regra.transicoes.Add(transacaoErro);
                            deveCriarEstadoErro = 1;
                        }
                    }
                }
                if (deveCriarEstadoErro == 1)
                {
                    Regra regra = new Regra()
                    {
                        nomeRegra  = "!",
                        final      = true,
                        valida     = true,
                        transicoes = new List <ItemRegra>()
                    };

                    foreach (var letra in alfabeto)
                    {
                        ItemRegra transicaoErro = new ItemRegra()
                        {
                            regraTransicao = "!",
                            simbolo        = letra,
                            valida         = true
                        };
                        regra.transicoes.Add(transicaoErro);
                    }
                    regras.Add(regra);
                    nomesEstados.Add("!");
                }


                ImprimirRegras(regras);
                ImprimirCSV(regras, alfabeto, nomesEstados, "AutomatoFinitoEstadoErro.csv");
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            String readLine = "";

            readLine = Console.ReadLine();
            //Console.WriteLine(" Input Found  : " + readLine);
            //Console.ReadLine();

            //-----------------Counting Charecters :

            Char[] inputClone = readLine.ToCharArray();
            int    countAlpha = 0;
            int    countQuoma = 0;

            for (int j = 0; j < inputClone.Length; j++)
            {
                //Console.WriteLine("inputClone[] : " + inputClone[j]);
                // if (String.Equals( inputClone[j], (String)"N") )
                if (Char.Equals(inputClone[j], 'N'))
                {
                    countAlpha++;
                }
                if (Char.Equals(inputClone[j], 'E'))
                {
                    countAlpha++;
                }
                if (Char.Equals(inputClone[j], 'W'))
                {
                    countAlpha++;
                }
                if (Char.Equals(inputClone[j], 'S'))
                {
                    countAlpha++;
                }
                if (Char.Equals(inputClone[j], ','))
                {
                    countQuoma++;
                }
            }



            if (countQuoma == 0)
            {
                if (countAlpha == 1)
                {
                    //Console.WriteLine(" countAlpha : "+ countAlpha);
                    //Console.WriteLine(" countQuoma : " + countQuoma);
                    //Console.ReadLine();
                    for (int i = 1; i < inputClone.Length; i++)
                    {
                        if (!Char.IsDigit(inputClone[i]))
                        {
                            //  break;
                        }
                        String trim = readLine.Substring(1, readLine.Length - 1);
                        Console.WriteLine(trim);
                        Console.ReadLine();
                    }
                }
            }
            //------------------------------Another Case for countQuoma :
            if (countQuoma > 0)
            {
                if (countAlpha > 1)
                {
                    LinkedList <String> directionList = new LinkedList <String>();
                    LinkedList <int>    distList      = new LinkedList <int>();

                    var   bits     = readLine.Split(',');
                    int[] distance = new int[bits.Length];

                    distance = getDistance(bits);

                    directionList = getDirection(bits);

                    int totalDistance = getTotalDistance(distance);

                    for (int ls = 0; ls < distance.Length; ls++)
                    {
                        distList.AddLast(distance[ls]);
                    }

                    // ... matrice of (x , y) ::
                    int[,] matrcBlock = new int[totalDistance * 2, totalDistance * 2];

                    for (int r = 0; r < (totalDistance * 2); r++)
                    {
                        //String plotToScreen="";
                        for (int s = 0; s < (totalDistance * 2); s++)
                        {
                            matrcBlock[r, s] = 0;
                            // plotToScreen += " " + 0;
                        }
                        //Console.WriteLine(plotToScreen+'\n');
                    }

                    int[] midPoint = new int[2];
                    midPoint[0] = totalDistance;
                    midPoint[1] = totalDistance;


                    matrcBlock = plotPath(0, midPoint, distList, matrcBlock, directionList);

                    int count = 0;

                    for (int t = 0; t < totalDistance * 2; t++)
                    {
                        for (int q = 0; q < totalDistance * 2; q++)
                        {
                            if (matrcBlock[t, q] == 1)
                            {
                                count++;
                            }
                        }
                    }

                    Console.WriteLine(count);
                    int rightTurns = 0;
                    LinkedList <String> newDirList = new LinkedList <string>();
                    newDirList = getDirection(bits);
                    //newDirList = getDirection(0,directionList);
                    rightTurns = getRightTurns(0, newDirList);
                    if (rightTurns > 0)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Right Turns : " + rightTurns);
                    }
                    Console.ReadLine();
                }
            }
        }
Example #7
0
 public override bool Equals(char x, char y)
 {
     return(Char.Equals(x, y));
 }
        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (tipoO.Equals('N'))
                {
                    CheckControls(tabPage2);
                    if (contT == 0)
                    {
                        if (Int32.Parse(editTextProveedores.Text) != 0)
                        {
                            vaciarCamposBusquedas();
                            Modelo.ContactoProveedores c = new Modelo.ContactoProveedores();

                            c.idContactos = Int16.Parse(editTextContacto.Text);
                            c.idproveedor = Int16.Parse(editTextProveedores.Text);
                            c.nombre      = editTextNombre.Text;
                            c.correo1     = editTextCorreo1.Text;
                            c.correo2     = editTextCorreo2.Text;
                            c.telefono    = editTextTelefono.Text;

                            Object item = a.guardarContacto(c);

                            System.Reflection.PropertyInfo msg = item.GetType().GetProperty("message");
                            System.Reflection.PropertyInfo r   = item.GetType().GetProperty("code");
                            String message = (String)(msg.GetValue(item, null));
                            int    code    = (int)(r.GetValue(item, null));

                            if (code == 1)
                            {
                                ResetControls(tabPage2);
                                DisableControls(tabPage2);
                                tipoO = 's';
                                Recarga();
                                this.tabControl1.SelectTab(0);
                                MessageBox.Show(message, "OK", MessageBoxButtons.OK, MessageBoxIcon.None);
                            }
                            else if (code == 2)
                            {
                                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show("Contacto Proveedor no puede ser 0", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Se deben de llenar todos los campos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    contT = 0;
                }
                else if (tipoO.Equals('E'))
                {
                    CheckControls(tabPage2);
                    if (contT == 0)
                    {
                        var datos = int.Parse(editTextProveedores.Text);
                        Modelo.ContactoProveedores mo = new Modelo.ContactoProveedores();
                        mo.idContactos = Int16.Parse(editTextContacto.Text);
                        mo.idproveedor = datos;
                        mo.nombre      = editTextNombre.Text;
                        mo.correo1     = editTextCorreo1.Text;
                        mo.correo2     = editTextCorreo2.Text;
                        mo.telefono    = editTextTelefono.Text;

                        Object item = a.editarContacto(mo);

                        System.Reflection.PropertyInfo m = item.GetType().GetProperty("message");
                        System.Reflection.PropertyInfo b = item.GetType().GetProperty("code");
                        String message = (String)(m.GetValue(item, null));
                        int    code    = (int)(b.GetValue(item, null));

                        if (code == 1)
                        {
                            ResetControls(tabPage2);
                            DisableControls(tabPage2);
                            tipoO = 's';
                            Recarga();
                            MessageBox.Show(message, "OK", MessageBoxButtons.OK, MessageBoxIcon.None);
                        }
                        else if (code == 2)
                        {
                            MessageBox.Show("Se deben de llenar todos los campos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        contT = 0;
                    }
                }
                else if (tipoO.Equals('s'))
                {
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #9
0
        private IEnumerator SetupNewsTiles()
        {
            using (UnityWebRequest webRequest =
                       UnityWebRequest.Get("http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=1178460&count=3&maxlength=110&format=json")) {
                // Request and wait for the desired page.
                yield return(webRequest.SendWebRequest());

                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    Debug.LogError(webRequest.error);
                    yield break;
                }

                //Debug.Log(webRequest.downloadHandler.text);


                SteamAppNewsHolder appNewsHolder = JsonUtility.FromJson <SteamAppNewsHolder>(webRequest.downloadHandler.text);

                bool isFirst = true;

                foreach (SteamNewsItem item in appNewsHolder.appnews.newsitems)
                {
                    StartupApp_WelcomeTile tile = Instantiate(newsItemPF, tileSpawnRectTrans).GetComponent <StartupApp_WelcomeTile>();

                    //string version = item.title.Replace("Desktop Portal v", "");
                    int index = 0;
                    index = item.title.IndexOf("Portal v", StringComparison.Ordinal) + 8;
                    if (index != 0)
                    {
                        string version = item.title.Substring(index);
                        tile.versionText.SetText(version);

                        if (isFirst && version != DPSettings.config.lastSeenVersion)
                        {
                            tile.newIcon.SetActive(true);
                            DPSettings.config.lastSeenVersion = version;
                        }
                    }


                    if (item.tags.Contains("patchnotes"))
                    {
                        tile.title.SetText("Patch");
                    }

                    else
                    {
                        tile.title.SetText("Update");
                    }

                    tile.contents.SetText(item.contents);


                    tile.GetComponent <CUIOpenLink>().linkToLaunch = item.url;

                    //Get the image
                    using (UnityWebRequest announcementPage = UnityWebRequest.Get(item.url)) {
                        yield return(announcementPage.SendWebRequest());

                        //Debug.Log(announcementPage.downloadHandler.text);

                        string link = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/clans/36888522/";

                        int j = announcementPage.downloadHandler.text.IndexOf(link, StringComparison.Ordinal) + link.Length;

                        for (int i = 0; i < 100; i++)
                        {
                            Char yay = announcementPage.downloadHandler.text[j + i];
                            if (yay.Equals('"'))
                            {
                                break;
                            }
                            else
                            {
                                link += yay;
                            }
                        }

                        //Download image:
                        using (UnityWebRequest imageRequest = UnityWebRequestTexture.GetTexture(link)) {
                            yield return(imageRequest.SendWebRequest());

                            if (imageRequest.isNetworkError || imageRequest.isHttpError)
                            {
                                Debug.LogError(imageRequest.error);
                            }
                            else
                            {
                                Texture img = ((DownloadHandlerTexture)imageRequest.downloadHandler).texture;

                                tile.bgImage.texture   = img;
                                tile.mainImage.texture = img;
                            }
                        }
                    }


                    isFirst = false;
                }
            }
        }
Example #10
0
        private void alfa()
        {
            string mark = _content;

            if (_content.Contains(@"\P"))
            {
                mark = _content.Split('\\')[0];
            }

            int tot = mark.Length;

            int  numCount        = 0;
            bool multiplier      = false;
            int  multiplierCount = 0;

            int numShape = 0;
            int numDiam  = 0;

            for (int i = 0; i < tot; i++)
            {
                char cur = mark[i];
                if (!Char.IsNumber(cur))
                {
                    if (Char.Equals(cur, '*') && multiplier == false)
                    {
                        multiplier      = true;
                        multiplierCount = i;
                    }
                    else
                    {
                        numCount = i;
                        break;
                    }
                }
            }

            for (int j = numCount; j < tot; j++)
            {
                char cur = mark[j];

                if (Char.IsNumber(cur))
                {
                    numShape = j;
                    break;
                }
            }

            bool doubleDigit = false;

            for (int k = numShape; k < tot; k++)
            {
                char cur = mark[k];

                if (Char.IsNumber(cur))
                {
                    if (cur.Equals('1') && doubleDigit == false)
                    {
                        doubleDigit = true;
                        continue;
                    }
                    else if (cur.Equals('2') && doubleDigit == false)
                    {
                        doubleDigit = true;
                        continue;
                    }
                    else if (cur.Equals('3') && doubleDigit == false)
                    {
                        doubleDigit = true;
                        continue;
                    }
                    else
                    {
                        numDiam = k + 1;
                        break;
                    }
                }
            }

            int temp = numCount;

            if (multiplier == true)
            {
                temp = numCount - multiplierCount - 1;
                int number = Int32.Parse(mark.Substring(0, multiplierCount));

                int count = Int32.Parse(mark.Substring(multiplierCount + 1, temp));
                _count = number * count;
            }
            else
            {
                _count = Int32.Parse(mark.Substring(0, temp));
            }

            temp      = tot - numCount;
            _position = mark.Substring(numCount, temp);

            temp   = numShape - numCount;
            _shape = mark.Substring(numCount, temp);

            temp      = numDiam - numShape;
            _diameter = Int32.Parse(mark.Substring(numShape, temp));

            temp   = tot - numDiam;
            _other = Int32.Parse(mark.Substring(numDiam, temp));
        }
        //analizador_Lexico lexico
        public async void analizador_Lexico(String totalTexto)
        {
            ////
            int opcion  = 0;
            int columna = 0;
            int fila    = 1;

            totalTexto = totalTexto + " ";

            char[] charsRead = new char[totalTexto.Length];
            using (StringReader reader = new StringReader(totalTexto))
            {
                await reader.ReadAsync(charsRead, 0, totalTexto.Length);
            }

            StringBuilder reformattedText = new StringBuilder();

            using (StringWriter writer = new StringWriter(reformattedText))
            {
                for (int i = 0; i < charsRead.Length; i++)
                {
                    columna++;
                    Char c = totalTexto[i];
                    switch (opcion)
                    {
                    case 0:
                        //VERIFICA SI LO QUE VIENE ES LETRA
                        if (char.IsLetter(c))
                        {
                            charInicial  = "";
                            opcion       = 1;
                            auxiliar    += c;
                            charInicial += c;
                        }

                        //VERIFICA SI ES ESPACIO EN BLANCO O SALTO DE LINEA
                        else if (c.Equals('\n'))
                        {
                            opcion  = 0;
                            columna = 0; //COLUMNA 0
                            fila++;      //FILA INCREMENTA
                        }
                        //VERIFICA SI ES ESPACIO EN BLANCO O SALTO DE LINEA
                        else if (char.IsWhiteSpace(c))
                        {
                            columna++;
                            opcion = 0;
                        }
                        //VERIFICA SI LO QUE VIENE ES DIGITO
                        else if (char.IsDigit(c))
                        {
                            opcion    = 2;
                            auxiliar += c;
                        }
                        //VERIFICA SI LO QUE VIENE ES SIGNO DE PUNTUACION
                        else if (char.IsPunctuation(c))
                        {
                            //Console.WriteLine("esta entrando a puntuacion");

                            if (c.Equals('"'))
                            {
                                columna++;
                                opcion = 3;
                                i--;
                            }
                            else if (c.Equals(','))
                            {
                                opcion = 5;
                                i--;
                            }
                            else if (c.Equals('{'))
                            {
                                TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Llave_Izquierda");
                                pintarLexemas(c.ToString(), "llave", 0);
                            }
                            else if (c.Equals('}'))
                            {
                                TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Llave_Derecha");
                                pintarLexemas(c.ToString(), "llave", 0);
                            }
                            else if (c.Equals(';'))
                            {
                                TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Punto_y_Coma");
                                pintarLexemas(c.ToString(), "punto", 0);
                            }
                            else if (c.Equals(':'))
                            {
                                TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Dos_puntos");
                            }

                            /*else if (c.Equals('('))
                             * {
                             *  TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Parentesis_Derecho");
                             * }
                             * else if (c.Equals(')'))
                             * {
                             *  TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Parentesis_Izquierdo");
                             * }
                             * else if (c.Equals('['))
                             * {
                             *  TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Corchete_Derecho");
                             * }
                             * else if (c.Equals(']'))
                             * {
                             *  TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Corchete_Izquierdo");
                             * }*/
                            else if (c.Equals('%'))
                            {
                                TokenControlador.Instancia.agregarToken(fila, columna, c.ToString(), "Simb_Punt_Porcentaje");
                            }
                            else
                            {
                                //Console.WriteLine("ULTIMO ELSE PUNTUACION");
                                columna++;
                                TokenControlador.Instancia.agregarError(fila, columna, c.ToString(), "Simb_Desconocido");
                                opcion = 10;
                                i--;
                            }
                        }
                        //LO MANDA A SIGNOS DESCONOCIDOS
                        else
                        {
                            columna++;
                            //Console.WriteLine("esta entrando al ultimo else");
                            TokenControlador.Instancia.agregarError(fila, columna, c.ToString(), "Simb_Desconocido");
                            opcion = 10;
                            i--;
                        }
                        break;

                    case 1:
                        if (Char.IsLetterOrDigit(c) || c == '_')
                        {
                            auxiliar += c;
                            opcion    = 1;
                        }
                        else
                        {
                            if (auxiliar.Equals("Grafica") || auxiliar.Equals("Nombre") || auxiliar.Equals("Continente") ||
                                auxiliar.Equals("Pais") || auxiliar.Equals("Poblacion") || auxiliar.Equals("Saturacion") ||
                                auxiliar.Equals("Bandera"))
                            {
                                TokenControlador.Instancia.agregarToken(fila, columna, auxiliar, "Palabra_Reservada_" + auxiliar);
                                pintarLexemas(auxiliar, "reservada", 0);
                            }
                            else
                            {
                                TokenControlador.Instancia.agregarError(fila, columna, auxiliar, "Patron_Desconocido_" + auxiliar);
                                alertMessage("Se detecto un error, Linea" + fila + " , columna " + columna);
                            }

                            auxiliar = "";
                            i--;
                            opcion = 0;
                        }
                        break;

                    case 2:
                        if (Char.IsDigit(c))
                        {
                            auxiliar += c;
                            opcion    = 2;
                        }
                        else if (c == '.')
                        {
                            opcion    = 8;
                            auxiliar += c;
                        }
                        else
                        {
                            TokenControlador.Instancia.agregarToken(fila, columna, auxiliar, "Digito");
                            pintarLexemas(auxiliar, "numero", 0);
                            auxiliar = "";
                            i--;
                            opcion = 0;
                        }
                        break;

                    case 3:
                        if (c == '"')
                        {
                            auxiliar += c;
                            opcion    = 4;
                        }
                        break;

                    case 4:
                        if (c != '"')
                        {
                            if (c.Equals('\n'))
                            {
                                fila++; columna = 0;
                            }
                            auxiliar += c;
                            opcion    = 4;
                        }
                        else
                        {
                            opcion = 5;
                            i--;
                        }
                        break;

                    case 5:
                        if (c == '"')
                        {
                            auxiliar += c;
                            TokenControlador.Instancia.agregarToken(fila, columna, auxiliar, "Cadena");
                            pintarLexemas(auxiliar, "cadena", 0);
                            opcion   = 0;
                            auxiliar = "";
                        }
                        break;

                    case 8:
                        if (char.IsDigit(c))
                        {
                            opcion    = 9;
                            auxiliar += c;
                        }
                        else
                        {
                            opcion   = 0;
                            auxiliar = "";
                        }
                        break;

                    case 9:
                        if (Char.IsDigit(c))
                        {
                            opcion    = 9;
                            auxiliar += c;
                        }
                        else
                        {
                            TokenControlador.Instancia.agregarToken(fila, columna, auxiliar, "Digito");
                            auxiliar = "";
                            i--;

                            opcion = 0;
                        }

                        break;

                    case 10:
                        auxiliar += c;
                        //TokenControlador.Instancia.error(auxiliar, "Desconocido");
                        opcion   = 0;
                        auxiliar = "";
                        break;
                    }
                }
            }
        }
Example #12
0
        private Int32 GetValueFromPostfixExpression(String postfixExpression)
        {
            IStack <SequentialNode <Int32> > stack = new SequentialStack <Int32>();

            Int32         length    = postfixExpression.Length;
            StringBuilder sbElement = new StringBuilder();

            for (Int32 i = 0; i < length; i++)
            {
                Char tmpCharExpression = postfixExpression[i];
                //方法一(当前实现)
                //判断是否是操作数之间的分隔符,如果是则将之前的字符串认为是一个操作数(例如:110)
                //方法二
                //也可以通过栈中的元素*10,相加之和再入栈
                if (m_split.Equals(tmpCharExpression))
                {
                    if (!String.IsNullOrWhiteSpace(sbElement.ToString()))
                    {
                        stack.Push(
                            new SequentialNode <Int32>()
                        {
                            Data = Int32.Parse(sbElement.ToString())
                        }
                            );
                        sbElement = new StringBuilder();
                    }
                    continue;
                }
                //当出现运算符时,弹出栈里面的数字进行运算
                if (Char.IsNumber(tmpCharExpression))
                {
                    sbElement.Append(tmpCharExpression.ToString());
                }
                else if (stack.Count > 0)
                {
                    SequentialNode <Int32> node1 = stack.Pop();
                    SequentialNode <Int32> node2 = stack.Pop();
                    Int32 result = 0;
                    switch (tmpCharExpression)
                    {
                    case '+':
                        result = node2.Data + node1.Data;
                        break;

                    case '-':
                        result = node2.Data - node1.Data;
                        break;

                    case '*':
                        result = node2.Data * node1.Data;
                        break;

                    case '/':
                        if (0 == node1.Data)
                        {
                            throw new Exception("Zero cannot be used as a divisor.");
                        }
                        result = node2.Data / node1.Data;
                        break;
                    }
                    stack.Push(new SequentialNode <Int32>()
                    {
                        Data = result
                    });
                }
            }

            return(stack.Pop().Data);
        }
Example #13
0
        void runConsole()
        {
            string doWeGoRoundAgain;

            do
            {
                printFilmName();
                int filmNumber = 0;
                int age        = 0;
                int UserAge    = 0;
                do
                {
                    Console.Write("\nEnter the number of the film you wish to see: ");
                    try
                    {
                        //film number validation
                        filmNumber = int.Parse(Console.ReadLine());
                        if (filmNumber < 1 || filmNumber > 5)
                        {
                            Console.Write("\nThe film number is invalid\n");
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch (FormatException)
                    {
                        filmNumber = 0;

                        Console.Write("\nThe film number is invalid\n");
                    }
                } while (filmNumber < 1 || filmNumber > 5);

                do
                {
                    //age validation
                    Console.Write("\nEnter your age: ");
                    try
                    {
                        UserAge = int.Parse(Console.ReadLine());
                        if (UserAge < 5 || UserAge > 120)
                        {
                            Console.Write("\nThe age is invalid\n");
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch (FormatException)
                    {
                        UserAge = 0;
                        Console.Write("\nThe age is invalid\n");
                    }
                } while (UserAge < 5 || UserAge > 120);

                Boolean allowed = false;
                switch (filmNumber)
                {
                case 1:
                    age = 15;
                    break;

                case 2:
                    age = 15;
                    break;

                case 3:
                    age = 12;
                    break;

                case 4:
                    age = 18;
                    break;

                case 5:
                    age = 1;
                    break;

                default:
                    age = 0;
                    Console.Write("\n That Film number is invalid. \n\n");
                    Program p = new Program();
                    p.runConsole();
                    break;
                }

                if (UserAge == 12 && filmNumber == 3)
                {
                    Console.Write("\nAre you accompanied with Adult? y or n: ");//condition check for 12A
                    int  resp = Console.Read();
                    Char x    = Convert.ToChar(resp);
                    Console.Read();
                    if (x.Equals('y'))
                    {
                        age     = 12;
                        allowed = true;
                    }
                    else if (x.Equals('n'))
                    {
                        age     = 12;
                        allowed = false;
                    }
                    else
                    {
                        Console.Write("\n Invalid input. ");
                        allowed = false;
                    }
                }
                else
                {
                    if (UserAge >= age)
                    {
                        allowed = true;
                    }
                    else
                    {
                        allowed = false;
                    }
                }
                if (allowed)
                {
                    Console.Write("\nEnjoy The Film.");
                }
                else
                {
                    Console.Write("\nAccess Denied - you are too young");
                }
                Console.Write("\n\nAnother Customer? (Y or N) : ");
                doWeGoRoundAgain = Console.ReadLine();
            } while (doWeGoRoundAgain.Equals("Y"));
            Console.ReadKey();
        }
Example #14
0
        public static void Encode(string path)
        {
            string R = "", Line = "";
            string s = File.ReadAllText(path);

            string[] c = File.ReadAllLines("C:\\Users\\Public\\Documents\\CSF.txt");
            File.WriteAllText("C:\\Users\\Public\\Documents\\CF.txt", "");
            foreach (char chara in s)
            {
                for (int i = 0; i < c.Length; i++)
                {
                    if (chara == '\n' && c[i].Length == 0)
                    {
                        int j = 0;
                        Line = c[i - 1];
                        while (Line[j] != ',')
                        {
                            R += Line[j];
                            j++;
                        }
                        File.AppendAllText("C:\\Users\\Public\\Documents\\CF.txt", R);
                        R = "";
                        break;
                    }
                    else if (c[i].Length > 1)
                    {
                        Line = c[i];
                        if (Char.Equals(Line[Line.Length - 1], chara) == true)   //char.equals= to compare two charcters
                        {
                            if (Char.Equals(Line[Line.Length - 1], chara) && Line[Line.Length - 2] == ',')
                            {
                                int j = 0;
                                while (Line[j] != ',')
                                {
                                    R += Line[j];
                                    j++;
                                }
                                break;
                            }
                            else if (Char.Equals(Line[Line.Length - 1], chara) && Line[Line.Length - 2] != ',')
                            {
                                continue;
                            }
                            else
                            {
                                int j = 0;
                                while (Line[j] != ',')
                                {
                                    R += Line[j];
                                    j++;
                                }
                                break;
                            }
                        }
                    }
                }
                if (R.Length >= 30000)
                {
                    File.AppendAllText("C:\\Users\\Public\\Documents\\CF.txt", R);
                    R = "";
                }
            }
            File.AppendAllText("C:\\Users\\Public\\Documents\\CF.txt", R);
            R = "";
        }
Example #15
0
    public Boolean runTest()
    {
        Console.Error.WriteLine("Co4234Equals.cs  runTest() started.");
        int  iCountErrors    = 0;
        int  iCountTestcases = 0;
        Char charVal1        = '\0';
        Char charRes1        = '\0';

        do
        {
            charVal1 = 'A';
            charRes1 = 'A';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_dj33");
            }
            charVal1 = 'Z';
            charRes1 = 'Z';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_h388");
            }
            charVal1 = 'a';
            charRes1 = 'a';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_khj38");
            }
            charVal1 = 'z';
            charRes1 = 'z';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_dk38");
            }
            charVal1 = '@';
            charRes1 = '@';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_ak38");
            }
            charVal1 = '[';
            charRes1 = '[';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_ahw7");
            }
            charVal1 = ' ';
            charRes1 = ' ';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_fjw9");
            }
            charVal1 = '\0';
            charRes1 = '\0';
            ++iCountTestcases;
            if (!charVal1.Equals(charRes1))
            {
                ++iCountErrors;
                print("E_djA9");
            }
        }while (false);
        if (iCountErrors == 0)
        {
            Console.Error.Write("Character\\Co4234Equals.cs: paSs.  iCountTestcases==");
            Console.Error.WriteLine(iCountTestcases);
            return(true);
        }
        else
        {
            Console.Error.Write("Co4234Equals.cs iCountErrors==");
            Console.Error.WriteLine(iCountErrors);
            Console.Error.WriteLine("Co4234Equals.cs   FAiL !");
            return(false);
        }
    }
 private Boolean IsElementStart(Char c)
 {
     return(c.Equals('<'));
 }
Example #17
0
        private State getNewState(Char c)
        {
            State state = State.Error;

            switch (c)
            {
            case '/':
                state = State.InSlash;
                break;

            case '<':
                state = State.InNotEqual;
                break;

            case '&':
                state = State.InAnd;
                break;

            case '|':
                state = State.InOR;
                break;

            case ':':
                state = State.Assignment;
                break;

            case '"':
                state = State.String;
                break;

            default:
                if (Char.IsLetter(c))
                {
                    state = State.Identifier;
                }
                else if (Char.IsDigit(c))
                {
                    state = State.Int;
                }
                else if (c == ' ' || c == '\t' || c == '\n')     //TODO check if it catches all white space conditions
                {
                    state = State.Start;
                }
                else
                {
                    foreach (string word in Token.SPECIAL_SYMBOLS.Keys)
                    {
                        if (c.Equals(word))
                        {
                            state = State.Done;
                            current_token.Type = Token.SPECIAL_SYMBOLS[word];
                        }
                    }
                }
                break;
            }
            if (state != State.Error && state != State.Start)
            {
                lexeme += c;
            }
            return(state);
        }
        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (tipo.Equals('N'))
                {
                    CheckControls(tabPage2);
                    if (contT == 0)
                    {
                        vaciarCamposBusquedas();
                        Modelo.CondicionesPago c = new Modelo.CondicionesPago();
                        c.codigo      = Int16.Parse(CodigoC.Text);
                        c.descripcion = DescripcionC.Text;
                        c.dias        = Int16.Parse(DiasC.Text);
                        c.anticipo    = AnticipoC.Checked;
                        c.porcentaje  = decimal.Parse(PorcentajeC.Text);
                        Object item = s.guardarPagos(c);

                        System.Reflection.PropertyInfo m = item.GetType().GetProperty("message");
                        System.Reflection.PropertyInfo a = item.GetType().GetProperty("code");
                        String message = (String)(m.GetValue(item, null));
                        int    code    = (int)(a.GetValue(item, null));

                        if (code == 1)
                        {
                            ResetControls(tabPage2);
                            DisableControls(tabPage2);
                            tipo = 's';
                            Recarga();
                            this.tabControl1.SelectTab(0);
                            MessageBox.Show(message, "OK", MessageBoxButtons.OK, MessageBoxIcon.None);
                        }
                        else if (code == 2)
                        {
                            MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Se deben de llenar todos los campos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    contT = 0;
                }
                else if (tipo.Equals('E'))
                {
                    CheckControls(tabPage2);
                    if (contT == 0)
                    {
                        Modelo.CondicionesPago c = new Modelo.CondicionesPago();
                        c.codigo      = Int16.Parse(CodigoC.Text);
                        c.descripcion = DescripcionC.Text;
                        c.dias        = Int16.Parse(DiasC.Text);
                        c.anticipo    = AnticipoC.Checked;
                        c.porcentaje  = decimal.Parse(PorcentajeC.Text);

                        Object item = s.editarPagos(c);

                        System.Reflection.PropertyInfo m = item.GetType().GetProperty("message");
                        System.Reflection.PropertyInfo a = item.GetType().GetProperty("code");
                        String message = (String)(m.GetValue(item, null));
                        int    code    = (int)(a.GetValue(item, null));

                        if (code == 1)
                        {
                            ResetControls(tabPage2);
                            DisableControls(tabPage2);
                            tipo = 's';
                            Recarga();
                            MessageBox.Show(message, "OK", MessageBoxButtons.OK, MessageBoxIcon.None);
                        }
                        else if (code == 2)
                        {
                            MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        contT = 0;
                    }
                }
                else if (tipo.Equals('s'))
                {
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #19
0
        /// <summary>
        /// Returns a token list for all the Kinds found in the in the input string.
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public IEnumerator <Token> Scan(TextReader reader)
        {
            while (reader.Peek() != -1)
            {
                if (Char.IsWhiteSpace((Char)reader.Peek()))
                {
                    reader.Read();
                }
                else if (Char.IsLetter((Char)reader.Peek()))
                {
                    string VarName = ScanVarName(reader);

                    if (VarName.ToLower() == "exists")
                    {
                        yield return(Token.FromKind(Kind.EXISTS));
                    }
                    else if (VarName.ToLower() == "forall")
                    {
                        yield return(Token.FromKind(Kind.FORALL));
                    }
                    else
                    {
                        yield return(Token.FromString(VarName));
                    }
                }
                else if (Char.Equals((Char)reader.Peek(), '<'))
                {
                    reader.Read();
                    if (Char.Equals((Char)reader.Peek(), '='))
                    {
                        reader.Read();
                        yield return(Token.FromKind(Kind.INV_IMPL));
                    }
                    else
                    {
                        yield return(Token.FromKind(Kind.LESSER));
                    }
                }
                else if (Char.Equals((Char)reader.Peek(), '='))
                {
                    reader.Read();
                    if (Char.Equals((Char)reader.Peek(), '>'))
                    {
                        reader.Read();
                        yield return(Token.FromKind(Kind.IMPL));
                    }
                    else
                    {
                        yield return(Token.FromKind(Kind.BIMP));
                    }
                }
                else if (Char.Equals((Char)reader.Peek(), '!'))
                {
                    reader.Read();
                    char c = (Char)reader.Peek();
                    switch (c)
                    {
                    case '&': reader.Read(); yield return(Token.FromKind(Kind.NAND)); break;

                    case '|': reader.Read(); yield return(Token.FromKind(Kind.NOR)); break;

                    case '=': reader.Read(); yield return(Token.FromKind(Kind.XOR)); break;

                    default:
                        yield return(Token.FromKind(Kind.NOT)); break;
                    }
                }
                else
                {
                    char c = (char)reader.Read();
                    switch (c)
                    {
                    case '&': yield return(Token.FromKind(Kind.CON)); break;

                    case '>': yield return(Token.FromKind(Kind.GREATER)); break;

                    case '|': yield return(Token.FromKind(Kind.DIS)); break;

                    case '0': yield return(Token.FromKind(Kind.NEG)); break;

                    case '1': yield return(Token.FromKind(Kind.POS)); break;

                    case '(': yield return(Token.FromKind(Kind.LPAR)); break;

                    case ')': yield return(Token.FromKind(Kind.RPAR)); break;

                    case ',': yield return(Token.FromKind(Kind.COMMA)); break;

                    default:
                        throw new ApplicationException("Illegal Character: '" + c + "'!!");
                    }
                }
            }
            yield return(Token.FromKind(Kind.EOF));

            reader.Close();
        }
Example #20
0
        /// <summary>
        /// validate inch like this 124'- 9".
        /// </summary>
        /// <param name="input">input string</param>
        /// <returns>true if input string is a valid inch.</returns>
        private Boolean ValidateInch(String input)
        {
            // check whether the input string is a valid double value.
            // if it's true, return directly, otherwise parse the string.
            try
            {
                Double.Parse(input);
                return(true);
            }
            catch (Exception)
            {
                // reasonable exception.
                // continue to parse the string in below lines if exception occurs.
            }

            String inputTrim  = input.Trim();
            int    number     = 0; // number [0, 9].
            int    sQuotation = 0; // single quotation mark.
            int    dQuotation = 0; // double quotation mark.
            int    hLine      = 0; // char '-' mark

            foreach (Char ch in inputTrim)
            {
                if (dQuotation > 0)
                {
                    return(false);
                }

                if ('0' <= ch && ch <= '9')
                {
                    number++;
                }
                else if (ch.Equals('\''))
                {
                    if (sQuotation > 0 || number == 0)
                    {
                        return(false);
                    }
                    sQuotation++;
                    number = 0;
                }
                else if (ch.Equals('\"'))
                {
                    if (dQuotation > 0 || number == 0)
                    {
                        return(false);
                    }
                    dQuotation++;
                    number = 0;
                }
                else if (ch.Equals('-'))
                {
                    if (hLine != 0 || sQuotation == 0 || (sQuotation != 0 && number != 0))
                    {
                        return(false);
                    }
                    hLine++;
                    number = 0;
                }
                else if (ch.Equals(' '))
                {
                    // skip the white space
                }
                else
                {
                    return(false);
                }
            }

            //check whether the parsed string is valid.
            int  length = inputTrim.Length;
            Char last   = inputTrim[length - 1];

            if (dQuotation > 0 && !last.Equals('\"'))
            {
                return(false);
            }

            if (sQuotation > 0 && dQuotation == 0 && !last.Equals('\''))
            {
                return(false);
            }
            return(true);
        }
Example #21
0
 protected Boolean IsValidRatingChar(Char c)
 {
     return(Char.IsDigit(c) || c.Equals('.'));
 }
Example #22
0
        private void OnKeyDownHandler(object sender, KeyEventArgs e)
        {
            var str = bindingCalcul.StrCalcul;

            switch (e.Key)
            {
            case Key.Delete:
                bindingCalcul.StrCalcul = "";
                break;

            case Key.Back:
                if (bindingCalcul.StrCalcul.Length > 0)
                {
                    bindingCalcul.StrCalcul = removeLastCharacter(bindingCalcul.StrCalcul);
                }
                break;

            case Key.Enter:
                CalculStr(str);
                break;

            case Key.Add:
                str += "+";
                AddCharToCalculStr(str);
                break;

            case Key.Subtract:
                str += "-";
                AddCharToCalculStr(str);
                break;

            case Key.Divide:
                str += "/";
                AddCharToCalculStr(str);
                break;

            case Key.Multiply:
                str += "*";
                AddCharToCalculStr(str);
                break;

            case Key.OemComma:
                str += ",";
                AddCharToCalculStr(str);
                break;

            case Key.Oem4:
                str += ")";
                AddCharToCalculStr(str);
                break;

            case Key.Oem3:
                str += "%";
                AddCharToCalculStr(str);
                break;

            case Key.NumPad1:
            case Key.D1:
                str += "1";
                AddCharToCalculStr(str);
                break;

            case Key.NumPad2:
            case Key.D2:
                str += "2";
                AddCharToCalculStr(str);
                break;

            case Key.NumPad3:
            case Key.D3:
                str += "3";
                AddCharToCalculStr(str);
                break;

            case Key.NumPad4:
            case Key.D4:
                str += "4";
                AddCharToCalculStr(str);
                break;

            case Key.NumPad5:
            case Key.D5:
                if (Keyboard.Modifiers == ModifierKeys.Shift || Key.NumPad5 == e.Key)
                {
                    str += "5";
                }
                else
                {
                    str += "(";
                }

                AddCharToCalculStr(str);
                break;

            case Key.NumPad6:
            case Key.D6:
                if (Keyboard.Modifiers == ModifierKeys.Shift || Key.NumPad6 == e.Key)
                {
                    str += "6";
                }
                else
                {
                    str += "-";
                }
                AddCharToCalculStr(str);
                break;

            case Key.NumPad7:
            case Key.D7:
                str += "7";
                AddCharToCalculStr(str);
                break;

            case Key.NumPad8:
            case Key.D8:
                str += "8";
                AddCharToCalculStr(str);
                break;

            case Key.NumPad9:
            case Key.D9:
                str += "9";
                AddCharToCalculStr(str);
                break;

            case Key.S:
                str += "s";
                AddCharToCalculStr(str);
                break;

            case Key.I:
                if (Char.Equals(str.ElementAt(str.Length - 1), 's'))
                {
                    str += "in(";
                }
                AddCharToCalculStr(str);
                break;

            case Key.Q:
                if (Char.Equals(str.ElementAt(str.Length - 1), 's'))
                {
                    str += "qrt(";
                }
                AddCharToCalculStr(str);
                break;

            case Key.T:
                str += "tan(";
                AddCharToCalculStr(str);
                break;

            case Key.C:
                if (Keyboard.Modifiers == ModifierKeys.Control)
                {
                    Clipboard.SetText(bindingCalcul.StrCalcul);
                }
                else
                {
                    str += "cos(";
                    AddCharToCalculStr(str);
                }
                break;

            case Key.A:
                str += "abs(";
                AddCharToCalculStr(str);
                break;

            case Key.E:
                str += "exp(";
                AddCharToCalculStr(str);
                break;

            case Key.L:
                str += "log(";
                AddCharToCalculStr(str);
                break;

            case Key.X:
                if (Keyboard.Modifiers == ModifierKeys.Control)
                {
                    Clipboard.SetText(bindingCalcul.StrCalcul);
                    bindingCalcul.StrCalcul = "";
                }
                break;

            case Key.V:
                if (Keyboard.Modifiers == ModifierKeys.Control)
                {
                    bindingCalcul.StrCalcul += Clipboard.GetText();
                }
                break;

            case Key.Z:
                if (Keyboard.Modifiers == ModifierKeys.Shift)
                {
                    Border           border  = (Border)this.GetVisualChild(0);
                    AdornerDecorator rnd     = (AdornerDecorator)border.Child;
                    ContentPresenter content = (ContentPresenter)rnd.Child;
                    DockPanel        dock    = (DockPanel)content.Content;
                    Grid             grid    = (Grid)dock.Children[1];

                    foreach (FrameworkElement element in grid.Children)
                    {
                        if (element is ListBox)
                        {
                            Grid.SetColumn(element, 0);
                            Grid.SetRow(element, 0);
                            Grid.SetColumnSpan(element, 2);
                            Grid.SetRowSpan(element, 1);
                        }
                        else if (element is Viewbox && Grid.GetRow(element) < 3)
                        {
                            Grid.SetColumn(element, 0);
                            Grid.SetRow(element, 1);
                            Grid.SetColumnSpan(element, 2);
                            Grid.SetRowSpan(element, 1);
                        }
                        else if (element is Grid)
                        {
                            Grid.SetColumn(element, 0);
                            Grid.SetRow(element, 2);
                            Grid.SetColumnSpan(element, 2);
                            Grid.SetRowSpan(element, 1);
                        }
                    }
                }
                break;
            }
        }
Example #23
0
 public static Boolean IsIdentifier(this String commandLine) => (!String.IsNullOrEmpty(commandLine)) && (Char.IsLetter(commandLine[0]) || Char.Equals(commandLine[0], '_'));
Example #24
0
        private bool validOperande(String str)
        {
            for (var i = 0; i < str.Length; i++)
            {
                if (this.listPattern.Contains(str.ElementAt(i)))
                {
                    if (!Char.IsDigit(str.ElementAtOrDefault(i - 1)) && !Char.Equals(str.ElementAtOrDefault(i - 1), ')'))
                    {
                        if (!Char.Equals(str.ElementAtOrDefault(i), '+') || !(Char.Equals(str.ElementAtOrDefault(i), '+') && Char.Equals(str.ElementAtOrDefault(i - 1), 'E')))
                        {
                            bindingCalcul.AffErreur = true;
                            bindingCalcul.Erreur    = "Opérande invalide";
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
        public void GetSymptomsList()
        {
            Console.WriteLine("Retriveing symptomsNamesList ...");
            using (HttpResponseMessage res = client.GetAsync($"{ConfigurationManager.Instance.config.URL_SymptomsList}").Result)
                using (HttpContent content = res.Content)
                    using (var stringReader = new StringReader(content.ReadAsStringAsync().Result))
                    {
                        List <PotentialSymptom> potentialSymptoms = new List <PotentialSymptom>();

                        string line;

                        //Iterate throught all lines
                        while ((line = stringReader.ReadLine()) != null)
                        {
                            if (line.Length >= 6 && line.Substring(0, 6).Equals("[Term]"))
                            {
                                //Loop for one symptom
                                PotentialSymptom myPotentialSymptom = new PotentialSymptom();
                                while ((line = stringReader.ReadLine()) != null && !line.Equals("") && !line.Equals("\n"))
                                {
                                    string name = "";
                                    //idHPO
                                    if (line.Length > 4 && line.Substring(0, 4).Equals("id: "))
                                    {
                                        myPotentialSymptom.IdHPO = line.Substring(4, 10);
                                    }
                                    else if (line.Length >= 6 && line.Substring(0, 6).Equals("name: "))
                                    {
                                        name = line.Substring(6).ToLower();
                                        if (!name.Equals(""))
                                        {
                                            Regex rgx = new Regex("/[^A-Za-z0-9\\s]/g");
                                            myPotentialSymptom.Name = rgx.Replace(name, "").ToLower();
                                        }
                                    }
                                    //synonyms
                                    else if (line.Length > 10 && line.Substring(0, 10).Equals("synonym: \""))
                                    {
                                        int  index   = 10;
                                        Char monChar = line[10];
                                        do
                                        {
                                            monChar = line[index];
                                            if (!monChar.Equals('\"'))
                                            {
                                                name += monChar;
                                            }

                                            index++;
                                        } while (!monChar.Equals('\"') && index < line.Length);//Char different from "

                                        if (!name.Equals(""))
                                        {
                                            Regex rgx = new Regex("/[^A-Za-z0-9\\s]/g");
                                            myPotentialSymptom.Synonyms.Add(rgx.Replace(name, "").ToLower());
                                        }
                                    }//superClass
                                    else if (line.Length > 6 && line.Substring(0, 6).Equals("is_a: "))
                                    {
                                        myPotentialSymptom.SuperClassId = line.Substring(6, 10);
                                    }
                                }

                                //PreTest
                                if (myPotentialSymptom.Name != null && !myPotentialSymptom.Name.Equals(""))
                                {
                                    potentialSymptoms.Add(myPotentialSymptom);
                                }
                            }
                        }


                        //Good id
                        string goodIdInParentNode = "HP:0000118";//Phenotypic abnormality

                        //Filtration from bad ids
                        List <Symptom> goodSymptoms = new List <Symptom>();
                        foreach (PotentialSymptom myPotentialSymptom in potentialSymptoms)
                        {
                            //Good id is not a valid symptom (only his children), so we avoid it
                            if (!myPotentialSymptom.IdHPO.Equals(goodIdInParentNode))
                            {
                                //Copy potential symptom to initiate iterating
                                PotentialSymptom temporaryPotentialSymptom = new PotentialSymptom();
                                temporaryPotentialSymptom.IdHPO        = myPotentialSymptom.IdHPO;
                                temporaryPotentialSymptom.Name         = myPotentialSymptom.Name;
                                temporaryPotentialSymptom.SuperClassId = myPotentialSymptom.SuperClassId;
                                temporaryPotentialSymptom.Synonyms     = myPotentialSymptom.Synonyms;

                                //Iterate throught Parents and Check if it's a Valid symptom
                                bool hasASuperClass = temporaryPotentialSymptom.SuperClassId != null;
                                bool validSymptom   = false;
                                while (hasASuperClass && !validSymptom)
                                {
                                    if (temporaryPotentialSymptom.SuperClassId == null)
                                    {
                                        hasASuperClass = false;
                                    }
                                    else
                                    {
                                        //If valid id
                                        if (temporaryPotentialSymptom.SuperClassId.Equals(goodIdInParentNode))
                                        {
                                            validSymptom = true;
                                        }
                                        else
                                        {
                                            //Contniue searching
                                            temporaryPotentialSymptom = potentialSymptoms.Where(x => x.IdHPO.Equals(temporaryPotentialSymptom.SuperClassId)).First();
                                        }
                                    }
                                }

                                if (validSymptom)
                                {
                                    //Conversion from potential to real symptom
                                    Symptom symptom = new Symptom();
                                    symptom.Name     = myPotentialSymptom.Name;
                                    symptom.Synonyms = myPotentialSymptom.Synonyms;
                                    SymptomsList.Add(symptom);
                                }
                            }
                        }

                        Console.WriteLine("SymptomsNamesList retrieved!!");
                    }
        }