Example #1
0
        public override bool Matches(Expression E, MatchContext Matched)
        {
            Expression matched;
            if (Matched.TryGetValue(Right, out matched))
            {
                if (Left.Matches(E ^ Binary.Divide(1, matched), Matched))
                    return true;
            }

            // x^0 = 1.
            if (E.EqualsOne() && Right.Matches(0, Matched))
                return true;
            // 0^x = 0.
            if (E.EqualsZero() && Left.Matches(0, Matched))
                return true;

            Binary PE = E as Power;
            if (!ReferenceEquals(PE, null) && Matched.TryMatch(() => Left.Matches(PE.Left, Matched) && Right.Matches(PE.Right, Matched)))
                return true;

            // If the exponent matches 1, E can match left.
            if (Matched.TryMatch(() => Right.Matches(1, Matched) && Left.Matches(E, Matched)))
                return true;

            if (Right.IsInteger() && Left.Matches(ComputerAlgebra.Power.New(E, Binary.Divide(1, Right)).Evaluate(), Matched))
                return true;

            return false;
        }
Example #2
0
        public override bool Matches(Expression E, MatchContext Matched)
        {
            // Move the constants in this pattern to E.
            IEnumerable<Expression> PTerms = Terms;
            IEnumerable<Expression> Constants = PTerms.OfType<Constant>();
            if (Constants.Any())
            {
                E = Binary.Subtract(E, New(Constants)).Evaluate();
                PTerms = PTerms.Except(Constants, RefComparer);
            }

            IEnumerable<Expression> ETerms = TermsOf(E);

            // Try starting the match at each term of the pattern.
            foreach (Expression p in PTerms)
            {
                // Remaining terms of the pattern.
                Expression P = New(PTerms.ExceptUnique(p, RefComparer));

                // If p is a variable, we have to handle the possibility that more than one term of E might match this term.
                if (p is Variable)
                {
                    // Check if p has already been matched. If it has, treat it as a constant and match the rest of the terms.
                    Expression matched;
                    if (Matched.TryGetValue(p, out matched))
                    {
                        // p has already been matched. Remove it out of E and match the remainder of the pattern.
                        if (P.Matches(Binary.Subtract(E, matched).Evaluate(), Matched))
                            return true;
                    }
                    else
                    {
                        // Try matching p to the various combinations of the terms of E.
                        for (int i = 1; i <= ETerms.Count(); ++i)
                        {
                            foreach (IEnumerable<Expression> e in ETerms.Combinations(i))
                                if (Matched.TryMatch(() =>
                                    p.Matches(New(e), Matched) &&
                                    P.Matches(New(ETerms.ExceptUnique(e, RefComparer)), Matched)))
                                    return true;
                        }

                        // Try matching p to identity.
                        if (Matched.TryMatch(() => p.Matches(0, Matched) && P.Matches(E, Matched)))
                            return true;
                    }
                }
                else
                {
                    // If p is not a variable, try matching it to any of the terms of E.
                    foreach (Expression e in ETerms)
                        if (Matched.TryMatch(() =>
                            p.Matches(e, Matched) &&
                            P.Matches(New(ETerms.ExceptUnique(e, RefComparer)), Matched)))
                            return true;
                }
            }

            return false;
        }
Example #3
0
			internal override void BackwardsMatch(MatchContext context)
			{
				foreach (ILPattern pattern in _sequence)
				{
					pattern.BackwardsMatch(context);
					if (!context.Success || context.Instruction == null) break;
				}
			}
Example #4
0
        internal bool TryBackwardsMatch(MatchContext context)
        {
            var checkpoint = context.Instruction;
            BackwardsMatch(context);
            if (context.Success) return true;

            context.Reset(checkpoint);
            return false;
        }
Example #5
0
			internal override void BackwardsMatch(MatchContext context)
			{
				if (context.Instruction == null)
				{
					context.Success = false;
					return;
				}
				context.Success = context.Instruction.OpCode == _code;
				context.MoveBackwards();
			}
Example #6
0
        /// <summary>
        /// Check if a call to this function with the given arguments matches an expression.
        /// </summary>
        /// <param name="Arguments"></param>
        /// <param name="E"></param>
        /// <param name="Matched"></param>
        /// <returns></returns>
        public virtual bool CallMatches(IEnumerable<Expression> Arguments, Expression E, MatchContext Matched)
        {
            Call EF = E as Call;
            if (!ReferenceEquals(EF, null))
            {
                if (!Equals(EF.Target))
                    return false;
                if (Arguments.Count() != EF.Arguments.Count())
                    return false;

                return Matched.TryMatch(() => Arguments.Reverse().Zip(EF.Arguments.Reverse(), (p, e) => p.Matches(e, Matched)).All());
            }

            return false;
        }
        public override void VisitField(FieldDefinition field)
        {
            base.VisitField(field);

            if (field.HasConstant)
            {
                var stringValue = field.Constant as string;
                if (stringValue != null && this.IsMatch(stringValue))
                {
                    var context = new MatchContext("String Match", this.mySearchString);
                    context["String"] = stringValue;
                    this.Aggregator.AddMatch(field, context);
                }
            }
        }
        private void CheckFieldReferenceAndAddIfMatch(Instruction instr, MethodDefinition method, string operation)
        {
            var field = (FieldReference)instr.Operand;

            if (this.myDeclaringTypeNamesToSearch.Contains(field.DeclaringType.Name))
            {
                foreach (var searchField in this.mySearchFields)
                {
                    if (field.DeclaringType.IsEqual(searchField.DeclaringType, false) && field.Name == searchField.Name && field.FieldType.IsEqual(searchField.FieldType))
                    {
                        var context = new MatchContext(operation, string.Format("{0} {1}", searchField.DeclaringType.FullName, searchField.Name));
                        this.Aggregator.AddMatch(instr, method, false, context);
                    }
                }
            }
        }
        public override void VisitType(TypeDefinition type)
        {
            if (type.BaseType == null)
            {
                return;
            }

            foreach (var searchType in this.mySearchBaseTypes)
            {
                if (type.BaseType.IsEqual(searchType, false))
                {
                    var context = new MatchContext("Derives from", searchType.Print());
                    this.Aggregator.AddMatch(type, context);
                    break;
                }
            }
        }
        public override void VisitType(TypeDefinition type)
        {
            if (type.Interfaces == null)
            {
                return;
            }

            TypeDefinition searchItf = null;
            foreach (TypeReference itf in type.Interfaces)
            {
                if (this.IsMatchingInterface(itf, out searchItf))
                {
                    var context = new MatchContext();
                    context[MatchContext.MatchReason] = "Implements interface";
                    context[MatchContext.MatchItem] = searchItf.Print();
                    this.Aggregator.AddMatch(type, context);
                }
            }
        }
        public override void VisitMethod(MethodDefinition method)
        {
            if (method.Body == null)
            {
                return;
            }

            MethodDefinition matchingMethod = null;
            foreach (Instruction ins in method.Body.Instructions)
            {
                if (Code.Callvirt == ins.OpCode.Code) // normal instance call
                {
                    if (this.IsMatchingMethod((MethodReference)ins.Operand, out matchingMethod))
                    {
                        var context = new MatchContext("Called method", matchingMethod.Print(myMethodFormat));
                        context["Type"] = matchingMethod.DeclaringType.FullName;
                        this.Aggregator.AddMatch(ins, method, false, context);
                    }
                }

                if (Code.Call == ins.OpCode.Code) // static function call
                {
                    if (this.IsMatchingMethod((MethodReference)ins.Operand, out matchingMethod))
                    {
                        var context = new MatchContext("Called method", matchingMethod.Print(myMethodFormat));
                        context["Type"] = matchingMethod.DeclaringType.FullName;
                        this.Aggregator.AddMatch(ins, method, false, context);
                    }
                }

                if (Code.Ldftn == ins.OpCode.Code) // Load Function Pointer for delegate call
                {
                    if (this.IsMatchingMethod((MethodReference)ins.Operand, out matchingMethod))
                    {
                        var context = new MatchContext("Called method", matchingMethod.Print(myMethodFormat));
                        context["Type"] = matchingMethod.DeclaringType.FullName;
                        this.Aggregator.AddMatch(ins, method, false, context);
                    }
                }
            }
        }
        public override void VisitField(FieldDefinition field)
        {
            TypeDefinition matchingType = null;
            if (this.IsMatching(this.mySearchTypeNames, this.mySearchTypes, field.FieldType, out matchingType))
            {
                var context = new MatchContext("Has Field Of Type", matchingType.Print());
                this.Aggregator.AddMatch(field, context);
                return;
            }

            var genType = field.FieldType as GenericInstanceType;
            if (genType != null)
            {
                foreach (TypeReference generic in genType.GenericArguments)
                {
                    if (this.IsMatching(this.mySearchTypeNames, this.mySearchTypes, generic, out matchingType))
                    {
                        var context = new MatchContext("Has Field Of Type", matchingType.Print());
                        this.Aggregator.AddMatch(field, context);
                        return;
                    }
                }
            }
        }
Example #13
0
 public MatchRepository(IOptions <DatabaseSettings> settings)
 {
     _context = new MatchContext(settings);
 }
Example #14
0
 protected abstract MatchContext Match(Ust ust, MatchContext context);
 public MatchRepository(MatchContext context)
 {
     _context = context;
 }
 public MatchRepository(MatchContext context)
 {
     _context = context ?? throw new ArgumentNullException(nameof(context));
 }
Example #17
0
 public override IEnumerable <(MatchResult, IEnumerable <Value>)> MatchSequence(IEnumerable <Value> exprs, MatchContext context)
 {
     return(_pattern.MatchSequence(exprs, context).Where(pair => ApplyCondition(pair.Item1)));
 }
Example #18
0
			internal override void BackwardsMatch(MatchContext context)
			{
				if (!_a.TryBackwardsMatch(context))
				{
					_b.BackwardsMatch(context);
				}
			}
 public StopQueueingForGameCommandHandler(MatchContext matchContext)
 {
     this.matchContext = matchContext;
 }
Example #20
0
 public override MatchContext Match(Expression expression, MatchContext context)
 {
     return(context.AddMatch(expression));
 }
 public TournamentStore(MatchContext matchContext)
 {
     _matchContext = matchContext;
 }
 public ThreadsController(MatchContext context, UserManager <User> userManager)
 {
     _context     = context;
     _userManager = userManager;
 }
        public override void VisitType(TypeDefinition type)
        {
            Tracer.Info(Level.L5, myType, "VisitType", "Visiting type {0}", new LazyFormat(() => type.Print()));

            TypeDefinition matchingType = null;
            // Find type float in class Class : IDictionary<int,float>
            foreach (TypeReference typeRef in type.Interfaces)
            {
                if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, typeRef, out matchingType))
                {
                    var context = new MatchContext(ImplementsInterfaceReason, matchingType.Print());
                    this.Aggregator.AddMatch(type, context);
                }
            }

            // find type float in class Class : KeyValuePair<int,float>
            if (type.BaseType != null)
            {
                if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, type.BaseType, out matchingType))
                {
                    var context = new MatchContext(InheritsFromReason, matchingType.Print());
                    this.Aggregator.AddMatch(type, context);
                }
            }
        }
 public override void VisitField(FieldDefinition field)
 {
     TypeDefinition matchingType = null;
     // exclude enums which would be marked as self users otherwise
     if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, field.FieldType, out matchingType) && field.FieldType.FullName != field.DeclaringType.FullName)
     {
         var context = new MatchContext(FieldTypeReason, matchingType.Print());
         this.Aggregator.AddMatch(field, context);
     }
 }
        public override void VisitLocals(Collection<VariableDefinition> locals, MethodDefinition declaringMethod)
        {
            base.VisitLocals(locals, declaringMethod);

            foreach (VariableDefinition variable in locals)
            {
                TypeDefinition matchingType = null;
                if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, variable.VariableType, out matchingType))
                {
                    var context = new MatchContext(LocalVariableReason, matchingType.Print());
                    this.Aggregator.AddMatch(declaringMethod, context);
                }
            }
        }
Example #26
0
        /// <summary>
        /// If a matcher in the sequence doesn't match, then it doesn't match
        /// </summary>
        /// <param name="context"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public override MatchResult Matches(MatchContext context, TokenEntity startToken, PatternMatcher nextPatternMatcher)
        {
            var tokenEntity = startToken;
            int start       = startToken?.Start ?? 0;
            int end         = 0;
            int minMatches  = 1;
            int maxMatches  = this.MaxMatches;

            switch (Ordinality)
            {
            case Ordinality.One:
                maxMatches = 1;
                break;

            case Ordinality.OneOrMore:
                break;

            case Ordinality.ZeroOrMore:
                minMatches = 0;
                break;

            case Ordinality.ZeroOrOne:
                minMatches = 0;
                maxMatches = 1;
                break;
            }

            int         matched     = 0;
            MatchResult matchResult = null;
            bool        found;

            do
            {
                found = false;
                for (int iPattern = 0; iPattern < PatternMatchers.Count; iPattern++)
                {
                    var patternMatcher = PatternMatchers[iPattern];
                    var result         = patternMatcher.Matches(context, tokenEntity, nextPatternMatcher);

                    if (result.Matched)
                    {
                        found = true;
                        matched++;
                        matchResult = result;
                        end         = Math.Max(result.End, end);
                        tokenEntity = matchResult.NextToken;
                        if (matched == maxMatches)
                        {
                            // then we are done;
                            return(new MatchResult(true, this, tokenEntity, start, end)
                            {
                                NextPatternMatch = result.NextPatternMatch
                            });
                        }
                        break;
                    }
                    else
                    {
                        if (matchResult != null)
                        {
                            matchResult.NextPatternMatch = result.NextPatternMatch;
                        }
                    }
                }
            } while (found && tokenEntity != null);

            if (matched < minMatches)
            {
                // not matched.
                return(new MatchResult(false, this)
                {
                    NextPatternMatch = matchResult?.NextPatternMatch
                });
            }

            return(new MatchResult(true, this, tokenEntity, start, end)
            {
                NextPatternMatch = matchResult?.NextPatternMatch
            });
        }
Example #27
0
 public MatchStore(MatchContext matchContext)
 {
     _matchContext = matchContext;
 }
Example #28
0
 public RaceRecordsController(MatchContext context, UserManager <User> userManager)
 {
     _context     = context;
     _userManager = userManager;
 }
Example #29
0
		internal abstract void BackwardsMatch(MatchContext context);
 public override bool CallMatches(IEnumerable<Expression> Arguments, Expression E, MatchContext Matched)
 {
     return base.CallMatches(Arguments, E, Matched) || LogE.Matches(E, Matched);
 }
 public PlayerStore(MatchContext matchContext)
 {
     if (matchContext == null) throw new ArgumentNullException("matchContext");
     _matchContext = matchContext;
 }
        public override MatchContext Match(ObjectCreateExpression objectCreateExpression, MatchContext context)
        {
            MatchContext newContext = Type.MatchUst(objectCreateExpression.Type, context);

            if (!newContext.Success)
            {
                return(newContext);
            }

            newContext = Arguments.Match(objectCreateExpression.Arguments, newContext);

            return(newContext.AddUstIfSuccess(objectCreateExpression));
        }
        public override void VisitMethodBody(MethodBody body)
        {
            var bSkipNext = false;

            foreach (Instruction instr in body.Instructions)
            {
                if (bSkipNext)
                {
                    bSkipNext = false;
                    continue;
                }

                TypeDefinition matchingType = null;

                if (instr.OpCode.Code == Code.Newobj || instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Calli || instr.OpCode.Code == Code.Callvirt)
                {
                    var genericMethodRef = instr.Operand as GenericInstanceMethod;
                    var method = instr.Operand as MethodReference;

                    TypeReference methodDeclaringType = null;
                    if (genericMethodRef != null)
                    {
                        methodDeclaringType = genericMethodRef.DeclaringType;

                        // Search for method references with type arguments like
                        // cl.GenericMethod<decimal, sbyte>(0, 1);
                        foreach (TypeReference generic in genericMethodRef.GenericArguments)
                        {
                            if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, generic, out matchingType))
                            {
                                var context = new MatchContext(UsedInGenericMethodReason, matchingType.Print());
                                this.Aggregator.AddMatch(instr, body.Method, true, context);
                            }
                        }
                    }
                    else if (method != null)
                    {
                        methodDeclaringType = method.DeclaringType;
                    }
                    else
                    {
                        // be robust. The type System.Web.Util.CalliHelper for example has strange opcodes inside it:
                        // .method assembly static void ArglessFunctionCaller(native int fp, object o) cil managed
                        // calli method instance void *()
                        continue;
                    }

                    if (methodDeclaringType != null)
                    {
                        if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, methodDeclaringType, out matchingType))
                        {
                            MatchContext context;
                            if (instr.OpCode.Code == Code.Newobj || method.Name == ".ctor")
                            {
                                context = new MatchContext(CtorCalledReason, method.Print(MethodPrintOption.Parameters | MethodPrintOption.ShortNames));
                            }
                            else
                            {
                                context = new MatchContext(MethodFromTypeCalledReason, method.Print(myMethodDisplayMode));
                            }
                            this.Aggregator.AddMatch(instr, body.Method, false, context);
                        }
                    }
                }

                // resolve using statements where IDisposable on a known type is called
                else if (instr.OpCode.Code == Code.Constrained || instr.OpCode.Code == Code.Initobj)
                {
                    // e.g.    using (new AsyncFlowControl()) {} calls Dispose via the IDisposable interface with a type constraint
                    // constrained [mscorlib]System.Threading.AsyncFlowControl
                    // callvirt instance void [mscorlib]System.IDisposable::Dispose()

                    var typeRef = (TypeReference)instr.Operand;

                    if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, typeRef, out matchingType))
                    {
                        MethodReference calledMethod = null;
                        if (instr.Next.OpCode.Code == Code.Callvirt)
                        {
                            calledMethod = (MethodReference)instr.Next.Operand;
                            bSkipNext = true;
                        }

                        MatchContext context;
                        if (instr.OpCode.Code == Code.Initobj)
                        {
                            context = new MatchContext(InitObjCalledReason, typeRef.FullName);
                        }
                        else
                        {
                            context = new MatchContext(InterfaceCall, string.Format("{0} on type {1}", calledMethod == null ? "" : calledMethod.Print(myMethodDisplayMode), typeRef.FullName));
                        }

                        this.Aggregator.AddMatch(instr, body.Method, true, context);
                    }
                }
                else if (instr.OpCode.Code == Code.Castclass)
                {
                    // Find type casts which are represented by the castclass opcode
                    // castclass [mscorlib]System.IDisposable
                    var typeRef = (TypeReference)instr.Operand;
                    if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, typeRef, out matchingType))
                    {
                        this.Aggregator.AddMatch(instr, body.Method, false, new MatchContext(CastReason, matchingType.Print()));
                    }
                }
                else if (instr.OpCode.Code == Code.Ldtoken && instr.Next.OpCode.Code == Code.Call)
                {
                    // Find typeof(Type) occurances which are represented in IL code as
                    // ldtoken [mscorlib]System.IDisposable
                    // call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
                    var typeRef = instr.Operand as TypeReference;

                    if (typeRef != null)
                    {
                        if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, typeRef, out matchingType))
                        {
                            var method = instr.Next.Operand as MethodReference;
                            if (method != null)
                            {
                                if (method.DeclaringType.FullName == "System.Type" && method.Name == "GetTypeFromHandle")
                                {
                                    this.Aggregator.AddMatch(instr.Next, body.Method, false, new MatchContext(TypeOfReason, matchingType.Print()));
                                }
                            }
                        }
                    }
                }
            }
        }
Example #34
0
        public static void Initialize(MatchContext context)
        {
            //context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            if (!context.Matches.Any())
            {
                var d = new DataPoint()
                {
                    X    = 1,
                    Y    = 1,
                    Z    = 2,
                    Time = DateTime.Now
                };
                var d2 = new DataPoint()
                {
                    X    = 3,
                    Y    = 9,
                    Z    = 2,
                    Time = DateTime.Now
                };
                var d3 = new DataPoint()
                {
                    X    = 1,
                    Y    = 6,
                    Z    = 2,
                    Time = DateTime.Now
                };
                var d4 = new DataPoint()
                {
                    X    = 8,
                    Y    = 0,
                    Z    = -3,
                    Time = DateTime.Now
                };


                var player = new Player()
                {
                    Name    = "Bob",
                    Active  = true,
                    Matches = new List <Match>()
                };

                var player2 = new Player()
                {
                    Name    = "Bob2",
                    Matches = new List <Match>()
                };

                var team = new Team()
                {
                    Name    = "Red Kangaroos",
                    Players = new List <Player>()
                };
                var team2 = new Team()
                {
                    Name    = "Blue Pandas",
                    Players = new List <Player>()
                };
                team.Players.Add(player);
                team2.Players.Add(player2);
                var match1 = new Match()
                {
                    Start   = DateTime.Now,
                    Active  = true,
                    Players = new List <Player>(),
                    Teams   = new List <Team>(),
                    Data    = new List <Data>()
                };
                var match2 = new Match()
                {
                    Start   = DateTime.Now,
                    Players = new List <Player>(),
                    Teams   = new List <Team>(),
                    Data    = new List <Data>()
                };
                var data = new Data()
                {
                    Accel  = new List <DataPoint>(),
                    Linear = new List <DataPoint>(),
                    Orient = new List <DataPoint>(),
                    Match  = match1,
                    Player = player,
                    Hits   = 4
                };
                data.Accel.Add(d4);
                data.Accel.Add(d);
                data.Linear.Add(d);
                data.Linear.Add(d4);
                data.Orient.Add(d4);
                data.Orient.Add(d);
                match1.Data.Add(data);
                //match2.Data.Add(data);

                var data2 = new Data()
                {
                    Accel  = new List <DataPoint>(),
                    Linear = new List <DataPoint>(),
                    Orient = new List <DataPoint>(),
                    Match  = match1,
                    Player = player2,
                    Hits   = 4
                };
                data2.Accel.Add(d2);
                data2.Accel.Add(d3);
                data2.Linear.Add(d3);
                data2.Linear.Add(d2);
                data2.Orient.Add(d2);
                data2.Orient.Add(d3);
                match1.Data.Add(data2);
                //match2.Data.Add(data2);

                match1.Teams.Add(team);
                match1.Teams.Add(team2);
                match1.Players.Add(player);
                match1.Players.Add(player2);
                context.Matches.Add(match1);


                match2.Teams.Add(team);
                match2.Teams.Add(team2);
                match2.Players.Add(player);
                match2.Players.Add(player2);
                context.Matches.Add(match2);

                /*
                 * var match2 = new Match()
                 * {
                 *  Start = DateTime.Now,
                 *  Players = new List<Player>()
                 * };*/

                //team.Players.Add(player);
                //match1.Players.Add(player);
                //match1.Teams[0] = team;

                /*
                 * player.Team = team;
                 * player.Matches.Add(match1);
                 * context.Players.Add(player);
                 */
                context.SaveChanges();
            }
        }
Example #35
0
 protected override bool OnMatch(MatchContext context, Expression node)
 {
     return(node.CodeNodeType != CodeNodeType.BinaryExpression);
 }
Example #36
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, NationalityContext nationalityContext, PlayerContext leagueContext, MatchContext matchContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
            nationalityContext.EnsureSeedDataForContext();
            leagueContext.EnsureSeedDataForContext();
            matchContext.EnsureSeedDataForContext();
            app.UseCors("MyPolicy");

            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Player, PlayerDto>(MemberList.Destination)
                .ForMember(dest => dest.PositionName, op => op.MapFrom(src => src.Position.ShortCode))
                .ForMember(dest => dest.TeamName, op => op.MapFrom(src => src.Team.Name))
                .ForMember(dest => dest.DateOfBirth, op => op.MapFrom(src => src.DateOfBirth.ToString("MM/dd/yyyy")));

                cfg.CreateMap <Manager, ManagerDto>(MemberList.Destination);
                cfg.CreateMap <Player, PlayerNameSurnameDto>(MemberList.Destination);
                cfg.CreateMap <Nationality, NationalityNameDto>(MemberList.Destination);
                cfg.CreateMap <League, LeagueNameNationalityDto>(MemberList.Destination);

                cfg.CreateMap <Player, PlayerExtendedDto>(MemberList.Destination)
                .ForMember(dest => dest.DateOfBirth, op => op.MapFrom(src => src.DateOfBirth.ToString("d")))
                .ForMember(dest => dest.PositionName, op => op.MapFrom(src => src.Position.PositionName))
                .ForMember(dest => dest.LeagueName, op => op.MapFrom(src => src.Team.League.Name))
                .ForMember(dest => dest.TeamName, op => op.MapFrom(src => src.Team.Name))
                .ForMember(dest => dest.NationalLeagueName,
                           op => op.MapFrom(src => src.Team.League.Nationality.Name))
                .ForMember(dest => dest.FlagNational,
                           op => op.MapFrom(src => src.Nationality.PngImage))
                .ForMember(dest => dest.FlagNationalLeague,
                           op => op.MapFrom(src => src.Team.League.Nationality.PngImage));

                cfg.CreateMap <Match, MatchDto>(MemberList.Destination)
                .ForMember(dest => dest.MatchDay, op => op.MapFrom(src => src.MatchDay.ToString("MM/dd/yyyy")));

                cfg.CreateMap <Team, TeamDto>(MemberList.Destination)
                .ForMember(dest => dest.NameStadium, op => op.MapFrom(src => src.Stadium.Name))
                .ForMember(dest => dest.CapacityStadium, op => op.MapFrom(src => src.Stadium.Capacity))
                .ForMember(dest => dest.NameLeague, op => op.MapFrom(src => src.League.Name));

                cfg.CreateMap <Match, MatchDetailsDto>(MemberList.Destination)
                .ForMember(dest => dest.MatchDay, op => op.MapFrom(src => src.MatchDay.ToString("MM/dd/yyyy")))
                .ForMember(dest => dest.Attendance, op => op.MapFrom(src => src.MatchDetails.Attendance))
                .ForMember(dest => dest.HomeTeamShots, op => op.MapFrom(src => src.MatchDetails.HomeTeamShots))
                .ForMember(dest => dest.AwayTeamShots, op => op.MapFrom(src => src.MatchDetails.AwayTeamShots))
                .ForMember(dest => dest.HomeTeamShotsOnTarget, op => op.MapFrom(src => src.MatchDetails.HomeTeamShotsOnTarget))
                .ForMember(dest => dest.AwayTeamShotsOnTarget, op => op.MapFrom(src => src.MatchDetails.AwayTeamShotsOnTarget))
                .ForMember(dest => dest.HomeTeamWoodWork, op => op.MapFrom(src => src.MatchDetails.HomeTeamWoodWork))
                .ForMember(dest => dest.AwayTeamWoodWork, op => op.MapFrom(src => src.MatchDetails.AwayTeamWoodWork))
                .ForMember(dest => dest.HomeTeamCorners, op => op.MapFrom(src => src.MatchDetails.HomeTeamCorners))
                .ForMember(dest => dest.AwayTeamCorners, op => op.MapFrom(src => src.MatchDetails.AwayTeamCorners))
                .ForMember(dest => dest.HomeTeamFoulsCommitted, op => op.MapFrom(src => src.MatchDetails.HomeTeamFoulsCommitted))
                .ForMember(dest => dest.AwayTeamFoulsCommitted, op => op.MapFrom(src => src.MatchDetails.AwayTeamFoulsCommitted))
                .ForMember(dest => dest.HomeTeamOffsides, op => op.MapFrom(src => src.MatchDetails.HomeTeamOffsides))
                .ForMember(dest => dest.AwayTeamOffsides, op => op.MapFrom(src => src.MatchDetails.AwayTeamOffsides))
                .ForMember(dest => dest.HomeYellowCards, op => op.MapFrom(src => src.MatchDetails.HomeYellowCards))
                .ForMember(dest => dest.AwayYellowCards, op => op.MapFrom(src => src.MatchDetails.AwayYellowCards))
                .ForMember(dest => dest.HomeTeamRedCards, op => op.MapFrom(src => src.MatchDetails.HomeTeamRedCards))
                .ForMember(dest => dest.AwayTeamRedCards, op => op.MapFrom(src => src.MatchDetails.AwayTeamRedCards));
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
Example #37
0
 public MatchContext MatchUst(Ust ust, MatchContext context)
 {
     return(Match(ust, context));
 }
        /// <summary>
        /// This method does nearly the same thing as the MatchesWildcardPattern method
        /// below; however, rather than returning an immediate result, it conditionally
        /// updates an array holding the type of match by each character.  The array
        /// is updated only when the entire pattern matches
        /// </summary>
        /// <param name="source">source string</param>
        /// <param name="pattern">pattern to use for matching</param>
        /// <param name="context">whether inclusion or exclusion</param>
        /// <param name="characterMatches">when more than one string is evaluated, nonStarMatches is used for reconciliation</param>
        /// <returns></returns>
        public void EvaluatePattern(string source, string patternPossiblyWithPrefix,
                                    ref MatchType[] characterMatches)
        {
            MatchContext context = patternPossiblyWithPrefix.StartsWith(ExclusionPrefix) ? MatchContext.Exclusion : MatchContext.Inclusion;
            var          pattern = patternPossiblyWithPrefix.Substring(context == MatchContext.Exclusion ? 1 : 0);

            MatchType[] matches = new MatchType[characterMatches.Length];
            Array.Copy(characterMatches, matches, characterMatches.Length);

            MatchType wildcardForContext    = (context == MatchContext.Inclusion) ? MatchType.WildcardInclusion : MatchType.WildcardExclusion;
            MatchType nonWildcardForContext = (context == MatchContext.Inclusion) ? MatchType.NonWildcardInclusion : MatchType.NonWildcardExclusion;


            //overwrite characterMatches, only if the overall pattern matches (inclusion or exclusion)
            if (Matches())
            {
                characterMatches = matches;
            }

            bool Matches()
            {
                //short-circuit for trivial results;
                if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(pattern))
                {
                    return(true);
                }

                //initialize string index variables
                int s = 0;
                int p = 0;

                //iterate over source and pattern characters until end of source
                //or pattern (short-circuiting if no match)
                for (; s < source.Length || p < pattern.Length; s++, p++)
                {
                    //return true if end of source and pattern
                    if (s == source.Length && p == pattern.Length)
                    {
                        return(true);
                    }

                    //handle matching characters without wildcard
                    else if (s < source.Length && p < pattern.Length && source[s] == pattern[p])
                    {
                        //overwrite when lower value
                        if (matches[s] < nonWildcardForContext)
                        {
                            matches[s] = nonWildcardForContext;
                        }
                        continue;
                    }

                    //handle asterix in pattern
                    else if (p < pattern.Length && pattern[p] == '*')
                    {
                        //advance through pattern string until non-asterix character is encountered or end of string
                        while (p < pattern.Length && pattern[p] == '*')
                        {
                            p++;
                        }


                        //advance the source to the first character that matches the pattern's next (non-asterix) character
                        while (s < source.Length && (p == pattern.Length || source[s] != pattern[p]))
                        {
                            //overwrite unmatched only with wildcard match
                            if (matches[s] < wildcardForContext)
                            {
                                matches[s] = wildcardForContext;
                            }
                            s++;
                        }
                        //if end of pattern is reached and it ends with '*', it matches
                        if (p == pattern.Length)
                        {
                            return(true);
                        }

                        //back up one, as the counter will advance p and s at the top of the loop
                        s--;
                        p--;
                        //corresponding characters don't match and pattern character isn't an asterix; so, non-match
                    }
                    else
                    {
                        return(false);
                    }
                }
                return(s == source.Length && p == pattern.Length);
            }
        }
Example #39
0
 public override MatchContext Match(NullLiteral nullLiteral, MatchContext context)
 {
     return(context.AddMatch(nullLiteral));
 }
			protected override bool OnMatch(MatchContext context, Expression node)
			{
				return (new SelfAssignment.SelfAssignmentExpression.SelfAssignmentSafetyChecker(this.get_ShouldSelfAssignPointers())).IsSafeToSelfAssign(node);
			}
 protected abstract Expression ApplyTransform(Expression x, MatchContext Matched);
			protected override bool OnMatch(MatchContext context, Expression node)
			{
				return node.get_CodeNodeType() != 24;
			}
Example #43
0
 public override IEnumerable <MatchResult> Match(Value expr, MatchContext context)
 {
     return(_literal.Equals(expr) ? new[] { context.WithMatch(expr) } : new MatchResult[0]);
 }
        public override bool Matches(IEnumerable actual, IMatchDiagnostics diagnostics)
        {
            if (actual == null)
            {
                diagnostics.MisMatched("items are null");
                return(false);
            }
            var list   = AsEfficientList(actual);
            var passed = true;
            var ctxt   = new MatchContext(m_matchers);
            int pos    = 0;

            for (; pos < list.Count; pos++)
            {
                var item        = list[pos];
                var matchPassed = false;
                if (ctxt.MatchersRemain())
                {
                    if (m_failOnAdditionalItems)
                    {
                        matchPassed = ctxt.Matches(item, pos, diagnostics);
                    }
                    else
                    {
                        //prevent useless diagnostics messages appearing in output as we call the matchers
                        //repeatably as we try to find a match
                        var childDiag = diagnostics.NewChild();
                        matchPassed = ctxt.Matches(item, pos, childDiag);
                        if (matchPassed)
                        {
                            diagnostics.Value(childDiag);
                        }
                    }
                }

                if (!matchPassed)
                {
                    if (m_failOnAdditionalItems)
                    {
                        passed = false;
                    }
                }
                if (!passed)
                {
                    var child = diagnostics.NewChild();
                    child.Value("position", pos);
                    child.Value("item", item);
                    diagnostics.MisMatched(child);
                    break;
                }
            }
            if (ctxt.MatchersRemain())
            {
                passed = false;
            }
            if (!passed)
            {
                if (!ctxt.MatchersRemain())
                {
                    diagnostics.Text("All matchers matched");
                }
                ctxt.AddMisMatchMessage(diagnostics);
                if (pos < list.Count)
                {
                    diagnostics.Child("Additional items not matched", SubSet(pos, list));
                }
            }
            return(passed);
        }
 public QueueForGameHandler(MatchContext matchContext, IMediator mediator)
 {
     this.matchContext = matchContext;
     this.mediator     = mediator;
 }
Example #46
0
        private static void GetMatches(MatchContext context, string league)
        {
            var    fileList   = getCSV($@"http://www.football-data.co.uk/mmz4281/1819/{league}.csv");
            var    matchList  = new List <Match>();
            League nameLeague = new League();

            switch (league)
            {
            case "I1":
            {
                nameLeague = context.Leagues.FirstOrDefault(l => l.Nationality.Name == "Italy" && l.Name == "Serie A");
                break;
            }

            case "E0":
            {
                nameLeague =
                    context.Leagues.FirstOrDefault(
                        l => l.Nationality.Name == "United Kingdom" && l.Name == "Premier League");
                break;
            }

            case "D1":
            {
                nameLeague = context.Leagues.FirstOrDefault(l => l.Nationality.Name == "Germany" && l.Name == "Bundesliga");
                break;
            }

            case "F1":
            {
                nameLeague = context.Leagues.FirstOrDefault(l => l.Nationality.Name == "France" && l.Name == "Ligue 1");
                break;
            }

            case "SP1":
            {
                nameLeague = context.Leagues.FirstOrDefault(l => l.Nationality.Name == "Spain" && l.Name == "LaLiga");
                break;
            }
            }

            var configCSV = new CsvHelper.Configuration.Configuration
            {
                Delimiter         = ",",
                IgnoreBlankLines  = true,
                HeaderValidated   = null,
                MissingFieldFound = null
            };

            using (var csv = new CsvReader(fileList, configCSV))
            {
                var matches = csv.GetRecords <MatchCSV>();
                foreach (var match in matches)
                {
                    matchList.Add(new Match
                    {
                        League   = nameLeague,
                        HomeTeam = context.Teams.FirstOrDefault(ht =>
                                                                Regex.IsMatch(ht.Name.RemoveDiacritics().ToLower(), FixTeamName(match.HomeTeam).ToLower())),
                        AwayTeam = context.Teams.FirstOrDefault(ht =>
                                                                Regex.IsMatch(ht.Name.RemoveDiacritics().ToLower(), FixTeamName(match.AwayTeam).ToLower())),
                        FTHomeGoals  = match.FTHG,
                        FTAwayGoals  = match.FTAG,
                        HTHomeGoals  = match.HTHG,
                        HTAwayGoals  = match.HTAG,
                        MatchDay     = DateTime.Parse(match.Date),
                        MatchDetails = GetMatchDetails(match, nameLeague.NationalityId, context,
                                                       context.Teams.FirstOrDefault(ht =>
                                                                                    Regex.IsMatch(ht.Name.RemoveDiacritics().ToLower(), FixTeamName(match.HomeTeam).ToLower()))
                                                       .StadiumId)
                    });
                }
            }

            context.Matches.AddRange(matchList);
            context.SaveChanges();
        }
Example #47
0
		public MatchContext BackwardsMatch(Instruction instruction)
		{
			MatchContext context = new MatchContext(instruction.Previous);
			BackwardsMatch(context);
			return context;
		}
Example #48
0
 public SportStore(MatchContext matchContext)
 {
     _matchContext = matchContext;
 }
Example #49
0
            protected override bool OnMatch(MatchContext context, Expression node)
            {
                SelfAssignmentSafetyChecker checker = new SelfAssignmentSafetyChecker(this.ShouldSelfAssignPointers);

                return(checker.IsSafeToSelfAssign(node));
            }
Example #50
0
 public override bool Matches(Expression E, MatchContext Matched)
 {
     return target.CallMatches(arguments, E, Matched);
 }
Example #51
0
			internal override void BackwardsMatch(MatchContext context)
			{
				_pattern.TryBackwardsMatch(context);
			}
Example #52
0
        private static MatchDetails GetMatchDetails(MatchCSV match, int refereeCountry, MatchContext context, int homeTeam)
        {
            var matchDetails = new MatchDetails
            {
                HomeTeamCorners        = match.HC,
                AwayTeamCorners        = match.AC,
                HomeTeamFoulsCommitted = match.HF,
                AwayTeamFoulsCommitted = match.AF,
                HomeTeamShots          = match.HS,
                AwayTeamShots          = match.AS,
                HomeTeamShotsOnTarget  = match.HST,
                AwayTeamShotsOnTarget  = match.AST,
                HomeYellowCards        = match.HY,
                AwayYellowCards        = match.AY,
                HomeTeamRedCards       = match.HR,
                AwayTeamRedCards       = match.AR,
                HomeTeamOffsides       = GetRandom(1, 7),
                AwayTeamOffsides       = GetRandom(1, 7),
                AwayTeamWoodWork       = GetRandom(0, 4),
                HomeTeamWoodWork       = GetRandom(0, 4),
                Attendance             = Convert.ToInt32(Math.Round((GetRandom(60, 95) * 0.01) * context.Stadium.FirstOrDefault(s => s.StadiumId == homeTeam).Capacity, 0)),
                RefereeId = match.Referee != null?GetReferee(match.Referee, refereeCountry, context) : context.Referees.FirstOrDefault(r => r.Name == "No data").RefereeId
            };

            context.MatchesDetails.Add(matchDetails);
            context.SaveChanges();
            return(matchDetails);
        }
Example #53
0
        public override IEnumerable <MatchResult> Match(Value expr, MatchContext context)
        {
            var engine = expr.Engine;

            return(_pattern.Match(expr, context).Where(ApplyCondition));
        }
 public override MatchContext Match(ThisReferenceToken thisReferenceToken, MatchContext context)
 {
     return(context.AddMatch(thisReferenceToken));
 }
Example #55
0
        public override MatchResult Matches(MatchContext context, TokenEntity startToken, PatternMatcher nextPatternMatcher)
        {
            var tokenEntity = startToken;

            if (tokenEntity != null)
            {
                if (nextPatternMatcher != null)
                {
                    MatchResult nextPatternMatch = nextPatternMatcher?.Matches(context, tokenEntity, null);
                    if (nextPatternMatch.Matched && nextPatternMatch.NextToken != tokenEntity)
                    {
                        return(new MatchResult(false, this)
                        {
                            NextPatternMatch = nextPatternMatch
                        });
                    }
                }

                if (!context.IsTokenMatched(tokenEntity))
                {
                    // if last child is a wildcard and it's end matches the last token's end
                    // then we will merge the wildcards together.
                    var previousToken  = context.GetPrevTokenEntity(tokenEntity);
                    var wildcardEntity = context.CurrentEntity.Children.FirstOrDefault(wildcard => wildcard.Type == this.entityType && wildcard.End == previousToken.End);
                    if (wildcardEntity != null)
                    {
                        var newEntity = new LucyEntity()
                        {
                            Type       = entityType,
                            Start      = wildcardEntity.Start,
                            End        = tokenEntity.End,
                            Score      = ((float)tokenEntity.End - wildcardEntity.Start) / context.Text.Length / 2,
                            Text       = context.Text.Substring(wildcardEntity.Start, tokenEntity.End - wildcardEntity.Start),
                            Resolution = context.Text.Substring(wildcardEntity.Start, tokenEntity.End - wildcardEntity.Start),
                        };

                        // remove old entity
                        context.CurrentEntity.Children.Remove(wildcardEntity);

                        // add new merged wildcard entity "joe" "smith" => "joe smith"
                        context.AddToCurrentEntity(newEntity);
                    }
                    else
                    {
                        var newEntity = new LucyEntity()
                        {
                            Type       = entityType,
                            Start      = tokenEntity.Start,
                            End        = tokenEntity.End,
                            Score      = ((float)tokenEntity.End - tokenEntity.Start) / context.Text.Length / 2,
                            Text       = context.Text.Substring(tokenEntity.Start, tokenEntity.End - tokenEntity.Start),
                            Resolution = context.Text.Substring(tokenEntity.Start, tokenEntity.End - tokenEntity.Start)
                        };
                        context.AddToCurrentEntity(newEntity);
                    }

                    return(new MatchResult(true, this, context.GetNextTokenEntity(tokenEntity), tokenEntity.Start, tokenEntity.End));
                }
            }

            return(new MatchResult(false, this));
        }
        public override void VisitMethod(MethodDefinition method)
        {
            TypeDefinition matchingType = null;
            // Check return type (recursively) to find all generic parameters
            if (IsMatching(myArgSearchTypeNames, mySearchArgTypes, method.ReturnType, out matchingType))
            {
                MatchContext context = new MatchContext(UsedAsMethodReturnType, matchingType.Print());
                Aggregator.AddMatch(method, context);
                return;
            }

            // check method paramters
            foreach (ParameterDefinition param in method.Parameters)
            {
                if (this.IsMatching(this.myArgSearchTypeNames, this.mySearchArgTypes, param.ParameterType, out matchingType))
                {
                    var context = new MatchContext(UsedAsMethodParameterReason, matchingType.Print());
                    this.Aggregator.AddMatch(method, context);
                    break;
                }
            }
        }
Example #57
0
        public override bool Matches(Expression E, MatchContext Matched)
        {
            Binary BE = E as Binary;
            if (!ReferenceEquals(BE, null) && BE.Operator == Operator)
                return Matched.TryMatch(() => Left.Matches(BE.Left, Matched) && Right.Matches(BE.Right, Matched));

            return false;
        }
Example #58
0
        public List <SnippetContext> GetKeywordsInContext(string text, params string[] keywords)
        {
            // Check input.

            if (string.IsNullOrEmpty(text))
            {
                return(new List <SnippetContext>());
            }

            if (keywords == null || keywords.Length == 0)
            {
                throw new ArgumentException("The keywords must be specified.", "keywords");
            }

            foreach (string keyword in keywords)
            {
                if (keyword.IndexOf(_newLine) != -1)
                {
                    throw new ArgumentException(string.Format("A keyword, '{0}', contains the new line"
                                                              + " string, '{1}'.", keyword, _newLine));
                }
            }

            // Find all the keyword occurrences. Use multiple regexes - one for each keyword. For
            // some (very strange!) reason this is an order of magnitude faster than simply ORing
            // all the keywords in one regex.

            Regex findExactMatch;

            Regex[] findKeywords = GetKeywordRegexes(keywords, out findExactMatch);

            IList <MatchContext> matches = GetAllMatches(text, findKeywords, findExactMatch);

            if (matches.Count == 0)
            {
                return(new List <SnippetContext>());
            }

            // Generate the snippets.

            List <SnippetContext> inContext = new List <SnippetContext>();
            int totalWords = 0;

            for (int firstMatchIndex = 0; firstMatchIndex < matches.Count; firstMatchIndex++)
            {
                // Work out the boundaries of the current line - the snippet must be within these.

                int startIndex = matches[firstMatchIndex].Match.Index;

                int leftBound, rightBound;
                GetSnippetBoundaries(text, startIndex, out leftBound, out rightBound);

                int lastMatchIndex        = firstMatchIndex;
                int spannedWords          = 1;
                int snippetTotalWordCount = 0;

                if (matches.Count > 1)
                {
                    // Work out the possible snippet lengths for this match.

                    int[] wordCounts = GetAvailableSnippetLengths(totalWords);
                    if (wordCounts == null)
                    {
                        break;                         // Enough words found, stop.
                    }
                    // Find the best snippet (one that includes the most matches) that fits into the
                    // available number of words.

                    FindBestWordSpan(text, rightBound, matches, wordCounts, firstMatchIndex,
                                     out lastMatchIndex, out spannedWords, out snippetTotalWordCount);
                }

                MatchContext lastMatch = matches[lastMatchIndex];
                int          endIndex  = lastMatch.Match.Index + lastMatch.Match.Length - 1;

                int availableWords;
                if (snippetTotalWordCount == 0)
                {
                    Debug.Assert(firstMatchIndex == lastMatchIndex, "firstMatchIndex == lastMatchIndex");
                    availableWords = GetNextSnippetLength(totalWords, matches.Count - firstMatchIndex,
                                                          inContext.Count) - 1;
                    Debug.Assert(availableWords > 0, "GetNextSnippetLength() returned 0 - how?");
                }
                else
                {
                    if (firstMatchIndex == 0 && lastMatchIndex == matches.Count - 1)
                    {
                        // All the keywords are in one snippet, might as well use all the avaialble words.

                        snippetTotalWordCount = LONG_SNIPPET_LENGTH;
                    }

                    availableWords = snippetTotalWordCount - spannedWords;
                }

                // Pad it with words on both sides to reach the required number of words.

                bool atSentenceStart, atSentenceEnd;
                int  addedWords = 0;

                if (availableWords == 0)
                {
                    bool dummy;
                    atSentenceStart = (IsAtSentenceBoundary(text, startIndex, leftBound, out dummy) != -1);

                    // Only set atSentenceEnd to true if there is a full stop (exclamation mark, etc.)
                    // at the end of it, not just if the end of the line is reached.

                    int tempIndex = IsAtSentenceBoundary(text, endIndex, rightBound,
                                                         out atSentenceEnd);
                    if (tempIndex != -1 && atSentenceEnd)
                    {
                        endIndex = tempIndex;                         // Include the end-of-sentence character in the snippet.
                    }
                }
                else
                {
                    addedWords = ExpandSnippet(text, availableWords, leftBound, rightBound,
                                               ref startIndex, ref endIndex, out atSentenceStart, out atSentenceEnd);
                }
                Debug.Assert(startIndex >= 0 && endIndex > 0, "startIndex >= 0 && endIndex > 0");

                // Highlight the keywords and add sentence start and end markers, if needed.

                SnippetContext snippet = AddKeywordHighlighting(text, matches, startIndex, endIndex,
                                                                firstMatchIndex, lastMatchIndex, atSentenceStart, atSentenceEnd);
                inContext.Add(snippet);

                totalWords     += spannedWords + addedWords;
                firstMatchIndex = lastMatchIndex;
            }

            return(inContext);
        }
 protected override Expression ApplyTransform(Expression x, MatchContext Matched)
 {
     return result.Substitute(Matched, true).Evaluate();
 }
Example #60
0
        private static IList <MatchContext> GetAllMatches(string text, Regex[] findKeywords, Regex findExactMatch)
        {
            List <MatchContext> matches = new List <MatchContext>();

            for (int i = 0; i < findKeywords.Length; i++)
            {
                MatchCollection keywordMatches = findKeywords[i].Matches(text);

                foreach (Match match in keywordMatches)
                {
                    MatchContext matchContext = new MatchContext();
                    matchContext.Match      = match;
                    matchContext.KeywordSet = 1 << i;

                    matches.Add(matchContext);
                }
            }

            matches.Sort(new MatchComparer());
            RemoveMatchesForOverlappedKeywords(matches);

            if (findExactMatch == null)
            {
                return(matches);
            }

            IEnumerable <Match> exactMatches = findExactMatch.Matches(text).Cast <Match>();

            if (!exactMatches.Any())
            {
                return(matches);
            }

            // If there are multiple keywords and an exact match is found start from there, so that
            // the exact match appears first. Ideally preceding partial matches should be returned
            // as well, but this is not implemented yet, so just remove all matches before the exact match.
            // The proper logic would need to avoid overlapping matches, if implemented.

            foreach (Match exactMatch in exactMatches)
            {
                int index = 0;
                while (index < matches.Count)
                {
                    MatchContext match = matches[index];

                    if (match.Match.Index < exactMatch.Index ||
                        match.Match.Index + match.Match.Length <= exactMatch.Index + exactMatch.Length)
                    {
                        matches.RemoveAt(index);
                    }
                    else
                    {
                        index++;
                    }
                }
            }

            matches.InsertRange(0, exactMatches.Select(
                                    m => new MatchContext {
                Match = m, KeywordSet = int.MaxValue
            }
                                    ));

            return(matches);
        }