public IReadOnlyList <RuleOutcome> Analyze(KustoCode code)
        {
            var outcomes = new List <RuleOutcome>();

            foreach (var node in code.Syntax.GetDescendants <BinaryExpression>())
            {
                if (node.Kind == SyntaxKind.ContainsExpression ||
                    node.Kind == SyntaxKind.NotContainsExpression ||
                    node.Kind == SyntaxKind.ContainsCsExpression ||
                    node.Kind == SyntaxKind.NotContainsCsExpression)
                {
                    var ruleOutcome = new RuleOutcome(Name,
                                                      score: 10,
                                                      message:
                                                      $"Avoid using 'contains' operator as it has high compute price." + Environment.NewLine +
                                                      $"Use 'has' operator in cases when full term match is desired.",
                                                      referenceText: node.ToString(),
                                                      severity: Severity.Suggestion,
                                                      category: Category.Performance,
                                                      textStart: node.TextStart);
                    outcomes.Add(ruleOutcome);
                }
            }
            return(outcomes);
        }
Esempio n. 2
0
        /// <summary>
        /// Add rule result to summary.
        /// </summary>
        private void AddToSummary(RuleBlock ruleBlock, RuleOutcome outcome)
        {
            if (!_Summary.TryGetValue(ruleBlock.RuleId, out RuleSummaryRecord s))
            {
                s = new RuleSummaryRecord(
                    ruleId: ruleBlock.RuleId,
                    ruleName: ruleBlock.RuleName,
                    tag: ruleBlock.Tag,
                    info: ruleBlock.Info
                    );

                _Summary.Add(ruleBlock.RuleId, s);
            }

            if (outcome == RuleOutcome.Pass)
            {
                s.Pass++;
                Context.Pass();
            }
            else if (outcome == RuleOutcome.Fail)
            {
                s.Fail++;
                Context.Fail();
            }
            else if (outcome == RuleOutcome.Error)
            {
                s.Error++;
            }
        }
Esempio n. 3
0
        public ActionResult Rules()
        {
            var         ruleinfo    = RuleDiscoveryProvider.GetDescriptions(Assembly.GetAssembly(typeof(VoatRuleContext))).Where(x => x.Enabled).Select(x => new RuleInformationWithOutcome(x)).OrderBy(x => x.Info.Rule.Number).ToList();
            RuleOutcome unevaluated = new RuleOutcome(RuleResult.Unevaluated, "UnevaluatedRule", "0.0", "This rule is unevaluated.");

            if (User.Identity.IsAuthenticated)
            {
                var context = new VoatRuleContext(User);

                //run every rule we can for the current user
                foreach (var rule in VoatRulesEngine.Instance.Rules)
                {
                    var info = ruleinfo.FirstOrDefault(x => x.Info.Rule.Name == rule.Name && x.Info.Rule.Number == rule.Number);
                    if (info != null)
                    {
                        RuleOutcome outcome = null;
                        if (((Rule <VoatRuleContext>)rule).TryEvaluate(context, out outcome))
                        {
                            info.Outcome = outcome;
                        }
                        else
                        {
                            info.Outcome = unevaluated;
                        }
                    }
                }
            }
            return(View("Rules", ruleinfo));
        }
        public async Task <RuleOutcome> EvaluateAsync(Vacancy subject)
        {
            RuleOutcome outcomeResult;

            var outcomeBuilder  = RuleOutcomeDetailsBuilder.Create(RuleId.TitlePopularity);
            var popularityScore = await _popularityService.GetTitlePopularityAsync(subject.ProgrammeId, subject.Title);

            var trainingProgramme = await _apprenticeshipProgrammeProvider.GetApprenticeshipProgrammeAsync(subject.ProgrammeId);

            var data = JsonConvert.SerializeObject(new TitlePopularityData
            {
                TrainingCode  = trainingProgramme.Id,
                TrainingTitle = trainingProgramme.Title,
                TrainingType  = trainingProgramme.ApprenticeshipType.ToString().ToLower()
            });

            if (popularityScore < _qaRulesConfig.TitlePopularityPercentageThreshold)
            {
                outcomeResult = new RuleOutcome(RuleId.TitlePopularity, 100, $"Title is not common for the training specified.", nameof(Vacancy.Title), null, data);
            }
            else
            {
                outcomeResult = new RuleOutcome(RuleId.TitlePopularity, 0, $"Title is common for the training specified.", nameof(Vacancy.Title), null, data);
            }

            var outcome = outcomeBuilder.Add(new RuleOutcome[] { outcomeResult })
                          .ComputeSum();

            return(outcome);
        }
 void AssertResultIsCorrect(RuleResult result, RuleOutcome expectedOutcome, IDictionary <string, object> expectedData)
 {
     Assert.Multiple(() =>
     {
         Assert.That(result, Has.Property(nameof(RuleResult.Outcome)).EqualTo(expectedOutcome), "Outcome is correct");
         Assert.That(result, Has.Property(nameof(RuleResult.Data)).EqualTo(expectedData), "Result data is correct");
     });
 }
Esempio n. 6
0
        public void VerboseConditionResult(int pass, int count, RuleOutcome outcome)
        {
            if (_Logger == null || !_Logger.ShouldWriteVerbose())
            {
                return;
            }

            _Logger.WriteVerbose(string.Concat(GetLogPrefix(), " -- [", pass, "/", count, "] [", outcome, "]"));
        }
Esempio n. 7
0
 protected InvokePipelineBuilderBase(Source[] source)
     : base(source)
 {
     Outcome             = RuleOutcome.Processed;
     _InputPath          = null;
     _VisitTargetObject  = PipelineReceiverActions.PassThru;
     _BindTargetNameHook = PipelineHookActions.BindTargetName;
     _BindTargetTypeHook = PipelineHookActions.BindTargetType;
     _BindFieldHook      = PipelineHookActions.BindField;
 }
Esempio n. 8
0
        public static VoteResponse Create(RuleOutcome outcome, int?recordedValue = null)
        {
            var status = Status.NotProcessed;

            if (outcome.Result == RuleResult.Allowed)
            {
                status = Status.Success;
            }
            if (outcome.Result == RuleResult.Denied)
            {
                status = Status.Denied;
            }
            return(new VoteResponse(status, recordedValue, outcome.ToString()));
        }
        public IReadOnlyList <RuleOutcome> Analyze(KustoCode code)
        {
            var outcomes = new List <RuleOutcome>();

            foreach (var node in code.Syntax.GetDescendants <BinaryExpression>())
            {
                if (!node.Right.IsConstant && !node.Left.IsConstant)
                {
                    continue;
                }

                if (node.Kind == SyntaxKind.EqualExpression ||
                    node.Kind == SyntaxKind.HasExpression ||
                    node.Kind == SyntaxKind.NotEqualExpression ||
                    node.Kind == SyntaxKind.NotHasExpression ||
                    node.Kind == SyntaxKind.StartsWithExpression ||
                    node.Kind == SyntaxKind.NotStartsWithExpression)
                {
                    string constValue = null;
                    if (node.Right.IsConstant && node.Right.ResultType.Name == "string")
                    {
                        constValue = node.Right.ConstantValue?.ToString();
                    }
                    else if (node.Left.IsConstant && node.Left.ResultType.Name == "string")
                    {
                        constValue = node.Left.ConstantValue?.ToString();
                    }

                    if (string.IsNullOrEmpty(constValue))
                    {
                        continue;
                    }

                    if (constValue.Length < 4)
                    {
                        var ruleOutcome = new RuleOutcome(Name,
                                                          score: 10,
                                                          message: Description,
                                                          referenceText: node.ToString(),
                                                          severity: Severity.Suggestion,
                                                          category: Category.Performance,
                                                          textStart: node.TextStart);
                        outcomes.Add(ruleOutcome);
                    }
                }
            }
            return(outcomes);
        }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RuleResult"/> class.
        /// </summary>
        /// <param name="outcome">The outcome of validation.</param>
        /// <param name="data">An optional collection of arbitrary key/value data which is provided by the validation rule logic.</param>
        /// <param name="exception">
        /// An optional exception which caused the validation process to error.  This parameter must be <see langword="null"/>
        /// if the <paramref name="outcome"/> is not <see cref="RuleOutcome.Errored"/>.
        /// </param>
        /// <exception cref="ArgumentException">
        /// If the <paramref name="outcome"/> is not <see cref="RuleOutcome.Errored"/> but the <paramref name="exception"/>
        /// is not <see langword="null"/>.
        /// </exception>
        public RuleResult(RuleOutcome outcome,
                          IDictionary <string, object> data = null,
                          Exception exception = null)
        {
            if (outcome != RuleOutcome.Errored && !(exception is null))
            {
                var message = String.Format(GetExceptionMessage("MayNotHaveExceptionIfNotErroredOutcome"),
                                            nameof(RuleResult),
                                            $"{nameof(RuleOutcome)}.{nameof(RuleOutcome.Errored)}");
                throw new ArgumentException(message, nameof(exception));
            }

            Outcome   = outcome;
            Data      = new ReadOnlyDictionary <string, object>(data ?? new Dictionary <string, object>());
            Exception = exception;
        }
Esempio n. 11
0
        /// <summary>
        /// Add a record to the result.
        /// </summary>
        /// <param name="ruleRecord">The record after processing a rule.</param>
        internal void Add(RuleRecord ruleRecord)
        {
            _Outcome = GetWorstCase(ruleRecord.Outcome);
            _Time   += ruleRecord.Time;
            _Total++;

            if (ruleRecord.Outcome == RuleOutcome.Error)
            {
                _Error++;
            }
            if (ruleRecord.Outcome == RuleOutcome.Fail)
            {
                _Fail++;
            }
            _Record.Add(ruleRecord);
        }
Esempio n. 12
0
 private RuleOutcome GetWorstCase(RuleOutcome outcome)
 {
     if (outcome == RuleOutcome.Error || _Outcome == RuleOutcome.Error)
     {
         return(RuleOutcome.Error);
     }
     else if (outcome == RuleOutcome.Fail || _Outcome == RuleOutcome.Fail)
     {
         return(RuleOutcome.Fail);
     }
     else if (outcome == RuleOutcome.Pass || _Outcome == RuleOutcome.Pass)
     {
         return(RuleOutcome.Pass);
     }
     return(outcome);
 }
        public void GetPriorityShouldReturn7ForAnAttributeWithEveryPropertySet(string stringVal,
                                                                               RuleOutcome outcome,
                                                                               Type type)
        {
            var sut = new FailureMessageStrategyAttribute
            {
                MemberName          = stringVal,
                Outcome             = outcome,
                ParentValidatedType = type,
                RuleInterface       = type,
                RuleName            = stringVal,
                RuleType            = type,
                ValidatedType       = type,
            };

            Assert.That(() => sut.GetPriority(), Is.EqualTo(7));
        }
Esempio n. 14
0
        internal InvokeRulePipeline(PipelineContext context, Source[] source, PipelineReader reader, PipelineWriter writer, RuleOutcome outcome)
            : base(context, source, reader, writer)
        {
            HostHelper.ImportResource(source: Source, context: context);
            _RuleGraph = HostHelper.GetRuleBlockGraph(source: Source, context: context);
            RuleCount  = _RuleGraph.Count;

            if (RuleCount == 0)
            {
                Context.WarnRuleNotFound();
            }

            _Outcome           = outcome;
            _Summary           = new Dictionary <string, RuleSummaryRecord>();
            _ResultFormat      = context.Option.Output.As.Value;
            _SuppressionFilter = new RuleSuppressionFilter(context.Option.Suppression);
        }
Esempio n. 15
0
        public Task <RuleOutcome> EvaluateAsync(Vacancy subject)
        {
            var outcomeBuilder = RuleOutcomeDetailsBuilder.Create(RuleId);

            var score = subject.IsAnonymous ? 100 : 0;

            var outcomeResult = new RuleOutcome(
                RuleId,
                score,
                "Anonymous employer",
                nameof(Vacancy.EmployerName));

            var outcome = outcomeBuilder.Add(new [] { outcomeResult })
                          .ComputeSum();

            return(Task.FromResult(outcome));
        }
Esempio n. 16
0
        protected override void DoSolve()
        {
            RuleOutcome outcome;
            GameState   actualGameState  = Coordinator.CurrentGameState.Clone();
            Position    initialPosition  = actualGameState.YourOriginalCell.Position;
            int         initialY         = initialPosition.Y;
            GameState   mutableGameState = RulesEngineHelper.GetInitialGameState(actualGameState);

            try
            {
                if (initialY <= 14)  // TODO: Remove hard-coding!
                {
                    outcome = SolveWhenStartingInNorthernHemisphere(mutableGameState, actualGameState);
                }
                else
                {
                    // TODO: outcome = SolveWhenStartingInSouthernHemisphere(mutableGameState, newGameState);
                    outcome = new RuleOutcome
                    {
                        Status = RuleStatus.NoFurtherSuggestions
                    };
                }
            }
            catch (Exception exc)
            {
                outcome = new RuleOutcome
                {
                    Status          = RuleStatus.ExceptionThrown,
                    ExceptionThrown = exc
                };
            }

            if (outcome.Status == RuleStatus.NextMoveSuggested)
            {
                actualGameState.MakeMove(outcome.SuggestedMove);
                Coordinator.SetBestMoveSoFar(actualGameState);
            }
            else
            {
                NegaMaxSolver solver = new NegaMaxSolver();
                DelegateSolvingToAnotherSolver(solver);
            }

            return;
        }
Esempio n. 17
0
 internal RuleRecord(string ruleId, string ruleName, PSObject targetObject, string targetName, string targetType, TagSet tag, RuleHelpInfo info, Hashtable field, RuleOutcome outcome = RuleOutcome.None, RuleOutcomeReason reason = RuleOutcomeReason.None)
 {
     RuleId        = ruleId;
     RuleName      = ruleName;
     TargetObject  = targetObject;
     TargetName    = targetName;
     TargetType    = targetType;
     Outcome       = outcome;
     OutcomeReason = reason;
     Info          = info;
     if (tag != null)
     {
         Tag = tag.ToHashtable();
     }
     if (field != null && field.Count > 0)
     {
         Field = field;
     }
 }
Esempio n. 18
0
 internal BooleanWriter(WriteOutput output, RuleOutcome outcome)
     : base(output)
 {
     _Outcome = outcome;
 }
Esempio n. 19
0
 internal BooleanWriter(PipelineWriter output, RuleOutcome outcome)
     : base(output, null)
 {
     _Outcome = outcome;
 }
Esempio n. 20
0
 public void Limit(RuleOutcome outcome)
 {
     Outcome = outcome;
 }
Esempio n. 21
0
 private bool ShouldOutput(RuleOutcome outcome)
 {
     return(_Outcome == RuleOutcome.All ||
            (_Outcome == RuleOutcome.None && outcome == RuleOutcome.None) ||
            (_Outcome & outcome) > 0);
 }
Esempio n. 22
0
 private bool ShouldOutput(RuleOutcome outcome)
 {
     return(_ResultFormat == ResultFormat.Detail &&
            (_Outcome == RuleOutcome.All || (outcome & _Outcome) > 0));
 }
Esempio n. 23
0
        public void ShouldMap()
        {
            var shortDescriptionProfanityCheckRuleOutcome =
                new RuleOutcome(
                    RuleId.ProfanityChecks,
                    100,
                    "Profanity 'drat' found in 'ShortDescription'",
                    "ShortDescription",
                    new List <RuleOutcome>(), "{\"Profanity\" : \"drat\",\"Occurrences\" : 1}");

            var titleProfanityCheckRuleOutcome = new RuleOutcome(
                RuleId.ProfanityChecks,
                0,
                "No profanities found in 'Title'",
                "Title");

            var profanityChecksRuleOutcome = new RuleOutcome(
                RuleId.ProfanityChecks,
                100,
                "No profanities found in 'Title', Profanity 'drat' found in 'ShortDescription', etc",
                "",
                new List <RuleOutcome>
            {
                shortDescriptionProfanityCheckRuleOutcome,
                titleProfanityCheckRuleOutcome
            }
                );

            var sut = new ReviewFieldIndicatorMapper(new RuleMessageTemplateRunner());

            var review = new VacancyReview
            {
                ManualQaFieldIndicators = new List <ManualQaFieldIndicator>
                {
                    new ManualQaFieldIndicator
                    {
                        IsChangeRequested = false,
                        FieldIdentifier   = FieldIdentifiers.Title
                    },
                    new ManualQaFieldIndicator
                    {
                        IsChangeRequested = true,
                        FieldIdentifier   = FieldIdentifiers.ShortDescription
                    }
                },
                AutomatedQaOutcomeIndicators = new List <RuleOutcomeIndicator>
                {
                    new RuleOutcomeIndicator
                    {
                        IsReferred    = false,
                        RuleOutcomeId = titleProfanityCheckRuleOutcome.Id
                    },
                    new RuleOutcomeIndicator
                    {
                        IsReferred    = true,
                        RuleOutcomeId = shortDescriptionProfanityCheckRuleOutcome.Id
                    }
                },
                AutomatedQaOutcome = new RuleSetOutcome {
                    RuleOutcomes = new List <RuleOutcome> {
                        profanityChecksRuleOutcome
                    }
                }
            };

            var vm = sut.MapFromFieldIndicators(ReviewFieldMappingLookups.GetPreviewReviewFieldIndicators(), review).ToList();

            vm.Count.Should().Be(1);

            var shortDescription = vm.Single(v => v.ReviewFieldIdentifier == FieldIdentifiers.ShortDescription);

            shortDescription.ManualQaText.Should().NotBeNullOrEmpty();

            shortDescription.AutoQaTexts.Count.Should().Be(1);
            shortDescription.AutoQaTexts[0].Should().Be("Brief overview contains the phrase 'drat'");
        }
 public RuleOutcomeDetailsBuilder Add(RuleOutcome outcome)
 {
     return(Add(new[] { outcome }));
 }
        public void InitializePendulumState(Step <PendulumState> step, GameState gameStateAfterStep, GameState currentGameState, RuleOutcome outcome)
        {
            if (outcome.Status != RuleStatus.NextMoveSuggested && outcome.Status == RuleStatus.NoFurtherSuggestions)
            {
                return;
            }

            Position position    = gameStateAfterStep.YourCell.Position;
            Block    filledBlock = new Block
            {
                LeftX   = position.X,
                RightX  = position.X,
                TopY    = position.Y,
                BottomY = position.Y
            };

            step.RootStep.State = new PendulumState
            {
                Level       = 1,
                FilledBlock = filledBlock
                              // TODO: LeftGap =
                              // TODO: RightGap =
            };
        }
 ConstraintResult GetConstraintResult(RuleOutcome outcome, object actual)
 => new ConstraintResult(this, actual, outcome == expectedOutcome);
 public ValidationResultConstraint(RuleOutcome expectedOutcome)
 {
     this.expectedOutcome = expectedOutcome;
     Description          = $"Validation result with outcome {expectedOutcome}";
 }
Esempio n. 28
0
        private RuleOutcome SolveWhenStartingInNorthernHemisphere(GameState mutableGameState, GameState actualGameState)
        {
            RuleOutcome outcome;
            Position    nextPosition   = mutableGameState.YourOriginalCell.Position;
            int         nextMoveNumber = 0;

            Block leftBlock  = GetInitialLeftBlock(mutableGameState);
            Block rightBlock = GetInitialRightBlock(mutableGameState);

            /* Move to the equator: */
            int distance = 14 - nextPosition.Y;     // Remove hard-coding

            for (int i = 0; i < distance; i++)
            {
                nextMoveNumber++;
                nextPosition = new Position(nextPosition.X, nextPosition.Y + 1);
                outcome      = RulesEngineHelper.MoveToNextPosition(mutableGameState, actualGameState, nextPosition, nextMoveNumber);
                if (outcome.Status != RuleStatus.NoFurtherSuggestions)
                {
                    return(outcome);
                }

                // TODO: Update leftBlock and rightBlock
            }

            // Set up a state object to track various information:
            Position position = mutableGameState.YourCell.Position;
            NorthernPendulumBlock filledBlock = new NorthernPendulumBlock
            {
                LeftX     = position.X,
                RightX    = position.X,
                TopLeftY  = position.Y,
                TopRightY = position.Y,
                BottomY   = position.Y
            };

            // Swing the pendulum back and forth, increasing its length with each iteration:
            for (int pendulumLevel = 0; pendulumLevel < 13; pendulumLevel++)
            {
                Position targetPosition;
                int      targetX, targetY;

                // *** Move to first position:
                Dijkstra.Perform(mutableGameState);

                // Only move to first and second position if this reduces the opponent's gap:
                // ... bool isOpponentCloserToGapOnLeft =

                if (pendulumLevel % 2 == 0)
                {
                    // Going left:
                    targetX = Helper.NormalizedX(filledBlock.LeftX - 1);
                    targetY = filledBlock.TopLeftY - 1;
                }
                else
                {
                    // Going right:
                    targetX = Helper.NormalizedX(filledBlock.RightX + 1);
                    targetY = filledBlock.TopRightY - 1;
                }
                targetPosition = new Position(targetX, targetY);
                outcome        = RulesEngineHelper.MoveToPositionAlongAnyRoute(mutableGameState, actualGameState, ref nextMoveNumber, targetPosition);
                if (outcome.Status != RuleStatus.NoFurtherSuggestions)
                {
                    return(outcome);
                }

                // Update filled block:
                if (pendulumLevel % 2 == 0)
                {
                    // Going left:
                    filledBlock.LeftX    = targetX;
                    filledBlock.TopLeftY = targetY;
                }
                else
                {
                    // Going right:
                    filledBlock.RightX    = targetX;
                    filledBlock.TopRightY = targetY;
                }

                // *** Move to second position:
                Dijkstra.Perform(mutableGameState);

                if (pendulumLevel % 2 == 0)
                {
                    // Going left:
                    targetX = Helper.NormalizedX(filledBlock.LeftX - 1);
                }
                else
                {
                    // Going right:
                    targetX = Helper.NormalizedX(filledBlock.RightX + 1);
                }
                targetY        = filledBlock.BottomY + 1;
                targetPosition = new Position(targetX, targetY);
                outcome        = RulesEngineHelper.MoveToPositionAlongAnyRoute(mutableGameState, actualGameState, ref nextMoveNumber, targetPosition);
                if (outcome.Status != RuleStatus.NoFurtherSuggestions)
                {
                    return(outcome);
                }

                // Update filled block:
                if (pendulumLevel % 2 == 0)
                {
                    // Going left:
                    filledBlock.LeftX = targetX;
                }
                else
                {
                    // Going right:
                    filledBlock.RightX = targetX;
                }
                filledBlock.BottomY = targetY;

                // *** Move to third position:
                Dijkstra.Perform(mutableGameState);

                if (pendulumLevel % 2 == 0)
                {
                    // Going right:
                    targetX = filledBlock.RightX;
                }
                else
                {
                    // Going left:
                    targetX = filledBlock.LeftX;
                }
                targetY        = filledBlock.BottomY;
                targetPosition = new Position(targetX, targetY);
                outcome        = RulesEngineHelper.MoveToPositionAlongAnyRoute(mutableGameState, actualGameState, ref nextMoveNumber, targetPosition);
                if (outcome.Status != RuleStatus.NoFurtherSuggestions)
                {
                    return(outcome);
                }
            }

            // No more pre-programmed moves to make... hand over to normal solver now:
            outcome = new RuleOutcome
            {
                Status = RuleStatus.NoFurtherSuggestions
            };

            return(outcome);
        }