コード例 #1
0
        public CSG(HashSet <string> NTS, Alphabet TS, string S, Rules rules)
        {
            this.NTS   = NTS;
            this.TS    = TS;
            this.S     = S;
            this.rules = rules;
            if (NTS.Intersect(TS).Count() > 0)
            {
                throw new ArgumentException("NTS and TS must be disjoint!");
            }
            if (!NTS.Contains(S))
            {
                throw new ArgumentException("S must be contained in NTS!");
            }
            if (rules.Keys.Any(rs => TS.IsSupersetOf(rs.Symbols)))
            {
                throw new ArgumentException($"Left-hand side of all rules must contain NTS!");
            }
            var  allSymbols = new HashSet <string>(NTS.Union(TS));
            bool x          = rules.Any(r => !allSymbols.IsSupersetOf(r.Key.Symbols));
            bool y          = rules.Any(r => r.Value.Any(rs => !rs[0].Equals("") && !allSymbols.IsSupersetOf(rs.Symbols)));

            if (rules.Any(r => !allSymbols.IsSupersetOf(r.Key.Symbols) || r.Value.Any(rs => !rs[0].Equals("") && !allSymbols.IsSupersetOf(rs.Symbols))))
            {
                throw new ArgumentException($"Rules can not contain symbols that are neither NTS nor TS!");
            }
        }
コード例 #2
0
        /// <summary>
        /// Adds the table rule.
        /// </summary>
        /// <param name="name">Name of the table rule</param>
        /// <param name="description">Description of th rule</param>
        /// <param name="builder">Builder used to create the rule definition (see <see cref="TableRule"/> for details)</param>
        /// <exception cref="DmnBuilderException">Throws <see cref="DmnBuilderException"/> when the definition has already been built</exception>
        /// <exception cref="ArgumentNullException"> when the <paramref name="name"/> is not provided</exception>
        /// <exception cref="ArgumentException"> when the <paramref name="name"/> is empty or whitespace</exception>
        /// <exception cref="ArgumentNullException"> when the <paramref name="builder"/> is not provided</exception>
        /// <exception cref="DmnBuilderException">Throws <see cref="DmnBuilderException"/> when the rule with given <paramref name="name"/> already exists</exception>
        public TableDecision WithRule(string name, string description, Func <TableRule.TableRuleInputBuilder, TableRule.TableRuleOutputBuilder> builder)
        {
            if (IsBuilt)
            {
                throw Logger.Error <DmnBuilderException>($"Decision is already built");
            }
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Missing rule name", nameof(name));
            }
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (Rules.Any(r => r.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)))
            {
                throw Logger.Error <DmnBuilderException>($"Rule {name} already exists");
            }

            var rule = new TableRule(Variables, Decisions, InputsByRef, OutputsByRef, RulesInternal.Count, name, description);

            builder.Invoke(new TableRule.TableRuleInputBuilder(rule));

            RulesInternal.Add(rule);
            return(this);
        }
コード例 #3
0
            /// <summary>
            /// 判断活动在指定平台是否有效
            /// </summary>
            /// <param name="platform">适用平台</param>
            /// <returns></returns>
            public bool IsValid(Platform platform)
            {
                var now       = DateTime.Now;
                var available = ((Platform & platform) == platform);//检查当前促销是否适用于给定平台

                return(Status && StartedOn < now && now < StoppedOn && available && Rules.Any(x => x.Status));
            }
コード例 #4
0
        public override void AppendCSS(Env env, Context context)
        {
            if (env.Compress && Rules != null && !Rules.Any())
            {
                return;
            }

            env.Output.Append(Name);

            if (!string.IsNullOrEmpty(Identifier))
            {
                env.Output.Append(" ");
                env.Output.Append(Identifier);
            }

            if (Rules != null)
            {
                // Append pre comments as we out put each rule ourselves
                if (Rules.PreComments)
                {
                    env.Output.Append(Rules.PreComments);
                }

                AppendRules(env);
                env.Output.Append("\n");
            }
            else
            {
                env.Output
                .Append(" ")
                .Append(Value)
                .Append(";\n");
            }
        }
コード例 #5
0
ファイル: Validation.cs プロジェクト: zeroyou/FormEditor
        public bool IsValidFor(IEnumerable <FieldWithValue> allCollectedFieldValues, IPublishedContent content)
        {
            // swap the rule fields for the actual fields collected by the form model
            foreach (var rule in Rules)
            {
                if (rule.Field == null)
                {
                    // should not happen!
                    continue;
                }
                var collectedField = allCollectedFieldValues.FirstOrDefault(f => f.Name == rule.Field.Name);
                if (collectedField != null)
                {
                    rule.Field = collectedField;
                }
            }

            Invalid = Rules.Any(r => r.IsApplicable == false)
                      // it's impossible to validate the rule if we have frontend only conditions in play
                                ? false
                      // the validation fails if all rules are fulfilled
                                : Rules.All(r => r.IsFulfilledBy(allCollectedFieldValues, content));

            return(Invalid == false);
        }
コード例 #6
0
        /// <summary>
        /// Generate SonarQube specifc rules based on Roslyn based diagnostics
        /// </summary>
        public Rules GenerateRules(IEnumerable<DiagnosticAnalyzer> analyzers)
        {
            if (analyzers == null)
            {
                throw new ArgumentNullException("analyzers");
            }

            Rules rules = new Rules();

            foreach (DiagnosticAnalyzer analyzer in analyzers)
            {
                Rules analyzerRules = GetAnalyzerRules(analyzer);
                
                foreach (Rule analyzerRule in analyzerRules)
                {
                    if (rules.Any(r => String.Equals(r.Key, analyzerRule.Key, Rule.RuleKeyComparer)))
                    {
                        logger.LogWarning(UIResources.RuleGen_DuplicateKey, analyzerRule.Key);
                        continue;
                    }

                    rules.Add(analyzerRule);
                }
            }
            
            return rules;
        }
コード例 #7
0
        /// <summary>
        /// Adds a new rule (both to the <see cref="RulesFile"/> and the in memory <see cref="Rules"/> collection).
        /// </summary>
        /// <param name="f"></param>
        /// <param name="action"></param>
        /// <returns>The new / existing rule that covers failure</returns>
        protected IsIdentifiableRule Add(Failure f, RuleAction action)
        {
            var rule = new IsIdentifiableRule
            {
                Action    = action,
                IfColumn  = f.ProblemField,
                IfPattern = RulesFactory.GetPattern(this, f),
                As        =
                    action == RuleAction.Ignore?
                    FailureClassification.None :
                    f.Parts.Select(p => p.Classification).FirstOrDefault()
            };

            //don't add identical rules
            if (Rules.Any(r => r.AreIdentical(rule)))
            {
                return(rule);
            }

            Rules.Add(rule);

            var contents = Serialize(rule, true);

            File.AppendAllText(RulesFile.FullName, contents);
            History.Push(new OutBaseHistory(rule, contents));

            return(rule);
        }
コード例 #8
0
ファイル: Scanner.cs プロジェクト: juleswijt/AdventOfCode2020
        public long CalculateDeparture()
        {
            var remainingTickets = new List <Ticket>();

            foreach (var ticket in Tickets)
            {
                var valid = true;
                foreach (var number in ticket.Values)
                {
                    if (Rules.Any(x => x.IsInRange(number)))
                    {
                        continue;
                    }

                    valid = false;
                }

                if (valid)
                {
                    remainingTickets.Add(ticket);
                }
            }


            var ruleOrder = new Dictionary <Rule, List <int> >();

            foreach (var ticket in remainingTickets)
            {
                var ticketOrder = Rules.ToDictionary(rule => rule, rule => new List <int>());
                for (var index = 0; index < ticket.Values.Length; index++)
                {
                    var number = ticket.Values[index];

                    foreach (var rule in Rules.Where(x => x.IsInRange(number)))
                    {
                        ticketOrder[rule].Add(index);
                    }
                }

                if (ruleOrder.Count == 0)
                {
                    ruleOrder = ticketOrder;
                    continue;
                }

                foreach (var(rule, indexes) in ruleOrder.ToArray())
                {
                    var ticketIndex = ticketOrder[rule];
                    ruleOrder[rule] = indexes.Intersect(ticketIndex).ToList();
                }
            }

            FilterRules(ruleOrder);

            return(FilteredRules
                   .Where(x => x.Value.Name.StartsWith("departure"))
                   .Select(x => x.Key)
                   .Aggregate(1L, (current, key) => current * MyTicket.Values[key]));
        }
コード例 #9
0
        public void AddRuleIfMissing(string name, string message, RuleType ruleType = RuleType.DataAttribute)
        {
            if (Rules.Any(rule => rule.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
            {
                return;
            }

            AddRule(name, message, ruleType);
        }
コード例 #10
0
        public override void AppendCSS(Env env)
        {
            if (Rules == null || !Rules.Any())
            {
                return;
            }

            ((Ruleset)Evaluate(env)).AppendCSS(env, new Context());
        }
コード例 #11
0
ファイル: Mapper.cs プロジェクト: ferhatcandas/TStack.MongoDB
 /// <summary>
 /// ruleName for easyly access this rule
 /// </summary>
 /// <param name="ruleName"></param>
 /// <returns></returns>
 public Mapper <TEntity> Rule(string ruleName)
 {
     if (Rules.Any(x => x.Name == ruleName))
     {
         throw new ArgumentException($"{nameof(ruleName)} is exist on rule list");
     }
     _rule = new Rule <TEntity>();
     _rule.SetName(ruleName);
     return(this);
 }
コード例 #12
0
 public void Validate()
 {
     if (Deck.Any() && Rules.Any())
     {
         Results.Clear();
         foreach (Rule rule in Rules)
         {
             Results.Add(rule.Validate(Deck));
         }
     }
 }
コード例 #13
0
        public IEnumerator <TToken> GetEnumerator()
        {
            if (Rules == null)
            {
                throw new Exception("Rules must be set");
            }

            if (EofToken == null)
            {
                throw new Exception("EofToken must be set");
            }

            _length = int.MaxValue;
            _source = _sourceEnumerable.GetEnumerator();
            _read   = new List <char>(16);

            _index = 0;

            Line   = 1;
            Column = 1;

            while (_index < _length)
            {
                SkipWhiteSpace();

                if (SkipComment())
                {
                    continue;
                }

                if (_index >= _length)
                {
                    break;
                }

                StartLine   = Line;
                StartColumn = Column;

                var    ch    = PeekChar();
                TToken token = null;

                if (!Rules.Any(rule => rule(ch, out token)))
                {
                    throw Error("Unexpected character '{0}'", ch);
                }

                yield return(token);
            }

            while (true)
            {
                yield return(EofToken);
            }
        }
コード例 #14
0
        public virtual IQueryable <T> ApplyRules <T>(IQueryable <T> collection)
        {
            if (Rules.Any())
            {
                var predicate = Rules
                                .GetStateRule <T>()
                                .Predicate;
                collection = collection
                             .Where(predicate);
            }

            return(collection);
        }
コード例 #15
0
        public virtual IEnumerable <T> ApplyRules <T>(IEnumerable <T> collection)
        {
            if (Rules.Any())
            {
                var predicate = Rules
                                .GetStateRule <T>()
                                .Predicate
                                .Compile();
                collection = collection
                             .Where(predicate);
            }

            return(collection);
        }
コード例 #16
0
        public Transaction[] Parse(string input, Stock userStock, Stock externalStock, TransactionType defaultOutcome,
                                   TransactionType defaultIncome, bool generateMissingStocks = false)
        {
            Balances.Clear();
            if (userStock != null)
            {
                Balances[userStock] = new Dictionary <DateTime, decimal>();
            }

            var output = new List <Transaction>();
            var lines  = input.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string line in lines)
            {
                var elements = ColumnSplitter == null
                                   ? line.Count(x => x == ';') >= (Rules.Any() ? Rules.Max(x => x.Index) : 0)
                                         ? line.Split(';')
                                         : line.Split(new[] { line.Contains("\",\"") ? "\",\"" : "," }, StringSplitOptions.None)
                                   : line.Split(new[] { ColumnSplitter }, StringSplitOptions.None);

                elements = elements.Select(x => x.Replace("\"", string.Empty)).ToArray();
                var transaction = new Transaction
                {
                    ExternalStock = externalStock,
                    UserStock     = userStock
                };
                transaction.Positions.Add(new Position());

                bool match = Rules.Any();
                foreach (var rule in Rules)
                {
                    if (!MatchRule(rule, elements, transaction, defaultIncome, defaultOutcome, userStock, generateMissingStocks))
                    {
                        match = false;
                        break;
                    }
                }

                transaction.RecalculateId();
                if (match)
                {
                    output.Add(transaction);
                }
            }

            return(output.ToArray());
        }
コード例 #17
0
ファイル: Scanner.cs プロジェクト: juleswijt/AdventOfCode2020
        public long CalculateErrorRate()
        {
            var errorRate = 0;

            foreach (var ticket in Tickets)
            {
                foreach (var number in ticket.Values)
                {
                    if (!Rules.Any(x => x.IsInRange(number)))
                    {
                        errorRate += number;
                    }
                }
            }

            return(errorRate);
        }
コード例 #18
0
        public override void AppendCSS(Env env)
        {
            try
            {
                if (Rules == null || !Rules.Any())
                {
                    return;
                }

                var evaluated = (Root)Evaluate(env);
                evaluated.Rules.InsertRange(0, evaluated.CollectImports().Cast <Node>());
                evaluated.AppendCSS(env, new Context());
            }
            catch (ParsingException e)
            {
                throw Error(e);
            }
        }
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     if (Rules != null && Rules.Any())
     {
         writer.WritePropertyName("rules");
         writer.WriteStartArray();
         foreach (var item in Rules)
         {
             writer.WriteStringValue(item);
         }
         writer.WriteEndArray();
     }
     writer.WritePropertyName("@odata.type");
     writer.WriteStringValue(ODataType);
     writer.WritePropertyName("name");
     writer.WriteStringValue(Name);
     writer.WriteEndObject();
 }
コード例 #20
0
ファイル: RuleService.cs プロジェクト: tomtangrx/Papercut
 public void Handle(PapercutClientReadyEvent @event)
 {
     _logger.Debug("Attempting to Load Rules from {RuleFileName} on AppReady", RuleFileName);
     try
     {
         // accessing "Rules" forces the collection to be loaded
         if (Rules.Any())
         {
             _logger.Information(
                 "Loaded {RuleCount} from {RuleFileName}",
                 Rules.Count,
                 RuleFileName);
         }
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Error loading rules from file {RuleFileName}", RuleFileName);
     }
 }
コード例 #21
0
        public void Handle(PapercutClientReadyEvent @event)
        {
            _logger.Information("Attempting to Load Rules from {RuleFileName} on AppReady", RuleFileName);

            try
            {
                // accessing "Rules" forces the collection to be loaded
                if (Rules.Any())
                {
                    _logger.Information(
                        "Loaded {RuleCount} from {RuleFileName}",
                        Rules.Count,
                        RuleFileName);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error loading rules from file {RuleFileName}", RuleFileName);
            }

            // rules loaded/updated event
            this._messageBus.Publish(new RulesUpdatedEvent(this.Rules.ToArray()));

            Rules.CollectionChanged += RuleCollectionChanged;
            HookPropertyChangedForRules(Rules);

            // the backend service handles rules running if it's online
            if (!_coordinator.IsBackendServiceOnline)
            {
                _logger.Debug("Setting up Rule Dispatcher Observable");

                // observe message watcher and run rules when a new message arrives
                Observable.FromEventPattern <NewMessageEventArgs>(
                    e => _messageWatcher.NewMessage += e,
                    e => _messageWatcher.NewMessage -= e,
                    TaskPoolScheduler.Default)
                .DelaySubscription(TimeSpan.FromSeconds(1))
                .Subscribe(e => _rulesRunner.Run(Rules.ToArray(), e.EventArgs.NewMessage));
            }
        }
コード例 #22
0
ファイル: Day16Solution.cs プロジェクト: johnboker/AoC2020
        public void Solve2()
        {
            var validTickets = NearbyTickets.Where(a => a.IsValid(Rules)).ToList();
            var columns      = validTickets.First().Numbers.Count();

            for (var i = 0; i < columns; i++)
            {
                for (var r = 0; r < Rules.Count(); r++)
                {
                    var rule = Rules[r];
                    var ruleValidForAllTickets = validTickets.All(a => rule.IsValid(a.Numbers[i]));
                    if (ruleValidForAllTickets)
                    {
                        Rules[r].Columns.Add(i);
                    }
                }
            }

            var doneRules = new List <Rule>();

            while (Rules.Any(r => r.Columns.Count() > 1))
            {
                var singleRule = Rules.FirstOrDefault(a => a.Columns.Count() == 1);
                doneRules.Add(singleRule);
                Rules.Remove(singleRule);
                Rules.ForEach(r => r.Columns.Remove(singleRule.Columns[0]));
            }

            var sum = 1D;

            foreach (var r in doneRules.Where(a => a.Name.StartsWith("departure")))
            {
                sum *= MyTicket.Numbers[r.Columns[0]];
            }

            Console.WriteLine(sum);
        }
コード例 #23
0
        private void AddRule_Executed(UInt16?priority)
        {
            if (!priority.HasValue)
            {
                UInt16 lowPriority;
                if (!Rules.Any())
                {
                    lowPriority = 1;
                }
                else
                {
                    lowPriority = (UInt16)(Rules.Max(x => x.Priority) + 1);
                }

                var newRule = new FormattingRuleData(lowPriority);
                Rules.Add(newRule);
                this.SelectedRule = newRule;

                return;
            }

            var templateRule = Rules.FirstOrDefault(x => x.Priority == priority.Value);

            if (templateRule != null)
            {
                var newRule = templateRule.Clone();
                newRule.Priority++;

                foreach (var rule in Rules.Where(x => x.Priority >= newRule.Priority))
                {
                    rule.Priority++;
                }

                Rules.Insert(Rules.IndexOf(templateRule) + 1, newRule);
                this.SelectedRule = newRule;
            }
        }
コード例 #24
0
 /// <summary>
 /// Checks for similar rules
 /// </summary>
 /// <param name="rule"></param>
 /// <returns></returns>
 public bool IsSimilarRuleExists(Rule rule)
 {
     return(Rules.Any(r => r == rule));
 }
コード例 #25
0
 private bool CheckReverseRules(string stringToCheck)
 {
     return(Rules.Any(x => !x.ConformsToRule(stringToCheck)));
 }
コード例 #26
0
        public void Load(Assembly assembly)
        {
            var types = assembly.GetTypes();

            foreach (var type in types)
            {
                if (!type.IsSubclassOf(typeof(Rule)))
                {
                    continue;
                }

                var friendlyNameAttribute =
                    (FriendlyNameAttribute)Attribute.GetCustomAttribute(type, typeof(FriendlyNameAttribute));

                var name = friendlyNameAttribute != null ? friendlyNameAttribute.Name : type.Name;

                var disableAttribute =
                    (DisabledAttribute)Attribute.GetCustomAttribute(type, typeof(DisabledAttribute));

                var group          = string.Empty;
                var groupAttribute =
                    (GroupAttribute)Attribute.GetCustomAttribute(type, typeof(GroupAttribute));

                if (groupAttribute != null)
                {
                    group = groupAttribute.Name;
                }

                var priority          = uint.MaxValue;
                var priorityAttribute =
                    (PriorityAttribute)Attribute.GetCustomAttribute(type, typeof(PriorityAttribute));

                if (priorityAttribute != null)
                {
                    priority = priorityAttribute.Priority;
                }

                IList <object> parameters = new List <object>();

                if (ServiceProvider != null)
                {
                    parameters = ResolveDependencies(type);
                }

                var rule = (Rule)Activator.CreateInstance(type, parameters.ToArray());
                rule.Priority = priority;
                rule.Name     = name;
                rule.Group    = group;

                if (disableAttribute != null)
                {
                    DisabledRules.Add(rule);
                    continue;
                }

                Rules.Add(rule);
            }

            if (Rules.Any() == false)
            {
                throw new ArgumentException(
                          "A referenced assembly must contain at least one subclass implementation of the abstract class Rule.");
            }
        }
コード例 #27
0
 public override bool ShouldImport(LogEntry logEntry) =>
 Rules.Any(rule => rule.ShouldImport(logEntry));
コード例 #28
0
 public bool IsSatisfiedBy(ClaimsPrincipal principal)
 {
     return(Operator == RuleSetOperator.Or
         ? Rules.Any(r => r.IsSatisfiedBy(principal))
         : Rules.All(r => r.IsSatisfiedBy(principal)));
 }
コード例 #29
0
 internal bool ContainsRule(string id)
 {
     return(Rules.Any(rule => rule.Id == id));
 }
コード例 #30
0
 public override bool IsMatch(DateTime day)
 {
     return(Rules.Any(r => r.IsMatch(day)));
 }
コード例 #31
0
ファイル: Day16.cs プロジェクト: gabr/AdventOfCode
 public bool IsTicketFieldValid(int ticketField) =>
 Rules.Any(rule => IsFieldValidForRule(ticketField, rule.Ranges));