Beispiel #1
0
 public void AddRule(Rule rule)
 {
     lock (_rules)
     {
         _rules.Add(rule);
     }
 }
Beispiel #2
0
        public AsmBaseGrammar()
        {
            space = CharSeq(" ");
            tab = CharSeq("\t");
            simple_ws = space | tab;
            eol = Opt(CharSeq("\r")) + CharSeq("\n");
            multiline_ws = simple_ws | eol;
            ws = Eat(multiline_ws);
            digit = CharRange('0', '9');
            number = Leaf(Plus(digit));
            lower_case_letter = CharRange('a', 'z');
            upper_case_letter = CharRange('A', 'Z');
            letter = lower_case_letter | upper_case_letter;
            sign = CharSet("$-");

            opcode = Leaf(letter + Star(letter));
            register = Leaf(CharSeq("r") + Plus(digit));
            memoryAddress = CharSeq("[") + register + CharSeq("]");
            constant = sign + number;
            operand = register | memoryAddress | constant;
            comment_content = Leaf(Star(AnythingBut(eol)));
            comment = CharSet(";") + comment_content;

            InitializeRules<AsmBaseGrammar>();
        }
 public override Rule AddNewRule(string name, string pageTypeLeft, string pageTypeRight, string ruleTextLeft, string ruleTextRight)
 {
     if (!RuleExists(name))
     {
         RuleEventArgs e = new RuleEventArgs();
         e.RuleName = name;
         e.CurrentRule = null;
         if (OnCreatingRule != null)
             OnCreatingRule(null, e);
         if (!e.CancelEvent)
         {
             Rule newRule = new Rule(name, pageTypeLeft, pageTypeRight);
             newRule.RuleTextLeft = ruleTextLeft;
             newRule.RuleTextRight = ruleTextRight;
             RuleDataStore.Save(newRule);
             e.CurrentRule = newRule;
             if (OnCreatedRule != null)
                 OnCreatedRule(null, e);
             UpdateCache();
             return newRule;
         }
         else
             return null;
     }
     return null;
 }
Beispiel #4
0
        public void Tamagotchi_Dead_DoNothing()
        {
            var rules = new Rule[]
            {
                new AthleticRule(),
                new BordedomRule(),
                new CrazinessRule(),
                new FatigueRule(),
                new HungerRule(),
                new IsolationRule(),
                new MuchiesRule(),
                new SleepDeprivationRule(),
                new StarvationRule()
            };

            rules = rules.OrderBy(r => r.Order).ToArray();

            Tamagotchi t1 = new Tamagotchi("test", rules);

            t1.HasDied = true;

            var now = DateTime.UtcNow + TimeSpan.FromHours(2);

            Assert.IsFalse(t1.EatAction(now));
            Assert.IsFalse(t1.RefreshRules(now));

            Assert.AreNotEqual(t1.LastAllRulesPassedUtc, now);
        }
        /// <summary>
        /// Displays the specified item.
        /// </summary>
        /// <param name="rule">
        /// The item.
        /// </param>
        public void Display(Rule rule)
        {
            this._rule = rule;

              this.TypeName.Text = rule.TypeName;
              this.NotNull.Checked = rule.NotNull;
              this.CanBeNull.Checked = rule.CanBeNull;
              this.PublicParameterAssertion.Text = rule.PublicParameterAssertion;
              this.NonPublicParameterAssertion.Text = rule.NonPublicParameterAssertion;
              this.ReturnAssertion.Text = rule.ReturnAssertion;

              var rows = this.ValueAssertions.Rows;

              rows.Clear();

              foreach (var key in rule.ValueAssertions)
              {
            rows.Add(new[]
            {
              key
            });
              }

              this.EnableButtons();
        }
Beispiel #6
0
        private static IQueryable<Customer> FilterCustomers(IQueryable<Customer> customers, Rule rule)
        {
            if (rule.field == "CustomerId")
            {
                int result;
                if (!int.TryParse(rule.data, out result))
                    return customers;
                return customers.Where(c => c.CustomerID == Convert.ToInt32(rule.data));

            }
            if (rule.field == "Name")
                return from c in customers
                       where c.FirstName.Contains(rule.data) || c.LastName.Contains(rule.data)
                       select c;
            if (rule.field == "Company")
                return customers.Where(c => c.CompanyName.Contains(rule.data));
            if (rule.field == "EmailAddress")
                return customers.Where(c => c.EmailAddress.Contains(rule.data));
            if (rule.field == "Last Modified")
            {
                DateTime result;
                if (!DateTime.TryParse(rule.data, out result))
                    return customers;
                if (result < new DateTime(1754, 1, 1)) // sql can't handle dates before 1-1-1753
                    return customers;
                return customers.Where(c => c.ModifiedDate.Date == Convert.ToDateTime(rule.data).Date);
            }
            if (rule.field == "Telephone")
                return customers.Where(c => c.Phone.Contains(rule.data));
            return customers;
        }
        public void Define_rule()
        {
            var conditions = new RuleCondition[]
                {
                    Conditions.Equal((Order x) => x.Name, "JOE"),
                    Conditions.GreaterThan((Order x) => x.Amount, 10000.0m),
                };

            var consequences = new RuleConsequence[]
                {
                    Consequences.Delegate<Order>((session,x) => { _result = x; }),
                    Consequences.Delegate<Order>((session,x) => { _resultB = x; }),
                };

            _rule = new OdoyuleRule("RuleA", conditions, consequences);
            _rule2 = new OdoyuleRule("RuleB", conditions, consequences);

            conditions = new RuleCondition[]
                {
                    Conditions.Equal((Account a) => a.Name, "JOE"),
                };

            consequences = new RuleConsequence[]
                {
                    Consequences.Delegate((Session session, Account a) => { }),
                };

            _rule3 = new OdoyuleRule("RuleC", conditions, consequences);
        }
Beispiel #8
0
        public static ParserState Parse(string source, IAbstractSyntaxTreePrinter printer = null, Rule rule = null)
        {
            if (rule == null)
                rule = _grammar.file;

            var state = new ParserState(source);
            try
            {
                if (rule.Match(state))
                {
                    if (state.AtEndOfInput())
                    {
                        if (printer != null)
                            printer.Print(state.GetRoot());

                        return state;
                    }

                    throw new ParsingException(state, rule, message: "Failed to read end of input");
                }

                throw new ParsingException(state, rule, message: "Failed to parse source");
            }
            catch (ParsingException e)
            {
                return state.Exception(e);
            }
        }
Beispiel #9
0
 public AddToBehavior(string name, Type type, Spec spec, Rule rule)
 {
     Name = name;
     Type = type;
     Spec = spec;
     Rule = rule;
 }
Beispiel #10
0
 private void AddCondition(Rule rule, AdvTree advTree)
 {
     var node = new Node();
     node.Text = rule.Name;
     node.Tag = rule;
     AddNode(node, advTree);
 }
Beispiel #11
0
 /// <summary> TODO - note the logic feels a bit messy. Need to rethink it and make it
 /// simpler. When the first conditional element is Exist, it can only have
 /// literal constraints, so we shouldn't need to check if the last node
 /// is a join. That doesn't make any sense. Need to rethink this and clean
 /// it up. Peter Lin 10/14/2007
 /// </summary>
 public override void compileFirstJoin(ICondition condition, Rule.IRule rule)
 {
     BaseJoin bjoin = new ExistJoinFrst(ruleCompiler.Engine.nextNodeId());
     ExistCondition cond = (ExistCondition) condition;
     BaseNode base_Renamed = cond.LastNode;
     if (base_Renamed != null)
     {
         if (base_Renamed is BaseAlpha)
         {
             ((BaseAlpha) base_Renamed).addSuccessorNode(bjoin, ruleCompiler.Engine, ruleCompiler.Memory);
         }
         else if (base_Renamed is BaseJoin)
         {
             ((BaseJoin) base_Renamed).addSuccessorNode(bjoin, ruleCompiler.Engine, ruleCompiler.Memory);
         }
     }
     else
     {
         // the rule doesn't have a literal constraint so we need to Add
         // ExistJoinFrst as a child
         ObjectTypeNode otn = ruleCompiler.findObjectTypeNode(cond.TemplateName);
         otn.addSuccessorNode(bjoin, ruleCompiler.Engine, ruleCompiler.Memory);
     }
     // important, do not call this before ExistJoinFrst is added
     // if it's called first, the List<Object> will return index
     // out of bound, since there's nothing in the list
     cond.addNode(bjoin);
 }
Beispiel #12
0
        public void Tamagotchi_Rule_TwentyFiveHours()
        {
            var rules = new Rule[]
            {
                new AthleticRule(),
                new BordedomRule(),
                new CrazinessRule(),
                new FatigueRule(),
                new HungerRule(),
                new IsolationRule(),
                new MuchiesRule(),
                new SleepDeprivationRule(),
                new StarvationRule()
            };

            rules = rules.OrderBy(r => r.Order).ToArray();

            var now = DateTime.UtcNow;
            Tamagotchi t1 = new Tamagotchi("test", rules);

            var inTheFuture = now + TimeSpan.FromHours(25);
            t1.RefreshRules(inTheFuture);

            Assert.AreEqual(100, t1.Sleep);
            Assert.AreEqual(100, t1.Boredom);
            Assert.AreEqual(100, t1.Health);
            Assert.AreEqual(100, t1.Hunger);

            Assert.IsTrue(t1.HasDied);

            Assert.AreEqual(t1.LastAllRulesPassedUtc, inTheFuture);
        }
Beispiel #13
0
        public bool Validate(out string validateMessage, out Rule rule)
        {
            bool result = true;
            rule = new Rule();

            validateMessage = "Rule Ok";

            if (m_ConditionContainer.m_ConditionList.Count > 0)
            {
                GraphToRule converter = new GraphToRule(m_TargetObject.GetComponent<State>() as State);

                rule.m_Rule = converter.Convert(m_Rule.m_Name, m_ConditionContainer.m_ConditionList[0], m_ActionContainer.m_ActionList);
                rule.SetContext(m_TargetObject.GetComponent<InferenceEngine>() as InferenceEngine);

                try
                {
                    result = rule.Validate();
                }
                catch (InvalidRuleException e)
                {
                    Debug.Log (e.Message);
                    validateMessage = e.Message;
                }
            }

            return result;
        }
Beispiel #14
0
        public async Task SaveRule(Rule rule)
        {
            ApParseRule parseRule;
            if (string.IsNullOrEmpty(rule.Id))
            {
                parseRule = new ApParseRule
                {
                    ACL = new ParseACL(ParseUser.CurrentUser)
                    {
                        PublicReadAccess = false, 
                        PublicWriteAccess = false
                    }
                };
            }
            else
            {
                parseRule = ParseObject.CreateWithoutData<ApParseRule>(rule.Id);
            }

            parseRule.Name = rule.Name;
            parseRule.Prefix = rule.Prefix;
            parseRule.Taxons = rule.Taxons.IsNullOrEmpty() ? null : rule.Taxons.ToList();
            parseRule.Kommuner = rule.Kommuner.IsNullOrEmpty() ? null : rule.Kommuner.ToList();
            parseRule.Landskap = rule.Landskap.IsNullOrEmpty() ? null : rule.Landskap.ToList();
            parseRule.IsActive = rule.IsActive;
            parseRule.User = ParseUser.CurrentUser;

            await parseRule.SaveAsync();
        }
Beispiel #15
0
 public RuleEditor(Rule rule, bool targetVisible)
 {
     InitializeComponent();
     Rule = rule;
     Geometry.GeometryFromString(GeomertrySettings.RuleEditor, this);
     _targetVisible = targetVisible;
 }
    // Constructor
    public LSystem(string _axiom, Rule[] ruleset)
    {
        rules = ruleset;
        generation = 0;

        alphabet = _axiom;
    }
Beispiel #17
0
 public void Simple_When_is_a_predicate_for_evaluting_the_Condition()
 {
     IRule<Customer> rule = new Rule<Customer>();
     rule.When(p => p.PurchasedAmount >= 10000);
     rule.Then(p => p.customerType = CustomerType.Normal);
     rule.Execute(new Customer { PurchasedAmount = 100001 }).customerType.Should().Be(CustomerType.Normal);
 }
Beispiel #18
0
	// Use this for initialization
	void Start ()
	{

		Board board = new Board(3,3);
		board.SetPiece(0,0, Piece.DiePiece("One","White"));
		board.SetPiece(0,1, Piece.DiePiece("Two","White"));
		board.SetPiece(0,2, Piece.DiePiece("Three", "Black"));

		Rule rule1 = new Rule(new AllHave(new PropertyCheckers.PropertyHasValue("Face","One")));
		Rule rule2 = new Rule(new ExistsOneHas(new PropertyCheckers.PropertyHasValue("Face","One")));
		Rule rule3 = new Rule(new AllHave(new PropertyCheckers.Not(new PropertyCheckers.PropertyHasValue("Colour","Blue"))));
		Rule rule4 = new Rule(new FaceSum(new Comparers<int>.LessThan(), 7));
		Rule rule5 = new Rule(new PropertyCount(new PropertyCheckers.PropertyHasValue("Face","One"),new Comparers<int>.Equal(), 1));

		System.Diagnostics.Debug.Assert(rule1.Evaluate(board) == false);
		System.Diagnostics.Debug.Assert(rule2.Evaluate(board) == true);
		System.Diagnostics.Debug.Assert(rule3.Evaluate(board) == true);
		System.Diagnostics.Debug.Assert(rule4.Evaluate(board) == true);
		System.Diagnostics.Debug.Assert(rule5.Evaluate(board) == true);

		Debug.Log (rule1.ToString());

		rule2.And(rule4);
		Debug.Log (rule2.ToString());
		Rule rule6 = new Rule(new ExistsOneHas(new PropertyCheckers.PropertyHasValue("Face","One")));
		Rule rule7 = new Rule(new FaceSum(new Comparers<int>.LessThan(), 7));
		rule6.And(rule7);
		Debug.Log (rule6.ToString());


		System.Diagnostics.Debug.Assert(rule2.Evaluate(board) == true);
	}
        /// <summary>
        ///   Creates a new instance of the <see cref="SchematronValidationEventArgs"/>.
        /// </summary>
        /// <param name="schematron">The <see cref="SchematronDocument"/> that detected the event.</param>
        /// <param name="queryEngine">The <see cref="IQueryLanguage"/> that detected the event.</param>
        /// <param name="pattern">The active <see cref="Pattern"/>.</param>
        /// <param name="rule">The <see cref="Sepia.Schematron.Rule"/> that caused the event to be raised.</param>
        /// <param name="assertion">The <see cref="Sepia.Schematron.Assertion"/> that caused the event to be raised.</param>
        /// <param name="context">An <see cref="object"/> that provides the context for the <paramref name="rule"/> and <paramref name="assertion"/>.</param>
        /// <param name="instance">An <see cref="XPathNavigator"/> to the document node that cause the event to be raised.</param>
        public SchematronValidationEventArgs(SchematronDocument schematron, IQueryLanguage queryEngine, Pattern pattern, Rule rule, Assertion assertion, object context, XPathNavigator instance)
        {
            this.schematron = schematron;
             this.queryEngine = queryEngine;
             this.pattern = pattern;
             this.rule = rule;
             this.assertion = assertion;
             this.instance = instance.Clone();

             if (assertion == null)
             {
            message = "A schematron validation event occured.";
             }
             else
             {
            message = assertion.Message.ToString(instance, context);
             }

             List<string> diagnostics = new List<string>();
             if (assertion != null && !string.IsNullOrEmpty(assertion.Diagnostics))
             {
            foreach (string id in assertion.Diagnostics.Split(' '))
            {
               Diagnostic diagnostic = schematron.Diagnostics[id];
               diagnostics.Add(diagnostic.Message.ToString(instance, context));
            }
             }
             this.diagnostics = diagnostics.ToArray();
        }
Beispiel #20
0
	public void CreateHeldBlockAtPointer()
	{
		if(pointerOver.Count > 0) {
			GameObject objOver = pointerOver[0];


			if(rule == null && objOver.CompareTag("RuleConstructionArea")) {
				GameObject newBlock = (GameObject)Instantiate(heldBlockPrefab, objOver.transform.position, Quaternion.identity);
				RuleBlock block = newBlock.GetComponent<RuleBlock>();


				newBlock.transform.SetParent(contentArea);

				rule = new Rule(block.GetNode());
			} else if(objOver.CompareTag("BlockSlot")) {
				GameObject newBlock = (GameObject)Instantiate(heldBlockPrefab, objOver.transform.position, Quaternion.identity);
				RuleBlock block = newBlock.GetComponent<RuleBlock>();

				RuleBlockSlot slot = objOver.GetComponent<RuleBlockSlot>();
				newBlock.transform.SetParent(objOver.transform.parent);
				slot.SetChildInParent(block.GetNode());

				//have to manually call this because disabling the object prevents the slot from removing itself
				RemovePointerOver(objOver);
				objOver.SetActive(false);
			}
		}
		//Debug.Log (rule.ToString());
	}
Beispiel #21
0
 /// <summary> the method is responsible for compiling a TestCE pattern to a testjoin node.
 /// It uses the globally declared prevCE and prevJoinNode
 /// </summary>
 public virtual BaseJoin compileJoin(ICondition condition, int position, Rule.IRule rule)
 {
     TestCondition tc = (TestCondition) condition;
     ShellFunction fn = (ShellFunction) tc.Function;
     fn.lookUpFunction(ruleCompiler.Engine);
     IParameter[] oldpm = fn.Parameters;
     IParameter[] pms = new IParameter[oldpm.Length];
     for (int ipm = 0; ipm < pms.Length; ipm++)
     {
         if (oldpm[ipm] is ValueParam)
         {
             pms[ipm] = ((ValueParam) oldpm[ipm]).cloneParameter();
         }
         else if (oldpm[ipm] is BoundParam)
         {
             BoundParam bpm = (BoundParam) oldpm[ipm];
             // now we need to resolve and setup the BoundParam
             Binding b = rule.getBinding(bpm.VariableName);
             BoundParam newpm = new BoundParam(b.LeftRow, b.LeftIndex, 9, bpm.ObjectBinding);
             newpm.VariableName = bpm.VariableName;
             pms[ipm] = newpm;
         }
     }
     BaseJoin joinNode = null;
     if (tc.Negated)
     {
         joinNode = new NTestNode(ruleCompiler.Engine.nextNodeId(), fn.Function, pms);
     }
     else
     {
         joinNode = new TestNode(ruleCompiler.Engine.nextNodeId(), fn.Function, pms);
     }
     ((TestNode) joinNode).lookUpFunction(ruleCompiler.Engine);
     return joinNode;
 }
		protected virtual void CopyProperties(Rule rule, RuleData ruleData)
		{
			rule.UseErrorMessageProvider = ruleData.UseErrorMessageProvider;
			rule.ErrorMessage = ruleData.ErrorMessage;
			rule.Severity = ruleData.Severity;
			rule.RuleSet = ruleData.RuleSet;
		}
        public void ConditionalLogic()
        {
            Order order = this.GetOrder();
            Rule rule = new Rule()
            {
                Operator = System.Linq.Expressions.ExpressionType.AndAlso.ToString("g"),
                Rules = new List<Rule>()
                {
                    new Rule(){ MemberName = "Customer.LastName", TargetValue = "Doe", Operator = "Equal"},
                    new Rule(){ 
                        Operator = "Or",
                        Rules = new List<Rule>(){
                            new Rule(){ MemberName = "Customer.FirstName", TargetValue = "John", Operator = "Equal"},
                            new Rule(){ MemberName = "Customer.FirstName", TargetValue = "Jane", Operator = "Equal"}
                        }
                    }
                }
            };
            MRE engine = new MRE();
            var fakeName = engine.CompileRule<Order>(rule);
            bool passes = fakeName(order);
            Assert.IsTrue(passes);

            order.Customer.FirstName = "Philip";
            passes = fakeName(order);
            Assert.IsFalse(passes);
        }
Beispiel #24
0
 /* public PackageAssembly(string assemblyName, Rule rule ,string filename ) {
     Name = assemblyName;
     Rule = rule;
     _files = new FileEntry(filename, Path.GetFileName(filename)).SingleItemAsEnumerable();
 } */
 public PackageAssembly(string assemblyName, Rule rule, IEnumerable<string> files)
 {
     Name = assemblyName;
     Rule = rule;
     // when given just filenames, strip the
     _files = files.Select(each => new FileEntry(each, Path.GetFileName(each)));
 }
Beispiel #25
0
 /* zCode is a string that is the action associated with a rule.  Expand the symbols in this string so that the refer to elements of the parser stack. */
 private static void TranslateRuleCode(Context ctx, Rule rule)
 {
     var used = new bool[rule.RHSymbols.Length]; /* True for each RHS element which is used */
     var lhsused = false; /* True if the LHS element has been used */
     if (rule.Code == null) { rule.Code = "\n"; rule.Lineno = rule.RuleLineno; }
     var b = new StringBuilder();
     var z = rule.Code;
     for (var cp = 0; cp < z.Length; cp++)
     {
         if (char.IsLetter(z[cp]) && (cp == 0 || (!char.IsLetterOrDigit(z[cp - 1]) && z[cp - 1] != '_')))
         {
             var xp = cp + 1;
             for (; char.IsLetterOrDigit(z[xp]) || z[xp] == '_'; xp++) ;
             //var saved = z[xp];
             var xpLength = xp - cp;
             if (rule.LHSymbolAlias != null && z.Substring(cp, xpLength) == rule.LHSymbolAlias)
             {
                 b.AppendFormat("yygotominor.yy{0}", rule.LHSymbol.DataTypeID);
                 cp = xp;
                 lhsused = true;
             }
             else
             {
                 for (var i = 0; i < rule.RHSymbols.Length; i++)
                     if (rule.RHSymbolsAlias[i] != null && z.Substring(cp, xpLength) == rule.RHSymbolsAlias[i])
                     {
                         /* If the argument is of the form @X then substituted the token number of X, not the value of X */
                         if (cp > 0 && z[cp - 1] == '@')
                         {
                             b.Length--;
                             b.AppendFormat("yymsp[{0}].major", i - rule.RHSymbols.Length + 1);
                         }
                         else
                         {
                             var symbol = rule.RHSymbols[i];
                             var dataTypeID = (symbol.Type == SymbolType.MultiTerminal ? symbol.Children[0].DataTypeID : symbol.DataTypeID);
                             b.AppendFormat("yymsp[{0}].minor.yy{1}", i - rule.RHSymbols.Length + 1, dataTypeID);
                         }
                         cp = xp;
                         used[i] = true;
                         break;
                     }
             }
         }
         b.Append(z[cp]);
     }
     /* Check to make sure the LHS has been used */
     if (rule.LHSymbolAlias != null && !lhsused)
         ctx.RaiseError(ref ctx.Errors, rule.RuleLineno, "Label \"{0}\" for \"{1}({2})\" is never used.", rule.LHSymbolAlias, rule.LHSymbol.Name, rule.LHSymbolAlias);
     /* Generate destructor code for RHS symbols which are not used in the reduce code */
     for (var i = 0; i < rule.RHSymbols.Length; i++)
     {
         if (rule.RHSymbolsAlias[i] != null && !used[i])
             ctx.RaiseError(ref ctx.Errors, rule.RuleLineno, "Label {0} for \"{1}({2})\" is never used.", rule.RHSymbolsAlias[i], rule.RHSymbols[i].Name, rule.RHSymbolsAlias[i]);
         else if (rule.RHSymbolsAlias[i] == null && HasDestructor(rule.RHSymbols[i], ctx))
             b.AppendFormat("  yy_destructor(yypParser,{0},&yymsp[{1}].minor);\n", rule.RHSymbols[i].ID, i - rule.RHSymbols.Length + 1);
     }
     if (rule.Code != null)
         rule.Code = (b.ToString() ?? string.Empty);
 }
Beispiel #26
0
        static void Main(string[] args) {
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            if (args.Length < 3) {
                help();
                return;
            }
            String source_dir = args[1].Replace("\"", "");
            String target_dir = args[2].Replace("\"", "");

            XmlDocument xml_rules = new XmlDocument();
            xml_rules.Load(args[0]);

        //read list of languages that should be ignored or renamed
            Dictionary<String, String> langs = new Dictionary<String, String>();
            foreach (XmlNode node in xml_rules.SelectNodes("//lang")) {
                langs.Add( node.SelectSingleNode("@id").InnerText,  node.SelectSingleNode("@renameTo").InnerText);
            }

        //read list of rules and apply each rule
            foreach (XmlNode node in xml_rules.SelectNodes("//rule")) {
                Rule r = new Rule(node);
                StringBuilder sb = new StringBuilder();
                apply_rule(r, source_dir, target_dir, langs, sb);
                Console.WriteLine(sb.ToString());
            }
        }
        static internal string GetRulePreview(Rule rule)
        {
            StringBuilder rulePreview = new StringBuilder();

            if (rule != null)
            {
                rulePreview.Append("IF ");
                if (rule.Condition != null)
                    rulePreview.Append(rule.Condition.ToString() + " ");
                rulePreview.Append("THEN ");

                foreach (RuleAction action in rule.ThenActions)
                {
                    rulePreview.Append(action.ToString());
                    rulePreview.Append(' ');
                }

                if (rule.ElseActions.Count > 0)
                {
                    rulePreview.Append("ELSE ");
                    foreach (RuleAction action in rule.ElseActions)
                    {
                        rulePreview.Append(action.ToString());
                        rulePreview.Append(' ');
                    }
                }
            }

            return rulePreview.ToString();
        }
Beispiel #28
0
 private OrderRouter()
 {
     routeRules = Rule.Create<OrderModel>(o => o.Status == OrderStatus.New, o => Route())
                      .Add(o => o.Status == OrderStatus.NameChosen, o => container.Add(new OrderView(new OrderViewModel(o))))
                      .Add(o => o.Status == OrderStatus.ItemsSelected, o => container.Add(new CheckoutView(new CheckoutViewModel(o))))
                      .Add(o => o.Status == OrderStatus.Submitted, o => container.Add(new CompleteView(new CompleteViewModel(o))));
 }
Beispiel #29
0
        private static IQueryable<Customer> FilterCustomers(IQueryable<Customer> customers, Rule rule)
        {
            switch (rule.field)
            {
                case "CustomerId":
                    return customers.Where(c => c.CustomerId == rule.data);

                case "Name":
                    return customers.Where(c => c.Fullname.ToLower().Contains(rule.data.ToLower()));

                case "Company":
                    return customers.Where(c => c.Company.ToLower().Contains(rule.data.ToLower()));

                case "EmailAddress":
                    return customers.Where(c => c.EmailAddress.ToLower().Contains(rule.data.ToLower()));

                case "Last Modified":
                    DateTime dateResult;
                    return !DateTime.TryParse(rule.data, out dateResult) ? customers : customers.Where(c => c.LastModified.Date == dateResult.Date);

                case "Telephone":
                    return customers.Where(c => c.Telephone.ToLower().Contains(rule.data.ToLower()));

                default:
                    return customers;
            }
        }
Beispiel #30
0
 internal bool SetPendingInvocation(Rule rule, bool isPending)
 {
     if (isPending)
         return pendingInvocation.Add(rule);
     else
         return pendingInvocation.Remove(rule);
 }
Beispiel #31
0
        public void RuleAndException_1()
        {
            BentleyOttmanAlgorithm algo = new BentleyOttmanAlgorithm(new DateTime(2020, 8, 1), new DateTime(2020, 8, 3, 23, 59, 59));

            Rule rule1 = new Rule(new Guid(),
                                  new DateTime(2020, 6, 1, 9, 0, 0),
                                  new DateTime(2020, 6, 1, 17, 0, 0),
                                  1,
                                  TimeMeasure.Days);

            Exclusion exclusion1 = new Exclusion(
                new DateTime(2020, 8, 2, 0, 0, 0),
                new DateTime(2020, 8, 3, 0, 0, 0),
                0,
                TimeMeasure.None
                );

            algo.AddRule(rule1);
            algo.AddRule(exclusion1);

            var result = algo.GetResult();

            Assert.AreEqual(2, result.Count);
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var    formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
            string message;

            try {
                message = Validator.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                message = ValidatorOptions.LanguageManager.GetStringForValidator <CreditCardValidator>();
            }
            message = formatter.BuildMessage(message);


            yield return(new ModelClientValidationRule {
                ValidationType = "creditcard",
                ErrorMessage = message
            });
        }
Beispiel #33
0
        public void ShouldFailToReadAndThrowInvalidInputException()
        {
            ICharReader           reader;
            ILexer                lexer;
            Rule                  word;
            TokenMatch            tokenMatch;
            InvalidInputException ex;

            word = new Rule("Word", Parse.Characters("token"));

            reader = new MockedCharReader("token");
            lexer  = new Lexer(word);

            tokenMatch = lexer.Read(reader);
            Assert.IsTrue(tokenMatch.Success);
            Assert.AreEqual("Word", tokenMatch.Token.Class);
            Assert.AreEqual("token", tokenMatch.Token.Value);

            reader = new MockedCharReader("toked");
            lexer  = new Lexer(word);

            ex = Assert.ThrowsException <InvalidInputException>(() => tokenMatch = lexer.Read(reader));
            Assert.AreEqual('d', ex.Input);
        }
        public void FragOnUnion()
        {
            // arrange
            Schema       schema = ValidationUtils.CreateSchema();
            DocumentNode query  = Utf8GraphQLParser.Parse(@"
                {
                    dog {
                       ... fragOnUnion
                    }
                }

                fragment fragOnUnion on CatOrDog {
                    ... on Dog {
                        name
                    }
                }
            ");

            // act
            QueryValidationResult result = Rule.Validate(schema, query);

            // assert
            Assert.False(result.HasErrors);
        }
Beispiel #35
0
        public async Task ShouldBeFullyAvailable_AndPartly_FutureAiredEpisodes_NoRequest()
        {
            var search = new SearchTvShowViewModel()
            {
                Id             = 999,
                SeasonRequests = new List <SeasonRequests>
                {
                    new SeasonRequests
                    {
                        Episodes = new List <EpisodeRequests>
                        {
                            new EpisodeRequests
                            {
                                Available = true,
                                AirDate   = new System.DateTime(2020, 01, 01)
                            },
                            new EpisodeRequests
                            {
                                Available = true,
                                AirDate   = new System.DateTime(2020, 01, 02)
                            },
                            new EpisodeRequests
                            {
                                Available = true,
                                AirDate   = new System.DateTime(2029, 01, 02)
                            },
                        }
                    }
                }
            };
            var result = await Rule.Execute(search);

            Assert.True(result.Success);
            Assert.That(search.FullyAvailable, Is.True);
            Assert.That(search.PartlyAvailable, Is.True);
        }
        public void BasicEqualityExpression()
        {
            using (var context = new BloggingContext(GetDBOptions()))
            {
                context.Blogs.Add(new Blog {
                    Url = "http://test.com"
                });
                context.SaveChanges();

                var testBlog = context.Blogs.FirstOrDefault(b => b.Url == "http://test.com");

                var  fields = MRE.Member.GetFields(typeof(Blog));
                Rule rule   = new Rule
                {
                    MemberName  = "Url",
                    Operator    = mreOperator.Equal.ToString("g"),
                    TargetValue = "http://test.com"
                };

                var blog2 = context.Blogs.Where(MRE.ToExpression <Blog>(rule, false)).FirstOrDefault();

                Assert.IsTrue(testBlog.BlogId == blog2.BlogId);
            }
        }
        public void CorrectTypeOnFragment()
        {
            // arrange
            IDocumentValidatorContext context = ValidationUtils.CreateContext();
            DocumentNode query = Utf8GraphQLParser.Parse(@"
                {
                    dog {
                        ...correctType
                    }
                }

                fragment correctType on Dog {
                    name
                }
            ");

            context.Prepare(query);

            // act
            Rule.Validate(context, query);

            // assert
            Assert.Empty(context.Errors);
        }
Beispiel #38
0
        public void TestOverlappingBoundaryNames()
        {
            string content = "Return-Path: <*****@*****.**>\r\n" +
                             "From: \"test\" <*****@*****.**>\r\n" +
                             "To: \"Test\" <*****@*****.**>\r\n" +
                             "Subject: rtest\r\n" +
                             "Date: Thu, 22 Jan 2009 13:20:32 +0100\r\n" +
                             "MIME-Version: 1.0\r\n" +
                             "Content-Type: multipart/mixed;\r\n" +
                             "    boundary=\"----=_NextPart_000_000D_01C97C94.33D5E670\"\r\n" +
                             "\r\n" +
                             "This is a multi-part message in MIME format.\r\n" +
                             "\r\n" +
                             "------=_NextPart_000_000D_01C97C94.33D5E670\r\n" +
                             "Content-Type: multipart/alternative;\r\n" +
                             "    boundary=\"----=_NextPart_000_000D_01C97C94.33D5E670.ALT\"\r\n" +
                             "\r\n" +
                             "\r\n" +
                             "------=_NextPart_000_000D_01C97C94.33D5E670.ALT\r\n" +
                             "Content-Type: text/plain;\r\n" +
                             "    charset=\"iso-8859-1\"\r\n" +
                             "Content-Transfer-Encoding: quoted-printable\r\n" +
                             "\r\n" +
                             "test\r\n" +
                             "------=_NextPart_000_000D_01C97C94.33D5E670.ALT\r\n" +
                             "Content-Type: text/html;\r\n" +
                             "    charset=\"iso-8859-1\"\r\n" +
                             "Content-Transfer-Encoding: quoted-printable\r\n" +
                             "\r\n" +
                             "<a>test</a>\r\n" +
                             "\r\n" +
                             "------=_NextPart_000_000D_01C97C94.33D5E670.ALT--\r\n" +
                             "\r\n" +
                             "------=_NextPart_000_000D_01C97C94.33D5E670\r\n" +
                             "Content-Type: application/octet-stream;\r\n" +
                             "    name=\"test.vbs\"\r\n" +
                             "Content-Transfer-Encoding: 7bit\r\n" +
                             "Content-Disposition: attachment;\r\n" +
                             "    filename=\"test.vbs\"\r\n" +
                             "\r\n" +
                             "s = \"abc\"\r\n" +
                             "\r\n" +
                             "msgbox mid(s,1,100000)\r\n" +
                             "------=_NextPart_000_000D_01C97C94.33D5E670--\r\n" +
                             "\r\n" +
                             "";


            // Add an account
            Account account = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test");

            Rule rule = account.Rules.Add();

            rule.Name   = "Criteria test";
            rule.Active = true;

            RuleCriteria ruleCriteria = rule.Criterias.Add();

            ruleCriteria.UsePredefined = false;
            ruleCriteria.HeaderField   = "Subject";
            ruleCriteria.MatchType     = eRuleMatchType.eMTContains;
            ruleCriteria.MatchValue    = "rtest";
            ruleCriteria.Save();

            // Add action
            RuleAction ruleAction = rule.Actions.Add();

            ruleAction.Type       = eRuleActionType.eRASetHeaderValue;
            ruleAction.HeaderName = "SomeHeader";
            ruleAction.Value      = "SomeValue";
            ruleAction.Save();

            // Save the rule in the database
            rule.Save();

            var smtpClientSimulator = new SmtpClientSimulator();

            // Spam folder
            smtpClientSimulator.SendRaw("*****@*****.**", "*****@*****.**", content);

            string sContents = Pop3ClientSimulator.AssertGetFirstMessageText("*****@*****.**", "test");

            Assert.IsTrue(sContents.IndexOf("SomeHeader: SomeValue") > 0);
            Assert.IsTrue(sContents.IndexOf("------=_NextPart_000_000D_01C97C94.33D5E670.ALT--") > 0);
        }
Beispiel #39
0
        static Parser()
        {
            states[0]   = new State(new int[] { 11, 5 }, new int[] { -17, 1, -16, 3, -14, 102 });
            states[1]   = new State(new int[] { 3, 2 });
            states[2]   = new State(-1);
            states[3]   = new State(new int[] { 11, 5, 3, -45 }, new int[] { -14, 4 });
            states[4]   = new State(-44);
            states[5]   = new State(new int[] { 16, 100, 8, 47, 15, 49, 13, 51, 14, 52 }, new int[] { -6, 6, -5, 101, -7, 70, -8, 53, -9, 50 });
            states[6]   = new State(new int[] { 4, 38 }, new int[] { -1, 7 });
            states[7]   = new State(new int[] { 17, 8 });
            states[8]   = new State(new int[] { 18, 94, 8, 47, 15, 49, 13, 51, 14, 52 }, new int[] { -15, 9, -5, 98, -7, 70, -8, 53, -9, 50 });
            states[9]   = new State(new int[] { 18, 10, 23, 91 });
            states[10]  = new State(new int[] { 19, 11 });
            states[11]  = new State(new int[] { 4, 38, 8, 47, 15, 49, 13, 51, 14, 52, 9, 75, 10, 87 }, new int[] { -13, 12, -10, 90, -11, 15, -1, 16, -5, 64, -7, 70, -8, 53, -9, 50, -3, 73 });
            states[12]  = new State(new int[] { 20, 13, 4, 38, 8, 47, 15, 49, 13, 51, 14, 52, 9, 75, 10, 87 }, new int[] { -10, 14, -11, 15, -1, 16, -5, 64, -7, 70, -8, 53, -9, 50, -3, 73 });
            states[13]  = new State(-37);
            states[14]  = new State(-36);
            states[15]  = new State(-30);
            states[16]  = new State(new int[] { 21, 17, 25, 61, 17, 54 });
            states[17]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 18, -4, 31, -1, 34, -3, 41 });
            states[18]  = new State(new int[] { 22, 19, 7, 23 });
            states[19]  = new State(new int[] { 25, 20 });
            states[20]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 21, -4, 31, -1, 34, -3, 41 });
            states[21]  = new State(new int[] { 24, 22, 7, 23 });
            states[22]  = new State(-27);
            states[23]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 24, -4, 31, -1, 34, -3, 41 });
            states[24]  = new State(-4);
            states[25]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42, 13, 51, 14, 52 }, new int[] { -2, 26, -9, 28, -4, 31, -1, 34, -3, 41 });
            states[26]  = new State(new int[] { 18, 27, 7, 23 });
            states[27]  = new State(-3);
            states[28]  = new State(new int[] { 18, 29 });
            states[29]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 30, -4, 31, -1, 34, -3, 41 });
            states[30]  = new State(new int[] { 7, 23, 22, -12, 24, -12, 18, -12, 23, -12 });
            states[31]  = new State(-5);
            states[32]  = new State(-15);
            states[33]  = new State(-16);
            states[34]  = new State(new int[] { 21, 35, 17, 54, 22, -6, 7, -6, 24, -6, 18, -6, 23, -6 });
            states[35]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 36, -4, 31, -1, 34, -3, 41 });
            states[36]  = new State(new int[] { 22, 37, 7, 23 });
            states[37]  = new State(-9);
            states[38]  = new State(-2);
            states[39]  = new State(-7);
            states[40]  = new State(-8);
            states[41]  = new State(-10);
            states[42]  = new State(new int[] { 8, 47, 15, 49, 13, 51, 14, 52 }, new int[] { -7, 43, -8, 53, -9, 50 });
            states[43]  = new State(new int[] { 21, 44 });
            states[44]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 45, -4, 31, -1, 34, -3, 41 });
            states[45]  = new State(new int[] { 22, 46, 7, 23 });
            states[46]  = new State(-11);
            states[47]  = new State(new int[] { 15, 49, 13, 51, 14, 52 }, new int[] { -8, 48, -9, 50 });
            states[48]  = new State(-21);
            states[49]  = new State(-23);
            states[50]  = new State(-24);
            states[51]  = new State(-25);
            states[52]  = new State(-26);
            states[53]  = new State(-22);
            states[54]  = new State(new int[] { 18, 59, 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -12, 55, -2, 60, -4, 31, -1, 34, -3, 41 });
            states[55]  = new State(new int[] { 18, 56, 23, 57 });
            states[56]  = new State(-13);
            states[57]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 58, -4, 31, -1, 34, -3, 41 });
            states[58]  = new State(new int[] { 7, 23, 18, -18, 23, -18 });
            states[59]  = new State(-14);
            states[60]  = new State(new int[] { 7, 23, 18, -17, 23, -17 });
            states[61]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 62, -4, 31, -1, 34, -3, 41 });
            states[62]  = new State(new int[] { 24, 63, 7, 23 });
            states[63]  = new State(-29);
            states[64]  = new State(new int[] { 4, 38 }, new int[] { -1, 65 });
            states[65]  = new State(new int[] { 25, 66, 24, 69 });
            states[66]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 67, -4, 31, -1, 34, -3, 41 });
            states[67]  = new State(new int[] { 24, 68, 7, 23 });
            states[68]  = new State(-28);
            states[69]  = new State(-31);
            states[70]  = new State(new int[] { 21, 71, 4, -20 });
            states[71]  = new State(new int[] { 22, 72 });
            states[72]  = new State(-19);
            states[73]  = new State(new int[] { 24, 74 });
            states[74]  = new State(-32);
            states[75]  = new State(new int[] { 17, 76 });
            states[76]  = new State(new int[] { 13, 51, 14, 52 }, new int[] { -9, 77 });
            states[77]  = new State(new int[] { 4, 38 }, new int[] { -1, 78 });
            states[78]  = new State(new int[] { 25, 79 });
            states[79]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 80, -4, 31, -1, 34, -3, 41 });
            states[80]  = new State(new int[] { 23, 81, 7, 23 });
            states[81]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 82, -4, 31, -1, 34, -3, 41 });
            states[82]  = new State(new int[] { 18, 83, 7, 23 });
            states[83]  = new State(new int[] { 19, 84 });
            states[84]  = new State(new int[] { 4, 38, 8, 47, 15, 49, 13, 51, 14, 52, 9, 75, 10, 87 }, new int[] { -13, 85, -10, 90, -11, 15, -1, 16, -5, 64, -7, 70, -8, 53, -9, 50, -3, 73 });
            states[85]  = new State(new int[] { 20, 86, 4, 38, 8, 47, 15, 49, 13, 51, 14, 52, 9, 75, 10, 87 }, new int[] { -10, 14, -11, 15, -1, 16, -5, 64, -7, 70, -8, 53, -9, 50, -3, 73 });
            states[86]  = new State(-33);
            states[87]  = new State(new int[] { 17, 25, 26, 32, 27, 33, 4, 38, 5, 39, 6, 40, 12, 42 }, new int[] { -2, 88, -4, 31, -1, 34, -3, 41 });
            states[88]  = new State(new int[] { 24, 89, 7, 23 });
            states[89]  = new State(-34);
            states[90]  = new State(-35);
            states[91]  = new State(new int[] { 8, 47, 15, 49, 13, 51, 14, 52 }, new int[] { -5, 92, -7, 70, -8, 53, -9, 50 });
            states[92]  = new State(new int[] { 4, 38 }, new int[] { -1, 93 });
            states[93]  = new State(-42);
            states[94]  = new State(new int[] { 19, 95 });
            states[95]  = new State(new int[] { 4, 38, 8, 47, 15, 49, 13, 51, 14, 52, 9, 75, 10, 87 }, new int[] { -13, 96, -10, 90, -11, 15, -1, 16, -5, 64, -7, 70, -8, 53, -9, 50, -3, 73 });
            states[96]  = new State(new int[] { 20, 97, 4, 38, 8, 47, 15, 49, 13, 51, 14, 52, 9, 75, 10, 87 }, new int[] { -10, 14, -11, 15, -1, 16, -5, 64, -7, 70, -8, 53, -9, 50, -3, 73 });
            states[97]  = new State(-38);
            states[98]  = new State(new int[] { 4, 38 }, new int[] { -1, 99 });
            states[99]  = new State(-41);
            states[100] = new State(-39);
            states[101] = new State(-40);
            states[102] = new State(-43);

            for (int sNo = 0; sNo < states.Length; sNo++)
            {
                states[sNo].number = sNo;
            }

            rules[1]  = new Rule(-18, new int[] { -17, 3 });
            rules[2]  = new Rule(-1, new int[] { 4 });
            rules[3]  = new Rule(-2, new int[] { 17, -2, 18 });
            rules[4]  = new Rule(-2, new int[] { -2, 7, -2 });
            rules[5]  = new Rule(-2, new int[] { -4 });
            rules[6]  = new Rule(-2, new int[] { -1 });
            rules[7]  = new Rule(-2, new int[] { 5 });
            rules[8]  = new Rule(-2, new int[] { 6 });
            rules[9]  = new Rule(-2, new int[] { -1, 21, -2, 22 });
            rules[10] = new Rule(-2, new int[] { -3 });
            rules[11] = new Rule(-2, new int[] { 12, -7, 21, -2, 22 });
            rules[12] = new Rule(-2, new int[] { 17, -9, 18, -2 });
            rules[13] = new Rule(-3, new int[] { -1, 17, -12, 18 });
            rules[14] = new Rule(-3, new int[] { -1, 17, 18 });
            rules[15] = new Rule(-4, new int[] { 26 });
            rules[16] = new Rule(-4, new int[] { 27 });
            rules[17] = new Rule(-12, new int[] { -2 });
            rules[18] = new Rule(-12, new int[] { -12, 23, -2 });
            rules[19] = new Rule(-5, new int[] { -7, 21, 22 });
            rules[20] = new Rule(-5, new int[] { -7 });
            rules[21] = new Rule(-7, new int[] { 8, -8 });
            rules[22] = new Rule(-7, new int[] { -8 });
            rules[23] = new Rule(-8, new int[] { 15 });
            rules[24] = new Rule(-8, new int[] { -9 });
            rules[25] = new Rule(-9, new int[] { 13 });
            rules[26] = new Rule(-9, new int[] { 14 });
            rules[27] = new Rule(-11, new int[] { -1, 21, -2, 22, 25, -2, 24 });
            rules[28] = new Rule(-11, new int[] { -5, -1, 25, -2, 24 });
            rules[29] = new Rule(-11, new int[] { -1, 25, -2, 24 });
            rules[30] = new Rule(-10, new int[] { -11 });
            rules[31] = new Rule(-10, new int[] { -5, -1, 24 });
            rules[32] = new Rule(-10, new int[] { -3, 24 });
            rules[33] = new Rule(-10, new int[] { 9, 17, -9, -1, 25, -2, 23, -2, 18, 19, -13, 20 });
            rules[34] = new Rule(-10, new int[] { 10, -2, 24 });
            rules[35] = new Rule(-13, new int[] { -10 });
            rules[36] = new Rule(-13, new int[] { -13, -10 });
            rules[37] = new Rule(-14, new int[] { 11, -6, -1, 17, -15, 18, 19, -13, 20 });
            rules[38] = new Rule(-14, new int[] { 11, -6, -1, 17, 18, 19, -13, 20 });
            rules[39] = new Rule(-6, new int[] { 16 });
            rules[40] = new Rule(-6, new int[] { -5 });
            rules[41] = new Rule(-15, new int[] { -5, -1 });
            rules[42] = new Rule(-15, new int[] { -15, 23, -5, -1 });
            rules[43] = new Rule(-16, new int[] { -14 });
            rules[44] = new Rule(-16, new int[] { -16, -14 });
            rules[45] = new Rule(-17, new int[] { -16 });
        }
Beispiel #40
0
        static void testListOfRemove(ListOf lof, SBase s)
        {
            string ename = s.getElementName();

            lof.append(s);
            SBase c = lof.get(0);

            if (c is CompartmentType)
            {
                CompartmentType x = (lof as ListOfCompartmentTypes).remove(0); c = x;
            }
            else if (c is Compartment)
            {
                Compartment x = (lof as ListOfCompartments).remove(0); c = x;
            }
            else if (c is Constraint)
            {
                Constraint x = (lof as ListOfConstraints).remove(0); c = x;
            }
            else if (c is EventAssignment)
            {
                EventAssignment x = (lof as ListOfEventAssignments).remove(0); c = x;
            }
            else if (c is Event)
            {
                Event x = (lof as ListOfEvents).remove(0); c = x;
            }
            else if (c is FunctionDefinition)
            {
                FunctionDefinition x = (lof as ListOfFunctionDefinitions).remove(0); c = x;
            }
            else if (c is InitialAssignment)
            {
                InitialAssignment x = (lof as ListOfInitialAssignments).remove(0); c = x;
            }
            else if (c is Parameter)
            {
                Parameter x = (lof as ListOfParameters).remove(0); c = x;
            }
            else if (c is Reaction)
            {
                Reaction x = (lof as ListOfReactions).remove(0); c = x;
            }
            else if (c is Rule)
            {
                Rule x = (lof as ListOfRules).remove(0); c = x;
            }
            else if (c is Species)
            {
                Species x = (lof as ListOfSpecies).remove(0); c = x;
            }
            else if (c is SpeciesReference)
            {
                SimpleSpeciesReference x = (lof as ListOfSpeciesReferences).remove(0); c = x;
            }
            else if (c is SpeciesType)
            {
                SpeciesType x = (lof as ListOfSpeciesTypes).remove(0); c = x;
            }
            else if (c is UnitDefinition)
            {
                UnitDefinition x = (lof as ListOfUnitDefinitions).remove(0); c = x;
            }
            else if (c is Unit)
            {
                Unit x = (lof as ListOfUnits).remove(0); c = x;
            }
            else
            {
                ERR("[testListOfRemove] Error: (" + ename + ") : ListOfXXX::remove() failed.");
                return;
            }

            if (c == null)
            {
                ERR("[testListOfRemove] Error: (" + ename + ") : ListOfXXX::remove() failed.");
                return;
            }

            string enameGet = c.getElementName();

            if (ename == enameGet)
            {
                //Console.Out.WriteLine("[testListOfRemove] OK: (" + ename + ") remove(" + enameGet + ") : type match.");
                OK();
            }
            else
            {
                ERR("[testListOfRemove] Error: (" + ename + ") remove(" + enameGet + ") : type mismatch.");
            }
        }
        static bool GoToY(List <Track> tracks, List <int> chunks, ref bool tracksStarted, ref bool tracksFinshed, ref Rule ruleBroke, float YPosition, float withIn, TrackType type, float yawGoal)
        {
            CommandHandeler commandHandeler = new CommandHandeler();
            List <Command>  commands        = new List <Command>();
            bool            buildPass       = true;

            bool  firstStrightTrack = true;
            float lastY             = 0;
            float lastDiffernce     = 0;

            buildPass = BuildToPitch.Run(tracks, chunks, ref tracksStarted, ref tracksFinshed, ref ruleBroke, 0);
            if (!buildPass)
            {
                return(false);
            }

            while (!((tracks.Last().Position.Y < YPosition + (withIn / 2) && tracks.Last().Position.Y > YPosition - (withIn / 2))) && buildPass)
            {
                if (tracks.Last().Orientation.Yaw == yawGoal)
                {
                    commands.Clear();
                    commands.Add(new Command(true, TrackType.Stright, new Orientation(0, 0, 0)));
                    buildPass = commandHandeler.Run(commands, tracks, chunks, tracksStarted, tracksFinshed, ref ruleBroke);

                    float differnce = Math.Abs(tracks.Last().Position.Y - lastY);
                    if (!firstStrightTrack)
                    {
                        //This Means You Passed The Goal Point, This could have been done by turning, Or After the Fact. But You Are now going the wrong way.
                        if (differnce > lastDiffernce)
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        firstStrightTrack = true;
                    }

                    lastY         = tracks.Last().Position.Y;
                    lastDiffernce = differnce;
                }
                else
                {
                    commands.Clear();
                    commands.Add(new Command(true, type, new Orientation(0, 0, 0)));
                    buildPass = commandHandeler.Run(commands, tracks, chunks, tracksStarted, tracksFinshed, ref ruleBroke);
                }
            }
            if (tracks.Last().Position.Y < YPosition + (withIn / 2) && tracks.Last().Position.Y > YPosition - (withIn / 2))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
 public GreaterThanRule(IWidget widget, Rule rule)
 {
 }
 public static float GetDetailRotation(this Rule rule)
 {
     return(rule.EvaluateDefault <float>("rotation", 0));
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ConstantValueRule{T}" /> class.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="rule">The rule.</param>
 public ConstantValueRule(T value, Rule rule) : base(rule)
 {
     Value = value;
 }
 /// <summary>
 /// Builds the expression for rule.
 /// </summary>
 /// <param name="rule">The rule.</param>
 /// <param name="typeParamExpressions">The type parameter expressions.</param>
 /// <param name="ruleInputExp">The rule input exp.</param>
 /// <returns>Expression type</returns>
 internal abstract RuleFunc <RuleResultTree> BuildDelegateForRule(Rule rule, RuleParameter[] ruleParams);
Beispiel #46
0
        static Parser()
        {
            states[0]   = new State(-4, new int[] { -1, 1, -2, 3, -72, 4 });
            states[1]   = new State(new int[] { 128, 2 });
            states[2]   = new State(-1);
            states[3]   = new State(-2);
            states[4]   = new State(-5, new int[] { -73, 5 });
            states[5]   = new State(new int[] { 143, -12, 166, -12, 128, -7 }, new int[] { -3, 6, -4, 7, -5, 9, -6, 10, -7, 11 });
            states[6]   = new State(-3);
            states[7]   = new State(new int[] { 143, -12, 166, -12, 128, -7 }, new int[] { -3, 8, -4, 7, -5, 9, -6, 10, -7, 11 });
            states[8]   = new State(-6);
            states[9]   = new State(-8);
            states[10]  = new State(-9);
            states[11]  = new State(new int[] { 143, 12, 166, 114 }, new int[] { -8, 113 });
            states[12]  = new State(new int[] { 130, 58 }, new int[] { -9, 13 });
            states[13]  = new State(-15, new int[] { -74, 14 });
            states[14]  = new State(-16, new int[] { -75, 15 });
            states[15]  = new State(-17, new int[] { -76, 16 });
            states[16]  = new State(new int[] { 123, 18 }, new int[] { -10, 17 });
            states[17]  = new State(-10);
            states[18]  = new State(new int[] { 166, 111, 169, 112, 125, -19, 179, -24 }, new int[] { -11, 19, -12, 21, -13, 23, -14, 24, -15, 25, -16, 109 });
            states[19]  = new State(new int[] { 125, 20 });
            states[20]  = new State(-18);
            states[21]  = new State(new int[] { 166, 111, 169, 112, 125, -19, 179, -24 }, new int[] { -11, 22, -12, 21, -13, 23, -14, 24, -15, 25, -16, 109 });
            states[22]  = new State(-20);
            states[23]  = new State(-21);
            states[24]  = new State(-22);
            states[25]  = new State(new int[] { 179, 108 }, new int[] { -17, 26, -18, 94 });
            states[26]  = new State(new int[] { 123, 29 }, new int[] { -33, 27, -34, 28 });
            states[27]  = new State(-23);
            states[28]  = new State(-53);
            states[29]  = new State(-56, new int[] { -35, 30, -36, 32 });
            states[30]  = new State(new int[] { 125, 31 });
            states[31]  = new State(-54);
            states[32]  = new State(new int[] { 130, 93, 125, -55, 133, -38 }, new int[] { -37, 33, -38, 34, -39, 35, -80, 37, -43, 63, -44, 64, -45, 65, -46, 66, -47, 68, -48, 69, -49, 92 });
            states[33]  = new State(-57);
            states[34]  = new State(-58);
            states[35]  = new State(new int[] { 59, 36 });
            states[36]  = new State(-60);
            states[37]  = new State(new int[] { 130, 58, 133, 62 }, new int[] { -24, 38, -25, 46, -29, 47, -30, 48, -31, 49, -32, 55, -9, 56, -26, 59, -27, 60, -28, 61 });
            states[38]  = new State(new int[] { 130, 44 }, new int[] { -40, 39, -42, 40, -23, 42 });
            states[39]  = new State(-61);
            states[40]  = new State(-63, new int[] { -41, 41 });
            states[41]  = new State(-62);
            states[42]  = new State(-65, new int[] { -70, 43 });
            states[43]  = new State(-64);
            states[44]  = new State(-33, new int[] { -79, 45 });
            states[45]  = new State(-39);
            states[46]  = new State(-66);
            states[47]  = new State(-40);
            states[48]  = new State(-45);
            states[49]  = new State(-51, new int[] { -81, 50, -83, 51 });
            states[50]  = new State(-46);
            states[51]  = new State(new int[] { 91, 52 });
            states[52]  = new State(new int[] { 93, 53 });
            states[53]  = new State(-52, new int[] { -84, 54 });
            states[54]  = new State(-50);
            states[55]  = new State(-47);
            states[56]  = new State(-49, new int[] { -82, 57 });
            states[57]  = new State(-48);
            states[58]  = new State(-14);
            states[59]  = new State(-41);
            states[60]  = new State(-42);
            states[61]  = new State(-43);
            states[62]  = new State(-44);
            states[63]  = new State(-59);
            states[64]  = new State(-67);
            states[65]  = new State(-68);
            states[66]  = new State(new int[] { 59, 67 });
            states[67]  = new State(-69);
            states[68]  = new State(-70);
            states[69]  = new State(new int[] { 61, 91 }, new int[] { -50, 70 });
            states[70]  = new State(new int[] { 191, 90 }, new int[] { -51, 71, -52, 72, -53, 73, -54, 74, -55, 75, -56, 76, -57, 77, -58, 78, -59, 79, -60, 80, -61, 81, -62, 82, -63, 83, -64, 84, -65, 85, -66, 86, -67, 87, -68, 88, -69, 89 });
            states[71]  = new State(-71);
            states[72]  = new State(-75);
            states[73]  = new State(-76);
            states[74]  = new State(-77);
            states[75]  = new State(-78);
            states[76]  = new State(-79);
            states[77]  = new State(-80);
            states[78]  = new State(-81);
            states[79]  = new State(-82);
            states[80]  = new State(-83);
            states[81]  = new State(-84);
            states[82]  = new State(-85);
            states[83]  = new State(-86);
            states[84]  = new State(-87);
            states[85]  = new State(-88);
            states[86]  = new State(-89);
            states[87]  = new State(-90);
            states[88]  = new State(-91);
            states[89]  = new State(-92);
            states[90]  = new State(-93);
            states[91]  = new State(-74);
            states[92]  = new State(-72);
            states[93]  = new State(-73);
            states[94]  = new State(new int[] { 130, 97 }, new int[] { -19, 95 });
            states[95]  = new State(-30, new int[] { -77, 96 });
            states[96]  = new State(-28);
            states[97]  = new State(new int[] { 40, 98 });
            states[98]  = new State(-32, new int[] { -78, 99 });
            states[99]  = new State(new int[] { 41, -34, 130, -38, 133, -38 }, new int[] { -20, 100, -21, 103, -22, 104, -80, 105 });
            states[100] = new State(new int[] { 41, 101 });
            states[101] = new State(-33, new int[] { -79, 102 });
            states[102] = new State(-31);
            states[103] = new State(-35);
            states[104] = new State(-36);
            states[105] = new State(new int[] { 130, 58, 133, 62 }, new int[] { -25, 106, -29, 47, -30, 48, -31, 49, -32, 55, -9, 56, -26, 59, -27, 60, -28, 61 });
            states[106] = new State(new int[] { 130, 44 }, new int[] { -23, 107 });
            states[107] = new State(-37);
            states[108] = new State(-29);
            states[109] = new State(new int[] { 166, 111, 169, 112, 179, -24 }, new int[] { -15, 110, -16, 109 });
            states[110] = new State(-25);
            states[111] = new State(-26);
            states[112] = new State(-27);
            states[113] = new State(-11);
            states[114] = new State(-13);

            for (int sNo = 0; sNo < states.Length; sNo++)
            {
                states[sNo].number = sNo;
            }

            rules[1]  = new Rule(-71, new int[] { -1, 128 });
            rules[2]  = new Rule(-1, new int[] { -2 });
            rules[3]  = new Rule(-2, new int[] { -72, -73, -3 });
            rules[4]  = new Rule(-72, new int[] {});
            rules[5]  = new Rule(-73, new int[] {});
            rules[6]  = new Rule(-3, new int[] { -4, -3 });
            rules[7]  = new Rule(-3, new int[] {});
            rules[8]  = new Rule(-4, new int[] { -5 });
            rules[9]  = new Rule(-5, new int[] { -6 });
            rules[10] = new Rule(-6, new int[] { -7, 143, -9, -74, -75, -76, -10 });
            rules[11] = new Rule(-7, new int[] { -7, -8 });
            rules[12] = new Rule(-7, new int[] {});
            rules[13] = new Rule(-8, new int[] { 166 });
            rules[14] = new Rule(-9, new int[] { 130 });
            rules[15] = new Rule(-74, new int[] {});
            rules[16] = new Rule(-75, new int[] {});
            rules[17] = new Rule(-76, new int[] {});
            rules[18] = new Rule(-10, new int[] { 123, -11, 125 });
            rules[19] = new Rule(-11, new int[] {});
            rules[20] = new Rule(-11, new int[] { -12, -11 });
            rules[21] = new Rule(-12, new int[] { -13 });
            rules[22] = new Rule(-13, new int[] { -14 });
            rules[23] = new Rule(-14, new int[] { -15, -17, -33 });
            rules[24] = new Rule(-15, new int[] {});
            rules[25] = new Rule(-15, new int[] { -16, -15 });
            rules[26] = new Rule(-16, new int[] { 166 });
            rules[27] = new Rule(-16, new int[] { 169 });
            rules[28] = new Rule(-17, new int[] { -18, -19, -77 });
            rules[29] = new Rule(-18, new int[] { 179 });
            rules[30] = new Rule(-77, new int[] {});
            rules[31] = new Rule(-19, new int[] { 130, 40, -78, -20, 41, -79 });
            rules[32] = new Rule(-78, new int[] {});
            rules[33] = new Rule(-79, new int[] {});
            rules[34] = new Rule(-20, new int[] {});
            rules[35] = new Rule(-20, new int[] { -21 });
            rules[36] = new Rule(-21, new int[] { -22 });
            rules[37] = new Rule(-22, new int[] { -80, -25, -23 });
            rules[38] = new Rule(-80, new int[] {});
            rules[39] = new Rule(-23, new int[] { 130, -79 });
            rules[40] = new Rule(-25, new int[] { -29 });
            rules[41] = new Rule(-25, new int[] { -26 });
            rules[42] = new Rule(-26, new int[] { -27 });
            rules[43] = new Rule(-27, new int[] { -28 });
            rules[44] = new Rule(-28, new int[] { 133 });
            rules[45] = new Rule(-29, new int[] { -30 });
            rules[46] = new Rule(-30, new int[] { -31, -81 });
            rules[47] = new Rule(-31, new int[] { -32 });
            rules[48] = new Rule(-32, new int[] { -9, -82 });
            rules[49] = new Rule(-82, new int[] {});
            rules[50] = new Rule(-81, new int[] { -83, 91, 93, -84 });
            rules[51] = new Rule(-83, new int[] {});
            rules[52] = new Rule(-84, new int[] {});
            rules[53] = new Rule(-33, new int[] { -34 });
            rules[54] = new Rule(-34, new int[] { 123, -35, 125 });
            rules[55] = new Rule(-35, new int[] { -36 });
            rules[56] = new Rule(-36, new int[] {});
            rules[57] = new Rule(-36, new int[] { -36, -37 });
            rules[58] = new Rule(-37, new int[] { -38 });
            rules[59] = new Rule(-37, new int[] { -43 });
            rules[60] = new Rule(-38, new int[] { -39, 59 });
            rules[61] = new Rule(-39, new int[] { -80, -24, -40 });
            rules[62] = new Rule(-40, new int[] { -42, -41 });
            rules[63] = new Rule(-41, new int[] {});
            rules[64] = new Rule(-42, new int[] { -23, -70 });
            rules[65] = new Rule(-70, new int[] {});
            rules[66] = new Rule(-24, new int[] { -25 });
            rules[67] = new Rule(-43, new int[] { -44 });
            rules[68] = new Rule(-44, new int[] { -45 });
            rules[69] = new Rule(-45, new int[] { -46, 59 });
            rules[70] = new Rule(-46, new int[] { -47 });
            rules[71] = new Rule(-47, new int[] { -48, -50, -51 });
            rules[72] = new Rule(-48, new int[] { -49 });
            rules[73] = new Rule(-49, new int[] { 130 });
            rules[74] = new Rule(-50, new int[] { 61 });
            rules[75] = new Rule(-51, new int[] { -52 });
            rules[76] = new Rule(-52, new int[] { -53 });
            rules[77] = new Rule(-53, new int[] { -54 });
            rules[78] = new Rule(-54, new int[] { -55 });
            rules[79] = new Rule(-55, new int[] { -56 });
            rules[80] = new Rule(-56, new int[] { -57 });
            rules[81] = new Rule(-57, new int[] { -58 });
            rules[82] = new Rule(-58, new int[] { -59 });
            rules[83] = new Rule(-59, new int[] { -60 });
            rules[84] = new Rule(-60, new int[] { -61 });
            rules[85] = new Rule(-61, new int[] { -62 });
            rules[86] = new Rule(-62, new int[] { -63 });
            rules[87] = new Rule(-63, new int[] { -64 });
            rules[88] = new Rule(-64, new int[] { -65 });
            rules[89] = new Rule(-65, new int[] { -66 });
            rules[90] = new Rule(-66, new int[] { -67 });
            rules[91] = new Rule(-67, new int[] { -68 });
            rules[92] = new Rule(-68, new int[] { -69 });
            rules[93] = new Rule(-69, new int[] { 191 });
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ConstantValueRule{T}" /> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 /// <param name="rule">The rule.</param>
 public ConstantValueRule(string name, T value, Rule rule) : base(name, rule)
 {
     Value = value;
 }
Beispiel #48
0
        private void rulesListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.rulesListView.SelectedItems.Count > 0)
            {
                Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;

                this.nameTextBox.Enabled          = true;
                this.activeCheckBox.Enabled       = true;
                this.reevaluationComboBox.Enabled = true;
                this.priorityTextBox.Enabled      = true;
                this.conditionTextBox.Enabled     = true;
                this.thenTextBox.Enabled          = true;
                this.elseTextBox.Enabled          = true;

                this.nameTextBox.Text                   = rule.Name;
                this.activeCheckBox.Checked             = rule.Active;
                this.reevaluationComboBox.SelectedIndex = (int)rule.ReevaluationBehavior;
                this.priorityTextBox.Text               = rule.Priority.ToString(CultureInfo.CurrentCulture);

                //Condition
                this.conditionTextBox.Text = rule.Condition != null?rule.Condition.ToString().Replace("\n", "\r\n") : string.Empty;

                try
                {
                    this.ruleParser.ParseCondition(this.conditionTextBox.Text);
                    conditionErrorProvider.SetError(this.conditionTextBox, string.Empty);
                }
                catch (RuleSyntaxException ex)
                {
                    conditionErrorProvider.SetError(this.conditionTextBox, ex.Message);
                }

                //Then
                this.thenTextBox.Text = GetActionsString(rule.ThenActions);
                try
                {
                    this.ruleParser.ParseStatementList(this.thenTextBox.Text);
                    thenErrorProvider.SetError(this.thenTextBox, string.Empty);
                }
                catch (RuleSyntaxException ex)
                {
                    thenErrorProvider.SetError(this.thenTextBox, ex.Message);
                }

                //Else
                this.elseTextBox.Text = GetActionsString(rule.ElseActions);
                try
                {
                    this.ruleParser.ParseStatementList(this.elseTextBox.Text);
                    elseErrorProvider.SetError(this.elseTextBox, string.Empty);
                }
                catch (RuleSyntaxException ex)
                {
                    elseErrorProvider.SetError(this.elseTextBox, ex.Message);
                }

                this.deleteToolStripButton.Enabled = true;
            }
            else
            {
                this.nameTextBox.Text          = string.Empty;
                this.activeCheckBox.Checked    = false;
                this.reevaluationComboBox.Text = string.Empty;
                this.priorityTextBox.Text      = string.Empty;
                this.conditionTextBox.Text     = string.Empty;
                this.thenTextBox.Text          = string.Empty;
                this.elseTextBox.Text          = string.Empty;

                this.nameTextBox.Enabled          = false;
                this.activeCheckBox.Enabled       = false;
                this.reevaluationComboBox.Enabled = false;
                this.priorityTextBox.Enabled      = false;
                this.conditionTextBox.Enabled     = false;
                this.thenTextBox.Enabled          = false;
                this.elseTextBox.Enabled          = false;
                conditionErrorProvider.SetError(this.conditionTextBox, string.Empty);
                thenErrorProvider.SetError(this.thenTextBox, string.Empty);
                elseErrorProvider.SetError(this.elseTextBox, string.Empty);

                this.deleteToolStripButton.Enabled = false;
            }
        }
Beispiel #49
0
    // ------------------------------------------------------------------
    // 建立新關卡.
    public void NewStage()
    {
        // 清空遊戲資料.
        DataGame.pthis.Clear();
        DataPickup.pthis.Clear();
        // 清空物件.
        ClearObj();

        // 重置跑步旗標.
        bCanRun = true;
        // 重新計算數值.
        DataPlayer.pthis.iStaminaLimit = Rule.StaminaLimit();
        Rule.StaminaReset();
        Rule.StaminaRecovery();
        Rule.CriticalStrikeReset();
        Rule.AddDamageReset();
        Rule.BombReset();
        Rule.ShieldReset();
        Rule.RandomCollect();

        // 資料存檔.
        DataPlayer.pthis.Save();

        DataGame.pthis.fRunDouble = 1.0f;

        // 選擇關卡風格編號.
        DataPlayer.pthis.iStyle = Tool.RandomPick(GameDefine.StageStyle);
        // 選音樂.
        AudioCtrl.pthis.PlayBG();

        // 預先載入地圖物件.
        UITool.pthis.PreLoadMapObj(DataPlayer.pthis.iStyle);

        // 建立地圖資料.
        MapCreater.pthis.Create();
        // 建立撿取資料.
        PickupCreater.pthis.Create();

        SaveGame();

        // 建立地圖物件.
        MapCreater.pthis.Show(0);
        // 建立撿取物件.
        PickupCreater.pthis.Show(0);

        DataMap.pthis.Save();

        // UI初始化.
        P_UI.pthis.StartNew();

        // 鏡頭位置調整.
        CameraCtrl.pthis.StartNew();

        // 新遊戲 - 淡出淡入天數後開始遊戲.
        SysUI.pthis.ShowDay();

        Statistics.pthis.ResetResource();
        Statistics.pthis.ResetDamage();

        // 到數開始.
        bShowCount = false;
        Invoke("CountStart", 3);
    }
 /// <summary>
 ///     Creates the value node.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="input">The input.</param>
 /// <param name="begin">The begin.</param>
 /// <param name="matchedRule">The matched rule.</param>
 /// <returns>ValueNode&lt;T&gt;.</returns>
 protected override ValueNode <T> CreateValueNode(string name, string input, int begin, Rule matchedRule) => new ConstantValueNode <T>(name, input, begin, Value, matchedRule);
        public void CallingOnDeleteOrUpdateSetsOnUpdateAndOnDeleteOnForeignKeyExpression(Rule rule)
        {
            var builder = new CreateColumnExpressionBuilder(null, null)
            {
                CurrentForeignKey = new ForeignKeyDefinition()
            };

            builder.OnDeleteOrUpdate(rule);
            Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule));
            Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule));
        }
Beispiel #52
0
        static private RuleInferenceEngine getInferenceEngine()
        {
            RuleInferenceEngine rie = new RuleInferenceEngine();

            Rule rule = new Rule(Bicycle);

            rule.AddAntecedent(new ClauseIs("vehicleType", "cycle"));
            rule.AddAntecedent(new ClauseIs("num_wheels", "2"));
            rule.AddAntecedent(new ClauseIs("motor", "no"));
            rule.Consequent = new ClauseIs("vehicle", Bicycle);
            rie.AddRule(rule);

            rule = new Rule(Tricycle);
            rule.AddAntecedent(new ClauseIs("vehicleType", "cycle"));
            rule.AddAntecedent(new ClauseIs("num_wheels", "3"));
            rule.AddAntecedent(new ClauseIs("motor", "no"));
            rule.Consequent = new ClauseIs("vehicle", Tricycle);
            rie.AddRule(rule);

            rule = new Rule(Motorcycle);
            rule.AddAntecedent(new ClauseIs("vehicleType", "cycle"));
            rule.AddAntecedent(new ClauseIs("num_wheels", "2"));
            rule.AddAntecedent(new ClauseIs("motor", "yes"));
            rule.Consequent = new ClauseIs("vehicle", Motorcycle);
            rie.AddRule(rule);

            rule = new Rule(SportsCar);
            rule.AddAntecedent(new ClauseIs("vehicleType", "automobile"));
            rule.AddAntecedent(new ClauseIs("size", "medium"));
            rule.AddAntecedent(new ClauseIs("num_doors", "2"));
            rule.Consequent = new ClauseIs("vehicle", SportsCar);
            rie.AddRule(rule);

            rule = new Rule(Sedan);
            rule.AddAntecedent(new ClauseIs("vehicleType", "automobile"));
            rule.AddAntecedent(new ClauseIs("size", "medium"));
            rule.AddAntecedent(new ClauseIs("num_doors", "4"));
            rule.Consequent = new ClauseIs("vehicle", Sedan);
            rie.AddRule(rule);

            rule = new Rule(MiniVan);
            rule.AddAntecedent(new ClauseIs("vehicleType", "automobile"));
            rule.AddAntecedent(new ClauseIs("size", "medium"));
            rule.AddAntecedent(new ClauseIs("num_doors", "3"));
            rule.Consequent = new ClauseIs("vehicle", MiniVan);
            rie.AddRule(rule);

            rule = new Rule(SUV);
            rule.AddAntecedent(new ClauseIs("vehicleType", "automobile"));
            rule.AddAntecedent(new ClauseIs("size", "large"));
            rule.AddAntecedent(new ClauseIs("num_doors", "4"));
            rule.Consequent = new ClauseIs("vehicle", SUV);
            rie.AddRule(rule);

            rule = new Rule(Cycle);
            rule.AddAntecedent(new ClauseLt("num_wheels", "4"));
            rule.Consequent = new ClauseIs("vehicleType", "cycle");
            rie.AddRule(rule);

            rule = new Rule(Automobile);
            rule.AddAntecedent(new ClauseIs("num_wheels", "4"));
            rule.AddAntecedent(new ClauseIs("motor", "yes"));
            rule.Consequent = new ClauseIs("vehicleType", "automobile");
            rie.AddRule(rule);

            return(rie);
        }
		/// <summary>determine if the resources involved are restricted to a part, and then process a rule</summary>
		public void Process_rule(List<Part> parts, Rule r, EnvironmentAnalyzer env, VesselAnalyzer va)
		{
			// evaluate modifiers
			double k = Modifiers.Evaluate(env, va, this, r.modifiers);
			Process_rule_inner_body(k, null, r, env, va);
		}
Beispiel #54
0
 public ConfiguredRule(Rule rule)
 {
     this.rule          = rule;
     this.RuleCode      = this.rule.RuleCode;
     CalculatedDiscount = GetDiscount(rule);
 }
 protected override void WalkRule(Rule rule)
 {
     base.WalkRule(rule);
     this.currentNames.Clear();
 }
Beispiel #56
0
    void Start()
    {
        moduleId            = moduleIdCounter++;
        startingTimeSeconds = (int)BombInfo.GetTime();
        day   = DateTime.Now.Day;
        month = DateTime.Now.Month;

        // ** RULE SEED ** //
        var rnd = RuleSeedable.GetRNG();

        Debug.LogFormat(@"[Mega Man 2 #{0}] Using rule seed: {1}", moduleId, rnd.Seed);
        robotMasters = rnd.Seed == 1
            ? new[] { "Air Man", "Bubble Man", "Crash Man", "Flash Man", "Heat Man", "Metal Man", "Quick Man", "Wood Man" }
            : rnd.ShuffleFisherYates(new[] { "Cold Man", "Magma Man", "Dust Man", "Sword Man", "Splash Woman", "Ice Man", "Quick Man", "Hard Man", "Pharaoh Man", "Charge Man", "Pirate Man", "Pump Man", "Galaxy Man", "Grenade Man", "Snake Man", "Burst Man", "Cut Man", "Air Man", "Magnet Man", "Toad Man", "Gyro Man", "Tomahawk Man", "Wood Man", "Strike Man", "Blade Man", "Aqua Man", "Shade Man", "Flash Man", "Flame Man", "Concrete Man", "Metal Man", "Needle Man", "Wave Man", "Knight Man", "Slash Man", "Shadow Man", "Sheep Man", "Ground Man", "Wind Man", "Fire Man", "Stone Man", "Tengu Man", "Bright Man", "Centaur Man", "Cloud Man", "Frost Man", "Dynamo Man", "Chill Man", "Turbo Man", "Napalm Man", "Jewel Man", "Drill Man", "Freeze Man", "Blizzard Man", "Gravity Man", "Junk Man", "Clown Man", "Hornet Man", "Skull Man", "Solar Man", "Commando Man", "Yamato Man", "Dive Man", "Search Man", "Gemini Man", "Bubble Man", "Guts Man", "Tornado Man", "Astro Man", "Plug Man", "Elec Man", "Crystal Man", "Nitro Man", "Burner Man", "Spark Man", "Spring Man", "Plant Man", "Star Man", "Ring Man", "Top Man", "Crash Man", "Bomb Man", "Heat Man", "Magic Man" });

        var presetCoordinates = new Dictionary <string, Coords>
        {
            { "Air Man", new Coords("B2", "E1") },
            { "Bubble Man", new Coords("D5", "D2") },
            { "Crash Man", new Coords("D4", "B1") },
            { "Flash Man", new Coords("C5", "B3") },
            { "Heat Man", new Coords("C1", "E4") },
            { "Metal Man", new Coords("B4", "E5") },
            { "Quick Man", new Coords("C3", "D3") },
            { "Wood Man", new Coords("E2", "C4") }
        };

        var availableCoordinates = new List <string>();

        for (var row = 1; row < 5; row++)
        {
            for (var col = 0; col < 5; col++)
            {
                availableCoordinates.Add((char)('A' + row) + "" + (col + 1));
            }
        }
        for (int i = 0; i < 8; i++)
        {
            if (presetCoordinates.ContainsKey(robotMasters[i]))
            {
                availableCoordinates.Remove(presetCoordinates[robotMasters[i]].DeadCoord);
                availableCoordinates.Remove(presetCoordinates[robotMasters[i]].AliveCoord);
            }
        }

        rnd.ShuffleFisherYates(availableCoordinates);

        var coordinatesIx = 0;
        var coordinates   = new Coords[8];

        for (var i = 0; i < 8; i++)
        {
            if (presetCoordinates.ContainsKey(robotMasters[i]))
            {
                coordinates[i] = presetCoordinates[robotMasters[i]];
            }
            else
            {
                coordinates[i] = new Coords(availableCoordinates[coordinatesIx], availableCoordinates[coordinatesIx + 1]);
                coordinatesIx += 2;
            }
        }

        // These must all have at least 3 because each of them can potentially occur 3 times
        var allAABatteries = BombInfo.GetBatteryCount(Battery.AA) + BombInfo.GetBatteryCount(Battery.AAx3) + BombInfo.GetBatteryCount(Battery.AAx4);
        var brules         = rnd.ShuffleFisherYates(newArray(
                                                        new EdgeworkRule("# of batteries", BombInfo.GetBatteryCount()),
                                                        new EdgeworkRule("# of D batteries", BombInfo.GetBatteryCount(Battery.D)),
                                                        new EdgeworkRule("# of AA batteries", allAABatteries),
                                                        new EdgeworkRule("# of battery holders", BombInfo.GetBatteryHolderCount())).ToList());

        var irules = rnd.ShuffleFisherYates(newArray(
                                                new EdgeworkRule("# of indicators", BombInfo.GetIndicators().Count()),
                                                new EdgeworkRule("# of lit indicators", BombInfo.GetOnIndicators().Count()),
                                                new EdgeworkRule("# of unlit indicators", BombInfo.GetOffIndicators().Count())).ToList());

        var prules = rnd.ShuffleFisherYates(newArray(
                                                new EdgeworkRule("# of ports", BombInfo.GetPortCount()),
                                                new EdgeworkRule("# of port types", BombInfo.CountUniquePorts()),
                                                new EdgeworkRule("# of port plates", BombInfo.GetPortPlates().Count())).ToList());

        var srules = rnd.ShuffleFisherYates(newArray(
                                                new EdgeworkRule("first SN digit", BombInfo.GetSerialNumberNumbers().First()),
                                                new EdgeworkRule("second SN digit", BombInfo.GetSerialNumberNumbers().Skip(1).First()),
                                                new EdgeworkRule("last SN digit", BombInfo.GetSerialNumberNumbers().Last())).ToList());

        var inds = rnd.ShuffleFisherYates(new List <string> {
            "SND", "CLR", "CAR", "IND", "FRQ", "SIG", "NSA", "MSA", "TRN", "BOB", "FRK"
        });
        var ports = rnd.ShuffleFisherYates(new List <Port> {
            Port.DVI, Port.Parallel, Port.PS2, Port.RJ45, Port.Serial, Port.StereoRCA
        });
        var operatorNames = new[] { "=", "≤", "≥", "≠" };

        var ops = new Func <int, int, int, bool>((x, y, op) =>
        {
            switch (op)
            {
            case 0: return(x == y);

            case 1: return(x <= y);

            case 2: return(x >= y);

            default: return(x != y);
            }
        });

        var possibleAliveConditions = newArray <Func <int, bool, Rule> >(
            (op, presence) => { var indicator = inds[0]; inds.RemoveAt(0); return(new Rule(string.Format("indicator labeled “{0}” {1}", indicator, presence ? "present" : "absent"), _ => !presence ^ BombInfo.IsIndicatorPresent(indicator))); },
            (op, presence) => { var indicator = inds[0]; inds.RemoveAt(0); return(new Rule(string.Format("lit indicator labeled “{0}” {1}", indicator, presence ? "present" : "absent"), _ => !presence ^ BombInfo.IsIndicatorOn(indicator))); },
            (op, presence) => { var indicator = inds[0]; inds.RemoveAt(0); return(new Rule(string.Format("unlit indicator labeled “{0}” {1}", indicator, presence ? "present" : "absent"), _ => !presence ^ BombInfo.IsIndicatorOff(indicator))); },
            (op, presence) => { var number = rnd.Next(1, 6); return(new Rule(string.Format("E-Tanks spot {0} A{1}", operatorNames[op], number), eTankNumber => ops(eTankNumber, number, op), eTanks: true)); },
            (op, presence) => { var brule = brules[0]; brules.RemoveAt(0); var number = rnd.Next(1, 11); return(new Rule(string.Format("{0} {1} {2}", brule.Name, operatorNames[op], number), _ => ops(brule.Value, number, op))); },
            (op, presence) => { var irule = irules[0]; irules.RemoveAt(0); var number = rnd.Next(2, 6); return(new Rule(string.Format("{0} {1} {2}", irule.Name, operatorNames[op], number), _ => ops(irule.Value, number, op))); },
            (op, presence) => { var prule = prules[0]; prules.RemoveAt(0); var number = rnd.Next(2, 8); return(new Rule(string.Format("{0} {1} {2}", prule.Name, operatorNames[op], number), _ => ops(prule.Value, number, op))); },
            (op, presence) => { var srule = srules[0]; srules.RemoveAt(0); var number = rnd.Next(0, 10); return(new Rule(string.Format("{0} {1} {2}", srule.Name, operatorNames[op], number), _ => ops(srule.Value, number, op))); },
            (op, presence) => { var port = ports[0]; ports.RemoveAt(0); return(new Rule(string.Format("{0} port {1}", port, presence ? "present" : "absent"), _ => !presence ^ BombInfo.IsPortPresent(port))); },
            (op, presence) => { var brule = brules[0]; brules.RemoveAt(0); var irule = irules[0]; irules.RemoveAt(0); return(new Rule(string.Format("{0} {1} {2}", brule.Name, operatorNames[op], irule.Name), _ => ops(brule.Value, irule.Value, op))); },
            (op, presence) => { var brule = brules[0]; brules.RemoveAt(0); var prule = prules[0]; prules.RemoveAt(0); return(new Rule(string.Format("{0} {1} {2}", brule.Name, operatorNames[op], prule.Name), _ => ops(brule.Value, prule.Value, op))); },
            (op, presence) => { var brule = brules[0]; brules.RemoveAt(0); var srule = srules[0]; srules.RemoveAt(0); return(new Rule(string.Format("{0} {1} {2}", brule.Name, operatorNames[op], srule.Name), _ => ops(brule.Value, srule.Value, op))); },
            (op, presence) => { var irule = irules[0]; irules.RemoveAt(0); var prule = prules[0]; prules.RemoveAt(0); return(new Rule(string.Format("{0} {1} {2}", irule.Name, operatorNames[op], prule.Name), _ => ops(irule.Value, prule.Value, op))); },
            (op, presence) => { var irule = irules[0]; irules.RemoveAt(0); var srule = srules[0]; srules.RemoveAt(0); return(new Rule(string.Format("{0} {1} {2}", irule.Name, operatorNames[op], srule.Name), _ => ops(irule.Value, srule.Value, op))); },
            (op, presence) => { var prule = prules[0]; prules.RemoveAt(0); var srule = srules[0]; srules.RemoveAt(0); return(new Rule(string.Format("{0} {1} {2}", prule.Name, operatorNames[op], srule.Name), _ => ops(prule.Value, srule.Value, op))); }
            ).ToList();

        if (rnd.Seed != 1)
        {
            possibleAliveConditions.Add((op, presence) => { var number = rnd.Next(5, 31); return(new Rule(string.Format("# of modules on the bomb {0} {1}", operatorNames[op], number), _ => ops(BombInfo.GetModuleNames().Count, number, op))); });
            possibleAliveConditions.Add((op, presence) => { var number = rnd.Next(10, 61); return(new Rule(string.Format("Starting time of the bomb {0} {1} minutes", operatorNames[op], number), _ => ops(startingTimeSeconds, number * 60, op))); });
        }
        rnd.ShuffleFisherYates(possibleAliveConditions);

        var aliveConditions     = new Rule[8];
        var anyETanksConditions = false;

        for (var i = 0; i < 8; i++)
        {
            var ruleInfo = possibleAliveConditions[i];
            var op       = rnd.Next(0, 4);
            var presence = rnd.Next(0, 2) == 0;
            aliveConditions[i] = ruleInfo(op, presence);
            if (aliveConditions[i].ETanks)
            {
                anyETanksConditions = true;
            }
        }

        var numbers             = rnd.ShuffleFisherYates(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        var numbersObjArr       = numbers.Cast <object>().ToArray();
        var possibleETanksRules = (rnd.Seed == 1
            ? new[] { new EdgeworkRule("sum of all digits in the serial number", BombInfo.GetSerialNumberNumbers().Sum()) }
            : newArray(
                                       new EdgeworkRule("sum of all digits in the serial number", BombInfo.GetSerialNumberNumbers().Sum()),
                                       new EdgeworkRule("sum of the alphabetic positions of the letters in the serial number", BombInfo.GetSerialNumberLetters().Select(ltr => ltr - 'A' + 1).Sum()),
                                       new EdgeworkRule("sum of the alphabetic positions of the letters in all indicators", BombInfo.GetIndicators().SelectMany(i => i).Select(ltr => ltr - 'A' + 1).Sum()),
                                       new EdgeworkRule(string.Format("sum of the values of the indicators, where lit={0} and unlit={1}", numbersObjArr), BombInfo.GetOnIndicators().Count() * numbers[0] + BombInfo.GetOffIndicators().Count() * numbers[1]),
                                       new EdgeworkRule(string.Format("sum of the values of the ports, where parallel={0}, serial={1}, DVI-D={2}, Stereo RCA={3}, PS/2={4} and RJ-45={5} (other port types are 0)", numbersObjArr),
                                                        BombInfo.GetPortCount(Port.Parallel) * numbers[0] +
                                                        BombInfo.GetPortCount(Port.Serial) * numbers[1] +
                                                        BombInfo.GetPortCount(Port.DVI) * numbers[2] +
                                                        BombInfo.GetPortCount(Port.StereoRCA) * numbers[3] +
                                                        BombInfo.GetPortCount(Port.PS2) * numbers[4] +
                                                        BombInfo.GetPortCount(Port.RJ45) * numbers[5]),
                                       new EdgeworkRule(string.Format("sum of the values of the batteries, where AA={0} and D={1}", numbersObjArr), allAABatteries * numbers[0] + BombInfo.GetBatteryCount(Battery.D) * numbers[1]),
                                       new EdgeworkRule("number of modules on the bomb (including needies)", BombInfo.GetModuleNames().Count),
                                       new EdgeworkRule("number of modules on the bomb (excluding needies)", BombInfo.GetSolvableModuleNames().Count),
                                       new EdgeworkRule("number of the current month when the bomb was activated", month),
                                       new EdgeworkRule("day of the month when the bomb was activated", day),
                                       new EdgeworkRule("total number of Mega Man 2 modules on the bomb", BombInfo.GetSolvableModuleNames().Count(m => m == "Mega Man 2")))).ToList();

        if (rnd.Seed != 1 && !anyETanksConditions)
        {
            var aliveTmp = aliveConditions.Count(rule => rule.Evaluate(0));
            possibleETanksRules.Add(new EdgeworkRule("total number of robot masters that are alive", aliveTmp));
            possibleETanksRules.Add(new EdgeworkRule("total number of robot masters that are dead", 8 - aliveTmp));
        }

        var eTankRuleIx = rnd.Next(0, possibleETanksRules.Count);
        var eTank       = (possibleETanksRules[eTankRuleIx].Value + 4) % 5 + 1;

        // ** END RULE SEED GENERATION ** //


        var availableRobotMasterIxs = Enumerable.Range(0, 8).ToList();

        int ix = Random.Range(0, availableRobotMasterIxs.Count);

        selectedMaster = availableRobotMasterIxs[ix];
        availableRobotMasterIxs.RemoveAt(ix);
        selectedWeapon = availableRobotMasterIxs[Random.Range(0, availableRobotMasterIxs.Count)];

        RobotMastersDisplay.material.mainTexture = RobotMasters.First(tx => tx.name == robotMasters[selectedMaster]);
        WeaponsDisplay.material.mainTexture      = Weapons.First(tx => tx.name == robotMasters[selectedWeapon]);

        solution    = new string[9];
        solution[8] = "A" + eTank;
        Debug.LogFormat(@"[Mega Man 2 #{0}] ETanks spot is: {1}", moduleId, solution[8]);

        for (int i = 0; i < 8; i++)
        {
            var alive = i == selectedMaster ? true : i == selectedWeapon ? false : aliveConditions[i].Evaluate(eTank);
            Debug.LogFormat(@"[Mega Man 2 #{0}] {1} is {2} ({3})", moduleId, robotMasters[i], alive ? "alive" : "dead", i == selectedMaster ? "robot master shown on module" : i == selectedWeapon ? "weapon shown on module" : aliveConditions[i].Text + " = " + (aliveConditions[i].Evaluate(eTank) ? "true" : "false"));
            solution[i] = alive ? coordinates[i].AliveCoord : coordinates[i].DeadCoord;
        }

        Debug.LogFormat(@"[Mega Man 2 #{0}] Password is: {1}", moduleId, solution.Join(", "));
    }
 public static bool IsRoadFix(this Rule rule)
 {
     return(rule.EvaluateDefault("roadFix", false));
 }
        public static bool Run(List <Track> _tracks, List <int> _chunks, ref bool _tracksStarted, ref bool _tracksFinshed, ref Rule _ruleBroke, float YPosition, float withIn)
        {
            CommandHandeler commandHandeler = new CommandHandeler();

            List <Command> commands = new List <Command>();

            //Copy
            Coaster coaster = new Coaster();

            coaster.SetTracks        = _tracks;
            coaster.SetChunks        = _chunks;
            coaster.SetTracksStarted = _tracksStarted;
            coaster.SetTracksFinshed = _tracksFinshed;

            List <Track> tracks        = coaster.GetCurrentTracks;
            List <int>   chunks        = coaster.GetCurrentChunks;
            bool         tracksStarted = coaster.GetCurrentTracksStarted;
            bool         tracksFinshed = coaster.GetCurrentTracksFinshed;
            Rule         ruleBroke     = _ruleBroke;

            bool  passed  = false;
            float yawGoal = 0;


            //Goal Yaw
            if (YPosition > tracks.Last().Position.Y)
            {
                yawGoal = 90;
            }
            else
            {
                yawGoal = 270;
            }

            if (GoToY(tracks, chunks, ref tracksStarted, ref tracksFinshed, ref ruleBroke, YPosition, withIn, TrackType.Left, yawGoal))
            {
                passed = GoToY(_tracks, _chunks, ref _tracksStarted, ref _tracksFinshed, ref _ruleBroke, YPosition, withIn, TrackType.Left, yawGoal);
            }

            if (!passed)
            {
                tracks        = coaster.GetCurrentTracks;
                chunks        = coaster.GetCurrentChunks;
                tracksStarted = coaster.GetCurrentTracksStarted;
                tracksFinshed = coaster.GetCurrentTracksFinshed;
                ruleBroke     = _ruleBroke;

                if (GoToY(tracks, chunks, ref tracksStarted, ref tracksFinshed, ref ruleBroke, YPosition, withIn, TrackType.Right, yawGoal))
                {
                    passed = GoToY(_tracks, _chunks, ref _tracksStarted, ref _tracksFinshed, ref _ruleBroke, YPosition, withIn, TrackType.Right, yawGoal);
                }
            }


            return(passed);
        }
 public static string GetDetail(this Rule rule)
 {
     return(rule.Evaluate <string>("detail"));
 }
Beispiel #60
0
 public RuleChecker(Rule ruleToCheck, Page currentPage)
 {
     _ruleToCheck = ruleToCheck;
     _currentPage = currentPage;
 }