public void TestRewriteChildren()
    {
        var  one      = new Lit(1);
        var  two      = new Lit(2);
        var  minusTwo = new Neg(two);
        Expr expr     = new Add(one, minusTwo);

        {
            var rewritten = expr.RewriteChildren(_ => new Lit(3));

            Assert.Equal(6, Eval(rewritten));
        }
        {
            var result = expr.RewriteChildren(x => x);

            Assert.Same(expr, result);
        }
    }
    public async ValueTask TestRewriteChildrenAsync()
    {
        var  one      = new Lit(1);
        var  two      = new Lit(2);
        var  minusTwo = new Neg(two);
        Expr expr     = new Add(one, minusTwo);

        {
            var rewritten = await expr.RewriteChildren(_ => ValueTask.FromResult((Expr) new Lit(3)));

            Assert.Equal(6, Eval(rewritten));
        }
        {
            var result = await expr.RewriteChildren(x => ValueTask.FromResult(x));

            Assert.Same(expr, result);
        }
    }
 public Type Visit(Neg node) //also for substraction?
 {
     if (node[1] != null)    //two operands -> substraction
     {
         VisitBinaryOperator("-", node, Type.INT);
     }
     else  //one operand -> negation
     {
         if (Visit((dynamic)node[0]) != Type.INT)
         {
             throw new SemanticError(
                       String.Format(
                           "Operator - requires one operand of type {1}",
                           Type.INT),
                       node.AnchorToken);
         }
     }
     return(Type.INT);
 }
    public async ValueTask TestZipFoldAsync()
    {
        {
            var one      = new Lit(1);
            var two      = new Lit(2);
            var minusTwo = new Neg(two);
            var expr     = new Add(one, minusTwo);

            Assert.True(await EqualAsync(expr, expr));
        }
        {
            var one      = new Lit(1);
            var two      = new Lit(2);
            var minusTwo = new Neg(two);
            var left     = new Add(one, minusTwo);
            var right    = new Add(two, minusTwo);

            Assert.False(await EqualAsync(left, right));
        }
    }
        public double Analyze(string s)
        {
            var score = 0;
            var wc    = 0;

            foreach (var w in s.Split('\n', '\r', '-', '=', '(', ')', ' ', '\t', '!', '.', ',', '?', '"', '\''))
            {
                var ww = w.ToLower();
                if (Pos.Contains(ww))
                {
                    score++;
                }
                if (Neg.Contains(ww))
                {
                    score--;
                }
                wc++;
            }
            return(1 / (1 + Math.Exp(-Sensitivity * (score + Bias) / wc)));
        }
    public void TestZipFold()
    {
        {
            var one      = new Lit(1);
            var two      = new Lit(2);
            var minusTwo = new Neg(two);
            var expr     = new Add(one, minusTwo);

            Assert.True(Equal(expr, expr));
        }
        {
            var one      = new Lit(1);
            var two      = new Lit(2);
            var minusTwo = new Neg(two);
            var left     = new Add(one, minusTwo);
            var right    = new Add(two, minusTwo);

            Assert.False(Equal(left, right));
        }
    }
Example #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            string password = codifica_MD5(detallePassWord.Text);

            if (Modo == 'm')
            {
                //if (Neg.modificar(Usu.UsuarioID, detalleEmail.Text, detalleNombre.Text,
                //    password, detalleApe.Text, detalleDNI2.Text, detalleTel.Text,
                //    detalleCalle.Text, "", detalleCP.Text, Usu.PuebloID, Usu.ProvinciaID, detalleNacido.Text))
                if (Neg.modificar(Usu))
                {
                    statusStrip1.Visible          = true;
                    toolStripStatusLabel1.Visible = true;
                    toolStripStatusLabel1.Text    = "Usuario modificado";
                }
                else
                {
                    statusStrip1.Visible          = true;
                    toolStripStatusLabel1.Visible = true;
                    toolStripStatusLabel1.Text    = "Error al modificar el usuario";
                }
            }
            else
            if (Modo == 'i')
            {
                if (Neg.insertar(detalleEmail.Text, detalleNombre.Text,
                                 password, detalleApe.Text, detalleDNI.Text, detalleTel.Text,
                                 detalleCalle.Text, "", detalleCP.Text, "2331", "46", detalleNacido.Text))
                {
                    statusStrip1.Visible          = true;
                    toolStripStatusLabel1.Visible = true;
                    toolStripStatusLabel1.Text    = "Usuario creado";
                }
                else
                {
                    statusStrip1.Visible          = true;
                    toolStripStatusLabel1.Visible = true;
                    toolStripStatusLabel1.Text    = "Error al crear usuario";
                }
            }
        }
Example #8
0
        public bool TryGenerate(Function fuction, int block_id, Opcode op, IOperand[] oprands, out IOperand result)
        {
            result = Variable.GetTemporary();
            Instruction instruction;

            switch (op)
            {
            case Opcode.Neg: {
                instruction = new Neg(oprands[0]);
                break;
            }

            case Opcode.Add: {
                instruction = new Add(oprands[0], oprands[1]);
                break;
            }

            case Opcode.Sub: {
                instruction = new Sub(oprands[0], oprands[1]);
                break;
            }

            case Opcode.Mul: {
                instruction = new Mul(oprands[0], oprands[1]);
                break;
            }

            case Opcode.Div: {
                instruction = new Div(oprands[0], oprands[1]);
                break;
            }

            default:
                return(false);
            }
            // Function.Instructions.Add(instruction);
            // Function.Results.Add(result);
            // Blocks[block_id].AppendInstruction(Instructions.Length() - 1);

            return(true);
        }
    public void TestDescendantAt()
    {
        var  one      = new Lit(1);
        var  two      = new Lit(2);
        var  minusTwo = new Neg(two);
        Expr expr     = new Add(one, minusTwo);
        {
            var result = expr.DescendantAt(new[] { Direction.Down, Direction.Right });

            Assert.Same(minusTwo, result);
        }
        {
            var result = expr.DescendantAt(Array.Empty <Direction>());

            Assert.Same(expr, result);
        }
        {
            Assert.Throws <InvalidOperationException>(() => expr.DescendantAt(new[] { Direction.Down, Direction.Left }));
            Assert.Throws <InvalidOperationException>(() => expr.DescendantAt(new[] { Direction.Right }));
            Assert.Throws <InvalidOperationException>(() => expr.DescendantAt(new[] { Direction.Up }));
        }
    }
Example #10
0
    public void TestReplaceDescendantAt()
    {
        var  one      = new Lit(1);
        var  two      = new Lit(2);
        var  minusTwo = new Neg(two);
        Expr expr     = new Add(one, minusTwo);
        {
            var result = expr.ReplaceDescendantAt(new[] { Direction.Down, Direction.Right }, one);

            Assert.Equal(2, Eval(result));
        }
        {
            var result = expr.ReplaceDescendantAt(new[] { Direction.Down, Direction.Right }, minusTwo);

            Assert.Same(expr, result);
        }
        {
            Assert.Throws <InvalidOperationException>(() => expr.ReplaceDescendantAt(new[] { Direction.Down, Direction.Left }, one));
            Assert.Throws <InvalidOperationException>(() => expr.ReplaceDescendantAt(new[] { Direction.Right }, one));
            Assert.Throws <InvalidOperationException>(() => expr.ReplaceDescendantAt(new[] { Direction.Up }, one));
        }
    }
Example #11
0
    public void TestRewriteDescendantAt()
    {
        var  one      = new Lit(1);
        var  two      = new Lit(2);
        var  minusTwo = new Neg(two);
        Expr expr     = new Add(one, minusTwo);
        {
            var result = expr.RewriteDescendantAt(new[] { Direction.Down }, x => x is Lit l ? new Lit(l.Value + 1) : x);

            Assert.Equal(0, Eval(result));
        }
        {
            var result = expr.RewriteDescendantAt(new[] { Direction.Down }, x => x);

            Assert.Same(expr, result);
        }
        {
            Assert.Throws <InvalidOperationException>(() => expr.RewriteDescendantAt(new[] { Direction.Down, Direction.Left }, x => x));
            Assert.Throws <InvalidOperationException>(() => expr.RewriteDescendantAt(new[] { Direction.Right }, x => x));
            Assert.Throws <InvalidOperationException>(() => expr.RewriteDescendantAt(new[] { Direction.Up }, x => x));
        }
    }
Example #12
0
    public async ValueTask TestRewriteDescendantAtAsync()
    {
        var  one      = new Lit(1);
        var  two      = new Lit(2);
        var  minusTwo = new Neg(two);
        Expr expr     = new Add(one, minusTwo);
        {
            var result = await expr.RewriteDescendantAt(
                new[] { Direction.Down },
                x => ValueTask.FromResult(x is Lit l ? new Lit(l.Value + 1) : x)
                );

            Assert.Equal(0, Eval(result));
        }
        {
            var result = await expr.RewriteDescendantAt(
                new[] { Direction.Down },
                x => ValueTask.FromResult(x)
                );

            Assert.Same(expr, result);
        }
        {
            await Assert.ThrowsAsync <InvalidOperationException>(async() => await expr.RewriteDescendantAt(
                                                                     new[] { Direction.Down, Direction.Left },
                                                                     x => ValueTask.FromResult(x)
                                                                     ));

            await Assert.ThrowsAsync <InvalidOperationException>(async() => await expr.RewriteDescendantAt(
                                                                     new[] { Direction.Right },
                                                                     x => ValueTask.FromResult(x)
                                                                     ));

            await Assert.ThrowsAsync <InvalidOperationException>(async() => await expr.RewriteDescendantAt(
                                                                     new[] { Direction.Up },
                                                                     x => ValueTask.FromResult(x)
                                                                     ));
        }
    }
Example #13
0
    private PLS CreateExpression(int size)
    {
        PLS predicate = CreateUnaryExpression();
        int sizeLeft  = size;

        if (sizeLeft > 0)
        {
            int j      = Random.Range(0, 4);
            PLS newExp = CreateExpression(sizeLeft - 1);
            switch (j)
            {
            case 0:
                predicate = new And(predicate, newExp);
                break;

            case 1:
                predicate = new Or(predicate, newExp);
                break;

            case 2:
                predicate = new To(predicate, newExp);
                break;

            case 3:
                predicate = new Equiv(predicate, newExp);
                break;
            }
        }
        int i = Random.Range(0, 2);

        if (i > 0)
        {
            predicate = new Neg(predicate);
        }
        return(predicate);
    }
Example #14
0
 //-----------------------------------------------------------
 public string Visit(Neg node)
 {
     return("\t\tldc.i4.0\n\t\t" + Visit((dynamic)node[0]) + "\n\t\tsub.ov\n");
 }
Example #15
0
    //This function actually creates the object associated with each Instruction by using a long switch statement. The object
    //created is polymorphed up to an IInstruction and then returned from the function to be stored in the encodedInstrs list.
    //Ugly? Very. Effective? Extremely.
    private IInstruction createObject(string comm, int valToUse, int currentInstruc)
    {
        IInstruction retVal = null;

        switch (comm)
        {
        case "exit":
            retVal = new Exit(valToUse) as IInstruction;
            break;

        case "swap":
            retVal = new Swap() as IInstruction;
            break;

        case "inpt":
            retVal = new Inpt() as IInstruction;
            break;

        case "nop":
            retVal = new Nop() as IInstruction;
            break;

        case "pop":
            retVal = new Pop() as IInstruction;
            break;

        case "add":
            retVal = new Add() as IInstruction;
            break;

        case "sub":
            retVal = new Sub() as IInstruction;
            break;

        case "mul":
            retVal = new Mul() as IInstruction;
            break;

        case "div":
            retVal = new Div() as IInstruction;
            break;

        case "rem":
            retVal = new Rem() as IInstruction;
            break;

        case "and":
            retVal = new And() as IInstruction;
            break;

        case "or":
            retVal = new Or() as IInstruction;
            break;

        case "xor":
            retVal = new Xor() as IInstruction;
            break;

        case "neg":
            retVal = new Neg() as IInstruction;
            break;

        case "not":
            retVal = new Not() as IInstruction;
            break;

        case "goto":
            retVal = new Goto(valToUse) as IInstruction;
            break;

        case "ifeq":
            retVal = new If1(0, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifne":
            retVal = new If1(1, valToUse, currentInstruc) as IInstruction;
            break;

        case "iflt":
            retVal = new If1(2, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifgt":
            retVal = new If1(3, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifle":
            retVal = new If1(4, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifge":
            retVal = new If1(5, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifez":
            retVal = new If2(0, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifnz":
            retVal = new If2(1, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifmi":
            retVal = new If2(2, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifpl":
            retVal = new If2(3, valToUse, currentInstruc) as IInstruction;
            break;

        case "dup":
            retVal = new Dup(valToUse) as IInstruction;
            break;

        case "print":
            retVal = new Print() as IInstruction;
            break;

        case "dump":
            retVal = new Dump() as IInstruction;
            break;

        case "push":
            retVal = new Push(valToUse) as IInstruction;
            break;
        }
        return(retVal);
    }
Example #16
0
 public LoginForm()
 {
     InitializeComponent();
     neg = new Neg();
 }
 private Node group0() {
     boolean capturingGroup = false;
     Node head = null;
     Node tail = null;
     int save = _flags;
     root = null;
     int ch = next();
     if (ch == '?') {
         ch = skip();
         switch (ch) {
         case ':':   //  (?:xxx) pure group
             head = createGroup(true);
             tail = root;
             head.next = expr(tail);
             break;
         case '=':   // (?=xxx) and (?!xxx) lookahead
         case '!':
             head = createGroup(true);
             tail = root;
             head.next = expr(tail);
             if (ch == '=') {
                 head = tail = new Pos(head);
             } else {
                 head = tail = new Neg(head);
             }
             break;
         case '>':   // (?>xxx)  independent group
             head = createGroup(true);
             tail = root;
             head.next = expr(tail);
             head = tail = new Ques(head, INDEPENDENT);
             break;
         case '<':   // (?<xxx)  look behind
             ch = read();
             if (ASCII.isLower(ch) || ASCII.isUpper(ch)) {
                 // named captured group
                 String name = groupname(ch);
                 if (namedGroups().containsKey(name))
                     throw error(new String("Named capturing group <" + name
                                 + "> is already defined"));
                 capturingGroup = true;
                 head = createGroup(false);
                 tail = root;
                 namedGroups().put(name, new Integer(capturingGroupCount-1));
                 head.next = expr(tail);
                 break;
             }
             int start = _cursor;
             head = createGroup(true);
             tail = root;
             head.next = expr(tail);
             tail.next = lookbehindEnd;
             TreeInfo info = new TreeInfo();
             head.study(info);
             if (info.maxValid == false) {
                 throw error(new String("Look-behind group does not have "
                             + "an obvious maximum length"));
             }
             boolean hasSupplementary = findSupplementary(start, patternLength);
             if (ch == '=') {
                 head = tail = (hasSupplementary ?
                                new BehindS(head, info.maxLength,
                                            info.minLength) :
                                new Behind(head, info.maxLength,
                                           info.minLength));
             } else if (ch == '!') {
                 head = tail = (hasSupplementary ?
                                new NotBehindS(head, info.maxLength,
                                               info.minLength) :
                                new NotBehind(head, info.maxLength,
                                              info.minLength));
             } else {
                 throw error(new String("Unknown look-behind group"));
             }
             break;
         case '$':
         case '@':
             throw error(new String("Unknown group type"));
         default:    // (?xxx:) inlined match flags
             unread();
             addFlag();
             ch = read();
             if (ch == ')') {
                 return null;    // Inline modifier only
             }
             if (ch != ':') {
                 throw error(new String("Unknown inline modifier"));
             }
             head = createGroup(true);
             tail = root;
             head.next = expr(tail);
             break;
         }
     } else { // (xxx) a regular group
         capturingGroup = true;
         head = createGroup(false);
         tail = root;
         head.next = expr(tail);
     }
     accept(')', new String("Unclosed group"));
     _flags = save;
     // Check for quantifiers
     Node node = closure(head);
     if (node == head) { // No closure
         root = tail;
         return node;    // Dual return
     }
     if (head == tail) { // Zero length assertion
         root = node;
         return node;    // Dual return
     }
     if (node is Ques) {
         Ques ques = (Ques) node;
         if (ques.type == POSSESSIVE) {
             root = node;
             return node;
         }
         tail.next = new BranchConn();
         tail = tail.next;
         if (ques.type == GREEDY) {
             head = new Branch(head, null, tail);
         } else { // Reluctant quantifier
             head = new Branch(null, head, tail);
         }
         root = tail;
         return head;
     } else if (node is Curly) {
         Curly curly = (Curly) node;
         if (curly.type == POSSESSIVE) {
             root = node;
             return node;
         }
         // Discover if the group is deterministic
         TreeInfo info = new TreeInfo();
         if (head.study(info)) { // Deterministic
             GroupTail temp = (GroupTail) tail;
             head = root = new GroupCurly(head.next, curly.cmin,
                                curly.cmax, curly.type,
                                ((GroupTail)tail).localIndex,
                                ((GroupTail)tail).groupIndex,
                                          capturingGroup);
             return head;
         } else { // Non-deterministic
             int temp = ((GroupHead) head).localIndex;
             Loop loop;
             if (curly.type == GREEDY)
                 loop = new Loop(this.localCount, temp);
             else  // Reluctant Curly
                 loop = new LazyLoop(this.localCount, temp);
             Prolog prolog = new Prolog(loop);
             this.localCount += 1;
             loop.cmin = curly.cmin;
             loop.cmax = curly.cmax;
             loop.body = head;
             tail.next = loop;
             root = loop;
             return prolog; // Dual return
         }
     }
     throw error(new String("Internal logic error"));
 }
Example #18
0
        // builds node - constants, unary operators and binary operators
        private List <ISyntaxNode> BuildListSyntaxNode(string function)
        {
            List <ISyntaxNode> listNode = new List <ISyntaxNode>();

            for (int i = 0; i < function.Length; i++)
            {
                if (function[i] == 'p')
                {
                    ISyntaxNode pi = new Var(Math.PI);
                    listNode.Add(pi);
                    i++;
                }

                if (function[i] == 'e')
                {
                    ISyntaxNode e = new Var(Math.E);
                    listNode.Add(e);
                }

                if (function[i] == 'x')
                {
                    ISyntaxNode x = new X();
                    listNode.Add(x);
                }
                if (Char.IsNumber(function[i]))
                {
                    ISyntaxNode var = ReadVar(function, i, out i);
                    listNode.Add(var);
                }
                if (function[i] == '-')
                {
                    if (i == 0 || function[i - 1] == '(' || function[i + 1] == '(')
                    {
                        ISyntaxNode op = new Neg();
                        listNode.Add(op);
                        continue;
                    }
                }
                if (MyChar.IsBinaryOperation(function[i]))
                {
                    ISyntaxNode op = ReadOperation(function, i, out i);
                    listNode.Add(op);
                }
                if (function[i] == '(')
                {
                    ISyntaxNode op = new OpenBrackets();
                    listNode.Add(op);
                }
                if (function[i] == ')')
                {
                    ISyntaxNode op = new CloseBrackets();
                    listNode.Add(op);
                }
                if (function[i] == 's' || function[i] == 'c' || function[i] == 't' ||
                    function[i] == 'l' || function[i] == 'a')
                {
                    ISyntaxNode func = ReadFunction(function, i, out i);
                    listNode.Add(func);
                }
            }
            return(listNode);
        }
Example #19
0
 //-----------------------------------------------------------
 public void Visit(Neg node)
 {
     VisitChildren(node);
 }
Example #20
0
        static void Main(string[] args)
        {
            RunConfig runConfig;

            if (!TryParseArguments(args, out runConfig))
            {
                Usage();
                return;
            }

            var code = File.ReadAllText(args[0]);

            var pageState = new GraphicsState();

            var stack     = new LinearList <IOperation>();
            var execStack = new LinearList <IOperation>();
            var dictStack = new LinearList <IDictionary <string, IOperation> >();

            var system = new Dictionary <string, IOperation>();

            system["add"]    = new Add();
            system["sub"]    = new Substract();
            system["mul"]    = new Multiplicate();
            system["div"]    = new Divide();
            system["mod"]    = new Mod();
            system["def"]    = new Define();
            system["for"]    = new For();
            system["dup"]    = new Duplicate();
            system["index"]  = new Index();
            system["pop"]    = new Pop();
            system["exch"]   = new Exchange();
            system["repeat"] = new Repeat();
            system["array"]  = new EmptyArray();
            system["astore"] = new LoadArray();
            system["rand"]   = new Rand();
            system["cvi"]    = new ConvertToInteger();
            system["copy"]   = new Copy();
            system["roll"]   = new Roll();
            system["get"]    = new ArrayGet();
            system["put"]    = new ArrayPut();
            system["ne"]     = new NotEqual();
            system["eq"]     = new Equal();
            system["or"]     = new Or();
            system["ifelse"] = new IfElse();
            system["if"]     = new If();
            system["neg"]    = new Neg();
            system["not"]    = new Not();
            system["sqrt"]   = new Sqrt();
            system["lt"]     = new LessThan();
            system["ge"]     = new GreaterOrEqualThan();

            dictStack.Push(system);


            var graphics = new Dictionary <string, IOperation>();

            graphics["newpath"]      = new NewPath(pageState);
            graphics["closepath"]    = new ClosePath(pageState);
            graphics["fillpath"]     = new FillPath(pageState);
            graphics["setgray"]      = new SetGray(pageState);
            graphics["setrgbcolor"]  = new SetRGB(pageState);
            graphics["setlinewidth"] = new SetLineWidth(pageState);
            graphics["fill"]         = new FillPath(pageState);
            graphics["showpage"]     = new ShowPage(pageState);
            graphics["moveto"]       = new MoveTo(pageState);
            graphics["lineto"]       = new LineTo(pageState);
            graphics["rlineto"]      = new RelativeLineTo(pageState);
            graphics["gsave"]        = new SaveGraphicsState(pageState);
            graphics["grestore"]     = new RestoreGraphicsState(pageState);
            graphics["stroke"]       = new StrokePath(pageState);
            graphics["curveto"]      = new CurveTo(pageState);
            graphics["arc"]          = new Arc(pageState);

            dictStack.Push(graphics);

            dictStack.Push(new Dictionary <string, IOperation>());

            //execStack.Push(start);


            CodeParser.LoadCode(execStack,
                                @"
/findfont { pop (somefont) } def
/scalefont { exch pop } def
/setfont { pop } def
/setlinecap { pop } def
/srand { pop } def
");

            CodeParser.LoadCode(execStack, code);

            var state = new PreScriptState(stack, execStack, dictStack);

            while (execStack.Count > 0)
            {
                var operation = execStack.Pop();
                operation.Process(state);
            }
        }
Example #21
0
 public static Scalar <Type> operator -(Scalar <Type> x) => Neg <Type> .Create(x);