public PatternTestResult()
 {
     Events      = new List <PatternTestResultEventPattern>();
     Warnings    = new List <string>();
     Options     = new PatternOptions();
     _identifier = Guid.NewGuid();
 }
 public PatternTestSummary(string patternName)
 {
     _patternName = patternName;
     Patterns     = new List <PatternTestResult>();
     Options      = new PatternOptions();
     Frequencies  = new List <Frequency>();
     Unexpected   = new List <CleanAttribute>();
     KnownIdle    = new List <Duration>();
     Durations    = new List <Duration>();
 }
        private void PlayAnimation(ILaserPattern pattern, PatternOptions options)
        {
            if (!AnimationCompleted() || options.AnimationSpeed.ToString() == AnimationSpeed.Off.ToString())
            {
                return;
            }
            _laserAnimationStatus.AnimationCanceled = false;

            _animationTask = new Task(() => pattern.Project(options), TaskCreationOptions.LongRunning);
            _animationTask.Start();
            _previousExecutedPatterns.Add(pattern);
        }
예제 #4
0
        private static void Dump(string title, Pattern pattern)
        {
            const PatternOptions options = PatternOptions.FormatAndComment;

            if (!string.IsNullOrEmpty(title))
            {
                Console.WriteLine($"{title}:");
            }

            Console.WriteLine(pattern.ToString(options));
            Console.WriteLine("");
        }
        public void Project(PatternOptions options)
        {
            int totalLines = 4;

            if (totalLines < 2)
            {
                totalLines = 2;
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var colors = new List <LaserColors>();

            for (int i = 0; i < totalLines; i++)
            {
                colors.Add(_laserPatternHelper.GetRandomLaserColors());
            }

            AnimationSpeed animationSpeed = options.AnimationSpeed;
            double         iterations     = 0;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations / 6.3 < options.Total)
            {
                iterations += (double)animationSpeed / 700;
                if (stopwatch.ElapsedMilliseconds > options.DurationMilliseconds && options.DurationMilliseconds != 0 || _laserAnimationStatus.AnimationCanceled)
                {
                    break;
                }
                if (options.AnimationSpeed == AnimationSpeed.NotSet)
                {
                    animationSpeed = _laserAnimationStatus.AnimationSpeed;
                }

                for (int line = 0; line < totalLines; line++)
                {
                    int x = Convert.ToInt32(Math.Cos(iterations + line) * Math.Abs(_settings.maxLeft));
                    int y = Convert.ToInt32(Math.Sin(iterations) * Math.Abs(2000));

                    _laser.SendTo(x, y);
                    System.Threading.Thread.SpinWait(40000);

                    _laser.On(colors[line]);

                    System.Threading.Thread.SpinWait(6000);
                    _laser.Off();
                }
            }
        }
        public void PlayAll(PatternOptions options)
        {
            if (!AnimationCompleted())
            {
                return;
            }
            _playPatternTask = new Task(() =>
            {
                foreach (var pattern in _patterns)
                {
                    pattern.Project(options);
                }
            }, TaskCreationOptions.RunContinuationsAsynchronously);

            _playPatternTask.Start();
        }
예제 #7
0
 public void Initialize(string name, ScanType scanType, Action <IPattern> callback)
 {
     Events        = new List <IEventPattern>();
     OrginalEvents = new List <IEventPattern>();
     Options       = new PatternOptions();
     Sources       = new List <string>();
     Warnings      = new List <string>();
     Name          = name;
     Active        = true;
     _hasStarted   = false;
     ScanType      = scanType;
     if (callback != null)
     {
         OnFound += callback;
     }
 }
예제 #8
0
        public void Project(PatternOptions options)
        {
            LaserColors colors  = _laserPatternHelper.GetRandomLaserColors();
            int         xCenter = (_settings.maxLeft + _settings.maxRight) / 2;

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            AnimationSpeed animationSpeed = options.AnimationSpeed;
            int            iterations     = 0;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations < options.Total)
            {
                iterations++;
                if (options.AnimationSpeed == AnimationSpeed.NotSet)
                {
                    animationSpeed = _laserAnimationStatus.AnimationSpeed;
                }

                int left  = xCenter - 100;
                int right = xCenter + 100;

                int y = new Random(Guid.NewGuid().GetHashCode()).Next(_settings.minHeight, _settings.maxHeight);

                while (left > _settings.maxLeft || right < _settings.maxRight)
                {
                    if (stopwatch.ElapsedMilliseconds > options.DurationMilliseconds && options.DurationMilliseconds != 0 || _laserAnimationStatus.AnimationCanceled)
                    {
                        break;
                    }

                    _laser.SendTo(left -= (int)animationSpeed / 2, y);
                    System.Threading.Thread.SpinWait(30000);
                    _laser.On(colors);

                    _laser.SendTo(right += (int)animationSpeed / 2, y);
                    System.Threading.Thread.SpinWait(30000);
                    _laser.Off();
                    System.Threading.Thread.SpinWait(100);
                }
            }

            _laser.Off();
        }
        /// <summary>
        /// Plays the specified patternOptions, optional duration animation will stop after set milliseconds
        /// </summary>
        /// <param name="patternName"></param>
        /// <param name="animationSpeed"></param>
        /// <param name="duration"></param>
        public void PlayPattern(PatternOptions options)
        {
            if (!AnimationCompleted())
            {
                return;
            }
            _playPatternTask = new Task(() =>
            {
                ILaserPattern pattern = _patterns.Find(p => p.GetType().Name == options.PatternName);
                if (pattern == null)
                {
                    return;
                }

                pattern.Project(options);
            }, TaskCreationOptions.RunContinuationsAsynchronously);

            _playPatternTask.Start();
        }
예제 #10
0
        /// <summary>
        /// Returns the set of exemplar characters for a locale.
        /// </summary>
        /// <param name="options">
        /// Bitmask for options to apply to the exemplar pattern.
        /// Specify zero to retrieve the exemplar set as it is
        /// defined in the locale data.  Specify <see cref="PatternOptions.Case"/>
        /// to retrieve a case-folded exemplar
        /// set.  See <see cref="PatternOptions"/> for a complete list of valid options.  The
        /// <see cref="PatternOptions.IgnoreSpace"/> bit is always set, regardless of the
        /// value of <paramref name="options"/>.
        /// </param>
        /// <param name="extype">The type of exemplar set to be retrieved,
        /// <see cref="ExemplarSetType.Standard"/>, <see cref="ExemplarSetType.Index"/>,
        /// <see cref="ExemplarSetType.Auxiliary"/>, or <see cref="ExemplarSetType.Punctuation"/>.</param>
        /// <returns>
        /// The set of exemplar characters for the given locale.
        /// If there is nothing available for the locale,
        /// then null is returned if <see cref="NoSubstitute"/> is <c>true</c>, otherwise the
        /// root value is returned (which may be <see cref="UnicodeSet.Empty"/>.
        /// </returns>
        /// <exception cref="IndexOutOfRangeException">If <paramref name="extype"/> is invalid.</exception>
        /// <stable>ICU 3.4</stable>
        public UnicodeSet GetExemplarSet(PatternOptions options, ExemplarSetType extype)
        {
            string[] exemplarSetTypes =
            {
                "ExemplarCharacters",
                "AuxExemplarCharacters",
                "ExemplarCharactersIndex",
                "ExemplarCharactersCurrency",
                "ExemplarCharactersPunctuation"
            };

            // ICU4N: Currency was never supported in .NET
//#pragma warning disable 612, 618
//            if (extype == ES_CURRENCY)
//#pragma warning restore 612, 618
//            {
//                // currency symbol exemplar is no longer available
//                return noSubstitute ? null : UnicodeSet.Empty;
//            }

            try
            {
                string            aKey         = exemplarSetTypes[(int)extype]; // will throw an out-of-bounds exception
                ICUResourceBundle stringBundle = (ICUResourceBundle)bundle.Get(aKey);

                if (noSubstitute && !bundle.IsRoot && stringBundle.IsRoot)
                {
                    return(null);
                }
                string unicodeSetPattern = stringBundle.GetString();
                return(new UnicodeSet(unicodeSetPattern, UnicodeSet.IgnoreSpace | options));
            }
            catch (IndexOutOfRangeException aiooe)
            {
                throw new ArgumentException(aiooe.Message, aiooe);
            }
            catch (Exception)
            {
                return(noSubstitute ? null : UnicodeSet.Empty);
            }
        }
예제 #11
0
        public void Project(PatternOptions options)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var color = _laserPatternHelper.GetRandomLaserColors();

            AnimationSpeed animationSpeed = options.AnimationSpeed;
            double         sin            = 0;
            int            iterations     = 0;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations < options.Total * 2000)
            {
                if (stopwatch.ElapsedMilliseconds > options.DurationMilliseconds && options.DurationMilliseconds != 0 || _laserAnimationStatus.AnimationCanceled)
                {
                    break;
                }
                if (options.AnimationSpeed == AnimationSpeed.NotSet)
                {
                    animationSpeed = _laserAnimationStatus.AnimationSpeed;
                }

                for (int i = _settings.maxLeft; i < _settings.maxRight; i += 15)
                {
                    iterations++;
                    sin += 0.026;

                    int y = Convert.ToInt32(Math.Sin(sin) * Math.Abs(_settings.maxHeight));
                    _laser.SendTo(i, y);

                    if (i == _settings.maxLeft)
                    {
                        System.Threading.Thread.SpinWait(22000);
                    }
                    _laser.On(color);
                }

                _laser.Off();
            }
        }
        public void Project(PatternOptions options)
        {
            LaserColors colors    = _laserPatternHelper.GetRandomLaserColors();
            var         stopwatch = new Stopwatch();

            stopwatch.Start();

            AnimationSpeed animationSpeed = options.AnimationSpeed;
            var            xPos           = new List <int> {
                _settings.maxLeft, _settings.maxRight
            };
            double iterations = 0;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations / 6.3 < options.Total)
            {
                iterations += (double)animationSpeed / 1400;
                if (options.AnimationSpeed == AnimationSpeed.NotSet)
                {
                    animationSpeed = _laserAnimationStatus.AnimationSpeed;
                }

                for (int line = 0; line < 2; line++)
                {
                    if (stopwatch.ElapsedMilliseconds > options.DurationMilliseconds && options.DurationMilliseconds != 0 || _laserAnimationStatus.AnimationCanceled)
                    {
                        break;
                    }

                    for (int j = 0; j < 3; j++)
                    {
                        int y = Convert.ToInt32(Math.Sin(iterations + line) * Math.Abs(2000));

                        _laser.SendTo(xPos[line], y);
                        System.Threading.Thread.SpinWait(15000);
                        _laser.On(colors);
                    }
                }
            }

            _laser.Off();
        }
예제 #13
0
 public static bool TryParse(
     IEnumerable <string> values,
     string optionName,
     OptionValueProvider provider,
     out Filter?filter,
     bool allowNull = false,
     OptionValueProvider?namePartProvider  = null,
     FileNamePart defaultNamePart          = FileNamePart.Name,
     PatternOptions includedPatternOptions = PatternOptions.None)
 {
     return(TryParse(
                values: values,
                optionName: optionName,
                provider: provider,
                filter: out filter,
                namePart: out _,
                allowNull: allowNull,
                namePartProvider: namePartProvider,
                defaultNamePart: defaultNamePart,
                includedPatternOptions: includedPatternOptions));
 }
예제 #14
0
        public void Project(PatternOptions options)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            int iterations = 0;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations < options.Total * 100)
            {
                iterations++;
                if (stopwatch.ElapsedMilliseconds > options.DurationMilliseconds && options.DurationMilliseconds != 0 || _laserAnimationStatus.AnimationCanceled)
                {
                    break;
                }

                LaserColors colors = _laserPatternHelper.GetRandomLaserColors();

                _laser.SendTo(_laserPatternHelper.GetRandomXPosition(), _laserPatternHelper.GetRandomYPosition());
                _laser.On(colors);
                System.Threading.Thread.SpinWait(20000);
                _laser.Off();
            }
        }
        public void Project(PatternOptions options)
        {
            LaserColors colors    = _laserPatternHelper.GetRandomLaserColors();
            var         stopwatch = new Stopwatch();

            stopwatch.Start();

            AnimationSpeed animationSpeed = options.AnimationSpeed;
            int            iterations     = 0;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations < options.Total)
            {
                iterations++;

                for (int i = _settings.maxHeight; i > _settings.minHeight; i -= (int)animationSpeed)
                {
                    if (stopwatch.ElapsedMilliseconds > options.DurationMilliseconds && options.DurationMilliseconds != 0 || _laserAnimationStatus.AnimationCanceled)
                    {
                        break;
                    }
                    if (options.AnimationSpeed == AnimationSpeed.NotSet)
                    {
                        animationSpeed = _laserAnimationStatus.AnimationSpeed;
                    }

                    _laser.SendTo(_settings.maxLeft, i);
                    System.Threading.Thread.SpinWait(30000);
                    _laser.On(colors);

                    _laser.SendTo(_settings.maxRight, i);
                    System.Threading.Thread.SpinWait(30000);
                }
            }

            _laser.Off();
        }
        public void Project(PatternOptions options)
        {
            int xCenter = (_settings.maxLeft + _settings.maxRight) / 2;

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            AnimationSpeed animationSpeed = options.AnimationSpeed;
            int            iterations     = 0;

            List <LaserColors> colors = GetRandomColors();
            int totalLines            = colors.Count;
            int lineDistance          = (Math.Abs(_settings.maxLeft) + Math.Abs(_settings.maxRight)) / totalLines;

            int previousColorChange = 0;
            int y = _settings.maxHeight;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations < options.Total)
            {
                if (y > _settings.minHeight)
                {
                    y -= (int)animationSpeed / 5 + 2;
                }
                else
                {
                    iterations++;
                    y = _settings.maxHeight;
                }

                if (options.AnimationSpeed == AnimationSpeed.NotSet)
                {
                    animationSpeed = _laserAnimationStatus.AnimationSpeed;
                }

                int iterationThreshold = 0;
                try
                {
                    iterationThreshold = 600 / (int)animationSpeed;
                }

                catch (Exception e) { }

                if (iterations - previousColorChange > iterationThreshold)
                {
                    previousColorChange = iterations;
                    colors = GetRandomColors();
                }

                for (int i = 0; i < totalLines; i++)
                {
                    _laser.SendTo(_settings.maxLeft + lineDistance * i, y);
                    System.Threading.Thread.SpinWait(16000);

                    _laser.On(colors[i]);
                }

                _laser.Off();
            }

            _laser.Off();
        }
 public void PlayPattern([FromBody] PatternOptions options)
 {
     _patternLogic.PlayPattern(options);
 }
예제 #18
0
        public void Project(PatternOptions options)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            AnimationSpeed animationSpeed = options.AnimationSpeed;
            int            iterations     = 0;

            var random = new Random(Guid.NewGuid().GetHashCode());
            List <LaserPositionAndColors> laserPosAndColors = GetPredifinedLaserPositionAndColors();

            int previousColorChange = 0;

            bool xToLeft = false;
            bool yUp     = false;

            while (stopwatch.ElapsedMilliseconds < options.DurationMilliseconds || iterations < options.Total * 100)
            {
                iterations++;

                LaserPositionAndColors lastLaserPositionAndColors = laserPosAndColors.Last();
                int x = lastLaserPositionAndColors.X;
                int y = lastLaserPositionAndColors.Y;

                if (xToLeft)
                {
                    x -= random.Next(-10 / (int)animationSpeed, (int)animationSpeed * 3 + 15);
                }
                else
                {
                    x += random.Next(-10 / (int)animationSpeed, (int)animationSpeed * 3 + 15);
                }

                if (yUp)
                {
                    y += random.Next(-10 / (int)animationSpeed, (int)animationSpeed * 3 + 15);
                }
                else
                {
                    y -= random.Next(-10 / (int)animationSpeed, (int)animationSpeed * 3 + 15);
                }

                if (x >= _settings.maxRight && !xToLeft)
                {
                    xToLeft = true;
                }
                else if (x <= _settings.maxLeft && xToLeft)
                {
                    xToLeft = false;
                }

                if (y >= _settings.maxHeight && yUp)
                {
                    yUp = false;
                }
                else if (y <= _settings.minHeight && !yUp)
                {
                    yUp = true;
                }

                var color = lastLaserPositionAndColors.LaserColors;
                if (iterations - previousColorChange > 25)
                {
                    previousColorChange = iterations;
                    color = _laserPatternHelper.GetRandomLaserColors();
                }

                laserPosAndColors.Add(new LaserPositionAndColors
                {
                    LaserColors = color,
                    Y           = y,
                    X           = x
                });

                foreach (var laserposAndColor in laserPosAndColors)
                {
                    _laser.SendTo(laserposAndColor.X, laserposAndColor.Y);
                    _laser.On(laserposAndColor.LaserColors);
                }

                if (laserPosAndColors.Count > 100 - (int)animationSpeed)
                {
                    laserPosAndColors.RemoveRange(0, 1);
                }
            }

            _laser.Off();
        }
예제 #19
0
        internal static bool TryParseRegexOptions(
            IEnumerable <string> options,
            string optionsParameterName,
            out RegexOptions regexOptions,
            out PatternOptions patternOptions,
            PatternOptions includedPatternOptions = PatternOptions.None,
            OptionValueProvider provider          = null)
        {
            regexOptions = RegexOptions.None;

            if (!TryParseAsEnumFlags(options, optionsParameterName, out patternOptions, provider: provider ?? OptionValueProviders.PatternOptionsProvider))
            {
                return(false);
            }

            Debug.Assert((patternOptions & (PatternOptions.CaseSensitive | PatternOptions.IgnoreCase)) != (PatternOptions.CaseSensitive | PatternOptions.IgnoreCase));

            if ((patternOptions & PatternOptions.CaseSensitive) != 0)
            {
                includedPatternOptions &= ~PatternOptions.IgnoreCase;
            }
            else if ((patternOptions & PatternOptions.IgnoreCase) != 0)
            {
                includedPatternOptions &= ~PatternOptions.CaseSensitive;
            }

            patternOptions |= includedPatternOptions;

            if ((patternOptions & PatternOptions.Compiled) != 0)
            {
                regexOptions |= RegexOptions.Compiled;
            }

            if ((patternOptions & PatternOptions.CultureInvariant) != 0)
            {
                regexOptions |= RegexOptions.CultureInvariant;
            }

            if ((patternOptions & PatternOptions.ECMAScript) != 0)
            {
                regexOptions |= RegexOptions.ECMAScript;
            }

            if ((patternOptions & PatternOptions.ExplicitCapture) != 0)
            {
                regexOptions |= RegexOptions.ExplicitCapture;
            }

            if ((patternOptions & PatternOptions.IgnoreCase) != 0)
            {
                regexOptions |= RegexOptions.IgnoreCase;
            }

            if ((patternOptions & PatternOptions.IgnorePatternWhitespace) != 0)
            {
                regexOptions |= RegexOptions.IgnorePatternWhitespace;
            }

            if ((patternOptions & PatternOptions.Multiline) != 0)
            {
                regexOptions |= RegexOptions.Multiline;
            }

            if ((patternOptions & PatternOptions.RightToLeft) != 0)
            {
                regexOptions |= RegexOptions.RightToLeft;
            }

            if ((patternOptions & PatternOptions.Singleline) != 0)
            {
                regexOptions |= RegexOptions.Singleline;
            }

            return(true);
        }
예제 #20
0
        public static bool TryParse(
            IEnumerable <string> values,
            string optionName,
            OptionValueProvider provider,
            out Filter?filter,
            out FileNamePart namePart,
            bool allowNull = false,
            OptionValueProvider?namePartProvider  = null,
            FileNamePart defaultNamePart          = FileNamePart.Name,
            PatternOptions includedPatternOptions = PatternOptions.None)
        {
            filter   = null;
            namePart = defaultNamePart;

            string?pattern = values.FirstOrDefault();

            if (pattern == null)
            {
                if (allowNull)
                {
                    return(true);
                }
                else
                {
                    throw new InvalidOperationException($"Option '{OptionNames.GetHelpText(optionName)}' is required.");
                }
            }

            TimeSpan            matchTimeout = Regex.InfiniteMatchTimeout;
            string?             groupName    = null;
            string?             separator    = null;
            Func <string, bool>?predicate    = null;

            List <string>?options = null;

            foreach (string option in values.Skip(1))
            {
                int index = option.IndexOfAny(_equalsOrLessThanOrGreaterThanChars);

                if (index != -1)
                {
                    string key = option.Substring(0, index);

                    if (!provider.ContainsKeyOrShortKey(key))
                    {
                        WriteOptionError(option, optionName, provider);
                        return(false);
                    }

                    string value = option.Substring(index + 1);

                    if (OptionValues.Group.IsKeyOrShortKey(key))
                    {
                        groupName = value;
                        continue;
                    }
                    else if (OptionValues.ListSeparator.IsKeyOrShortKey(key))
                    {
                        separator = value;
                        continue;
                    }
                    else if (OptionValues.Part.IsKeyOrShortKey(key))
                    {
                        if (!TryParseAsEnum(
                                value,
                                out namePart,
                                provider: namePartProvider ?? OptionValueProviders.NamePartKindProvider))
                        {
                            WriteOptionValueError(
                                value,
                                OptionValues.Part,
                                namePartProvider ?? OptionValueProviders.NamePartKindProvider);
                            return(false);
                        }

                        continue;
                    }
                    else if (OptionValues.Timeout.IsKeyOrShortKey(key))
                    {
                        if (!TryParseMatchTimeout(value, out matchTimeout))
                        {
                            WriteOptionValueError(value, OptionValues.Timeout);
                            return(false);
                        }

                        continue;
                    }
                }

                if (Expression.TryParse(option, out Expression? expression))
                {
                    if (OptionValues.Length.IsKeyOrShortKey(expression.Identifier) &&
                        provider.ContainsKeyOrShortKey(expression.Identifier))
                    {
                        try
                        {
                            predicate = PredicateHelpers.GetLengthPredicate(expression);
                            continue;
                        }
                        catch (ArgumentException)
                        {
                            WriteOptionValueError(
                                expression.Value,
                                OptionValues.Length,
                                HelpProvider.GetExpressionsText("  ", includeDate: false));
                            return(false);
                        }
                    }
                    else
                    {
                        WriteOptionError(option, optionName, provider);
                        return(false);
                    }
                }

                (options ??= new List <string>()).Add(option);
            }

            if (!TryParseRegexOptions(
                    options,
                    optionName,
                    out RegexOptions regexOptions,
                    out PatternOptions patternOptions,
                    includedPatternOptions,
                    provider))
            {
                return(false);
            }

            switch (patternOptions & (PatternOptions.WholeWord | PatternOptions.WholeLine))
            {
            case PatternOptions.None:
            case PatternOptions.WholeWord:
            case PatternOptions.WholeLine:
            {
                break;
            }

            default:
            {
                string helpValue = OptionValueProviders.PatternOptionsProvider
                                   .GetValue(nameof(PatternOptions.WholeWord)).HelpValue;

                string helpValue2 = OptionValueProviders.PatternOptionsProvider
                                    .GetValue(nameof(PatternOptions.WholeLine)).HelpValue;

                WriteError($"Values '{helpValue}' and '{helpValue2}' cannot be combined.");

                return(false);
            }
            }

            if ((patternOptions & PatternOptions.FromFile) != 0 &&
                !FileSystemHelpers.TryReadAllText(pattern, out pattern, ex => WriteError(ex)))
            {
                return(false);
            }

            pattern = BuildPattern(pattern, patternOptions, separator);

            if (pattern.Length == 0)
            {
                throw new InvalidOperationException(
                          $"Option '{OptionNames.GetHelpText(optionName)}' is invalid: pattern cannot be empty.");
            }

            Regex?regex = null;

            try
            {
                regex = new Regex(pattern, regexOptions, matchTimeout);
            }
            catch (ArgumentException ex)
            {
                WriteError(ex, $"Could not parse regular expression: {ex.Message}");
                return(false);
            }

            int groupIndex = -1;

            if (groupName != null)
            {
                groupIndex = regex.GroupNumberFromName(groupName);
                if (groupIndex == -1)
                {
                    string message = $"Group '{groupName}' does not exist.";

                    string[] groupNames = regex.GetGroupNames();

                    if (groupNames.Length > 1)
                    {
                        message += " Existing group names: "
                                   + $"{TextHelpers.Join(", ", " and ", groupNames.Where(f => f != "0"))}.";
                    }

                    WriteError(message);
                    return(false);
                }
            }

            filter = new Filter(
                regex,
                isNegative: (patternOptions & PatternOptions.Negative) != 0,
                groupNumber: groupIndex,
                predicate: predicate);

            return(true);
        }
예제 #21
0
        private static string BuildPattern(
            string pattern,
            PatternOptions patternOptions,
            string?separator)
        {
            bool literal = (patternOptions & PatternOptions.Literal) != 0;

            if ((patternOptions & PatternOptions.List) != 0)
            {
                IEnumerable <string> values;

                if ((patternOptions & PatternOptions.FromFile) != 0 &&
                    separator == null)
                {
                    values = TextHelpers.ReadLines(pattern).Where(f => f.Length > 0);
                }
                else
                {
                    values = pattern.Split(separator ?? ",", StringSplitOptions.RemoveEmptyEntries);
                }

                pattern = JoinValues(values);
            }
            else if (literal)
            {
                pattern = RegexEscape.Escape(pattern);
            }

            if ((patternOptions & PatternOptions.WholeWord) != 0)
            {
                pattern = @"\b(?:" + pattern + @")\b";
            }
            else if ((patternOptions & PatternOptions.WholeLine) != 0)
            {
                pattern = @"(?:\A|(?<=\n))(?:" + pattern + @")(?:\z|(?=\r?\n))";
            }

            if ((patternOptions & PatternOptions.Equals) == PatternOptions.Equals)
            {
                return(@"\A(?:" + pattern + @")\z");
            }
            else if ((patternOptions & PatternOptions.StartsWith) != 0)
            {
                return(@"\A(?:" + pattern + ")");
            }
            else if ((patternOptions & PatternOptions.EndsWith) != 0)
            {
                return("(?:" + pattern + @")\z");
            }

            return(pattern);

            string JoinValues(IEnumerable <string> values)
            {
                using (IEnumerator <string> en = values.GetEnumerator())
                {
                    if (en.MoveNext())
                    {
                        string value = en.Current;

                        if (en.MoveNext())
                        {
                            StringBuilder sb = StringBuilderCache.GetInstance();

                            AppendValue(value, sb);

                            do
                            {
                                sb.Append("|");
                                AppendValue(en.Current, sb);
                            } while (en.MoveNext());

                            return(StringBuilderCache.GetStringAndFree(sb));
                        }

                        return((literal) ? RegexEscape.Escape(value) : value);
                    }

                    return("");
                }
            }

            void AppendValue(string value, StringBuilder sb)
            {
                if (literal)
                {
                    sb.Append(RegexEscape.Escape(value));
                }
                else
                {
                    sb.Append("(?:");
                    sb.Append(value);
                    sb.Append(")");
                }
            }
        }
예제 #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PatternSettings"/> class with a specified options.
 /// </summary>
 /// <param name="options">A bitwise combination of the enumeration values.</param>
 public PatternSettings(PatternOptions options)
 {
     Options = options;
     IdentifierBoundary = IdentifierBoundary.AngleBrackets;
     IndentSize = 4;
 }
예제 #23
0
 internal bool HasOption(PatternOptions options) => (Options & options) != 0;
예제 #24
0
 /// <summary>
 /// Determines whether specified options are set in the options of the current instance.
 /// </summary>
 /// <param name="options">A bitwise combination of the enumeration values.</param>
 /// <returns></returns>
 public bool HasOptions(PatternOptions options) => (Options & options) == options;
예제 #25
0
        ////CLOVER:ON

        /// <summary>
        /// Returns the set of exemplar characters for a locale. Equivalent to calling
        /// <see cref="GetExemplarSet(UCultureInfo, PatternOptions, ExemplarSetType)"/> with the
        /// extype == <see cref="ExemplarSetType.Standard"/>.
        /// </summary>
        /// <param name="locale">Locale for which the exemplar character set
        /// is to be retrieved.</param>
        /// <param name="options">
        /// <see cref="PatternOptions"/> flags to apply to the exemplar pattern.
        /// Specify <see cref="PatternOptions.Default"/> to retrieve the exemplar set as it is
        /// defined in the locale data.  Specify <see cref="PatternOptions.Case"/> to retrieve a case-folded exemplar
        /// set.  See <see cref="PatternOptions"/> for a complete list of valid options.  The
        /// <see cref="PatternOptions.IgnoreSpace"/> bit is always set, regardless of the
        /// value of <paramref name="options"/>.
        /// </param>
        /// <returns>The set of exemplar characters for the given locale.</returns>
        /// <stable>ICU 3.0</stable>
        public static UnicodeSet GetExemplarSet(UCultureInfo locale, PatternOptions options)
        {
            return(LocaleData.GetInstance(locale).GetExemplarSet(options, ExemplarSetType.Standard));
        }
예제 #26
0
 /// <summary>
 /// Constructs a pattern text that represents the current instance with options that modify the pattern.
 /// </summary>
 /// <param name="options">A bitwise combination of the enumeration values that modify the pattern.</param>
 /// <returns></returns>
 public string ToString(PatternOptions options)
 {
     return(ToString(new PatternSettings(options)));
 }
예제 #27
0
 /// <summary>
 /// Returns the set of exemplar characters for a <paramref name="locale"/>.
 /// Equivalent to calling <c>new LocaleData(locale)</c>. <see cref="GetExemplarSet(PatternOptions, ExemplarSetType)"/>.
 /// </summary>
 /// <param name="locale">Locale for which the exemplar character set
 /// is to be retrieved.</param>
 /// <param name="options">
 /// <see cref="PatternOptions"/> flags to apply to the exemplar pattern.
 /// Specify <see cref="PatternOptions.Default"/> to retrieve the exemplar set as it is
 /// defined in the locale data.  Specify <see cref="PatternOptions.Case"/> to retrieve a case-folded exemplar
 /// set.  See <see cref="PatternOptions"/> for a complete list of valid options.  The
 /// <see cref="PatternOptions.IgnoreSpace"/> bit is always set, regardless of the
 /// value of <paramref name="options"/>.
 /// </param>
 /// <param name="extype">The type of exemplar set to be retrieved,
 /// <see cref="ExemplarSetType.Standard"/>, <see cref="ExemplarSetType.Index"/>,
 /// <see cref="ExemplarSetType.Auxiliary"/>, or <see cref="ExemplarSetType.Punctuation"/>.</param>
 /// <returns>The set of exemplar characters for the given <paramref name="locale"/>.</returns>
 /// <stable>ICU 3.0</stable>
 public static UnicodeSet GetExemplarSet(ULocale locale, PatternOptions options, ExemplarSetType extype)
 {
     return(LocaleData.GetInstance(locale).GetExemplarSet(options, extype));
 }
예제 #28
0
 /// <summary>
 /// Determines whether specified options are set in the options of the current instance.
 /// </summary>
 /// <param name="options">A bitwise combination of the enumeration values.</param>
 /// <returns></returns>
 public bool HasOptions(PatternOptions options) => (Options & options) == options;
예제 #29
0
        ///CLOVER:ON

        /**
         * Returns the set of exemplar characters for a locale. Equivalent to calling {@link #getExemplarSet(ULocale, int, int)} with
         * the extype == {@link #ES_STANDARD}.
         *
         * @param locale    Locale for which the exemplar character set
         *                  is to be retrieved.
         * @param options   Bitmask for options to apply to the exemplar pattern.
         *                  Specify zero to retrieve the exemplar set as it is
         *                  defined in the locale data.  Specify
         *                  UnicodeSet.CASE to retrieve a case-folded exemplar
         *                  set.  See {@link UnicodeSet#applyPattern(String,
         *                  int)} for a complete list of valid options.  The
         *                  IGNORE_SPACE bit is always set, regardless of the
         *                  value of 'options'.
         * @return          The set of exemplar characters for the given locale.
         * @stable ICU 3.0
         */
        public static UnicodeSet GetExemplarSet(ULocale locale, PatternOptions options)
        {
            return(LocaleData.GetInstance(locale).GetExemplarSet(options, ES_STANDARD));
        }
예제 #30
0
        public static bool TryParse(
            IEnumerable <string> values,
            string optionName,
            OptionValueProvider provider,
            out Filter filter,
            bool allowNull = false,
            NamePartKind defaultNamePart          = NamePartKind.Name,
            PatternOptions includedPatternOptions = PatternOptions.None)
        {
            filter = null;

            string pattern = values.FirstOrDefault();

            if (pattern == null)
            {
                if (allowNull)
                {
                    return(true);
                }
                else
                {
                    throw new InvalidOperationException($"Option '{OptionNames.GetHelpText(optionName)}' is required.");
                }
            }

            TimeSpan             matchTimeout = Regex.InfiniteMatchTimeout;
            string               groupName    = null;
            NamePartKind         namePart     = defaultNamePart;
            string               separator    = null;
            Func <Capture, bool> predicate    = null;

            List <string> options = null;

            foreach (string option in values.Skip(1))
            {
                int index = option.IndexOf("=");

                if (index != -1)
                {
                    string key   = option.Substring(0, index);
                    string value = option.Substring(index + 1);

                    if (OptionValues.Group.IsKeyOrShortKey(key))
                    {
                        groupName = value;
                        continue;
                    }
                    else if (OptionValues.ListSeparator.IsKeyOrShortKey(key))
                    {
                        separator = value;
                        continue;
                    }
                    else if (OptionValues.Part.IsKeyOrShortKey(key))
                    {
                        if (!TryParseAsEnum(value, out namePart, provider: OptionValueProviders.NamePartKindProvider))
                        {
                            string helpText = OptionValueProviders.NamePartKindProvider.GetHelpText();
                            WriteError($"Option '{OptionValues.Part.HelpValue}' has invalid value '{value}'. Allowed values: {helpText}.");
                            return(false);
                        }

                        continue;
                    }
                    else if (OptionValues.Timeout.IsKeyOrShortKey(key))
                    {
                        if (!TryParseMatchTimeout(value, out matchTimeout))
                        {
                            WriteError($"Option '{OptionValues.Timeout.HelpValue}' has invalid value '{value}'.");
                            return(false);
                        }

                        continue;
                    }
                }

                if (Expression.TryParse(option, out Expression expression))
                {
                    if (OptionValues.Length.IsKeyOrShortKey(expression.Identifier))
                    {
                        try
                        {
                            predicate = PredicateHelpers.GetLengthPredicate(expression);
                            continue;
                        }
                        catch (ArgumentException)
                        {
                            WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{option}'.");
                            return(false);
                        }
                    }
                    else
                    {
                        WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{option}'. Allowed values: {provider.GetHelpText()}.");
                        return(false);
                    }
                }

                (options ?? (options = new List <string>())).Add(option);
            }

            if (!TryParseRegexOptions(options, optionName, out RegexOptions regexOptions, out PatternOptions patternOptions, includedPatternOptions, provider))
            {
                return(false);
            }

            switch (patternOptions & (PatternOptions.WholeWord | PatternOptions.WholeLine))
            {
            case PatternOptions.None:
            case PatternOptions.WholeWord:
            case PatternOptions.WholeLine:
            {
                break;
            }

            default:
            {
                WriteError($"Values '{OptionValueProviders.PatternOptionsProvider.GetValue(nameof(PatternOptions.WholeWord)).HelpValue}' and '{OptionValueProviders.PatternOptionsProvider.GetValue(nameof(PatternOptions.WholeLine)).HelpValue}' cannot be combined.");
                return(false);
            }
            }

            if ((patternOptions & PatternOptions.FromFile) != 0 &&
                !FileSystemHelpers.TryReadAllText(pattern, out pattern))
            {
                return(false);
            }

            pattern = BuildPattern(pattern, patternOptions, separator);

            Regex regex = null;

            try
            {
                regex = new Regex(pattern, regexOptions, matchTimeout);
            }
            catch (ArgumentException ex)
            {
                WriteError(ex, $"Could not parse regular expression: {ex.Message}");
                return(false);
            }

            int groupIndex = -1;

            if (groupName != null)
            {
                groupIndex = regex.GroupNumberFromName(groupName);
                if (groupIndex == -1)
                {
                    string message = $"Group '{groupName}' does not exist.";

                    string[] groupNames = regex.GetGroupNames();

                    if (groupNames.Length > 1)
                    {
                        message += $" Existing group names: {TextHelpers.Join(", ", " and ", groupNames.Where(f => f != "0"))}.";
                    }

                    WriteError(message);
                    return(false);
                }
            }

            filter = new Filter(
                regex,
                namePart: namePart,
                groupNumber: groupIndex,
                isNegative: (patternOptions & PatternOptions.Negative) != 0,
                predicate);

            return(true);
        }
예제 #31
0
파일: Parser.cs 프로젝트: CyberSys/UTA
 public static PatternParser Pattern(string pattern,
                                     PatternOptions options = PatternOptions.Compiled,
                                     bool omitFromResult    = false)
 {
     return(new PatternParser(new Regex(pattern, (RegexOptions)options), omitFromResult));
 }
예제 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PatternSettings"/> class with a specified options.
 /// </summary>
 /// <param name="options">A bitwise combination of the enumeration values.</param>
 /// <exception cref="ArgumentException"><paramref name="options"/> has both <see cref="PatternOptions.CSharpLiteral"/> flag and <see cref="PatternOptions.VisualBasicLiteral"/> flag set.</exception>
 public PatternSettings(PatternOptions options)
 {
     Options            = options;
     IdentifierBoundary = IdentifierBoundary.AngleBrackets;
     IndentSize         = 4;
 }