protected void AddQuantifier(int min, int max, bool greedy)
        {
            List <PatternNode <TData, TOffset> > list = _alternation.Any() ? _alternation : _nodes;
            var quantifier = new Quantifier <TData, TOffset>(min, max, list.Last())
            {
                IsGreedy = greedy
            };

            list[list.Count - 1] = quantifier;
        }
示例#2
0
 public static Quantifier Quantifier(this Tuple tuple, INode node)
 {
     var quantifier = tuple.GetState<Quantifier>(node);
     if (quantifier == null)
     {
         quantifier = new Quantifier();
         tuple.SetState(node, quantifier);
     }
     return quantifier;
 }
示例#3
0
        public void Test0020_ConstuctorAcceptsPlusQuantifier()
        {
            Quantifier sut = new Quantifier("+");

            sut.Should().NotBeNull("the constructor should accept this input");
            sut.Lower.Should().Be(1, "the lower value of '+' is 1");
            sut.Upper.Should()
            .Be(int.MaxValue, "the infinite upper vlue of '+' has been capped at the maximum value of int.");
            sut.Type.Should().Be(Quantifier.Types.Range);
        }
示例#4
0
        public void Test0050_ConstuctorAcceptsInfinateNumericQuantifier()
        {
            var        fixedNum  = 7;
            var        testValue = string.Format("{{{0},}}", fixedNum);
            Quantifier sut       = new Quantifier(testValue);

            sut.Should().NotBeNull("the constructor should accept this input");
            sut.Lower.Should().Be(7, "the lower value of numeric quantifier '{0}' is {1}.", testValue, fixedNum);
            sut.Upper.Should().Be(int.MaxValue, "the upper value of numeric quantifier '{0}' is {1}.", testValue, int.MaxValue);
            sut.Type.Should().Be(Quantifier.Types.Range);
        }
示例#5
0
        // Quantifiers

        public VCExpr Quantify(Quantifier quan, List <TypeVariable /*!*/> /*!*/ typeParams, List <VCExprVar /*!*/> /*!*/ vars,
                               List <VCTrigger /*!*/> /*!*/ triggers, VCQuantifierInfos infos, VCExpr body)
        {
            Contract.Requires(body != null);
            Contract.Requires(infos != null);
            Contract.Requires(cce.NonNullElements(triggers));
            Contract.Requires(cce.NonNullElements(vars));
            Contract.Requires(cce.NonNullElements(typeParams));
            Contract.Ensures(Contract.Result <VCExpr>() != null);
            return(new VCExprQuantifier(quan, typeParams, vars, triggers, infos, body));
        }
示例#6
0
        public void Constructor_PassingAlphabeticCharacter_ExpectedVariableAssignedAndObjectConstructed()
        {
            // Arrange
            Quantifier quantifier = GetQuantifier();

            // Act
            char actualBoundVariable = quantifier.GetBoundVariable();

            // Assert
            actualBoundVariable.Should().Be(GetBoundVariable(), "Because the character should be assigned");
        }
示例#7
0
        public void QuantifierTest()
        {
            var         text     = "Canadians";
            var         target   = new ProperPluralNoun(text);
            IQuantifier expected = new Quantifier("5");
            IQuantifier actual;

            target.QuantifiedBy = expected;
            actual = target.QuantifiedBy;
            Check.That(actual).IsEqualTo(expected);
        }
示例#8
0
        internal static IEnumerable <string> getTriggers(Quantifier quantifier, bool display)
        {
            var bodyTerms = quantifier.BodyTerm.Args;

            if (bodyTerms == null || bodyTerms.Length <= 1)
            {
                return(Enumerable.Empty <string>());
            }

            return(bodyTerms.Take(bodyTerms.Length - 1).Select(x => ExtractTrigger(x, display)));
        }
示例#9
0
        public Group(IRegularExpression expression, string specifier, Quantifier quantifier)
        {
            if (expression == null || quantifier == null)
            {
                throw new ArgumentNullException();
            }

            Quantifier    = quantifier;
            Subexpression = expression;
            Specifier     = specifier;
        }
示例#10
0
        public void QuantifiedByTest()
        {
            var target      = new CommonSingularNoun("dog");
            var quantifying = new Quantifier("3");

            target.QuantifiedBy = quantifying;
            var actual = target.QuantifiedBy;

            Check.That(actual).IsEqualTo(quantifying);
            Check.That(target.QuantifiedBy.Quantifies).IsEqualTo(target);
        }
示例#11
0
        public static Quantifier Quantifier(this Tuple tuple, INode node)
        {
            var quantifier = tuple.GetState <Quantifier>(node);

            if (quantifier == null)
            {
                quantifier = new Quantifier();
                tuple.SetState(node, quantifier);
            }
            return(quantifier);
        }
示例#12
0
        public void QuantifiedByTest()
        {
            var         text     = "clowns";
            var         target   = new CommonPluralNoun(text);
            IQuantifier expected = new Quantifier("all");
            IQuantifier actual;

            target.QuantifiedBy = expected;
            actual = target.QuantifiedBy;
            Check.That(actual).IsEqualTo(expected);
        }
        public QuantifierPredicate(Quantifier quantifier, Variable variable, Sort typeBound, Predicate predicate)
        {
            Debug.Assert(quantifier != null);
            Debug.Assert(variable != null);
            Debug.Assert(typeBound != null);
            Debug.Assert(predicate != null);

            this.quantifier = quantifier;
            this.variable   = variable;
            this.typeBound  = typeBound;
            this.predicate  = predicate;
        }
示例#14
0
        public void Test0060_ConstuctorAcceptsBoundedNumericQuantifier()
        {
            var        lowerNum  = 7;
            var        upperNum  = 95;
            var        testValue = string.Format("{{{0},{1}}}", lowerNum, upperNum);
            Quantifier sut       = new Quantifier(testValue);

            sut.Should().NotBeNull("the constructor should accept this input");
            sut.Lower.Should().Be(7, "the lower value of numeric quantifier '{0}' is {1}.", testValue, lowerNum);
            sut.Upper.Should().Be(95, "the upper value of numeric quantifier '{0}' is {1}.", testValue, upperNum);
            sut.Type.Should().Be(Quantifier.Types.Range);
        }
示例#15
0
        public Parser(IParser <TInput, TOutput> initial, Func <IParser <TInput, TOutput>, IParser <TInput, TOutput> > getRight, Quantifier arity, string name = "")
        {
            Assert.ArgumentNotNull(initial, nameof(initial));
            Assert.ArgumentNotNull(getRight, nameof(getRight));

            _initial    = initial;
            _quantifier = arity;
            _left       = new LeftValue(name);
            _right      = getRight(_left);
            _getRight   = getRight;
            Name        = name;
        }
示例#16
0
 /// <summary>
 /// Reinitialize global variables that track the values of constituents.
 /// Called each time a new syntax rule is tried.
 /// </summary>
 private void ResetConstituentInformation()
 {
     Subject.Reset();
     Verb.Reset();
     Verb2.Reset();
     Object.Reset();
     PredicateAP.Reset();
     SubjectNounList.Reset();
     PredicateAPList.Reset();
     Quantifier.Reset();
     VerbNumber = null;
 }
        /// <inheritdoc />
        public string CreateQuantifier(IRegularExpressionFactoryContext ctx, Quantifier quantity, string quantifiedContentRegex)
        {
            if (string.IsNullOrEmpty(quantifiedContentRegex))
            {
                return(string.Empty);
            }

            quantifiedContentRegex = CreateNonCapturingGroup(ctx, quantifiedContentRegex);

            var defined = quantity.ToDefinedRange();

            var min = defined.Min.MaxUInt;
            var max = defined.Max.MaxUInt;

            if (min == 1 && max == 1)
            {
                return(quantifiedContentRegex);
            }

            return(CreateNonCapturingGroup(ctx, GetQuantifiedContent()));


            string GetQuantifiedContent()
            {
                if (min == 0 && max == 1)
                {
                    return($"{quantifiedContentRegex}?");
                }

                if (defined.Max.IsInfinite)
                {
                    if (min == 0)
                    {
                        return($"{quantifiedContentRegex}*");
                    }

                    if (min == 1)
                    {
                        return($"{quantifiedContentRegex}+");
                    }

                    return($"{quantifiedContentRegex}{{{min},}}");
                }

                if (min == max)
                {
                    return($"{quantifiedContentRegex}{{{min}}}");
                }

                return($"{quantifiedContentRegex}{{{min},{max}}}");
            }
        }
示例#18
0
        public override void Generate(GroupSet groups, Random rand, StringBuilder sb, int recursionDepth, int repetitionLimit)
        {
            if (possibleChars.Length == 0)
            {
                return;
            }
            var c = Quantifier.GetQuantity(rand, repetitionLimit);

            for (var i = 0; i < c; ++i)
            {
                sb.Append(possibleChars[rand.Next(possibleChars.Length)]);
            }
        }
示例#19
0
        private Decomposition DecomposeWFF(Quantifier f)
        {
            if (f is Existential)
            {
                return(DecomposeWFF((Existential)f));
            }
            else if (f is Universal)
            {
                return(DecomposeWFF((Universal)f));
            }

            throw new NotImplementedException(f.GetType().ToString());
        }
        // <item> (<middle> <item>)* with right-associativity in the production method

        public Parser(IParser <TInput, TOutput> item, IParser <TInput, TMiddle> middle, Func <Arguments, TOutput> produce, Quantifier quantifier, Func <IParseState <TInput>, TOutput>?getMissingRight = null, string name = "")
        {
            Assert.ArgumentNotNull(item, nameof(item));
            Assert.ArgumentNotNull(middle, nameof(middle));
            Assert.ArgumentNotNull(produce, nameof(produce));

            _item            = item;
            _middle          = middle;
            _produce         = produce;
            _getMissingRight = getMissingRight;
            _quantifier      = quantifier;
            Name             = name;
        }
示例#21
0
        public static int SortOrder(this Quantifier f)
        {
            if (f is Existential)
            {
                return(1);
            }
            else if (f is Universal)
            {
                return(int.MaxValue);
            }

            throw new NotImplementedException(f.GetType().ToString());
        }
示例#22
0
        private IEvaluatable GetTerm(string inputString)
        {
            var        pattern            = new Regex(_regexMatchFact, RegexOptions.IgnoreCase);
            var        matches            = pattern.Matches(inputString);
            Quantifier quantifier1        = string.IsNullOrEmpty(matches[0].Groups[2].Value) ? Quantifier.ALL: _quantifierSynonyms[matches[0].Groups[2].Value.ToUpperInvariant()];
            var        attributeName      = DecompressStringFully(matches[0].Groups[3].Value);
            Predicate  relationalOperator = _operatorSynonyms[matches[0].Groups[5].Value.ToUpperInvariant()];
            Quantifier quantifier2        = string.IsNullOrEmpty(matches[0].Groups[7].Value) ? quantifier1 : _quantifierSynonyms[matches[0].Groups[7].Value.ToUpperInvariant()];
            var        reflective         = !string.IsNullOrEmpty(matches[0].Groups[8].Value);
            var        attributeValue     = DecompressStringFully(matches[0].Groups[9].Value);

            return(new Proposition(attributeName, relationalOperator, attributeValue, reflective, quantifier1, quantifier2));
        }
示例#23
0
        public static bool Decomposable(this Quantifier f)
        {
            if (f is Existential)
            {
                return(true);
            }
            else if (f is Universal)
            {
                return(true);
            }

            throw new NotImplementedException(f.GetType().ToString());
        }
        public static QuantifiedExpression Make(Quantifier q, IEnumerable <VariableType> vars, BooleanExpression b)
        {
            var freeVars = b.GetVariables();

            foreach (var v in vars)
            {
                if (!freeVars.Contains(v))
                {
                    throw new ArgumentException();
                }
            }
            return(new QuantifiedExpression(q, vars, b));
        }
示例#25
0
        public void GetRandomQuantity(int minimum, int maximum)
        {
            var quantifier = new Quantifier(minimum, maximum);
            var random     = new Random();

            Assert.Multiple(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    var actual = quantifier.GetRandomRepeat(random);
                    Assert.Between(actual, minimum, maximum);
                }
            });
        }
示例#26
0
 /// <summary>
 /// Initializes a new insstance of a QuantifierFilter.
 /// </summary>
 /// <param name="leftHand">The value being compared to the set of values.</param>
 /// <param name="quantifier">The quantifier to use to compare the value to the set of values.</param>
 /// <param name="valueProvider">The source of values.</param>
 protected QuantifierFilter(IFilterItem leftHand, Quantifier quantifier, IValueProvider valueProvider)
 {
     if (leftHand == null)
     {
         throw new ArgumentNullException("leftHand");
     }
     if (valueProvider == null)
     {
         throw new ArgumentNullException("valueProvider");
     }
     LeftHand      = leftHand;
     Quantifier    = quantifier;
     ValueProvider = valueProvider;
 }
示例#27
0
        private bool EvaluateQuantifiedOperation(Quantifier quantifier1, IEnumerable <string> actualValues, Predicate op, Quantifier quantifier2, IEnumerable <string> expectedValues)
        {
            if (quantifier1 == Quantifier.ALL && quantifier2 == Quantifier.ALL)
            {
                return(actualValues.All(actualValue => expectedValues.All(expectedValue => EvaluateOperation(actualValue, op, expectedValue))));
            }

            if (quantifier1 == Quantifier.ALL && quantifier2 == Quantifier.ANY)
            {
                return(actualValues.All(actualValue => expectedValues.Any(expectedValue => EvaluateOperation(actualValue, op, expectedValue))));
            }

            if (quantifier1 == Quantifier.ALL && quantifier2 == Quantifier.SINGLE)
            {
                return(actualValues.All(actualValue => expectedValues.Where(expectedValue => EvaluateOperation(actualValue, op, expectedValue)).Count() == 1));
            }

            if (quantifier1 == Quantifier.ANY && quantifier2 == Quantifier.ALL)
            {
                return(actualValues.Any(actualValue => expectedValues.All(expectedValue => EvaluateOperation(actualValue, op, expectedValue))));
            }

            if (quantifier1 == Quantifier.ANY && quantifier2 == Quantifier.ANY)
            {
                return(actualValues.Any(actualValue => expectedValues.Any(expectedValue => EvaluateOperation(actualValue, op, expectedValue))));
            }

            if (quantifier1 == Quantifier.ANY && quantifier2 == Quantifier.SINGLE)
            {
                return(actualValues.Any(actualValue => expectedValues.Where(expectedValue => EvaluateOperation(actualValue, op, expectedValue)).Count() == 1));
            }

            if (quantifier1 == Quantifier.SINGLE && quantifier2 == Quantifier.ALL)
            {
                return(actualValues.Where(actualValue => expectedValues.All(expectedValue => EvaluateOperation(actualValue, op, expectedValue))).Count() == 1);
            }

            if (quantifier1 == Quantifier.SINGLE && quantifier2 == Quantifier.ANY)
            {
                return(actualValues.Where(actualValue => expectedValues.Any(expectedValue => EvaluateOperation(actualValue, op, expectedValue))).Count() == 1);
            }

            if (quantifier1 == Quantifier.SINGLE && quantifier2 == Quantifier.SINGLE)
            {
                return(actualValues.Where(actualValue => expectedValues.Where(expectedValue => EvaluateOperation(actualValue, op, expectedValue)).Count() == 1).Count() == 1);
            }

            throw new Exception("Invalid proposition quantification");
        }
示例#28
0
        private Quantifier CreateQuantifier(string name, string qid)
        {
            Quantifier quant;

            if (!model.quantifiers.TryGetValue(name, out quant))
            {
                quant                   = new Quantifier();
                quant.Qid               = qid;
                quant.Instances         = new List <Instantiation>();
                model.quantifiers[name] = quant;

                loadBoogieToken(quant);
            }
            return(quant);
        }
示例#29
0
        public void ToPrefixString_SucessorAssigned_ExpectedPrefixStringReturned()
        {
            // Arrange
            Quantifier quantifier = GetQuantifier();

            quantifier.LeftSuccessor = new Proposition('P');

            // Act
            string actualToPrefixString = quantifier.ToPrefixString();

            string expectedToPrefixString = $"{quantifier.Data}{quantifier.GetBoundVariable()}.(P)";

            // Assert
            actualToPrefixString.Should().Be(expectedToPrefixString, "Because that's the prefix format for the quantifier");
        }
示例#30
0
 public Proposition(
     string attributeName,
     Predicate operation,
     string attributeValue,
     bool binaryArgument            = false,
     Quantifier argument1Quantifier = Quantifier.ALL,
     Quantifier argument2Quantifier = Quantifier.ALL)
 {
     AttributeName       = attributeName;
     Operator            = operation;
     AttributeValue      = attributeValue;
     BinaryArgument      = binaryArgument;
     Argument1Quantifier = argument1Quantifier;
     Argument2Quantifier = argument2Quantifier;
 }
示例#31
0
        private static T AddPredicate <T>(T node, Expression expression, bool sign, Quantifier quantifier = null)
            where T : ISemantic
        {
            if (quantifier == null)
            {
                ((IPredicate)node).AddPredicate(
                    new Predicate((DbNode)(object)node, PredicateType.Existential, sign, LogicalOperator.And, expression));
            }
            else
            {
                ((IPredicate)node).AddPredicate(
                    new Predicate((DbNode)(object)node, PredicateType.Quantified, sign, LogicalOperator.And, expression, quantifier));
            }

            return(node);
        }
示例#32
0
 public DateFilter(DateTime query, Char q, String attribute) {
    this.query = query;
    this.attribute = attribute;
    switch (q)
    {
       case '>':
          this.q = Quantifier.AFTER;
          break;
       case '<':
          this.q = Quantifier.BEFORE;
          break;
       case '=':
          this.q = Quantifier.IN;
          break;
    }
 }
示例#33
0
 public IntListFilter(int query, Char q, String attribute)
 {
    this.query = query;
    this.attribute = attribute;
    switch (q)
    {
       case '>':
          this.q = Quantifier.GREATERTHAN;
          break;
       case '<':
          this.q = Quantifier.LESSTHAN;
          break;
       case '=':
          this.q = Quantifier.EQUALTO;
          break;
    }
 }
    private void Refresh()
    {
        //apagar os elementos no meu itemContainer
        int children = hooks.ItemContainer.transform.childCount;
        for (int i = 0; i < children; i++) {
            GameObject.Destroy (hooks.ItemContainer.transform.GetChild (i).gameObject);
        }

        //limpar as listas
        itemsInContainerList.Clear ();
        inventoryTotalList.Clear ();

        //fazer reset ao itemIndex
        itemIndex = 0;

        //ativar botoes e tudo o que for preciso ativar
        for (int i = 0; i < hooks.ItemsArea.Count(); i++) {
            hooks.ItemsArea [i].SetActive (true);
        }

        //initialize my list with 2 tables and 8 chairs
        SpecificItem specificItemTable = GameManager.Instance.SpecificItems.Find (x => x.Id == 59);
        SpecificItem specificItemChair = GameManager.Instance.SpecificItems.Find (x => x.Id == 58);

        Quantifier<SpecificItem> tables = new Quantifier<SpecificItem> (2, specificItemTable);
        inventoryTotalList.Add (tables);
        Quantifier<SpecificItem> chairs = new Quantifier<SpecificItem> (8, specificItemChair);
        inventoryTotalList.Add (chairs);

        //preender a minha lista de inventorio
        foreach (Player player in game.Players) {
            for (int i = 0; i < player.Inventory.Count; i++) {
                SpecificItem specificItem = player.Inventory [i].Item;
                int index = inventoryTotalList.FindIndex (speItem => speItem.Item.Id == specificItem.Id);
                if (index == -1) {
                    SpecificItem specificItemCopy = new SpecificItem (specificItem.Id,
                                                                 specificItem.Name,
                                                                 specificItem.IconId,
                                                                 specificItem.Price,
                                                                 specificItem.Theme,
                                                                 specificItem.GeneralItem);
                    Quantifier<SpecificItem> itemToAddWithQTD = new Quantifier<SpecificItem> (player.Inventory [i].Quantity, specificItemCopy);
                    inventoryTotalList.Add (itemToAddWithQTD);
                } else {
                    inventoryTotalList [index].Quantity += player.Inventory [i].Quantity;
                }
            }
        }

        inventoryTotalSize = inventoryTotalList.Count ();

        updateScene ();
    }
示例#35
0
	void Quantifier(out Expression e) {
		Quantifier q = new Quantifier();
		NodeType n;
		Expression cexpr;
		
		Quant(out n);
		Comprehension(out cexpr);
		Comprehension c = cexpr as Comprehension;
		if (c == null){
		 e = null;
		}else{
		 c.Type = SystemTypes.GenericIEnumerable.GetTemplateInstance(currentAssembly,SystemTypes.Boolean);
		 q.QuantifierType = n;
		 q.Comprehension = c;
		 q.Type = SystemTypes.Boolean;
		 q.SourceType = SystemTypes.Boolean;
		 e = q;
		}
		
	}
		public IArrayCompareCondition LowerThanOrEqualTo(string arrayPath, string path, object value, Quantifier? quantifier = null) =>
			new LowerThanOrEqualArrayCondition(arrayPath, path, value) { Quantifier = quantifier };
示例#37
0
 public override Expression VisitQuantifier(Quantifier quantifier)
 {
     if (quantifier == null) return null;
     return base.VisitQuantifier((Quantifier)quantifier.Clone());
 }
示例#38
0
        private IEnumerable<PatternNode<Word, ShapeNode>> LoadPatternNodes(XElement pseqElem, Dictionary<string, Tuple<string, SymbolicFeature>> variables,
			CharacterDefinitionTable defaultTable, Dictionary<string, string> groupNames)
        {
            foreach (XElement recElem in pseqElem.Elements())
            {
                PatternNode<Word, ShapeNode> node = null;
                switch (recElem.Name.LocalName)
                {
                    case "SimpleContext":
                        SimpleContext simpleCtxt = LoadSimpleContext(recElem, variables);
                        node = new Constraint<Word, ShapeNode>(simpleCtxt.FeatureStruct) {Tag = simpleCtxt};
                        break;

                    case "Segment":
                    case "BoundaryMarker":
                        CharacterDefinition cd = _charDefs[(string) recElem.Attribute(recElem.Name.LocalName == "Segment" ? "segment" : "boundary")];
                        node = new Constraint<Word, ShapeNode>(cd.FeatureStruct) {Tag = cd};
                        break;

                    case "OptionalSegmentSequence":
                        var minStr = (string) recElem.Attribute("min");
                        int min = string.IsNullOrEmpty(minStr) ? 0 : int.Parse(minStr);
                        var maxStr = (string) recElem.Attribute("max");
                        int max = string.IsNullOrEmpty(maxStr) ? -1 : int.Parse(maxStr);
                        node = new Quantifier<Word, ShapeNode>(min, max, new Group<Word, ShapeNode>(LoadPatternNodes(recElem, variables, defaultTable, groupNames)));
                        break;

                    case "Segments":
                        CharacterDefinitionTable segsTable = GetTable(recElem, defaultTable);
                        var shapeStr = (string) recElem.Element("PhoneticShape");
                        var segments = new Segments(segsTable, shapeStr);
                        node = new Group<Word, ShapeNode>(segments.Shape.Select(n => new Constraint<Word, ShapeNode>(n.Annotation.FeatureStruct))) {Tag = segments};
                        break;
                }

                Debug.Assert(node != null);
                var id = (string) recElem.Attribute("id");
                string groupName;
                if (groupNames == null || string.IsNullOrEmpty(id) || !groupNames.TryGetValue(id, out groupName))
                    yield return node;
                else
                    yield return new Group<Word, ShapeNode>(groupName, node);
            }
        }
示例#39
0
    public virtual Differences VisitQuantifier(Quantifier quantifier1, Quantifier quantifier2){
      Differences differences = new Differences(quantifier1, quantifier2);
      if (quantifier1 == null || quantifier2 == null){
        if (quantifier1 != quantifier2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      Quantifier changes = (Quantifier)quantifier2.Clone();
      Quantifier deletions = (Quantifier)quantifier2.Clone();
      Quantifier insertions = (Quantifier)quantifier2.Clone();

      Differences diff = this.VisitComprehension((Comprehension)quantifier1.Comprehension, (Comprehension)quantifier2.Comprehension);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Comprehension = diff.Changes as Comprehension;
      deletions.Comprehension = diff.Deletions as Comprehension;
      insertions.Comprehension = diff.Insertions as Comprehension;
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      if (quantifier1.QuantifierType == quantifier2.QuantifierType) differences.NumberOfSimilarities++; else differences.NumberOfDifferences++;

      if (differences.NumberOfDifferences == 0){
        differences.Changes = null;
        differences.Deletions = null;
        differences.Insertions = null;
      }else{
        differences.Changes = changes;
        differences.Deletions = deletions;
        differences.Insertions = insertions;
      }
      return differences;
    }
    private void Refresh()
    {
        for (int i = 0; i < amountOfPlayers; i++) {
            playersInventory [i].Clear ();
            game.Players [i].ItemsReturned = 0;

            for (int j = 0; j < game.Players[i].Inventory.Count; j++) {
                SpecificItem specificItem = game.Players [i].Inventory [j].Item;
                SpecificItem specificItemCopy = new SpecificItem (specificItem.Id,
                                                                 specificItem.Name,
                                                                 specificItem.IconId,
                                                                 specificItem.Price,
                                                                 specificItem.Theme,
                                                                 specificItem.GeneralItem);
                Quantifier<SpecificItem> itemToAddWithQTD = new Quantifier<SpecificItem> (game.Players [i].Inventory [j].Quantity, specificItemCopy);
                playersInventory [i].Add (itemToAddWithQTD);
            }
        }

        for (int i = 0; i < amountOfPlayers; i++) {

            playersSpent [i] = game.Players [i].TotalSpent ();
            updateCardboardInv (i);
        }

        updateTotalSpendingAmount ();
    }
示例#41
0
 public override Expression VisitQuantifier(Quantifier quantifier) {
   bool savedInsideQuantifier = this.insideQuantifier;
   this.insideQuantifier = true;
   quantifier.Comprehension = (Comprehension)this.VisitComprehension(quantifier.Comprehension);
   this.insideQuantifier = savedInsideQuantifier;
   if (quantifier.Comprehension == null)
     return null; // Signal error?
   TypeNode comprType = TypeNode.StripModifiers(quantifier.Comprehension.Type);
   if (comprType == null)
     return null; // Signal error?
   if (comprType.TemplateArguments == null || comprType.TemplateArguments.Count != 1)
     return null; // Signal error?
   if (!this.GetTypeView(comprType.TemplateArguments[0]).IsAssignableTo(quantifier.SourceType)) {
     this.HandleError(quantifier, Error.ImpossibleCast, this.GetTypeName(quantifier.SourceType), this.GetTypeName(comprType.TemplateArguments[0]));
   }
   return quantifier;
 }
        /// <summary>
        /// Parse an element and its quantifier, and put it in Item
        /// </summary>
        private Element ParseElement(Block Parent)
        {
            //Go through each of the helper functions to parse an element
            _caret.WS();
            Element el = PENamedBlock(Parent) ??
                   PEFunctionCall(Parent) ??
                   PEKeyword(Parent) ??
                   PEBinaryOperator(Parent) ??
                   PELiteral(Parent) ??
                   PEMemory(Parent) ??
                   PEBlock(Parent);
            //do
            //{
            //    _caret.WhiteSpace();
            //    Item = PENamedBlock(Parent);
            //    if (Item != null) break;
            //    Item = PEFunctionCall(Parent);
            //    if (Item != null) break;
            //    Item = PEKeyword(Parent);
            //    if (Item != null) break;
            //    Item = PEBinaryOperator(Parent);
            //    if (Item != null) break;
            //    Item = PELiteral(Parent);
            //    if (Item != null) break;
            //    Item = PEMemory(Parent);
            //    if (Item != null) break;
            //    Item = PEBlock(Parent);
            //    if (Item != null) break;
            //} while (false);

            if ((el is Literal) || //No quantifier for text literal
                (el is Variable) || //No quantifier for variables
                (el is ControlFlow) || //No quantifier for variables
                (el is BinaryOperator)) //No quantifier for binary operators
            {
                var q = new Quantifier();

                //No quantifier must be specified
                if (ParseQuantifier(ref q))
                    if ((el is ControlFlow) && (((ControlFlow)el).Type == ControlFlow.eType.Call))
                        el.Quantifier = q;
                    else
                        ThrowParseError("No quantifier must be specified here");
            }
            else if (el != null)
            {
                ParseQuantifier(ref el.Quantifier);
                if (el.Quantifier.SourcePosition.IsInit)
                    el.Annotation.SourcePosition.End = el.Quantifier.SourcePosition.End;
            }

            if (el != null)
                AddSourceCodeAnnotation(el);

            return el;
        }
    private void Advance()
    {
        //mudar os inventorios dos jogadores
        for (int i = 0; i < amountOfPlayers; i++) {
            game.Players [i].Inventory.Clear ();

            for (int j = 0; j < playersInventory[i].Count; j++) {
                SpecificItem specificItem = playersInventory [i] [j].Item;
                SpecificItem specificItemCopy = new SpecificItem (specificItem.Id,
                                                                 specificItem.Name,
                                                                 specificItem.IconId,
                                                                 specificItem.Price,
                                                                 specificItem.Theme,
                                                                 specificItem.GeneralItem);
                Quantifier<SpecificItem> itemToAddWithQTD = new Quantifier<SpecificItem> (playersInventory [i] [j].Quantity, specificItemCopy);
                game.Players [i].Inventory.Add (itemToAddWithQTD);
            }
        }

        game.CurrentCheckpoint = Game.Checkpoint.Party;

        GuiManager.Instance.messageCanvas.SetAndShow (MessageCanvasControl.LOADING_MESSAGE, false);
        Loom loom = Loom.Instance;
        loom.RunAsync (() =>
        {
            try {
                GameManager.Instance.Entity.SyncSaveGame (game);
                loom.QueueOnMainThread (() =>
                {
                    GuiManager manager = GuiManager.Instance;
                    manager.messageCanvas.Hide ();
                    manager.Show (manager.partyIntroCanvas);
                });
            } catch (Database.DatabaseException) {
                loom.QueueOnMainThread (() =>
                {
                    GuiManager.Instance.messageCanvas.SetAndShow (
                    "Ocorreu um erro com a Internet.\nPor favor tenta de novo.",
                    true);
                });
            }
        });
    }
        /// <summary>
        /// Parse the Quantifier, right after the element, and update the Item.Quantifier
        /// </summary>
        /// <returns>Returns true if a Quantifier is encountered, false otherwise</returns>
        private bool ParseQuantifier(ref Quantifier Quantifier)
        {
            if (_caret.Match(@"(?<_skw>(?<plus>\&)?((?<keyword>if_any|\?|as_many|\*|at_least_once|\+|never|\!)|\((?<min>\d*)((?<comma>,)(?<max>\d*))?\)))"))
            {
                if (_caret.LastMatch.Groups["plus"].Value != "")
                    Quantifier.Additive = true;

                switch (_caret.LastMatch.Groups["keyword"].Value.ToLower())
                {
                case "if_any":
                case "?":
                    Quantifier.Min = 0;
                    Quantifier.Max = 1;
                    break;
                case "as_many":
                case "*":
                    Quantifier.Min = 0;
                    Quantifier.Max = -1;
                    break;
                case "at_least_once":
                case "+":
                    Quantifier.Min = 1;
                    Quantifier.Max = -1;
                    break;
                case "never":
                case "!":
                    Quantifier.Min = 0;
                    Quantifier.Max = 0;
                    break;
                default:
                    string min = _caret.LastMatch.Groups["min"].Value, max = _caret.LastMatch.Groups["max"].Value;

                    //Get minimum
                    if (min == "") Quantifier.Min = 0;
                    else if (!int.TryParse(min, out Quantifier.Min)) ThrowParseError("Expecting an integer as minimum");

                    //Get maximum
                    if (max == "")
                        if (_caret.LastMatch.Groups["comma"].Value != "")
                            Quantifier.Max = -1;
                        else
                            Quantifier.Max = Quantifier.Min;
                    else if (!int.TryParse(max, out Quantifier.Max)) ThrowParseError("Expecting an integer as maximum");

                    //At least one must be specified
                    if ((min == "") && (max == "")) ThrowParseError("Specify at least minimum or maximum");

                    break;
                }

                if (Quantifier.Additive && ((Quantifier.Max == 0) || (Quantifier.Max ==1)))
                    ThrowParseError("& is redundant");

                Quantifier.SourcePosition = _caret.LastMatch;

                return true;
            }
            else if (_caret.Match(@"(?<_skw>(?<plus>\&))"))
                ThrowParseError("Did you mean & to be text concatenation? Leave a space for concatanation or specify a quantifier");

            return false;
        }
示例#45
0
        internal static IEnumerable<PatternNode<Word, ShapeNode>> DeepCloneExceptBoundaries(this IEnumerable<PatternNode<Word, ShapeNode>> nodes)
        {
            foreach (PatternNode<Word, ShapeNode> node in nodes)
            {
                var constraint = node as Constraint<Word, ShapeNode>;
                if (constraint != null && (constraint.FeatureStruct.IsEmpty || constraint.Type() != HCFeatureSystem.Boundary))
                {
                    yield return constraint.DeepClone();
                    continue;
                }

                var alternation = node as Alternation<Word, ShapeNode>;
                if (alternation != null)
                {
                    var newAlteration = new Alternation<Word, ShapeNode>(alternation.Children.DeepCloneExceptBoundaries());
                    if (newAlteration.Children.Count > 0)
                        yield return newAlteration;
                    continue;
                }

                var group = node as Group<Word, ShapeNode>;
                if (group != null)
                {
                    var newGroup = new Group<Word, ShapeNode>(group.Name, group.Children.DeepCloneExceptBoundaries());
                    if (newGroup.Children.Count > 0)
                        yield return newGroup;
                    continue;
                }

                var quantifier = node as Quantifier<Word, ShapeNode>;
                if (quantifier != null)
                {
                    var newQuantifier = new Quantifier<Word, ShapeNode>(quantifier.MinOccur, quantifier.MaxOccur, quantifier.Children.DeepCloneExceptBoundaries().SingleOrDefault());
                    if (newQuantifier.Children.Count > 0)
                        yield return newQuantifier;
                    continue;
                }

                var pattern = node as Pattern<Word, ShapeNode>;
                if (pattern != null)
                {
                    var newPattern = new Pattern<Word, ShapeNode>(pattern.Name, pattern.Children.DeepCloneExceptBoundaries());
                    if (newPattern.Children.Count > 0)
                        yield return newPattern;
                }
            }
        }
示例#46
0
 // forall{int i in xs; i > 0};
 // ==>
 // "forall{| {i32, $block::a, $1}; ::>(i32,i32){$block::a, 0} |}"
 public override Expression VisitQuantifier(Quantifier quantifier) {
   if (this._string == null){ this._string = new StringBuilder(); }
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       this._string.Append("$_forall");
       break;
     case NodeType.Exists:
       this._string.Append("$_exists");
       break;
     case NodeType.ExistsUnique:
       this._string.Append("$_exists1");
       break;
     case NodeType.Count:
       this._string.Append("$_count");
       break;
     case NodeType.Max:
       this._string.Append("$_max");
       break;
     case NodeType.Min:
       this._string.Append("$_min");
       break;
     case NodeType.Product:
       this._string.Append("$_product");
       break;
     case NodeType.Sum:
       this._string.Append("$_sum");
       break;
     default:
       this._string.Append("??"); // REVIEW: What would be a good default?
       break;
   }
   this.VisitComprehension(quantifier.Comprehension);
   return quantifier;
 }
示例#47
0
 public override Expression VisitQuantifier(Quantifier quantifier) {
   if (quantifier == null) return null;
   quantifier.Comprehension = (Comprehension)this.VisitComprehension(quantifier.Comprehension);
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
     case NodeType.Exists:
     case NodeType.ExistsUnique:
       // Quantifiers that are of type bool --> bool
       quantifier.Type = SystemTypes.Boolean;
       quantifier.SourceType = SystemTypes.Boolean;
       break;
     case NodeType.Count:
       // Quantifiers that are of type bool --> int
       quantifier.Type = SystemTypes.Int32;
       quantifier.SourceType = SystemTypes.Boolean;
       break;
     case NodeType.Max:
     case NodeType.Min:
     case NodeType.Product:
     case NodeType.Sum:
       // Quantifiers that are of type int --> int
       quantifier.Type = SystemTypes.Int32;
       quantifier.SourceType = SystemTypes.Int32;
       break;
     default:
       quantifier.Type = null; // REVIEW: What would be a good default?
       quantifier.SourceType = null;
       break;
   }
   return quantifier;
 }
    //cd = cardboard
    private void updateCardboardInv(int cd)
    {
        //primeiro: selecionar os itens que quero mostrar
        int playerInvCount = playersInventory [cd].Count;
        int numberOfItemsAdded = playerInvCount - itemIndex [cd];
        if (numberOfItemsAdded > 6) // o maximo sao 6 itens de cada vez
            numberOfItemsAdded = 6;
        Quantifier<SpecificItem>[] SelectedItems = new Quantifier<SpecificItem>[numberOfItemsAdded];
        playersInventory [cd].CopyTo (itemIndex [cd], SelectedItems, 0, numberOfItemsAdded);

        //segundo: ver se tenho 5 ou mais itens, se tiver entao fazer active a tudo
        //TODO: verificar se faz sentido adicionar uns ifs.
        int i = 0;
        Transform itemContainer = hooks.CardBoardItems [cd].transform.Find ("ItemsContainer");
        while (i < numberOfItemsAdded) {
            itemContainer.GetChild (i).gameObject.SetActive (true);
            i++;
        }
        while (i < 6) {
            itemContainer.GetChild (i).gameObject.SetActive (false);
            i++;
        }
        ShowCardBoardArrows (cd);

        //terceiro: fazer update tendo em conta o que estou a ver
        ItemCheckBoughtItem boughtItem;
        for (int j = 0; j < numberOfItemsAdded; j++) {
            boughtItem = itemContainer.GetChild (j).GetComponent<ItemCheckBoughtItem> ();
            boughtItem.ItemName = SelectedItems [j].Item.Name;
            boughtItem.ItemID = SelectedItems [j].Item.Id;
            boughtItem.ItemQTD = "x" + SelectedItems [j].Quantity.ToString ();
            boughtItem.ItemPrice = (SelectedItems [j].Item.Price * SelectedItems [j].Quantity);
            boughtItem.ItemImage = AssetsManager.Instance.
                SpecificItemsSprites [SelectedItems [j].Item.IconId];
        }

        //quarto, fazer update do total gasto
        hooks.CardBoardItems [cd].transform.Find ("PlayerSpent").GetComponent<Text> ().text = CultureConverter.ToPrice (playersSpent [cd]);
        //game.Players[cd].Inventory e playersInventory[cd]
    }
示例#49
0
 private IFilter buildQuantifierFilter(MatchResult result, IFilterItem leftHand, Quantifier quantifier, IValueProvider valueProvider)
 {
     MatchResult equalToResult = result.Matches[SqlGrammar.ComparisonOperator.EqualTo];
     if (equalToResult.IsMatch)
     {
         return new EqualToQuantifierFilter(leftHand, quantifier, valueProvider);
     }
     MatchResult notEqualToResult = result.Matches[SqlGrammar.ComparisonOperator.NotEqualTo];
     if (notEqualToResult.IsMatch)
     {
         return new NotEqualToQuantifierFilter(leftHand, quantifier, valueProvider);
     }
     MatchResult lessThanEqualToResult = result.Matches[SqlGrammar.ComparisonOperator.LessThanEqualTo];
     if (lessThanEqualToResult.IsMatch)
     {
         return new LessThanEqualToQuantifierFilter(leftHand, quantifier, valueProvider);
     }
     MatchResult greaterThanEqualToResult = result.Matches[SqlGrammar.ComparisonOperator.GreaterThanEqualTo];
     if (greaterThanEqualToResult.IsMatch)
     {
         return new GreaterThanEqualToQuantifierFilter(leftHand, quantifier, valueProvider);
     }
     MatchResult lessThanResult = result.Matches[SqlGrammar.ComparisonOperator.LessThan];
     if (lessThanResult.IsMatch)
     {
         return new LessThanQuantifierFilter(leftHand, quantifier, valueProvider);
     }
     MatchResult greaterThanResult = result.Matches[SqlGrammar.ComparisonOperator.GreaterThan];
     if (greaterThanResult.IsMatch)
     {
         return new GreaterThanQuantifierFilter(leftHand, quantifier, valueProvider);
     }
     throw new InvalidOperationException();
 }
 /// <summary>
 /// Initializes a new insstance of an GreaterThanEqualToQuantifierFilter.
 /// </summary>
 /// <param name="leftHand">The value being compared to the set of values.</param>
 /// <param name="quantifier">The quantifier to use to compare the value to the set of values.</param>
 /// <param name="valueProvider">The source of values.</param>
 public GreaterThanEqualToQuantifierFilter(IFilterItem leftHand, Quantifier quantifier, IValueProvider valueProvider)
     : base(leftHand, quantifier, valueProvider)
 {
 }
    private static string quantifier2str(Quantifier qtf)
    {
        //forall{comprehension}
        StringBuilder sb=new StringBuilder();
        

        sb.Append(quantifiertype2str(qtf.QuantifierType));
        sb.Append("{");
        sb.Append(comprehension2str(qtf.Comprehension));
        sb.Append("}");
        
        return sb.ToString();
    }
		public IArrayCompareCondition GreaterThan(string arrayPath, string path, object value, Quantifier? quantifier = null) =>
			new GreaterThanArrayCondition(arrayPath, path, value) { Quantifier = quantifier };
示例#53
0
 public virtual Expression VisitQuantifier(Quantifier quantifier){
   if (quantifier == null) return null;
   quantifier.Comprehension = (Comprehension)this.VisitComprehension(quantifier.Comprehension);
   return quantifier;
 }
示例#54
0
 public virtual void VisitQuantifier(Quantifier quantifier)
 {
   if (quantifier == null) return;
   this.VisitComprehension(quantifier.Comprehension);
 }
示例#55
0
 // TODO: Handle default values in the comprehension
 // Q{U i in enumerable, P(i); T(i)}
 public override Expression VisitQuantifier(Quantifier quantifier) {
   if (quantifier == null) return null;
   Comprehension comprehension = quantifier.Comprehension;
   if (comprehension == null) return null;
   Block block = new Block(new StatementList());
   block.HasLocals = true;
   #region Create local to act as accumulator for the quantifier
   Local b = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       b = new Local(Identifier.Empty,SystemTypes.Boolean,block);
       break;
     case NodeType.Exists:
       b = new Local(Identifier.Empty,SystemTypes.Boolean,block);
       break;
     case NodeType.ExistsUnique:
     case NodeType.Count:
     case NodeType.Max:
     case NodeType.Min:
     case NodeType.Product:
     case NodeType.Sum:
       b = new Local(Identifier.Empty,SystemTypes.Int32,block);
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Create local to act as accumulator for the quantifier
   
   if (comprehension.IsDisplay){
     #region Display: Generate a separate if-statement for each element
     Block endBlock = new Block(new StatementList());
     for(int i = 0, n = comprehension.Elements == null ? 0 : comprehension.Elements.Count; i < n; i++){
       #region assign the value of the term to b
       Statement updateB = null;
       switch (quantifier.QuantifierType){
         case NodeType.Forall:
           updateB = new AssignmentStatement(b,comprehension.Elements[i]);
           break;
         case NodeType.Exists:
           updateB = new AssignmentStatement(b,comprehension.Elements[i]);
           break;
         case NodeType.ExistsUnique:
         case NodeType.Count:
           // b := b + (T(i) ? 1 : 0)
           updateB = new AssignmentStatement(b,
             new BinaryExpression(b,
             new TernaryExpression(comprehension.Elements[i], Literal.Int32One, Literal.Int32Zero, NodeType.Conditional, SystemTypes.Int32),
             NodeType.Add));
           break;
         case NodeType.Product:
           // b := b * T(i)
           updateB = new AssignmentStatement(b, new BinaryExpression(b, comprehension.Elements[i], NodeType.Mul));
           break;
         case NodeType.Sum:
           // b := b + T(i)
           updateB = new AssignmentStatement(b, new BinaryExpression(b, comprehension.Elements[i], NodeType.Add));
           break;
         case NodeType.Max:
           // b := b < T(i) ? T(i) : b
           updateB = new AssignmentStatement(b,
             new TernaryExpression(new BinaryExpression(b, comprehension.Elements[i], NodeType.Lt, SystemTypes.Boolean),
             comprehension.Elements[i], b, NodeType.Conditional, SystemTypes.Int32));
           break;
         case NodeType.Min:
           // b := b > T(i) ? T(i) : b
           updateB = new AssignmentStatement(b,
             new TernaryExpression(new BinaryExpression(b, comprehension.Elements[i], NodeType.Gt, SystemTypes.Boolean),
             comprehension.Elements[i], b, NodeType.Conditional, SystemTypes.Int32));
           break;
         default:
           Debug.Assert(false);
           return null;
       }
       block.Statements.Add(updateB);
       #endregion assign the value of the term to b
       #region Test to see if loop should terminate early
       Expression condition = null;
       switch (quantifier.QuantifierType){
         case NodeType.Forall:
           condition = new UnaryExpression(b, NodeType.LogicalNot, SystemTypes.Boolean);
           block.Statements.Add(new Branch(condition, endBlock));
           break;
         case NodeType.Exists:
           condition = b;
           block.Statements.Add(new Branch(condition, endBlock));
           break;
         case NodeType.ExistsUnique:
           condition = new BinaryExpression(b,Literal.Int32One,NodeType.Gt,SystemTypes.Boolean);
           break;
         case NodeType.Count:
         case NodeType.Max:
         case NodeType.Min:
         case NodeType.Product:
         case NodeType.Sum:
           condition = Literal.False; // no short-circuit!! Need to evaluate all of the terms!
           break;
         default:
           Debug.Assert(false);
           return null;
       }
       #endregion Test to see if loop should terminate early
     }
     block.Statements.Add(endBlock);
     #endregion Display: Generate a separate if-statement for each element
   }else {
     #region "True" comprehension
     #region assign the value of the term to the accumulator
     Statement updateB = null;
     switch (quantifier.QuantifierType){
       case NodeType.Forall:
         // b := T(i);
         updateB = new AssignmentStatement(b,comprehension.Elements[0]);
         break;
       case NodeType.Exists:
         // b := T(i);
         updateB = new AssignmentStatement(b,comprehension.Elements[0]);
         break;
       case NodeType.ExistsUnique:
       case NodeType.Count:
         // b := b + T(i) ? 1 : 0; // TODO: is it better to try and generate "b += ..."?
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b,
           new TernaryExpression(comprehension.Elements[0],Literal.Int32One,Literal.Int32Zero,NodeType.Conditional,SystemTypes.Int32),
           NodeType.Add));
         break;
       case NodeType.Product:
         // b := b * T(i)
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b, comprehension.Elements[0], NodeType.Mul));
         break;
       case NodeType.Sum:
         // b := b + T(i)
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b, comprehension.Elements[0], NodeType.Add));
         break;
       case NodeType.Max:
         // b := b < T(i) ? T(i) : b
         updateB = new AssignmentStatement(b,
           new TernaryExpression(new BinaryExpression(b, comprehension.Elements[0], NodeType.Lt, SystemTypes.Boolean),
           comprehension.Elements[0], b, NodeType.Conditional, SystemTypes.Int32));
         break;
       case NodeType.Min:
         // b := b > T(i) ? T(i) : b
         updateB = new AssignmentStatement(b,
           new TernaryExpression(new BinaryExpression(b, comprehension.Elements[0], NodeType.Gt, SystemTypes.Boolean),
           comprehension.Elements[0], b, NodeType.Conditional, SystemTypes.Int32));
         break;
       default:
         Debug.Assert(false);
         return null;
     }
     block.Statements.Add(updateB);
     #endregion assign the value of the term to the accumulator
     #region Generate the "foreach" and "if P(x)" parts
     for (int i = comprehension.BindingsAndFilters.Count - 1; i >= 0; i--) {
       ComprehensionBinding binding = comprehension.BindingsAndFilters[i] as ComprehensionBinding ;
       if (binding != null){
         #region Test to see if loop should terminate early
         Expression condition = null;
         switch (quantifier.QuantifierType){
           case NodeType.Forall:
             condition = new UnaryExpression(b,NodeType.LogicalNot,SystemTypes.Boolean);
             break;
           case NodeType.Exists:
             condition = b;
             break;
           case NodeType.ExistsUnique:
             condition = new BinaryExpression(b,Literal.Int32One,NodeType.Gt,SystemTypes.Boolean);
             break;
           case NodeType.Count:
           case NodeType.Max:
           case NodeType.Min:
           case NodeType.Product:
           case NodeType.Sum:
             condition = Literal.False; // no short-circuit!! Need to evaluate all of the terms!
             break;
           default:
             Debug.Assert(false);
             return null;
         }
         block.Statements.Add(new If(condition,new Block(new StatementList(new Exit())),null));
         #endregion Test to see if loop should terminate early
         #region Wrap everything so far into a loop (either for or foreach)
         Expression forEachTargetVariable = binding.TargetVariable;
         if (binding.AsTargetVariableType != null){
           Local l = new Local(Identifier.For("SS$dummyForEachVar"),binding.SourceEnumerable.Type,block);
           forEachTargetVariable = l;
           Block b2 = new Block(new StatementList(2));
           b2.Statements.Add(new AssignmentStatement(binding.TargetVariable,
             new BinaryExpression(l,new MemberBinding(null,binding.AsTargetVariableType),NodeType.Isinst,binding.AsTargetVariableType)));
           b2.Statements.Add(new If(new BinaryExpression(binding.TargetVariable,new Literal(null,SystemTypes.Type),NodeType.Ne),
             block,null));
           block = b2;
         }
         if (binding.SourceEnumerable== null) 
           return null;
         CollectionEnumerator ce = binding.SourceEnumerable as CollectionEnumerator;
         UnaryExpression u = ce == null ? null : ce.Collection as UnaryExpression;
         BinaryExpression be = u == null ? null : u.Operand as BinaryExpression;
         if (be != null && be.NodeType == NodeType.Range){
           // implement Range with a for-loop
           AssignmentStatement init = new AssignmentStatement(forEachTargetVariable,be.Operand1);
           AssignmentStatement incr = new AssignmentStatement(forEachTargetVariable,
             new BinaryExpression(forEachTargetVariable,new Literal(1,SystemTypes.Int32),NodeType.Add,SystemTypes.Int32));
           Expression cond = new BinaryExpression(forEachTargetVariable,be.Operand2,NodeType.Le,SystemTypes.Boolean);
           #region Add loop invariant "be.Operand1 <= forEachTargetVariable"
           Block invariantBlock = new Block(new StatementList());
           Assertion assertion = new Assertion(new BinaryExpression(be.Operand1, forEachTargetVariable, NodeType.Le, SystemTypes.Boolean));
           assertion.SourceContext = be.SourceContext;
           foreach (Statement s in this.SerializeAssertion(this.currentModule, assertion.Condition, "For loop index must be at least first operand of range.", assertion.SourceContext, "LoopInvariant")) {
             invariantBlock.Statements.Add(s);
           }
           // need to put the generated invariants in the for-loop's condition because that's where VisitFor
           // puts any user-declared invariants.
           invariantBlock.Statements.Add(new ExpressionStatement(cond, cond.SourceContext));
           cond = new BlockExpression(invariantBlock, SystemTypes.Boolean);
           #endregion
           For forloop = new For(new StatementList(init),cond,new StatementList(incr),block);
           block = new Block(new StatementList(forloop));
         }else{
           // Just use the source enumerable as an IEnumerable in a foreach loop
           ForEach fe = new ForEach(binding.SourceEnumerable.Type,forEachTargetVariable,binding.SourceEnumerable,block);
           fe.ScopeForTemporaryVariables = binding.ScopeForTemporaryVariables;
           block = new Block(new StatementList(fe));
         }
         #endregion Wrap everything so far into a loop (either for or foreach)
       }else{ // it's a filter
         block = new Block(new StatementList(new If(comprehension.BindingsAndFilters[i],block,null)));
       }
     }
     #endregion
     #endregion
   }
   #region Choose initial value for accumulator
   Literal initialValue = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       initialValue = Literal.True;
       break;
     case NodeType.Exists:
       initialValue = Literal.False;
       break;
     case NodeType.ExistsUnique:
     case NodeType.Count:
     case NodeType.Sum:
       initialValue = Literal.Int32Zero;
       break;
     case NodeType.Product:
       initialValue = Literal.Int32One;
       break;
     case NodeType.Max:
       initialValue = new Literal(Int32.MinValue, SystemTypes.Int32);
       break;
     case NodeType.Min:
       initialValue = new Literal(Int32.MaxValue, SystemTypes.Int32);
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Choose initial value for accumulator
   #region Set the return value of the quantifier
   Expression valueToReturn = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       valueToReturn = b;
       break;
     case NodeType.Exists:
       valueToReturn = b;
       break;
     case NodeType.ExistsUnique:
       valueToReturn = new BinaryExpression(b,Literal.Int32One,NodeType.Eq,SystemTypes.Boolean);
       break;
     case NodeType.Count:
     case NodeType.Max:
     case NodeType.Min:
     case NodeType.Product:
     case NodeType.Sum:
       valueToReturn = b;
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Set the boolean to return as the value of the quantifier
   BlockExpression returnBlock = new BlockExpression(
     new Block(new StatementList(
     new AssignmentStatement(b,initialValue),
     block,
     new ExpressionStatement(valueToReturn))),
     SystemTypes.Boolean,comprehension.SourceContext);
   if (this.quantifiedVarStack == null) this.quantifiedVarStack = new System.Collections.Generic.Stack<ExpressionList>();
   this.quantifiedVarStack.Push(comprehension.BindingsAndFilters);
   Expression result = this.VisitBlockExpression(returnBlock);
   this.quantifiedVarStack.Pop();
   return result;
 }
    public override void OnFirstShow()
    {
        base.OnFirstShow ();

        hooks = canvas.GetComponent<PartyControlHooks> ();
        if (hooks == null)
            return;

        hooks.OnForwardHook = Forward;
        hooks.OnBackHook = Back;
        hooks.OnRefreshHook = Refresh;
        hooks.OnNextHook = ChangeItem;

        game = Gameplay.GameManager.Instance.ActiveGame;

        hooks.ThemeBG = AssetsManager.Instance.ThemeBackGrounds [game.Theme.IconId];

        indicationStars = new List<int> ();

        //id unico para os itens que estao na party, dois itens iguais teem que ter ids diferentes
        uniqueID = 0;

        inventoryTotalList = new List<Quantifier<SpecificItem>> ();

        //initialize my list with 2 tables and 8 chairs
        SpecificItem specificItemTable = GameManager.Instance.SpecificItems.Find (x => x.Id == 59);
        SpecificItem specificItemChair = GameManager.Instance.SpecificItems.Find (x => x.Id == 58);

        Quantifier <SpecificItem> tables = new Quantifier<SpecificItem> (2, specificItemTable);
        inventoryTotalList.Add (tables);
        Quantifier<SpecificItem> chairs = new Quantifier<SpecificItem> (8, specificItemChair);
        inventoryTotalList.Add (chairs);

        //preender a minha lista de inventorio
        foreach (Player player in game.Players) {
            for (int i = 0; i < player.Inventory.Count; i++) {
                SpecificItem specificItem = player.Inventory [i].Item;
                int index = inventoryTotalList.FindIndex (speItem => speItem.Item.Id == specificItem.Id);
                if (index == -1) {
                    SpecificItem specificItemCopy = new SpecificItem (specificItem.Id,
                                                                      specificItem.Name,
                                                                      specificItem.IconId,
                                                                      specificItem.Price,
                                                                      specificItem.Theme,
                                                                      specificItem.GeneralItem);
                    Quantifier<SpecificItem> itemToAddWithQTD = new Quantifier<SpecificItem> (player.Inventory [i].Quantity, specificItemCopy);
                    inventoryTotalList.Add (itemToAddWithQTD);
                } else {
                    inventoryTotalList [index].Quantity += player.Inventory [i].Quantity;
                }
            }
        }
        inventoryTotalSize = inventoryTotalList.Count ();

        itemsInContainerList = new List<Quantifier<SpecificItem>> ();

        foreach (GameObject item in hooks.ItemsArea) {
            item.GetComponent<ItemGeneral> ().AddItem = AddItem;
        }
        itemIndex = 0;
        updateScene ();
    }
 /// <summary>
 /// Initializes a new insstance of an LessThanQuantifierFilter.
 /// </summary>
 /// <param name="leftHand">The value being compared to the set of values.</param>
 /// <param name="quantifier">The quantifier to use to compare the value to the set of values.</param>
 /// <param name="valueProvider">The source of values.</param>
 public LessThanQuantifierFilter(IFilterItem leftHand, Quantifier quantifier, IValueProvider valueProvider)
     : base(leftHand, quantifier, valueProvider)
 {
 }
示例#58
0
 public virtual Expression VisitQuantifier(Quantifier quantifier1, Quantifier quantifier2)
 {
     if (quantifier1 == null) return null;
     if (quantifier2 == null)
     {
         quantifier1.Comprehension = (Comprehension)this.VisitComprehension(quantifier1.Comprehension, null);
     }
     else
     {
         quantifier1.Comprehension = (Comprehension)this.VisitComprehension(quantifier1.Comprehension, quantifier2.Comprehension);
     }
     return quantifier1;
 }