Example #1
0
        public void Settings_given_ObjectExists_should_HaveAllProperties()
        {
            //	#	Arrange and Act
            const string MyConfigPath = "myConfigPath";
            const string MyInitPathfilename = "myInitPathFileName";
            const string MyConnectionString = "myConnectionString";
            const string MyDatabaseName = "myDatabaseName";
            const int MyDatabaseIndex = 42;
            const string MyExcludedTablesRegex = "myExcludedTablesRegex";
            const string MyDatabaseXmlFile = "myDatabaseXmlFile";
            const string MyProjectPath = "MyProjectPath";
            var sut = new ParserSettings(
                MyConfigPath,
                MyInitPathfilename,
                MyConnectionString,
                MyDatabaseName,
                MyDatabaseIndex,
                MyExcludedTablesRegex,
                MyDatabaseXmlFile,
                MyProjectPath);

            //	#	Assert.
            Assert.AreEqual(MyConfigPath, sut.ConfigPath);
            Assert.AreEqual(MyInitPathfilename, sut.InitPathfilename);
            Assert.AreEqual(MyConnectionString, sut.ConnectionString);
            Assert.AreEqual(MyDatabaseName, sut.DatabaseName);
            Assert.AreEqual(MyDatabaseIndex, sut.DatabaseIndex);
            Assert.AreEqual(MyExcludedTablesRegex, sut.ExcludedTablesRegex);
            Assert.AreEqual(MyDatabaseXmlFile, sut.DatabaseXmlFile);
            Assert.AreEqual(MyProjectPath, sut.ProjectPath);

            Assert.IsFalse(
                sut.GetType().GetProperties().Any(p => p.GetValue(sut, null) == null),
                "All properties should be set for this test to work properly.");
        }
        public void Setting_instance_is_not_reusable()
        {
            var settings = new ParserSettings(helpWriter: Console.Out);

            var parser = new CommandLine.Parser(settings);

            Assert.ThrowsDelegate act = () => { var parser2 = new CommandLine.Parser(settings); };

            Assert.Throws<InvalidOperationException>(act);
        }
        public void Setting_instance_became_immutable_after_being_consumed()
        {
            var settings = new ParserSettings { ParsingCulture = new CultureInfo("it-IT") };

            var parser = new CommandLine.Parser(settings);

            Assert.ThrowsDelegate act = () => { settings.HelpWriter = Console.Out; };

            Assert.Throws<InvalidOperationException>(act);
        }
        public void Disposal_does_not_dispose_HelpWriter()
        {
            using (DisposeTrackingStringWriter textWriter = new DisposeTrackingStringWriter())
            {
                using (ParserSettings parserSettings = new ParserSettings())
                {
                    parserSettings.HelpWriter = textWriter;
                }

                textWriter.Disposed.Should().BeFalse("not disposed");
            }
        }
Example #5
0
        /// <summary>
        /// Constructor used for testing purpose.
        /// </summary>
        internal OptionMap(int capacity, ParserSettings settings)
        {
            _settings = settings;

            IEqualityComparer<string> comparer =
                _settings.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
            _names = new Dictionary<string, string>(capacity, comparer);
            _map = new Dictionary<string, OptionInfo>(capacity * 2, comparer);
            if (_settings.MutuallyExclusive)
            {
                _mutuallyExclusiveSetMap = new Dictionary<string, MutuallyExclusiveInfo>(capacity, StringComparer.OrdinalIgnoreCase);
            }
        }
        public void Setting_help_writer_using_property()
        {
            var writer = new StringWriter();
            var settings = new ParserSettings();
            settings.HelpWriter = writer;
            IParser parser = new Parser(settings);
            var options = new SimpleOptionsWithHelpOption();

            bool success = parser.ParseArguments(new string[] { "--help" }, options);

            success.Should().BeFalse();
            writer.ToString().Should().Be("MockOptions::GetUsage()");
        }
 public TestOptionalsAlternatePrefixCharsMultipleShortArgs()
 {
     ParserSignature = new ParserSettings {Prefixes = new[] {"+", "-"}};
     ArgumentSignatures = new[]
     {
         new Argument("-x") {ActionName = "store_true"}, new Argument("+y") {ActionName = "store_true"},
         new Argument("+z") {ActionName = "store_true"}
     };
     Failures = new[] {"-w", "-xyz", "+x", "-y", "+xyz"};
     Successes = new SuccessCollection
     {
         {"", new ParseResult {{"x", false}, {"y", false}, {"z", false}}},
         {"-x", new ParseResult {{"x", true}, {"y", false}, {"z", false}}},
         {"+y -x", new ParseResult {{"x", true}, {"y", true}, {"z", false}}},
         {"+yz -x", new ParseResult {{"x", true}, {"y", true}, {"z", true}}}
     };
 }
Example #8
0
 public static OptionMap Create(object target, ParserSettings settings)
 {
     var list = ReflectionUtil.RetrievePropertyList<BaseOptionAttribute>(target);
     if (list == null)
     {
         return null;
     }
     var map = new OptionMap(list.Count, settings);
     foreach (var pair in list)
     {
         if (pair.Left != null && pair.Right != null)
         {
             map[pair.Right.UniqueName] = new OptionInfo(pair.Right, pair.Left);
         }
     }
     map.RawOptions = target;
     return map;
 }
 public TestOptionalsAlternatePrefixChars()
 {
     ParserSignature = new ParserSettings { Prefixes = new[] { "+", ":", "/", "::" } };
     ArgumentSignatures = new[]
     {
         new Argument("+f") {ActionName = "store_true"}, new Argument("::bar"),
         new Argument("/baz") {ActionName = "store_const", ConstValue = 42}
     };
     Failures = new[] { "--bar", "-fbar", "-b B", "B", "-f", "--bar B", "-baz", "-h", "--help", "+h", "::help", "/help" };
     Successes = new SuccessCollection
     {
         {"", new ParseResult {{"bar", null}, {"baz", null}, {"f", false}}},
         {"+f", new ParseResult {{"bar", null}, {"baz", null}, {"f", true}}},
         {"::ba B", new ParseResult {{"bar", "B"}, {"baz", null}, {"f", false}}},
         {"+f ::bar B", new ParseResult {{"bar", "B"}, {"baz", null}, {"f", true}}},
         {"+f /b", new ParseResult {{"bar", null}, {"baz", 42}, {"f", true}}},
         {"/ba +f", new ParseResult {{"bar", null}, {"baz", 42}, {"f", true}}}
     };
 }
 public TestPrefixCharacterOnlyArguments()
 {
     ParserSignature = new ParserSettings { Prefixes = new[] { "-", "+" } };
     ArgumentSignatures = new[]
     {
         new Argument("-") {ConstValue = "badger", Destination = "x", ValueCount = new ValueCount("?")},
         new Argument("+") {Destination = "y", DefaultValue = 42, Type = typeof(int)},
         new Argument("-+-") {ActionName = "store_true", Destination = "z"}
     };
     Failures = new[] {"-y", "+ -"};
     Successes = new SuccessCollection
     {
         {"", new ParseResult {{"x", null}, {"y", 42}, {"z", false}}},
         {"-", new ParseResult {{"x", "badger"}, {"y", 42}, {"z", false}}},
         {"- X", new ParseResult {{"x", "X"}, {"y", 42}, {"z", false}}},
         {"+ -3", new ParseResult {{"x", null}, {"y", -3}, {"z", false}}},
         {"-+-", new ParseResult {{"x", null}, {"y", 42}, {"z", true}}},
         {"- ===", new ParseResult {{"x", "==="}, {"y", 42}, {"z", false}}}
     };
 }
		public ParserArguments(
			string expressionText, 
			ParserSettings settings, 
			Type expressionReturnType,
			IEnumerable<Parameter> declaredParameters
		)
		{
			ExpressionText = expressionText;
			ExpressionReturnType = expressionReturnType;

			Settings = settings;
			_declaredParameters = new Dictionary<string, Parameter>(settings.KeyComparer);
			foreach (var pe in declaredParameters)
			{
				try
				{
					_declaredParameters.Add(pe.Name, pe);
				}
				catch (ArgumentException)
				{
					throw new DuplicateParameterException(pe.Name);
				}
			}
		}
Example #12
0
 private static void ConfigureSettings(ParserSettings settings)
 {
     settings.MutuallyExclusive = true;
     settings.HelpWriter        = System.Console.Out;
 }
 public GeoJsonSerializer(JsonTextWriter writer, ParserSettings settings)
     : base(writer, settings)
 {
     _geometrySerializer = new GeometrySerializer(writer, settings);
 }
 public FhirJsonTryteSerializer(ParserSettings parserSettings, SerializerSettings serializerSettings)
 {
     this.Parser     = new FhirJsonParser(parserSettings);
     this.Serializer = new FhirJsonSerializer(serializerSettings);
 }
Example #15
0
 public StreamIniParser(ParserSettings settings = null)
 => _settings = settings ?? new ParserSettings();
Example #16
0
 public ParsedLog(string buildVersion, FightData fightData, AgentData agentData, SkillData skillData,
                  List <CombatItem> combatItems, List <Player> playerList, long evtcLogDuration, ParserSettings parserSettings, OperationController operation)
 {
     FightData      = fightData;
     AgentData      = agentData;
     SkillData      = skillData;
     PlayerList     = playerList;
     ParserSettings = parserSettings;
     _operation     = operation;
     //
     PlayerListBySpec = playerList.GroupBy(x => x.Prof).ToDictionary(x => x.Key, x => x.ToList());
     PlayerAgents     = new HashSet <AgentItem>(playerList.Select(x => x.AgentItem));
     _operation.UpdateProgressWithCancellationCheck("Creating GW2EI Combat Events");
     CombatData = new CombatData(combatItems, FightData, AgentData, SkillData, playerList);
     _operation.UpdateProgressWithCancellationCheck("Creating GW2EI Log Meta Data");
     LogData = new LogData(buildVersion, CombatData, evtcLogDuration);
     _operation.UpdateProgressWithCancellationCheck("GW2 Build " + LogData.GW2Version);
     //
     _operation.UpdateProgressWithCancellationCheck("Checking Success");
     FightData.Logic.CheckSuccess(CombatData, AgentData, FightData, PlayerAgents);
     if (FightData.FightEnd <= 2200)
     {
         throw new TooShortException();
     }
     if (ParserSettings.SkipFailedTries && !FightData.Success)
     {
         throw new SkipException();
     }
     _operation.UpdateProgressWithCancellationCheck("Checking CM");
     FightData.SetCM(CombatData, AgentData, FightData);
     //
     _operation.UpdateProgressWithCancellationCheck("Creating Buff Container");
     Buffs = new BuffsContainer(LogData.GW2Version);
     _operation.UpdateProgressWithCancellationCheck("Creating Damage Modifier Container");
     DamageModifiers = new DamageModifiersContainer(LogData.GW2Version);
     _operation.UpdateProgressWithCancellationCheck("Creating Mechanic Data");
     MechanicData = FightData.Logic.GetMechanicData();
     _operation.UpdateProgressWithCancellationCheck("Creating General Statistics Container");
     Statistics = new GeneralStatistics(CombatData, PlayerList, Buffs);
 }
Example #17
0
 public WebOfScienceParser(ParserSettings settings) : base(settings)
 {
 }
Example #18
0
 public ParserManager(Grammar grammar, ParserSettings settings)
     : this(grammar, settings.Algorithm, settings.NestingType, settings.Unit)
 {
 }
Example #19
0
        static void Main(string[] args)
        {
            var options = new Options();

            CommandLine.ParserSettings parserSettings = new ParserSettings();
            parserSettings.HelpWriter = Console.Error;
            CommandLine.Parser parser = new Parser(parserSettings);
            if (parser.ParseArguments(args, options))
            {
                if (options.Verbose)
                {
                    Console.WriteLine(options.Model);
                    Console.WriteLine(options.IP);
                    Console.WriteLine(options.Port);
                }
            }
            else
            {
                Environment.Exit(1);
            }

            string output;

/*
 *          string test1 = "{\"SettingInfo\":[{\"id\":40, \"name\":\"Boat Type\", \"type\":1, \"values\":[{\"id\":0, \"title\":\"Sailing\"}, {\"id\":1,\"title\":\"Fishing\"}, {\"id\":2, \"title\":\"Planing\" }]}]}";
 *          RootSettingInfo rootSettingInfo1 = JsonConvert.DeserializeObject<RootSettingInfo>(test1);
 *
 *          string test2 = "{\"SettingInfo\":[{\"id\":1,\"name\":\"Backlight Level\",\"type\":2,\"low\":0,\"high\":10}]}";
 *          RootSettingInfo rootSettingInfo2 = JsonConvert.DeserializeObject<RootSettingInfo>(test2);
 *
 *          string test3 = "{\"SettingInfo\":[{\"id\":2,\"name\":\"Night Mode\",\"type\":3}]}";
 *          RootSettingInfo rootSettingInfo3 = JsonConvert.DeserializeObject<RootSettingInfo>(test3);
 */

            Navico.NavicoDiscovery.MFD websocketMFD = null;

            if ((options.IP == null) && (options.Port == null))
            {
                List <Navico.NavicoDiscovery.MFD> MFDList = new List <Navico.NavicoDiscovery.MFD>();

                Thread newThread;
                newThread = new Thread(() => Navico.NavicoDiscovery.ReceiveNewMessage(MFDList));
                newThread.IsBackground = true;
                newThread.Start();

                newThread.Join();

                foreach (Navico.NavicoDiscovery.MFD mfd in MFDList)
                {
                    if (options.Model != null)
                    {
//                        if (string.Compare(mfd.Model, options.Model, true) != 0)
                        if (mfd.Model.IndexOf(options.Model) != 0)
                        {
                            continue;
                        }
                    }
                    if (options.IP != null)
                    {
//                        if (string.Compare(mfd.IP, options.IP, true) != 0)
                        if (mfd.IP.IndexOf(options.IP) != 0)
                        {
                            continue;
                        }
                    }

                    DbgOutput(string.Format("MFD: {0}\tModel: {1}\tIP: {2}", mfd.Name, mfd.Model, mfd.IP));
                    foreach (Navico.NavicoDiscovery.MFDService service in mfd.Services)
                    {
                        DbgOutput(string.Format("\tService: {0}\tVersion: {1}\tPort: {2}", service.Service, service.Version, service.Port));

                        if ((service.Service == "navico-nav-ws") /*|| (service.Service == "navico-navdata-websocket")*/)
                        {
                            if (websocketMFD == null)
                            {
                                websocketMFD             = mfd;
                                websocketMFD.Services    = null;
                                websocketMFD.Services    = new NavicoDiscovery.MFDService[1];
                                websocketMFD.Services[0] = service;
                            }
                        }
                    }
                }

                if (websocketMFD == null)
                {
                    return;
                }
            }
            else
            {
                websocketMFD          = new NavicoDiscovery.MFD();
                websocketMFD.IP       = options.IP;
                websocketMFD.Services = new NavicoDiscovery.MFDService[1];

                uint port = 2053;
                if (!options.Port.IsNullOrEmpty())
                {
                    port = Convert.ToUInt32(options.Port);
                }
                websocketMFD.Services[0] = new NavicoDiscovery.MFDService("navico-nav-ws", 0, port);
            }

            DbgOutput(string.Format("Connect to {0}:{1}", websocketMFD.IP, websocketMFD.Services[0].Port));

            string wsURL;

            wsURL = string.Format("ws://{0}:{1}", websocketMFD.IP, websocketMFD.Services[0].Port);
            //wsURL = string.Format("ws://172.28.29.224:2053");
            using (GoFree streamer = new GoFree(wsURL))
            {
                Listener l = new Listener(streamer);
                l.Subscribe(streamer);
                streamer.Connect();

                Thread.Sleep(500);
                Console.WriteLine("\nType \"exit\" to exit.\n");

                string data;

                if (options.RequestingAListOfDataIDs)
                {
                    DbgOutput("Requesting a list of data IDs");

//                    data = "{\"DataListReq\":{\"group\":1}}";
//                    streamer.Write(data);

                    RootDataListReq rootDataListReq = new RootDataListReq();
                    rootDataListReq.DataListReq = new DataListReq();

                    foreach (eDataGroup dataGroup in System.Enum.GetValues(typeof(eDataGroup)))
                    {
                        rootDataListReq.DataListReq.group = (int)dataGroup;
                        data = JsonConvert.SerializeObject(rootDataListReq);
                        streamer.Write(data);
                    }

                    Thread.Sleep(1000);
                }

                if (options.RequestFullInformationAboutADataValue)
                {
                    DbgOutput("Request full information about a data value");

//                    data = "{\"DataInfoReq\":[40]}";
//                    streamer.Write(data);

                    foreach (eDataType dataType in System.Enum.GetValues(typeof(eDataType)))
                    {
                        RootDataInfoReq rootDataInfoReq = new RootDataInfoReq();
                        rootDataInfoReq.DataInfoReq = new List <int>();
                        rootDataInfoReq.DataInfoReq.Add((int)dataType);
                        data = JsonConvert.SerializeObject(rootDataInfoReq);
                        streamer.Write(data);
                    }

                    Thread.Sleep(1000);
                }

                if (options.RequestingAValue)
                {
                    DbgOutput("Requesting a value");

//                    data = "{\"DataReq\":[{\"id\":1,\"repeat\":false,\"inst\":0}]}";
//                    streamer.Write(data);

                    foreach (eDataType dataType in System.Enum.GetValues(typeof(eDataType)))
                    {
                        RootDataReq rootDataReq = new RootDataReq();
                        rootDataReq.DataReq = new List <DataReq>();
                        DataReq dataReq = new DataReq();
                        dataReq.id = (int)dataType;
                        rootDataReq.DataReq.Add(dataReq);
                        data = JsonConvert.SerializeObject(rootDataReq);
                        streamer.Write(data);
                    }

                    Thread.Sleep(1000);
                }

                if (options.RequestASettingsGroup)
                {
                    DbgOutput("Request a settings group");

//                    data = "{\"SettingListReq\":[{\"group\":1}]}";
//                    streamer.Write(data);

                    foreach (eDataGroup dataGroup in System.Enum.GetValues(typeof(eDataGroup)))
                    {
                        RootSettingListReq rootSettingListReq = new RootSettingListReq();
                        rootSettingListReq.SettingListReq = new List <SettingListReq>();
                        SettingListReq settingListReq = new SettingListReq();
                        settingListReq.groupId = (int)dataGroup;
                        rootSettingListReq.SettingListReq.Add(settingListReq);
                        data = JsonConvert.SerializeObject(rootSettingListReq);
                        streamer.Write(data);
                    }

                    Thread.Sleep(1000);
                }

                if (options.RequestSettingInformation)
                {
                    DbgOutput("Request setting information");

//                    data = "{\"SettingInfoReq\":[1]}";
//                    streamer.Write(data);

                    foreach (eSettingIDs setting in System.Enum.GetValues(typeof(eSettingIDs)))
                    {
                        RootSettingInfoReq rootSettingInfoReq = new RootSettingInfoReq();
                        rootSettingInfoReq.SettingInfoReq = new List <int>();
                        rootSettingInfoReq.SettingInfoReq.Add((int)setting);
                        data = JsonConvert.SerializeObject(rootSettingInfoReq);
                        streamer.Write(data);
                    }

                    Thread.Sleep(1000);
                }

                if (options.RequestAListOfSettings)
                {
                    DbgOutput("Request a list of settings");

//                    data = "{\"SettingReq\":{\"ids\":[1,2,3],\"register\":false}}";
//                    streamer.Write(data);

                    foreach (eSettingIDs setting in System.Enum.GetValues(typeof(eSettingIDs)))
                    {
                        RootSettingReq rootSettingReq = new RootSettingReq();
                        rootSettingReq.SettingReq     = new SettingReq();
                        rootSettingReq.SettingReq.ids = new List <int>();
                        rootSettingReq.SettingReq.ids.Add((int)setting);
                        data = JsonConvert.SerializeObject(rootSettingReq);
                        streamer.Write(data);
                    }

                    Thread.Sleep(1000);
                }

                if (options.RegisterToReceiveAnEvent)
                {
                    DbgOutput("Register to receive an event");

//                    data = "{\"EventReg\":[1,2]}";
//                    streamer.Write(data);

                    foreach (eEvents eventValue in System.Enum.GetValues(typeof(eEvents)))
                    {
                        RootEventReg rootEventReg = new RootEventReg();
                        rootEventReg.EventReg = new List <int>();
                        rootEventReg.EventReg.Add((int)eventValue);
                        data = JsonConvert.SerializeObject(rootEventReg);
                        streamer.Write(data);
                    }

                    Thread.Sleep(1000);
                }

/*
 *              if (true)
 *              {
 *                  DbgOutput("Set event");
 *
 *                  foreach (eEvents eventValue in System.Enum.GetValues(typeof(eEvents)))
 *                  {
 *                      RootEventSet rootEventSet = new RootEventSet();
 *                      rootEventSet.EventSet = new List<EventSet>();
 *                      EventSet eventSet = new EventSet();
 *                      eventSet.id = (int)eventValue;
 *                      eventSet.
 *                      rootEventSet.EventSet.Add(eventSet);
 *                      data = JsonConvert.SerializeObject(rootEventSet);
 *                      streamer.Write(data);
 *                  }
 *
 *                  Thread.Sleep(1000);
 *              }
 */

                if (options.MOBEvent)
                {
                    DbgOutput("MOB event");

                    RootEventSet rootEventSet = new RootEventSet();
                    rootEventSet.EventSet = new List <EventSet>();
                    EventSet eventSet = new EventSet();
                    eventSet.id     = (int)eEvents.MOB;
                    eventSet.name   = "MOB";
                    eventSet.active = true;
                    rootEventSet.EventSet.Add(eventSet);
                    data = JsonConvert.SerializeObject(rootEventSet);
                    streamer.Write(data);

                    Thread.Sleep(1000);
                }

                if (options.CreateAWaypoint)
                {
                    DbgOutput("Create a waypoint");

                    RootEventSet rootEventSet = new RootEventSet();
                    rootEventSet.EventSet = new List <EventSet>();
                    EventSet eventSet = new EventSet();
                    eventSet.id        = (int)eEvents.WaypointCreate;
                    eventSet.latitude  = 50.9892;
                    eventSet.longitude = -1.4975;
                    eventSet.wpName    = "Waypoint1";
                    rootEventSet.EventSet.Add(eventSet);
                    data = JsonConvert.SerializeObject(rootEventSet);
                    streamer.Write(data);

                    Thread.Sleep(1000);
                }

                if (options.ActivateSilenceAcknowledgeDeactivateAnAlarm)
                {
                    DbgOutput("Activate/Silence/Acknowledge/Deactivate an alarm");

                    RootEventSet rootEventSet = new RootEventSet();
                    rootEventSet.EventSet = new List <EventSet>();
                    EventSet eventSet = new EventSet();
//                    eventSet.id = (int)eEvents.AlarmActivate;
                    eventSet.id = (int)eEvents.AlarmSilence;
//                    eventSet.id = (int)eEvents.AlarmAcknowledge;
//                    eventSet.id = (int)eEvents.AlarmDeactivate;
                    eventSet.alarmId   = 5;
                    eventSet.alarmText = "Low Speed";
                    eventSet.severity  = 1;
                    rootEventSet.EventSet.Add(eventSet);
                    data = JsonConvert.SerializeObject(rootEventSet);
                    streamer.Write(data);

                    Thread.Sleep(1000);
                }

                if (options.ResetATripLog)
                {
                    DbgOutput("Reset a trip log");

                    RootEventSet rootEventSet = new RootEventSet();
                    rootEventSet.EventSet = new List <EventSet>();
                    EventSet eventSet = new EventSet();
                    eventSet.id   = (int)eEvents.TripLogReset;
                    eventSet.inst = 0;
                    rootEventSet.EventSet.Add(eventSet);
                    data = JsonConvert.SerializeObject(rootEventSet);
                    streamer.Write(data);

                    Thread.Sleep(1000);
                }

                if (options.RegisterForVesselsId)
                {
                    DbgOutput("Register for vessels (id)");

//                    data = "{\"TrafficReq\":{\"subscribe\":true,\"id\":12345,\"sourceType\":0}}";
//                    streamer.Write(data);

                    RootTrafficReq rootTrafficReq = new RootTrafficReq();
                    rootTrafficReq.TrafficReq            = new TrafficReq();
                    rootTrafficReq.TrafficReq.subscribe  = true;
                    rootTrafficReq.TrafficReq.id         = 12345;
                    rootTrafficReq.TrafficReq.sourceType = 0;
                    data = JsonConvert.SerializeObject(rootTrafficReq);
                    streamer.Write(data);

                    Thread.Sleep(1000);
                }

                if (options.RegisterForVesselsType)
                {
                    DbgOutput("Register for vessels (type)");

//                    data = "{\"TrafficReg\":[0,2]}";
//                    streamer.Write(data);

                    RootTrafficReg rootTrafficReg = new RootTrafficReg();
                    rootTrafficReg.TrafficReg = new List <int>();
                    rootTrafficReg.TrafficReg.Add(0);
                    rootTrafficReg.TrafficReg.Add(2);
                    data = JsonConvert.SerializeObject(rootTrafficReg);
                    streamer.Write(data);
                }

                while (true)
                {
                    Thread.Sleep(500);

                    Console.Write("> ");
                    data = Console.ReadLine();
                    if (data == "exit")
                    {
                        break;
                    }

                    streamer.Write(data);
                }
            }
        }
Example #20
0
 private OptionMap(int capacity, ParserSettings settings)
Example #21
0
        static async Task Main(string[] args)
        {
            var settings  = new ParserSettings <Options>();
            var parser    = new CliParser <Options>();
            var validator = new BasicParseValidator <Options>();

            parser.Validator = validator;
            validator.AddRule(o => {
                if (o.Search == null || o.Search.HexCodes == null)
                {
                    return(null);
                }
                foreach (var code in o.Search.HexCodes)
                {
                    if (!Regex.IsMatch(code, "(0x)?[0-9A-Fa-f]{6}"))
                    {
                        return(new ValidationFailure(
                                   nameof(o.Search.HexCodes),
                                   $"HexCodes input '{code}' is not a valid six-character hex code."));
                    }
                }
                return(null);
            });
            validator.AddRule(o => {
                if (o?.Search?.HexCodes != null && o.Search.HexCodes.Count > 5)
                {
                    return(new ValidationFailure(
                               nameof(o.Search.HexCodes),
                               $"The service supports up to 5 hex codes. You provided {o.Search.HexCodes.Count}"
                               ));
                }
                return(null);
            });

            var opts = new Options();

            parser.Parse(args, opts);

            var api = new Api();

            if (opts.Color != null)
            {
                try
                {
                    var pal = await api.GetPalette(opts.Color.Id);

                    Program.PrintPalette(pal);
                }
                catch (ArgumentException e)
                {
                    Console.Error.WriteLine(e.Message);
                    return;
                }
            }
            if (opts.Search != null)
            {
                try
                {
                    var pals = await api.SearchPalettes(opts.Search);

                    if (pals.Count == 0)
                    {
                        Console.Error.WriteLine("No palettes found for search criteria.");
                        return;
                    }
                    Program.PrintPalettes(pals);
                }
                catch (ArgumentException e)
                {
                    Console.Error.WriteLine(e.Message);
                    return;
                }
            }
        }
Example #22
0
        /// <summary>
        /// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults.
        /// </summary>
        /// <returns>
        /// An instance of <see cref="CommandLine.Text.HelpText"/> class.
        /// </returns>
        /// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
        /// <param name='onError'>A delegate used to customize the text block of reporting parsing errors text block.</param>
        /// <param name='onExample'>A delegate used to customize <see cref="CommandLine.Text.Example"/> model used to render text block of usage examples.</param>
        /// <param name="verbsIndex">If true the output style is consistent with verb commands (no dashes), otherwise it outputs options.</param>
        /// <param name="maxDisplayWidth">The maximum width of the display.</param>
        /// <param name="parserSettings">Settings of the parser. Some settings are for help display.</param>
        /// <remarks>The parameter <paramref name="verbsIndex"/> is not ontly a metter of formatting, it controls whether to handle verbs or options.</remarks>
        public static HelpText AutoBuild <T>(
            ParserResult <T> parserResult,
            Func <HelpText, HelpText> onError,
            Func <Example, Example> onExample,
            ParserSettings parserSettings,
            bool verbsIndex     = false,
            int maxDisplayWidth = DefaultMaximumLength)
        {
            var auto = new HelpText
            {
                Heading   = HeadingInfo.Empty,
                Copyright = CopyrightInfo.Empty,
                AdditionalNewLineAfterOption = parserSettings.AdditionalNewLineAfterOption,
                AddDashesToOption            = !verbsIndex,
                MaximumDisplayWidth          = maxDisplayWidth
            };

            try
            {
                auto.Heading   = HeadingInfo.Default;
                auto.Copyright = CopyrightInfo.Default;
            }
            catch (Exception)
            {
                auto = onError(auto);
            }

            var errors = Enumerable.Empty <Error>();

            if (onError != null && parserResult.Tag == ParserResultType.NotParsed)
            {
                errors = ((NotParsed <T>)parserResult).Errors;

                if (errors.OnlyMeaningfulOnes().Any())
                {
                    auto = onError(auto);
                }
            }

            ReflectionHelper.GetAttribute <AssemblyLicenseAttribute>()
            .Do(license => license.AddToHelpText(auto, true));

            var usageAttr  = ReflectionHelper.GetAttribute <AssemblyUsageAttribute>();
            var usageLines = HelpText.RenderUsageTextAsLines(parserResult, onExample).ToMaybe();

            if (usageAttr.IsJust() || usageLines.IsJust())
            {
                var heading = auto.SentenceBuilder.UsageHeadingText();
                if (heading.Length > 0)
                {
                    auto.AddPreOptionsLine(heading);
                }
            }

            usageAttr.Do(
                usage => usage.AddToHelpText(auto, true));

            usageLines.Do(
                lines => auto.AddPreOptionsLines(lines));

            if ((verbsIndex && parserResult.TypeInfo.Choices.Any()) ||
                errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
            {
                auto.AddDashesToOption = false;
                auto.AddVerbs(parserResult.TypeInfo.Choices.ToArray());
            }
            else
            {
                auto.AddOptions(parserResult);
            }

            return(auto);
        }
Example #23
0
 public HtmlLoader(ParserSettings settings)
 {
     client = new HtmlWeb();
     url    = $"{settings.BaseUrl}/{settings.Prefix}";
 }
Example #24
0
        ////////////////////////////

        /// <summary>
        /// Zwraca przygotowane wyrażenie
        /// </summary>
        public void PrepareMainExpression(
            String ExpressionId,
            IList <Char> ExpressionChars,
            ParserSettings ParserSettings,
            ExpressionGroup ExpressionGroup)
        {
            try
            {
                Expression onpExpression = new Expression(ExpressionId);
                onpExpression.Tokens = TokenGetter.GetOptimizedTokens(ExpressionChars, ParserSettings);
                ExpressionGroup.Expressions[ExpressionId] = onpExpression;

                // zamiania znaków równości na wołanie funkcji
                List <ExpressionTokens> resultTokens = new List <ExpressionTokens>();
                while (true)
                {
                    ExpressionTokens setTokens = TakeSetTokens(
                        onpExpression.Tokens);

                    if (setTokens == null)
                    {
                        break;
                    }

                    resultTokens.Insert(0, setTokens);
                }

                Expression currentExpression = onpExpression;
                foreach (ExpressionTokens resultToken in resultTokens)
                {
                    Expression setExpression = new Expression();
                    setExpression.IsOnpExecution = false;
                    setExpression.Tokens         = resultToken;

                    ExpressionGroup.Expressions[setExpression.ID] = setExpression;

                    PrepareExpressions(
                        setExpression,
                        ParserSettings,
                        ExpressionGroup);

                    CorrectSetExpression(
                        setExpression,
                        currentExpression.ID,
                        ParserSettings,
                        ExpressionGroup);

                    currentExpression = setExpression;
                }

                ExpressionGroup.MainExpression = currentExpression;

                PrepareExpressions(
                    onpExpression,
                    ParserSettings,
                    ExpressionGroup);
            }
            catch (Exception ex)
            {
                throw new DynLanCompileException(
                          "Error in expression: '" + new string(Linq2.ToArray(ExpressionChars), 0, ExpressionChars.Count).Replace("'", "\\'") + "'; " + ex.Message,
                          ex);
            }
        }
Example #25
0
		public Detector(ParserSettings settings)
		{
			_settings = settings;
		}
Example #26
0
 public HelpCommand([NotNull] ParserSettings parserSettings) : base(Strings.Commands.Help)
 {
     ParserSettings = parserSettings;
 }
Example #27
0
        private Parser CreateTestParser(StringBuilder sb)
        {
            ParserSettings settings = new ParserSettings(new StringWriter(sb));

            return(new Parser(settings));
        }
Example #28
0
        /// <summary>
        /// Odszukanie ciągów QUEUE w wyrażeniu
        /// </summary>
        public void PrepareQueueExpressions(
            IList <ExpressionToken> Tokens,
            ParserSettings ParserSettings,
            ExpressionGroup ExpressionGroup)
        {
            ExpressionTokens outTokens    = new ExpressionTokens();
            ExpressionTokens queueTokens  = null;
            Boolean          queueStarted = false;
            Int32            startIndex   = -1;
            Int32            endIndex     = -1;

            for (var i = 0; i < Tokens.Count; i++)
            {
                ExpressionToken token = Tokens[i];

                // rozpoczecie sekwencji queue
                if (token != null &&
                    queueStarted == false &&
                    (OnpOnpTokenHelper.IsPropertyOperatorToken(token) || OnpOnpTokenHelper.IsFunctionOperatorToken(token)))
                {
                    ExpressionTokens sequence = new ExpressionTokens(
                        GetNextTokensOnSameLevel(Tokens, i));

                    ExpressionTokens prevSequence = new ExpressionTokens(
                        GetPrevTokensOnSameLevel(Tokens, i - 1));

                    if (queueTokens == null)
                    {
                        queueTokens = new ExpressionTokens();
                    }

                    if (prevSequence == null)
                    {
                        throw new FormatException();
                    }

                    queueTokens.AddRange(prevSequence);
                    queueTokens.AddRange(sequence);

                    queueStarted = true;
                    startIndex   = i - prevSequence.Count;

                    i += sequence.Count - 1;
                }
                // zakończenie sekwencji queue
                else if (
                    token != null &&
                    queueStarted == true &&
                    (
                        token.TokenType == TokenType.BRACKET_END ||
                        token.TokenType == TokenType.OPERATOR &&
                        !OnpOnpTokenHelper.IsPropertyOperatorToken(token) &&
                        !OnpOnpTokenHelper.IsFunctionOperatorToken(token)
                    ))
                {
                    endIndex = i - 1;

                    // zastapienie ciagu tokenków zmienną i podpiecie nowego wyrazenia do zmiennej
                    if (queueTokens != null && queueTokens.Count > 0)
                    {
                        ExpressionToken newToken = CreateQueueExpression(
                            queueTokens,
                            ParserSettings,
                            ExpressionGroup);

                        for (var j = endIndex; j >= startIndex; j--)
                        {
                            Tokens.RemoveAt(j);
                            i--;
                        }
                        Tokens.Insert(startIndex, newToken);
                    }

                    queueTokens  = null;
                    endIndex     = -1;
                    startIndex   = -1;
                    queueStarted = false;
                }
                // kontynuacja sekwencji queue
                else if (queueStarted == true)
                {
                    ExpressionTokens sequence = new ExpressionTokens(
                        GetNextTokensOnSameLevel(Tokens, i));

                    queueTokens.AddRange(
                        sequence);

                    i += sequence.Count - 1;
                }
            }

            // zastapienie ciagu tokenków zmienną i podpiecie nowego wyrazenia do zmiennej
            if (queueTokens != null && queueTokens.Count > 0)
            {
                endIndex = Tokens.Count - 1;

                ExpressionToken newToken = CreateQueueExpression(
                    queueTokens,
                    ParserSettings,
                    ExpressionGroup);

                for (var j = endIndex; j >= startIndex; j--)
                {
                    Tokens.RemoveAt(j);
                }

                Tokens.Insert(startIndex, newToken);
            }

            queueTokens = null;
            endIndex    = -1;
            startIndex  = -1;
        }
Example #29
0
 public override TokenParseResult Parse(Token token, ParserSettings settings)
 {
     return(GroupingType.ParseRule(this, token, settings));
 }
Example #30
0
        public static OptionMap Create(
            object target,
            IList<Pair<PropertyInfo, VerbOptionAttribute>> verbs,
            ParserSettings settings)
        {
            var map = new OptionMap(verbs.Count, settings);

            foreach (var verb in verbs)
            {
                var optionInfo = new OptionInfo(verb.Right, verb.Left, settings.ParsingCulture)
                {
                    HasParameterLessCtor = verb.Left.PropertyType.GetConstructor(Type.EmptyTypes) != null
                };

                if (!optionInfo.HasParameterLessCtor && verb.Left.GetValue(target, null) == null)
                {
                    throw new ParserException("Type {0} must have a parameterless constructor or" +
                        " be already initialized to be used as a verb command.".FormatInvariant(verb.Left.PropertyType));
                }

                map[verb.Right.UniqueName] = optionInfo;
            }

            map.RawOptions = target;
            return map;
        }
Example #31
0
        internal static Bundle.EntryComponent ToBundleEntry(this HttpWebResponse response, byte[] body, ParserSettings parserSettings, bool throwOnFormatException)
        {
            var result = new Bundle.EntryComponent();

            result.Response        = new Bundle.ResponseComponent();
            result.Response.Status = ((int)response.StatusCode).ToString();
            result.Response.SetHeaders(response.Headers);

            var contentType  = getContentType(response);
            var charEncoding = getCharacterEncoding(response);

            result.Response.Location = response.Headers[HttpUtil.LOCATION] ?? response.Headers[HttpUtil.CONTENTLOCATION];

#if PORTABLE45
            if (!String.IsNullOrEmpty(response.Headers[HttpUtil.LASTMODIFIED]))
            {
                result.Response.LastModified = DateTimeOffset.Parse(response.Headers[HttpUtil.LASTMODIFIED]);
            }
#else
            result.Response.LastModified = response.LastModified;
#endif
            result.Response.Etag = getETag(response);

            if (body != null)
            {
                result.Response.SetBody(body);

                if (IsBinaryResponse(response.ResponseUri.OriginalString, contentType))
                {
                    result.Resource = makeBinaryResource(body, contentType);
                    if (result.Response.Location != null)
                    {
                        var ri = new ResourceIdentity(result.Response.Location);
                        result.Resource.Id             = ri.Id;
                        result.Resource.Meta           = new Meta();
                        result.Resource.Meta.VersionId = ri.VersionId;
                        result.Resource.ResourceBase   = ri.BaseUri;
                    }
                }
                else
                {
                    var bodyText = DecodeBody(body, charEncoding);
                    var resource = parseResource(bodyText, contentType, parserSettings, throwOnFormatException);
                    result.Resource = resource;

                    if (result.Response.Location != null)
                    {
                        result.Resource.ResourceBase = new ResourceIdentity(result.Response.Location).BaseUri;
                    }
                }
            }

            return(result);
        }
Example #32
0
 public ScopusParser(ParserSettings settings) : base(settings)
 {
 }
Example #33
0
        public CommandParser(Parameters parameters)
        {
            command = new Command("", parameters);

            var grammar = $@"
equals = ""="";

shortOptions = /(?<= )-[_\w]+/;
shortOption = /(?<= )-[_\w]/;
longOption = /(?<= )--[_\w][-_\w]*/;
endOptions = /(?<= )--(?= )/;
doubleString = /""(?:\\\\""|\\\\[^""]|[^""\\\\])*""/;
singleString = /'(?:\\\\'|\\\\[^']|[^'\\\\])*'/;
identifier = /[_\w][-_\w]*/;
literal = /.+/;
ws = /\s+/;
path = /(([A-Za-z]:)?[\/\\\\])?[-_\\w.]+([\/\\\\][-_\\w.]+)*[\/\\\\]?/;

string = doubleString | singleString;
shortOptionWithValue = shortOption equals (identifier | string);
longOptionWithValue = longOption equals (identifier | string);

options = *(shortOptionWithValue | longOptionWithValue | shortOptions | longOption | identifier | string);

details = options ?(endOptions literal);

root = (string | path) ?details;
";

            var parserGen = new ParserGenerator();
            var settings  = new ParserSettings
            {
                Algorithm   = Algorithm.LL,
                NestingType = NestingType.Stack,
                Unit        = Unit.Character,
            };

            parser = parserGen.SpawnParser(settings, grammar, "ws");

            parser.AttachAction("shortOptions", (branch, recurse) =>
            {
                var startIndex = branch.Leaf.StartIndex;
                IEnumerable <BranchSemanticNode> nodes = branch.Leaf.MatchedText
                                                         .Skip(1)
                                                         .Select((c, i) =>
                {
                    return(new BranchSemanticNode((int)CommandNodeType.Argument,
                                                  new LeafSemanticNode((int)CommandNodeType.ShortOption, startIndex + 1 + i, c.ToString())));
                });

                return(new BranchSemanticNode((int)CommandNodeType.Arguments, startIndex, nodes));
            });

            parser.AttachAction("shortOption", (branch, recurse) =>
            {
                LeafParseNode nameNode = branch.Leaf;
                var startIndex         = nameNode.StartIndex;
                var name = nameNode.MatchedText[1].ToString();

                return(new BranchSemanticNode((int)CommandNodeType.Argument,
                                              new LeafSemanticNode((int)CommandNodeType.ShortOption, startIndex, name)));
            });

            parser.AttachAction("shortOptionWithValue", (branch, recurse) =>
            {
                LeafParseNode nameNode = branch.GetDescendant(0).Leaf;
                var startIndex         = nameNode.StartIndex;
                var name            = nameNode.MatchedText[1].ToString();
                ISemanticNode value = recurse(branch.GetDescendant(2));

                return(new BranchSemanticNode((int)CommandNodeType.Argument,
                                              new LeafSemanticNode((int)CommandNodeType.ShortOption, startIndex, name),
                                              value));
            });

            parser.AttachAction("longOption", (branch, recurse) =>
            {
                LeafParseNode nameNode = branch.Leaf;
                var startIndex         = nameNode.StartIndex;
                var name = nameNode.MatchedText.Substring(2);

                return(new BranchSemanticNode((int)CommandNodeType.Argument,
                                              new LeafSemanticNode((int)CommandNodeType.LongOption, startIndex, name)));
            });

            parser.AttachAction("longOptionWithValue", (branch, recurse) =>
            {
                LeafParseNode nameNode = branch.GetDescendant(0).Leaf;
                var startIndex         = nameNode.StartIndex;
                var name            = nameNode.MatchedText.Substring(2);
                ISemanticNode value = recurse(branch.GetDescendant(2));

                return(new BranchSemanticNode((int)CommandNodeType.Argument,
                                              new LeafSemanticNode((int)CommandNodeType.LongOption, startIndex, name),
                                              value));
            });

            parser.AttachAction("identifier", (branch, recurse) =>
            {
                LeafParseNode nameNode = branch.Leaf;
                var startIndex         = nameNode.StartIndex;
                var name = nameNode.MatchedText;

                return(new LeafSemanticNode((int)CommandNodeType.String, startIndex, name));
            });

            parser.AttachAction("doubleString", (branch, recurse) =>
            {
                var text = branch.Leaf.MatchedText;
                text     = text
                           .Substring(1, text.Length - 2)
                           .Replace(@"\\", @"\")
                           .Replace(@"\""", @"""");
                var startIndex = branch.Leaf.StartIndex;

                return(new LeafSemanticNode((int)CommandNodeType.String, startIndex, text));
            });

            parser.AttachAction("singleString", (branch, recurse) =>
            {
                var text = branch.Leaf.MatchedText;
                text     = text
                           .Substring(1, text.Length - 2)
                           .Replace(@"\\", @"\")
                           .Replace(@"\'", @"'");
                var startIndex = branch.Leaf.StartIndex;

                return(new LeafSemanticNode((int)CommandNodeType.String, startIndex, text));
            });

            parser.AttachAction("string", (branch, recurse) => recurse(branch.GetDescendant(0)));

            parser.AttachAction("options", (branch, recurse) =>
            {
                IEnumerable <ISemanticNode> options = branch.GetDescendant(0)
                                                      ?.Elements
                                                      ?.Select(recurse);

                return(new BranchSemanticNode((int)CommandNodeType.Options, branch.StartIndex, options ?? new ISemanticNode[0]));
            });

            parser.AttachAction("literal", (branch, recurse) =>
            {
                var value = branch.Leaf.MatchedText;

                return(new LeafSemanticNode((int)CommandNodeType.String, branch.StartIndex, value));
            });

            parser.AttachAction("details", (branch, recurse) =>
            {
                BranchParseNode optionsNode = branch.GetDescendant(0);
                BranchParseNode literalNode = branch.GetDescendant(1, 1);

                var results = new List <ISemanticNode>();

                if (optionsNode != null)
                {
                    results.Add(recurse(optionsNode));
                }
                if (literalNode != null)
                {
                    results.Add(recurse(literalNode));
                }

                return(new BranchSemanticNode((int)CommandNodeType.Details, branch.StartIndex, results));
            });

            parser.AttachAction("path", (branch, recurse) =>
            {
                var value = branch.MatchedText;

                return(new LeafSemanticNode((int)CommandNodeType.String, branch.StartIndex, value));
            });

            parser.AttachAction("root", (branch, recurse) =>
            {
                ISemanticNode path    = recurse(branch.GetDescendant(0));
                ISemanticNode details = recurse(branch.GetDescendant(1));

                return(new BranchSemanticNode((int)CommandNodeType.Root, path, details));
            });
        }
Example #34
0
        /// <summary>
        /// Parses a Group who's children are part of a chain and do not alternate
        /// </summary>
        /// <param name="group"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public TokenParseResult ParseRule(Grouping group, Token startToken, ParserSettings settings)
        {
            List <SyntaxNode> nodes       = new List <SyntaxNode>();
            TokenParseResult  groupResult = TokenParseResult.Failed(startToken);

            TokenParseResult ruleResult;
            int   ruleIdx;
            Rule  rule;
            Token token;
            // got the minimum results and wasn't an exception
            bool lastRuleOK;
            List <SyntaxNode> ruleNodes = new List <SyntaxNode>();

            ruleIdx    = 0;
            token      = startToken;
            lastRuleOK = true;

            while (lastRuleOK && ruleIdx < group.Count && token != null)
            {
                // every rule has its own scope
                rule = group[ruleIdx];
                ruleNodes.Clear();
                lastRuleOK = false;
                while (token != null)
                {
                    if (ruleResult = rule.Parse(token, settings))
                    {
                        ruleNodes.Add(ruleResult);
                        token = ruleResult.NextToken;
                        if (ruleNodes.Count >= rule.Quantifier.MaxValue)
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                lastRuleOK = (rule.Quantifier.MinValue <= ruleNodes.Count) ^ rule.IsException;


                // if we achieved min qty then add to nodes.
                if (lastRuleOK)
                {
                    nodes.AddRange(ruleNodes);
                    ruleIdx++;
                }
            }

            if (lastRuleOK && ruleIdx >= group.LastRequiredRuleIndex && nodes.Count > 0)
            {
                SyntaxNode parent = new SyntaxNode(group, startToken);
                parent.AddRange(nodes);
                // token should be set to the last succesful nextToken
                groupResult = TokenParseResult.Success(parent, token);
            }

            return(groupResult);
        }
Example #35
0
 public GeoJsonParser(string json, ParserSettings settings)
     : base(new JsonTextReader(new StringReader(json)), settings)
 {
     _geometryParser = new GeometryParser(Reader, settings);
 }
Example #36
0
 public FileModel()
 {
     SyncOffset = TimeSpan.Zero;
     Markers    = new ObservableCollection <IMarkerModel>();
     Settings   = new ParserSettings();
 }
 public HTMLParser(ParserSettings settings)
 {
     m_settings = settings;
 }
Example #38
0
 private static void ConfigureParser(ParserSettings s)
 {
     s.CaseInsensitiveEnumValues = true;
     s.AutoVersion = true;
     s.AutoHelp    = true;
 }
Example #39
0
 protected BaseParser(JsonTextReader reader, ParserSettings settings)
 {
     Reader = reader;
     Settings = settings;
 }
Example #40
0
 public NewPatientDefParser(ParserSettings settings)
 {
     mSettings = settings;
 }
Example #41
0
 private static void ConfigureCommandLineParser(ParserSettings obj)
 {
     obj.HelpWriter = Console.Out;
 }
Example #42
0
 protected BaseSerializer(JsonTextWriter writer, ParserSettings settings)
 {
     Writer = writer;
     Settings = settings;
 }
Example #43
0
        ////////////////////////////

        private void CorrectSetExpression(
            Expression SetExpression,
            String ValueExpressionID,
            ParserSettings ParserSettings,
            ExpressionGroup ExpressionGroup)
        {
            if (SetExpression.Tokens.Count == 0)
            {
                return;
            }

            // jeśli tylko jeden symbol (podstawienie do zmiennej)
            else if (SetExpression.Tokens.Count == 1)
            {
                ExpressionToken firstToken = SetExpression.Tokens[0];

                if (firstToken.TokenType != TokenType.VARIABLE)
                {
                    throw new PainIncorrectExpressionFormatException("Incorrect setting value to type " + firstToken.TokenType + "");
                }

                if (firstToken.TokenName.Length == 0 || Char.IsDigit(firstToken.TokenName[0]))
                {
                    throw new PainIncorrectExpressionFormatException("Incorrect name of token '" + firstToken.TokenName + "'");
                }

                SetExpression.Tokens.Clear();
                SetExpression.Tokens.AddRange(
                    new[] {
                    new ExpressionToken(MethodSetValue.Name.ToUpper(), TokenType.VARIABLE),
                    new ExpressionToken(OperatorTypeHelper.op_methodcall, TokenType.OPERATOR),
                    new ExpressionToken('(', TokenType.BRACKET_BEGIN),
                    new ExpressionToken("'" + firstToken.TokenName + "'", TokenType.VALUE),
                    new ExpressionToken(',', TokenType.SEPARATOR),
                    new ExpressionToken(ValueExpressionID, TokenType.VARIABLE),
                    new ExpressionToken(')', TokenType.BRACKET_END)
                });
            }
            // jeśli przypisanie wyniku do elementu listy lub dictionary
            else
            {
                Int32 lastIndex = SetExpression.Tokens.Count - 1;

                ExpressionTokens sequence2 = new ExpressionTokens(
                    new TokenizerQueue().
                    GetPrevTokensOnSameLevel(
                        SetExpression.Tokens,
                        lastIndex));

                ExpressionTokens sequence1 = new ExpressionTokens(
                    new TokenizerQueue().
                    GetPrevTokensOnSameLevel(
                        SetExpression.Tokens,
                        lastIndex - sequence2.Count));

                ExpressionTokens sequence0 = new ExpressionTokens(
                    new TokenizerQueue().
                    GetPrevTokensOnSameLevel(
                        SetExpression.Tokens,
                        lastIndex - sequence2.Count - sequence1.Count));

                // a.get@(b).c = d   ========>   a.get@(b).set2@('c',d)
                if (sequence2.Count == 1 &&
                    sequence1.Count == 1 &&
                    OnpOnpTokenHelper.IsPropertyOperatorToken(sequence1[0]))
                {
                    ExpressionToken propertyOperatorToken = sequence1[0];
                    ExpressionToken propertyNameToken     = sequence2[0];

                    SetExpression.Tokens.Remove(propertyNameToken);
                    SetExpression.Tokens.AddRange(
                        new[] {
                        new ExpressionToken(ExtenderSetValue.Name.ToUpper().ToCharArray(), TokenType.VARIABLE),
                        new ExpressionToken(OperatorTypeHelper.op_methodcall, TokenType.OPERATOR),
                        new ExpressionToken('(', TokenType.BRACKET_BEGIN),
                        new ExpressionToken("'" + propertyNameToken.TokenName + "'", TokenType.VALUE),
                        new ExpressionToken(',', TokenType.SEPARATOR),
                        new ExpressionToken(ValueExpressionID, TokenType.VARIABLE),
                        new ExpressionToken(')', TokenType.BRACKET_END)
                    });
                }
                // a.get@(b).get@(d) = e   ========>   a.get@(b).set2@(d,e)
                else if (
                    sequence2.Count > 1 &&
                    sequence1.Count == 1 &&
                    OnpOnpTokenHelper.IsFunctionOperatorToken(sequence1[0]) &&
                    sequence0.Count == 1 &&
                    (sequence0[0].TokenType == TokenType.PROPERTY_NAME || sequence0[0].TokenType == TokenType.VARIABLE))
                {
                    ExpressionToken  functionNameToken     = sequence0[0];
                    ExpressionToken  functionOperatorToken = sequence1[0];
                    ExpressionTokens functionCallToken     = sequence2;

                    functionNameToken.Set(
                        ExtenderCollectionSetter.NameChars, false);

                    Int32 bracketBeginIndex = SetExpression.
                                              Tokens.
                                              IndexOf(functionCallToken[0]);

                    SetExpression.Tokens.Insert(
                        bracketBeginIndex + 1,
                        new ExpressionToken(ValueExpressionID, TokenType.VARIABLE));

                    SetExpression.Tokens.Insert(
                        bracketBeginIndex + 2,
                        new ExpressionToken(',', TokenType.SEPARATOR));
                }
                else
                {
                    throw new PainIncorrectExpressionFormatException();
                }
            }
        }
Example #44
0
        /// <summary>
        /// zastapienie ciagu tokenków zmienną i podpiecie nowego wyrazenia do zmiennej
        /// </summary>
        public void CorrectQueueExpression(
            Expression Expression,
            ParserSettings ParserSettings,
            ExpressionGroup ExpressionGroup)
        {
            if (Expression == null)
            {
                return;
            }

            if (Expression.Tokens == null || Expression.Tokens.Count <= 0)
            {
                return;
            }

            for (var i = 0; i < Expression.Tokens.Count; i++)
            {
                ExpressionToken token      = Expression.Tokens[i];
                ExpressionToken token_next = i + 1 < Expression.Tokens.Count ? Expression.Tokens[i + 1] : null;
                ExpressionToken token_prev = i - 1 >= 0 ? Expression.Tokens[i - 1] : null;

                ExpressionTokens functionCallTokens = new ExpressionTokens(
                    GetNextTokensOnSameLevel(Expression.Tokens, i));

                if (functionCallTokens.Count > 1)
                {
                    // generowanie expressions dla wnętrz funkcji
                    IList <ExpressionTokens> functionParameters = Linq2.ToList(SplitTokensIntoFunctionParameters(functionCallTokens));
                    foreach (ExpressionTokens functionParameter in functionParameters)
                    {
                        // generowanie expression z wyrażenia z parametru
                        if (functionParameter.Count > 1)
                        {
                            Expression functionExpression = new Expression();
                            functionExpression.Tokens         = new ExpressionTokens(functionParameter);
                            functionExpression.IsOnpExecution = true;

                            ExpressionGroup.Expressions[functionExpression.ID] =
                                functionExpression;

                            new Tokenizer().PrepareExpressions(
                                functionExpression,
                                ParserSettings,
                                ExpressionGroup);

                            ExpressionToken functionParameterToken = new ExpressionToken(
                                functionExpression.ID.ToCharArray(),
                                TokenType.VARIABLE);

                            Int32 index = Expression.Tokens.
                                          RemoveSequence(functionParameter);

                            Expression.Tokens.Insert(
                                index,
                                functionParameterToken);

                            i = index;
                        }
                        // gdy pojedyncze wyrażenie w fukncji
                        else
                        {
                            Int32 index = Expression.Tokens.
                                          IndexOfSequence(functionParameter);

                            i = index;
                        }
                    }

                    // dla operatora @ ustalenie liczby parametrów
                    if (token_prev != null &&
                        token_prev.TokenType == TokenType.OPERATOR &&
                        (OnpOnpTokenHelper.IsFunctionOperatorToken(token_prev)))
                    {
                        token_prev.TokenData = new OnpTokenData();
                        token_prev.TokenData.FunctionParametersCount = functionParameters.Count;
                    }
                }
                else
                {
                    // zamiana typu zmiennej na property_name jeśli nie jest to pierwsza zmienna
                    if (i > 0 && (token.TokenType == TokenType.VARIABLE || token.TokenType == TokenType.VALUE))
                    {
                        if (token_next == null || !OnpOnpTokenHelper.IsFunctionOperatorToken(token_next))
                        {
                            token.TokenType = TokenType.PROPERTY_NAME;
                        }
                    }
                    // usunięcie operatorów typu 'get property' ('.')

                    /*else if (OnpOnpTokenHelper.IsPropertyOperatorToken(token) )
                     * {
                     *  queueTokens.RemoveAt(i);
                     *  i--;
                     * }*/
                }
            }
        }
Example #45
0
        ////////////////////////////

        /// <summary>
        /// Ustala kolejnośc tokenów zgodną z ONP
        /// </summary>
        private ExpressionTokens TransformToOnp(
            IList <ExpressionToken> Tokens,
            ParserSettings ParserSettings)
        {
            ExpressionTokens onpTokens = new ExpressionTokens();

            // defaul settings
            if (ParserSettings == null)
            {
                ParserSettings = new ParserSettings();
            }

            // przygotowanie stosu
            Stack <ExpressionToken> _tokenStack = new Stack <ExpressionToken>();

            // ONP
            for (int i = 0; i < Tokens.Count; i++)
            {
                ExpressionToken token = Tokens[i];

                if (token.TokenType == TokenType.VALUE ||
                    token.TokenType == TokenType.PROPERTY_NAME ||
                    token.TokenType == TokenType.VARIABLE ||
                    /*token.TokenType == TokenType.FUNCTION_CALL ||*/
                    token.TokenType == TokenType.WHITESPACE)
                {
                    onpTokens.Add(token);
                }
                else if (token.TokenType == TokenType.BRACKET_BEGIN)
                {
                    _tokenStack.Push(token);
                }
                else if (token.TokenType == TokenType.OPERATOR)
                {
                    while (_tokenStack.Count > 0)
                    {
                        var lV = _tokenStack.Peek();
                        if (lV.Priority >= token.Priority)
                        {
                            _tokenStack.Pop();
                            onpTokens.Add(lV);
                        }
                        else
                        {
                            break;
                        }
                    }
                    _tokenStack.Push(token);
                }
                else if (token.TokenType == TokenType.BRACKET_END)
                {
                    while (_tokenStack.Count > 0)
                    {
                        var lV = _tokenStack.Peek();
                        if (lV.TokenType == TokenType.BRACKET_BEGIN)
                        {
                            _tokenStack.Pop();
                            break;
                        }
                        else
                        {
                            _tokenStack.Pop();
                            onpTokens.Add(lV);
                        }
                    }
                }
            }

            while (_tokenStack.Count > 0)
            {
                onpTokens.Add(_tokenStack.Pop());
            }

            return(onpTokens);
        }
Example #46
0
 public GeometryParser(JsonTextReader reader, ParserSettings settings)
     : base(reader, settings)
 {
 }
Example #47
0
 public IParser Open(string filename, ParserSettings settings = null)
 {
     return(new CsvFile(filename, settings));
 }
Example #48
0
        public static OptionMap Create(object target, ParserSettings settings)
        {
            var list = ReflectionHelper.RetrievePropertyList<BaseOptionAttribute>(target);
            if (list == null)
            {
                return null;
            }

            var map = new OptionMap(list.Count, settings);

            foreach (var pair in list)
            {
                if (pair.Left != null && pair.Right != null)
                {
                    string uniqueName;
                    if (pair.Right.AutoLongName)
                    {
                        uniqueName = pair.Left.Name.ToLowerInvariant();
                        pair.Right.LongName = uniqueName;
                    }
                    else
                    {
                        uniqueName = pair.Right.UniqueName;
                    }

                    map[uniqueName] = new OptionInfo(pair.Right, pair.Left, settings.ParsingCulture);
                }
            }

            map.RawOptions = target;
            return map;
        }
Example #49
0
 /// <summary>
 /// Only used for testing
 /// </summary>
 /// <param name="settings"></param>
 internal CsvFile(StreamReader sr, ParserSettings settings)
 {
     this.sr = sr;
     readSettings(settings);
     readSignalsAndTime();
 }
Example #50
0
 public GeoJsonParser(TextReader reader, ParserSettings settings)
     : base(new JsonTextReader(reader), settings)
 {
     _geometryParser = new GeometryParser(Reader, settings);
 }
Example #51
0
 public ParserService(ScrapyDbContext scrapyDbContext, ParserSettings settings)
 {
     this._scrapyContext  = scrapyDbContext;
     this._settings       = settings;
     this._productService = new ProductService(scrapyDbContext);
 }
Example #52
0
 public MainStream_dop(ParserSettings parserSettings)
 {
     settings = parserSettings;
 }
 public GeometrySerializer(JsonTextWriter writer, ParserSettings settings)
     : base(writer, settings)
 {
 }