Esempio n. 1
0
        public static Dictionary<string, string> ParseCommandLine(string[] args)
        {
            var arguments = new Dictionary<string, string>();

              // App.Config Settings
              var appSettingKeys = ConfigurationManager.AppSettings.Keys;
              for (var i = 0; i < appSettingKeys.Count; i++)
              {
              var key = appSettingKeys[i];
              arguments.AddOrUpdate(key, ConfigurationManager.AppSettings[key]);
              }

              // Manual override through CLI.
              var p = new OptionSet()
                    {
                       {
                          "<>", v =>
                                   {
                                      if (!v.StartsWith("--"))
                                         return;
                                      var split = v.Split(new[] { '=' }, 2);
                                      if (split.Length != 2)
                                         return;
                                      arguments.AddOrUpdate(split[0].TrimStart('-'), split[1]);
                                   }
                          }
                    };

              p.Parse(args);
              return arguments;
        }
Esempio n. 2
0
        public void AddOrUpdateOverloadOne()
        {
            var dictionary = new Dictionary<string, string>();
            Func<string, string, string> updater = (key, oldValue) =>
            {
                key.Should().Be("fookey");
                oldValue.Should().Be("foo");
                return "bar";
            };

            Func<string, string, string> nullUpdater = null;

            dictionary.AddOrUpdate(key: "fookey", addValue: "foo", updateValueFactory: updater).Should().Be("foo");
            dictionary["fookey"].Should().Be("foo");
            dictionary.AddOrUpdate(key: "fookey", addValue: "foo", updateValueFactory: updater).Should().Be("bar");
            dictionary["fookey"].Should().Be("bar");

            // Null argument checks
            Action action = action = () => dictionary.AddOrUpdate(key: null, addValue: null, updateValueFactory: nullUpdater);
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("key");

            action = () => dictionary.AddOrUpdate(key: "foo", addValue: null, updateValueFactory: nullUpdater);
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("updateValueFactory");

            dictionary = null;
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("source");
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            var arguments = new Dictionary<string, string>();

             // App.Config Settings
             var appSettingKeys = ConfigurationManager.AppSettings.Keys;
             for (var i = 0; i < appSettingKeys.Count; i++)
             {
            var key = appSettingKeys[i];
            arguments.AddOrUpdate(key, ConfigurationManager.AppSettings[key]);
             }

             // Manual override through CLI.
             var p = new OptionSet()
                    {
                       {
                          "<>", v =>
                                   {
                                      if (!v.StartsWith("--"))
                                         return;
                                      var split = v.Split(new[] { '=' }, 2);
                                      if (split.Length != 2)
                                         return;
                                      arguments.AddOrUpdate(split[0].TrimStart('-'), split[1]);
                                   }
                          }
                    };

             p.Parse(args);

             var loader = new AssemblyLoader();
             var dbProvider = loader.CreateTypeFromAssembly<DbProvider>(arguments["dbp.provider"], arguments);
             var dbCodeFormatter = loader.CreateTypeFromAssembly<DbTraceCodeFormatter>(arguments["tcf.provider"], arguments);
             var codeHighlighter = loader.CreateTypeFromAssembly<HighlightCodeProvider>(arguments["hcp.provider"], arguments);
             var outputProvider = loader.CreateTypeFromAssembly<OutputProvider>(arguments["out.provider"], arguments);

             switch (arguments["app.mode"].ToLower().Trim())
             {
            case "generate":
               var generateCommand = new GenerateOutputCommand(dbProvider, dbCodeFormatter, codeHighlighter, outputProvider, arguments["app.traceName"]);
               generateCommand.Execute();
               break;

            case "start":
               var startCommand = new StartCommand(outputProvider, dbProvider, arguments["app.traceName"]);
               startCommand.Execute();
               break;

            case "stop":
               {
                  var stopCommand = new StopCommand(dbProvider, outputProvider, arguments["app.traceName"]);
                  stopCommand.Execute();
               }
               break;
             }
        }
Esempio n. 4
0
        public void AddOrUpdateTest_CommonValue_Exist()
        {
            IDictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.AddOrUpdate("key", "value");

            Assert.AreEqual(1, dictionary.Count);
            dictionary.AddOrUpdate("key", "newValue");
            Assert.AreEqual(1, dictionary.Count);
            Assert.IsTrue(dictionary.ContainsKey("key"));
            Assert.AreEqual("newValue", dictionary["key"]);
        }
        public void AddOrUpdate()
        {
            // Type
            var @this = new Dictionary<string, string>();

            // Examples
            string value1 = @this.AddOrUpdate("Fizz", "Buzz"); // return "Buzz";
            string value2 = @this.AddOrUpdate("Fizz", "Buzz2"); // return "Buzz2";

            // Unit Test
            Assert.AreEqual("Buzz", value1);
            Assert.AreEqual("Buzz2", value2);
        }
Esempio n. 6
0
        public void AddOrUpdateTest_ListValue_Exist()
        {
            IDictionary<string, IList<string>> dictionary = new Dictionary<string, IList<string>>();
            dictionary.AddOrUpdate("key", "value");

            Assert.AreEqual(1, dictionary.Count);
            dictionary.AddOrUpdate("key", "newValue");
            Assert.AreEqual(1, dictionary.Count);
            Assert.IsTrue(dictionary.ContainsKey("key"));
            Assert.IsNotNull(dictionary["key"]);
            Assert.AreEqual(2, dictionary["key"].Count);
            Assert.AreEqual("value", dictionary["key"].First());
            Assert.AreEqual("newValue", dictionary["key"].Last());
        }
        public void AddOrUpdateTestCase1()
        {
            var key = RandomValueEx.GetRandomString();
            var pair = new KeyValuePair<String, String>( key, RandomValueEx.GetRandomString() );
            var dic = new Dictionary<String, String>();

            var result = dic.AddOrUpdate( pair );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( pair.Value, result );

            pair = new KeyValuePair<String, String>( key, RandomValueEx.GetRandomString() );
            result = dic.AddOrUpdate( pair );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( pair.Value, result );
        }
        public void AddOrUpdateTestCase2()
        {
            var key = RandomValueEx.GetRandomString();
            var dic = new Dictionary<String, String>();

            var valueToAdd = RandomValueEx.GetRandomString();
            var result = dic.AddOrUpdate( key, () => valueToAdd );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( valueToAdd, result );

            valueToAdd = RandomValueEx.GetRandomString();
            result = dic.AddOrUpdate( key, () => valueToAdd );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( valueToAdd, result );
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!EnsureInternalSetup(solutionFullPath, ref properties))
                return false;

            var head_path = (string)properties.GetValueOrDefault("git:headPath", () => "");

            if (!File.Exists(head_path))
                return false;

            var head_content = File.ReadAllText(head_path);
            var branch_match = GitBranchRegex.Match(head_content);

            if (!branch_match.Success)
                return false;

            var branch_group = branch_match.Groups["branchName"];

            if (!branch_group.Success)
                return false;

            var branch_name = branch_group.Value;
            properties.Add("git:head", branch_name);

            properties.AddOrUpdate(KnownProperties.BranchName, branch_name);

            return true;
        }
		public void Update()
		{
			var keyedValues = new Dictionary<string, Value> { { "a", new Value { Data = "b" } } };
			keyedValues.AddOrUpdate("a", null, _ => _.Data = "c");

			Assert.AreEqual("c", keyedValues["a"].Data);
		}
		public void Add()
		{
			var keyedValues = new Dictionary<string, Value>();
			keyedValues.AddOrUpdate("a", () => new Value { Data = "b" }, null);

			Assert.AreEqual("b", keyedValues["a"].Data);
		}
Esempio n. 12
0
        public void TestRandomness(Func<List<int>> getRandomList, int rangeLength, int count)
        {
            var combinations = rangeLength.Factorial(rangeLength - count + 1);
            var iterations = combinations * 100;
            var ocurrences = new ConcurrentDictionary<long, int>(Environment.ProcessorCount, (int)combinations);

            var partitioner = Partitioner.Create(0, (long)iterations);
            Parallel.ForEach(partitioner, new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount},
                range =>
                {
                    //hopefully having a private dictionary will help concurrency
                    var privateOcurrences = new Dictionary<long, int>();
                    for (long i = range.Item1; i < range.Item2; ++i)
                    {
                        var list = getRandomList();
                        //this will only work when numbers are between 0 and 88
                        long acc = list.Aggregate<int, long>(0, (current, value) => (value + 11) + current*100);
                        privateOcurrences.AddOrUpdate(acc, 1, v => v + 1);
                    }
                    foreach (var privateOcurrence in privateOcurrences)
                    {
                        ocurrences.AddOrUpdate(privateOcurrence.Key,
                            privateOcurrence.Value,
                            (k, v) => v + privateOcurrence.Value);
                    }
                });

            var averageOcurrences = iterations / (combinations * 1.0m);
            var currentAverage = ocurrences.Values.Average();
            Debug.WriteLine("The average ocurrences of this implementation is {0} comparing to {1} in the 'perfect' scenario", currentAverage, averageOcurrences);
            Assert.Less(currentAverage, averageOcurrences * 1.05m);
            Assert.Greater(currentAverage, averageOcurrences * 0.95m);
        }
Esempio n. 13
0
        public void AddOrUpdate()
        {
            var dictionary = new Dictionary<string, string>();
            Action action = () => dictionary.AddOrUpdate(null, "");
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("key");
            dictionary = null;
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("source");

            var dictionaryTwo = new Dictionary<int, int>();
            dictionaryTwo.Add(1, 1);
            dictionaryTwo.AddOrUpdate(1, 2);
            dictionaryTwo[1].Should().Be(2);
            dictionaryTwo.AddOrUpdate(2, 3);
            dictionaryTwo[2].Should().Be(3);
        }
Esempio n. 14
0
        private static void FindAllListingsForProduct(Product product, List<Listing> listings, Dictionary<string, List<Listing>> allListingsOfProduct)
        {
            foreach (var listing in listings)
            {
                if (listing == null || listing.Picked || !ListingMatchesProduct(product.Tokens, listing.Tokens))
                    continue;

                listing.Picked = true;
                allListingsOfProduct.AddOrUpdate(product.ProductName, listing);
            }
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!TeamFoundationHelper.IsConnected())
                return false;

            var workspace = (Workspace) null;
            var branchObject = (BranchObject)null;

            var branchName = TeamFoundationHelper.GetBranchNameForItem(solutionFullPath, out workspace, out branchObject);

            if (branchName.IsNullOrEmpty())
                return false;

            properties.AddOrUpdate("tfs:workspace", workspace.Name);

            properties.AddOrUpdate(KnownProperties.BranchName, branchName);

            return true;
        }
Esempio n. 16
0
 private static void FindAllListingsForProductAsync(Product product, List<Listing> listings, Dictionary<string, List<Listing>> allListingsOfProduct)
 {
     Parallel.ForEach(listings, listing =>
                                    {
                                        if (
                                            !(listing == null || listing.Picked ||
                                              !ListingMatchesProduct(product.Tokens, listing.Tokens)))
                                        {
                                            listing.Picked = true;
                                            allListingsOfProduct.AddOrUpdate(product.ProductName, listing);
                                        }
                                    }
         );
 }
Esempio n. 17
0
        public void AddOrUpdate_KeyExists_KeyIsNotAddedAgain()
        {
            // Arrange
            var dictionary = new Dictionary<string, int> { };

            const string TestKey = "testKey";
            const int FirstValue = 1234;
            dictionary.Add(TestKey, FirstValue);

            // Act
            const int SecondValue = 4321;
            dictionary.AddOrUpdate(TestKey, SecondValue);

            // Assert
            Assert.Equal(1, dictionary.Count);
        }
Esempio n. 18
0
        public void AddOrUpdate_KeyDoesNotExist_NewKeyIsAdded()
        {
            // Arrange
            var dictionary = new Dictionary<string, int> { };

            const string TestKey = "testKey";
            const int FirstValue = 1234;
            dictionary.Add(TestKey, FirstValue);

            // Act
            const int SecondValue = 4321;
            dictionary.AddOrUpdate("newKey", SecondValue);

            // Assert
            Assert.Equal(2, dictionary.Count);
        }
Esempio n. 19
0
        public void AddOrUpdate_KeyExists_ValueIsUpdated()
        {
            // Arrange
            var dictionary = new Dictionary<string, int>();
            const string TestKey = "testKey";
            const int FirstValue = 1234;
            const int SecondValue = 4321;
            dictionary.Add(TestKey, FirstValue);

            // Act
            dictionary.AddOrUpdate(TestKey, SecondValue);
            int dictionaryValue;
            dictionary.TryGetValue(TestKey, out dictionaryValue);

            // Assert
            Assert.Equal(SecondValue, dictionaryValue);
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!EnsureInternalSetup(solutionFullPath, ref properties))
                return false;

            var branch_path = (string)properties.GetValueOrDefault("hg:branchPath", () => "");

            if (!File.Exists(branch_path))
                return false;

            var branch_name = File.ReadAllText(branch_path);

            if (branch_name.IsNullOrEmpty())
                return false;

            properties.Add("hg:head", branch_name);

            properties.AddOrUpdate(KnownProperties.BranchName, branch_name);

            return true;
        }
Esempio n. 21
0
        /// <summary>
        /// This function refreshes a local set of objects that will hold your user's balances in memory for quick
        /// and more efficient fetching for your game UI.
        /// This way, we save many JNI or static calls to native platforms.
        /// 
        /// NOTE: You don't need to call this function as it's automatically called when the game initializes.
        /// NOTE: This is less useful when you work in editor.
        /// </summary>
        public static void RefreshLocalInventory()
        {
            SoomlaUtils.LogDebug(TAG, "Refreshing local inventory");

            localItemBalances = new Dictionary<string, int> ();
            localUpgrades = new Dictionary<string, LocalUpgrade>();
            localEquippedGoods = new HashSet<string>();

            foreach(VirtualCurrency item in StoreInfo.Currencies){
                localItemBalances[item.ItemId] = VirtualCurrencyStorage.GetBalance(item);
            }

            foreach(VirtualGood item in StoreInfo.Goods){
                localItemBalances[item.ItemId] =  VirtualGoodsStorage.GetBalance(item);

                UpgradeVG upgrade = VirtualGoodsStorage.GetCurrentUpgrade(item);
                if (upgrade != null) {
                    int upgradeLevel = GetGoodUpgradeLevel(item.ItemId);
                    localUpgrades.AddOrUpdate(item.ItemId, new LocalUpgrade { itemId = upgrade.ItemId, level = upgradeLevel });
                }

                if (item is EquippableVG) {
                    if (VirtualGoodsStorage.IsEquipped((EquippableVG)item)) {
                        localEquippedGoods.Add(item.ItemId);
                    }
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Update device client settings
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        private async Task ProcessSettingsAsync(TwinCollection settings)
        {
            if (settings.Count > 0)
            {
                try {
                    await _lock.WaitAsync();

                    // Patch existing reported properties
                    var desired   = new Dictionary <string, VariantValue>();
                    var reporting = new Dictionary <string, VariantValue>();

                    foreach (KeyValuePair <string, dynamic> property in settings)
                    {
                        var value = (VariantValue)_serializer.FromObject(property.Value);
                        if (!ProcessEdgeHostSettings(property.Key, value, reporting))
                        {
                            desired.AddOrUpdate(property.Key, value);
                        }
                    }

                    if (reporting != null && reporting.Count != 0)
                    {
                        var collection = new TwinCollection();
                        foreach (var item in reporting)
                        {
                            collection[item.Key] = item.Value?.ConvertTo <object>();
                        }
                        await Client.UpdateReportedPropertiesAsync(collection);

                        _logger.Debug("Internal state updated...", reporting);
                    }

                    // Any controller properties left?
                    if (desired.Count == 0)
                    {
                        return;
                    }

                    _logger.Debug("Processing new settings...");
                    var reported = await _settings.ProcessSettingsAsync(desired);

                    if (reported != null && reported.Count != 0)
                    {
                        _logger.Debug("Reporting setting results...");
                        var collection = new TwinCollection();
                        foreach (var item in reported)
                        {
                            collection[item.Key] = item.Value?.ConvertTo <object>();
                        }
                        await Client.UpdateReportedPropertiesAsync(collection);

                        foreach (var item in reported)
                        {
                            _reported.AddOrUpdate(item.Key, item.Value);
                        }
                    }
                    _logger.Information("New settings processed.");
                }
                finally {
                    _lock.Release();
                }
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Increments the counter for the given alarm.
 /// </summary>
 /// <param name="alarm">The alarm that was raised.</param>
 public void IncrementCounter(Alarm alarm)
 {
     m_countBySeverity.AddOrUpdate((int)alarm.Severity, severity => 1L, (severity, count) => count + 1L);
 }
        /* This method will search for high cost dragons in the mulligan and allow their keep if you have early
         * level dragon Synergy
         * DSS = DragonSkin Sorcerer
         * TG = Twighlight Guardian
         * AZD = Azure Drake
         * CHIL =  Chillmaw
         * YSR = Ysera
         * Nef = Nefarian
         *
         * How to effectively call this method?
         * Dragons have different value points when it comes to matchups. Against Control I wouldn't mind having Azure Drake over Twighlight Guardian
         * since I am in no immediate threat, however against lovely paladins/hunters/mech mages, I would much rather keep twitghlight guardian.
         * To achieve that behavior one must call findDragonSynergy() and give appropriate priority to dragons ranging [1,6]
         * Example:
         * findDragonSynergy(Choices, 3, 1, 5, 2, 6, 7) will asign values to dragons in the following order
         * ************************
         * DragonSkin Sorcerer || 3
         * Twighlight Guardian || 1
         * Azure Drake         || 5
         * Chillmaw            || 2
         * Ysera               || 6
         * Nefarian            || 7
         * ************************
         * If you have early minions like welp and wyrmest agent, you want an activator for them, this method will
         * try to keep only 1 high cost dragon to activate your early drop minions.
         * In this case if you hand cosist of Twighlight Whelp, Wyrmest agent, DragonSkin Sorcerer and Chillmaw.
         * This method will keep DragonSkin Sorcerer for as an activator.
         *
         * In short, it keeps dragon with the lowest key to activate our minions.
         */
        public void findDragonSynergy(List <Card> Choices, int DDC, int TG, int AZD, int CHIL, int YSR, int NEF, int CHR) //v2.0
        {
            bool kiblerDragonActivator = false;

            _dragonList.AddOrUpdate(_dragonkinSorcerer, DDC);
            _dragonList.AddOrUpdate(_twilightGuardian, TG);
            _dragonList.AddOrUpdate(_azureDrake, AZD);
            _dragonList.AddOrUpdate(_chillmaw, CHIL);
            _dragonList.AddOrUpdate(_ysera, YSR);
            _dragonList.AddOrUpdate(_nefarian, NEF);
            _dragonList.AddOrUpdate(_chromaggus, CHR);

            /*
             * Yes, the proper way would be is to itterate through and find a min value,
             * but I figured since we know our decks, hardcoding values isn't half bad :3
             * Feel free to sort dragonList dictionary and whitelist dragons in proper order to support more dragons later on
             */
            int i = 0;

            while (true)
            {
                if (Choices.Any(c => c.Name == _dragonList.FirstOrDefault(x => x.Value == i).Key))
                {
                    _whiteList.AddOrUpdate(_dragonList.FirstOrDefault(x => x.Value == i).Key, false);
                    break;
                }
                i++;
                if (i > 7) //moved it from while condition
                {
                    break; //Doesn't bark anymore
                }
            }
        }
Esempio n. 25
0
        public Root parse(string filename, string[] code)
        {
            logger.Debug($"Parsing {filename}");
            if (logger.IsTraceEnable)
            {
                foreach (var line in code)
                {
                    logger.Trace(line);
                }
            }


            var startTime = DateTime.Now.Ticks;
            var ast       = new Root();


            // Track some state variables for this parsing round.
            string topic                      = "random"; // Default topic = random
            int    lineno                     = 0;
            bool   inComment                  = false;    // In a multi-line comment
            bool   inObject                   = false;    // In an object
            string objectName                 = null;     // Name of the current object
            string objectLanguage             = null;     // Programming language of the object
            ICollection <string> objectBuffer = null;     // Buffer for the current object
            string onTrigger                  = null;     // Trigger we're on
            //Trigger currentTriggerObject = null;        // Trigger we're on
            string previous = null;                       // The a %Previous trigger

            // File scoped parser options.
            IDictionary <string, string> local_options = new Dictionary <string, string>();

            local_options.AddOrUpdate("concat", "none");
            //local_options.Add("concat", "space");
            //local_options.Add("concat", "newline");

            // The given "code" is an array of lines, so jump right in.
            for (int i = 0; i < code.Length; i++)
            {
                lineno++; // Increment the line counter.
                string line = code[i] ?? "";
                logger.Debug("Original Line: " + line);

                // Trim the line of whitespaces.
                line = Util.Strip(line);


                if (line.Length == 0)
                {
                    continue; //Skip blank line
                }
                // Are we inside an object?
                if (inObject)
                {
                    if (line.StartsWith("<object") || line.StartsWith("< object"))
                    {
                        // End of the object. Did we have a handler?
                        if (!string.IsNullOrWhiteSpace(objectName))
                        {
                            var macro = new ObjectMacro
                            {
                                Code     = objectBuffer,
                                Language = objectLanguage,
                                Name     = objectName,
                            };

                            ast.addObject(macro);
                        }
                        objectName     = null;
                        objectLanguage = null;
                        objectBuffer   = null;
                        inObject       = false;
                    }
                    else
                    {
                        // Collect the code.
                        objectBuffer.Add(line);
                    }

                    continue;
                }


                // Look for comments.
                if (line.StartsWith("/*"))
                {
                    // Beginning a multi-line comment.
                    if (line.IndexOf("*/") > -1)
                    {
                        // It ends on the same line.
                        continue;
                    }
                    inComment = true;
                }
                else if (line.StartsWith("//"))
                {
                    // A single line comment.
                    continue;
                }
                else if (line.IndexOf("*/") > -1)
                {
                    // End a multi-line comment.
                    inComment = false;
                    continue;
                }
                if (inComment) //else if?
                {
                    continue;
                }

                // Skip any blank lines and weird lines.
                if (line.Length < 2)
                {
                    logger.Warn($"Weird single-character line '#" + line + "' found (in topic #" + topic + ")");
                    continue;
                }

                // Separate the command from the rest of the line.
                string cmd = line.Substring(0, 1);
                line = Util.Strip(line.Substring(1));


                logger.Debug("\tCmd: " + cmd);

                // Ignore in-line comments if there's a space before and after the "//".
                if (line.IndexOf(" // ") > -1)
                {
                    string[] split = line.Split(new[] { " // " }, StringSplitOptions.None);
                    line = split[0];
                    //remove space between comment and code
                    line = line.TrimEnd(' ');
                }

                // In the event of a +Trigger, if we are force-lowercasing it, then do so
                // In the event of a +Trigger, if we are force-lowercasing it, then do so
                // now before the syntax check.
                if (forceCase && cmd == CMD_TRIGGER)
                {
                    line = line.ToLower();
                }


                //Run a syntax check on this line
                try
                {
                    checkSyntax(cmd, line);
                }
                catch (ParserException pex)
                {
                    if (strict)
                    {
                        throw pex;
                    }
                    else
                    {
                        logger.Warn($"Syntax logger.error(: {pex.Message} at {filename} line {lineno} near {cmd} {line}");
                    }
                }


                // Reset the %Previous if this is a new +Trigger.
                if (cmd.Equals(CMD_TRIGGER))
                {
                    previous = "";
                }

                // Do a look-ahead to see ^Continue and %Previous.
                if (cmd != CMD_CONTINUE)
                {
                    for (int j = (i + 1); j < code.Length; j++)
                    {
                        // Peek ahead.
                        string peek = Util.Strip(code[j]);

                        // Skip blank.
                        if (peek.Length == 0) //peek.Length < 2?
                        {
                            continue;
                        }

                        // Get the command.
                        string peekCmd = peek.Substring(0, 1);
                        peek = Util.Strip(peek.Substring(1));

                        // Only continue if the lookahead line has any data.
                        if (peek.Length > 0)
                        {
                            // The lookahead command has to be a % or a ^
                            if (!peekCmd.Equals(CMD_CONTINUE) && !peekCmd.Equals(CMD_PREVIOUS))
                            {
                                break;
                            }

                            // If the current command is a +, see if the following is a %.
                            if (cmd.Equals(CMD_TRIGGER))
                            {
                                if (peekCmd.Equals(CMD_PREVIOUS))
                                {
                                    // It has a %Previous!
                                    previous = peek;
                                    break;
                                }
                                else
                                {
                                    previous = "";
                                }
                            }

                            // If the current command is a ! and the next command(s) are
                            // ^, we'll tack each extension on as a "line break".
                            if (cmd.Equals(CMD_DEFINE))
                            {
                                if (peekCmd.Equals(CMD_CONTINUE))
                                {
                                    line += "<crlf>" + peek;
                                }
                            }

                            // If the current command is not a ^ and the line after is
                            // not a %, but the line after IS a ^, then tack it onto the
                            // end of the current line.
                            if (!cmd.Equals(CMD_CONTINUE) && !cmd.Equals(CMD_PREVIOUS) && !cmd.Equals(CMD_DEFINE))
                            {
                                if (peekCmd.Equals(CMD_CONTINUE))
                                {
                                    // Concatenation character?
                                    ConcatMode concatMode = null;
                                    if (local_options.ContainsKey("concat"))
                                    {
                                        concatMode = ConcatMode.FromName(local_options["concat"]);
                                    }

                                    if (concatMode == null)
                                    {
                                        concatMode = concat ?? Config.DEFAULT_CONCAT;
                                    }

                                    line += concatMode.ConcatChar + peek;
                                }
                                else
                                {
                                    break; //?warn
                                }
                            }
                        }
                    }
                }

                // Start handling command types.
                //TODO: change to switch-case
                if (cmd.Equals(CMD_DEFINE))
                {
                    logger.Debug("\t! DEFINE");
                    //string[] halves = line.split("\\s*=\\s*", 2);
                    string[] halves = new Regex("\\s*=\\s*").Split(line, 2);
                    //string[] left = whatis[0].split("\\s+", 2);
                    string[] left   = new Regex("\\s+").Split(halves[0], 2);
                    string   value  = "";
                    string   kind   = ""; //global, var, sub, ...
                    string   name   = "";
                    bool     delete = false;

                    if (halves.Length == 2)
                    {
                        value = halves[1].Trim();
                    }

                    if (left.Length >= 1)
                    {
                        kind = left[0];
                        if (left.Length >= 2)
                        {
                            left = Util.CopyOfRange(left, 1, left.Length);
                            //name = left[1].Trim().ToLower();
                            name = Util.Join(left, " ").Trim();
                        }
                    }

                    // Remove line breaks unless this is an array.
                    if (!kind.Equals("array"))
                    {
                        value = value.Replace("<crlf>", "");
                    }

                    // Version is the only type that doesn't have a var.
                    if (kind.Equals("version"))
                    {
                        logger.Debug("\tUsing RiveScript version " + value);

                        // Convert the value into a double, catch exceptions.
                        double version = 0;
                        try
                        {
                            version = double.Parse(value ?? "", new NumberFormatInfo {
                                CurrencyDecimalSeparator = "."
                            });
                        }
                        catch (FormatException)
                        {
                            logger.Warn("RiveScript version \"" + value + "\" not a valid floating number", filename, lineno);
                            continue;
                        }

                        if (version > RS_VERSION)
                        {
                            throw new ParserException($"We can't parse RiveScript v {value} documents at {filename} line {lineno}. Only support {RS_VERSION}.");
                        }

                        continue;
                    }
                    else
                    {
                        // All the other types require a variable and value.
                        if (name.Equals(""))
                        {
                            logger.Warn("Missing a " + kind + " variable name", filename, lineno);
                            continue;
                        }
                        if (value.Equals(""))
                        {
                            logger.Warn("Missing a " + kind + " value", filename, lineno);
                            continue;
                        }
                        if (value.Equals(Constants.UNDEF_TAG))
                        {
                            // Deleting its value.
                            delete = true;
                        }
                    }

                    // Handle the variable set types.
                    //TODO: change to switch-case
                    if (kind.Equals("local"))
                    {
                        // Local file scoped parser options
                        logger.Debug("\tSet local parser option " + name + " = " + value);
                        local_options.AddOrUpdate(name, value);
                    }
                    else if (kind.Equals("global"))
                    {
                        // Is it a special global? (debug or depth or etc).
                        logger.Debug("\tSet global " + name + " = " + value);
                        ast.begin.addGlobals(name, value);
                    }
                    else if (kind.Equals("var"))
                    {
                        // Set a bot variable.
                        logger.Debug("\tSet bot variable " + name + " = " + value);
                        ast.begin.addVar(name, value);
                    }
                    else if (kind.Equals("array"))
                    {
                        // Set an array.
                        logger.Debug("\tSet array " + name);

                        // Deleting it?
                        if (delete)
                        {
                            ast.begin.removeArray(name);
                            continue;
                        }

                        // Did the array have multiple lines?
                        //string[] parts = value.split("<crlf>");
                        //WARN:
                        string[]             parts = value.Split("<crlf>");
                        ICollection <string> items = new List <string>();
                        for (int a = 0; a < parts.Length; a++)
                        {
                            // Split at pipes or spaces?
                            string[] pieces;
                            if (parts[a].IndexOf("|") > -1)
                            {
                                //pieces = parts[a].split("\\|");
                                pieces = new Regex("\\|").Split(parts[a]);
                            }
                            else
                            {
                                pieces = new Regex("\\s+").Split(parts[a]);
                            }

                            // Add the pieces to the final array.
                            for (int b = 0; b < pieces.Length; b++)
                            {
                                items.Add(pieces[b]);
                            }
                        }

                        // Store this array.
                        ast.begin.addArray(name, items);
                    }
                    else if (kind.Equals("sub"))
                    {
                        // Set a substitution.
                        logger.Debug("\tSubstitution " + name + " => " + value);
                        ast.begin.addSub(name, value);
                    }
                    else if (kind.Equals("person"))
                    {
                        // Set a person substitution.
                        logger.Debug("\tPerson substitution " + name + " => " + value);
                        ast.begin.addPerson(name, value);
                    }
                    else
                    {
                        logger.Warn("Unknown definition type \"" + kind + "\"", filename, lineno);
                        continue;
                    }
                }
                else if (cmd.Equals(CMD_LABEL))
                {
                    // > LABEL
                    logger.Debug("\t> LABEL");
                    //string[] label =  line.split("\\s+");
                    string[] label = line.SplitRegex("\\s+");
                    string   type  = "";
                    string   name  = "";
                    if (label.Length >= 1)
                    {
                        type = label[0].Trim().ToLower();
                    }
                    if (label.Length >= 2)
                    {
                        name = label[1].Trim();
                    }

                    // Handle the label types.
                    if (type.Equals("begin"))
                    {
                        // The BEGIN statement.
                        logger.Debug("\tFound the BEGIN Statement.");

                        // A BEGIN is just a special topic.
                        type = "topic";
                        name = "__begin__";
                    }

                    if (type.Equals("topic"))
                    {
                        if (forceCase)
                        {
                            name = name.ToLower();
                        }


                        // Starting a new topic.
                        logger.Debug("\tSet topic to " + name);
                        onTrigger = "";
                        //currentTriggerObject = null;
                        topic = name;

                        // Does this topic include or inherit another one?
                        if (label.Length >= 3)
                        {
                            int mode_includes = 1;
                            int mode_inherits = 2;
                            int mode          = 0;
                            for (int a = 2; a < label.Length; a++)
                            {
                                if (label[a].ToLowerInvariant().Equals("includes"))
                                {
                                    mode = mode_includes;
                                }
                                else if (label[a].ToLowerInvariant().Equals("inherits"))
                                {
                                    mode = mode_inherits;
                                }
                                else if (mode > 0)
                                {
                                    // This topic is either inherited or included.
                                    if (mode == mode_includes)
                                    {
                                        topicManager.topic(topic).includes(label[a]);
                                    }
                                    else if (mode == mode_inherits)
                                    {
                                        topicManager.topic(topic).inherits(label[a]);
                                    }
                                }
                            }
                        }
                    }
                    if (type.Equals("object"))
                    {
                        // If a field was provided, it should be the programming language.
                        string language = "";

                        if (label.Length >= 3)
                        {
                            language = label[2].ToLower();
                        }

                        // Only try to parse a language we support.
                        onTrigger = "";
                        if (language.Length == 0)
                        {
                            logger.Warn("Trying to parse unknown programming language (assuming it's CSharp)", filename, lineno);
                            language = Constants.CSharpHandlerName; // Assume it's JavaScript
                        }

                        //INFO: to remove?
                        //if (!handlers.ContainsKey(language))
                        //{
                        //    // We don't have a handler for this language.
                        //    logger.debug("We can't handle " + language + " object code!");
                        //    continue;
                        //}

                        // Start collecting its code!
                        objectName     = name;
                        objectLanguage = language;
                        objectBuffer   = new List <string>();
                        inObject       = true;
                    }
                }
                else if (cmd.Equals(CMD_ENDLABEL))
                {
                    // < ENDLABEL
                    logger.Debug("\t< ENDLABEL");
                    string type = line.Trim().ToLower();

                    if (type.Equals("begin") || type.Equals("topic"))
                    {
                        logger.Debug("\t\tEnd topic label.");
                        topic = "random";
                    }
                    else if (type.Equals("object"))
                    {
                        logger.Debug("\t\tEnd object label.");
                        inObject = false;
                    }
                    else
                    {
                        logger.Warn("Unknown end topic type \"" + type + "\"", filename, lineno);
                    }
                }
                else if (cmd.Equals(CMD_TRIGGER))
                {
                    // + TRIGGER
                    logger.Debug("\t+ TRIGGER pattern: " + line);

                    //currentTriggerObject = new Trigger(line);

                    //if (previous.Length > 0)
                    //{
                    //    onTrigger = line + "{previous}" + previous;
                    //    currentTriggerObject.setPrevious(true);
                    //    topicManager.topic(topic).addPrevious(line, previous);
                    //}
                    //else
                    //{
                    //    onTrigger = line;
                    //}

                    //topicManager.topic(topic).addTrigger(currentTriggerObject);


                    //TODO onld stuff to see
                    if (previous.Length > 0)
                    {
                        // This trigger had a %Previous. To prevent conflict, tag the
                        // trigger with the "that" text.
                        onTrigger = line + "{previous}" + previous;

                        topicManager.topic(topic).trigger(line).setPrevious(true);
                        topicManager.topic(topic).addPrevious(line, previous);
                    }
                    else
                    {
                        // Set the current trigger to this.
                        onTrigger = line;
                    }
                }
                else if (cmd.Equals(CMD_REPLY))
                {
                    // - REPLY
                    logger.Debug("\t- REPLY: " + line);

                    // This can't come before a trigger!
                    if (onTrigger.Length == 0)
                    {
                        logger.Warn("Reply found before trigger", filename, lineno);
                        continue;
                    }

                    // Warn if we also saw a hard redirect.
                    if (topicManager.topic(topic).trigger(onTrigger).hasRedirect())
                    {
                        logger.Warn("You can't mix @Redirects with -Replies", filename, lineno);
                    }

                    // Add the reply to the trigger
                    topicManager.topic(topic).trigger(onTrigger).addReply(line);
                }
                else if (cmd.Equals(CMD_PREVIOUS))
                {
                    // % PREVIOUS
                    // This was handled above.
                    continue;
                }
                else if (cmd.Equals(CMD_CONTINUE))
                {
                    // ^ CONTINUE
                    // This was handled above.
                    continue;
                }
                else if (cmd.Equals(CMD_REDIRECT))
                {
                    // @ REDIRECT
                    logger.Debug("\t@ REDIRECT: " + line);

                    // This can't come before a trigger!
                    if (onTrigger.Length == 0)
                    {
                        logger.Warn("Redirect found before trigger", filename, lineno);
                        continue;
                    }

                    // Add the redirect to the trigger.
                    // TODO: this extends RiveScript, not compat w/ Perl yet
                    topicManager.topic(topic).trigger(onTrigger).addRedirect(line);
                }
                else if (cmd.Equals(CMD_CONDITION))
                {
                    // * CONDITION
                    logger.Debug("\t* CONDITION: " + line);

                    // This can't come before a trigger!
                    if (onTrigger.Length == 0)
                    {
                        logger.Warn("Redirect found before trigger", filename, lineno);
                        continue;
                    }

                    // Add the condition to the trigger.
                    topicManager.topic(topic).trigger(onTrigger).addCondition(line);
                }
                else
                {
                    logger.Warn("Unrecognized command \"" + cmd + "\"", filename, lineno);
                }
            }

            //becouse we use topicmanager to manage topis, we have to fill ast topics
            foreach (var item in topicManager.listTopics())
            {
                ast.addTopic(item.Value);
            }


            if (logger.IsDebugEnable)
            {
                logger.Debug($"Parsing {filename} completed in {DateTime.Now.Ticks - startTime} ms");
            }

            return(ast);
        }
Esempio n. 26
0
    static private Dictionary<BoxedExpression, List<ProofObligation>> RemoveStrongerPremises(Dictionary<BoxedExpression, List<ProofObligation>> inferred)
    {
      var result = new Dictionary<BoxedExpression, List<ProofObligation>>();

      foreach (var pair in inferred)
      {
        BoxedExpression premise, condition;
        BinaryOperator bop;

        if (pair.Key.IsBinaryExpression(out bop, out premise, out condition) && bop == BinaryOperator.LogicalOr)
        {
          // premise || conddition, but we have already condition without premise
          if (inferred.ContainsKey(condition))
          {
            List<ProofObligation> obligations;

            // we already processed  "condition", so we update the proof obligation
            if (result.TryGetValue(condition, out obligations) || inferred.TryGetValue(condition, out obligations))
            {
              obligations.AddRange(pair.Value);
            }
            else
            {
              Contract.Assume(false, "Impossible case!");
            }


            // was: continue
            continue;
          }

          // premise || premise
          if (BoxedExpression.SimpleSyntacticEquality(premise, condition))
          {
            result.AddOrUpdate(premise, pair.Value);

            // was: result.Add(premise);
            continue;
          }

          // if cond ==> premise, remove the premise
          if (Implies(condition, premise))
          {
            result.AddOrUpdate(condition, pair.Value);
            // was: result.Add(condition);
            continue;
          }

          // a < b || a == b, becomes a <= b
          BoxedExpression joined;
          if (CanMergeTogether(condition, premise, out joined))
          {
            result.AddOrUpdate(joined, pair.Value);
            // result.Add(joined);
            continue;
          }

          // F: We depend on the order of the facts!!! We should iterate to a fixpoint or we should pre-sort the list of inferred facts

          // "premise && !premise || condition" becomes "premise && condition"
          BoxedExpression newPre;
          if(PremiseIsImpliedByOtherPreconditions(premise, condition, result.Keys, out newPre))
          {
            result.AddOrUpdate(newPre, pair.Value);
            continue;
          }
        }
        result.AddOrUpdate(pair.Key, pair.Value);
        // result.Add(pair);
      }

      return result;
    }
Esempio n. 27
0
        public void ChoseWeapon(List <Card.Cards> choices, int gz = 1, int eb = 2) //v2.0
        {
            _weaponList.AddOrUpdate(Glavezooka, gz);
            _weaponList.AddOrUpdate(EaglehornBow, eb);

            /*
             * Yes, the proper way would be is to itterate through and find a min value,
             * but I figured since we know our decks, hardcoding values isn't half bad :3
             * Feel free to sort dragonList dictionary and whitelist dragons in proper order to support more dragons later on
             */
            var i = 0;

            while (true)
            {
                if (choices.Any(c => c.ToString() == _weaponList.FirstOrDefault(x => x.Value == i).Key))
                {
                    _whiteList.AddOrUpdate(_weaponList.FirstOrDefault(x => x.Value == i).Key, false);
                    break;
                }
                i++;
                if (i > _weaponList.Count)
                {
                    break;
                }
            }
        }
Esempio n. 28
0
        private static List<EventHistoryRecord> ParseEventHistoryRecords(string[] lines, ref int index)
        {
            List<EventHistoryRecord> histories = new List<EventHistoryRecord>();
            EventHistoryRecord eventHistory;
            string currentLine;

            List<Token> tokens;
            List<Token> headers;
            Dictionary<Token, Token> fields;
            Token fieldHeader;
            Token field;

            int eventNumber;
            DateTime dateTime;
            double faultLocation;
            double current;
            double frequency;
            int group;
            int shot;

            string date;
            string time;

            // Parse header
            headers = Split(lines[index++]);

            // Skip to the next nonblank line
            SkipBlanks(lines, ref index);

            while (index < lines.Length)
            {
                currentLine = lines[index];

                // Empty line indicates end of event histories
                if (string.IsNullOrWhiteSpace(currentLine))
                    break;

                // Create a new event history record
                eventHistory = new EventHistoryRecord();

                // Parse fields
                tokens = Split(currentLine);

                // Initialize date and time variables
                date = null;
                time = null;

                fields = new Dictionary<Token, Token>();

                foreach (Token token in tokens)
                {
                    fieldHeader = headers.MinBy(header => token.Distance(header));
                    fields.AddOrUpdate(fieldHeader, token, (key, value) => value.JoinWith(token));
                }
                
                foreach (Token header in headers)
                {
                    if (fields.TryGetValue(header, out field))
                    {

                        switch (header.Text.ToUpper())
                        {
                            case "#":
                            case "REC_NUM":
                                // Parse the field as an event number
                                if (int.TryParse(field.Text, out eventNumber))
                                    eventHistory.EventNumber = eventNumber;

                                break;

                            case "DATE":
                                // Parse the field as a date value
                                date = field.Text;

                                // If both date and time have been provided, parse them as a DateTime
                                if ((object)time != null && TryParseDateTime(string.Format("{0} {1}", date, time), out dateTime))
                                    eventHistory.Time = dateTime;

                                break;

                            case "TIME":
                                // Parse the field as a time value
                                time = field.Text;

                                // If both date and time have been provided, parse them as a DateTime
                                if ((object)date != null && TryParseDateTime(string.Format("{0} {1}", date, time), out dateTime))
                                    eventHistory.Time = dateTime;

                                break;

                            case "EVENT":
                                // Parse the field as an event type
                                eventHistory.EventType = field.Text;
                                break;

                            case "LOCAT":
                            case "LOCATION":
                                // Parse the field as a fault location value
                                if (double.TryParse(field.Text, out faultLocation))
                                    eventHistory.FaultLocation = faultLocation;

                                break;

                            case "CURR":
                                // Parse the field as a current magnitude
                                if (double.TryParse(field.Text, out current))
                                    eventHistory.Current = current;

                                break;

                            case "FREQ":
                                // Parse the field as a frequency value
                                if (double.TryParse(field.Text, out frequency))
                                    eventHistory.Frequency = frequency;

                                break;

                            case "GRP":
                            case "GROUP":
                                // Parse the field as a group number
                                if (int.TryParse(field.Text, out group))
                                    eventHistory.Group = group;

                                break;

                            case "SHOT":
                                // Parse the field as a shot number
                                if (int.TryParse(field.Text, out shot))
                                    eventHistory.Shot = shot;

                                break;

                            case "TARGETS":
                                // Parse the field as targets
                                eventHistory.Targets = field.Text;
                                break;
                        }
                    }
                }

                // Add history record to the list of histories
                histories.Add(eventHistory);

                // Advance to the next line
                index++;
            }

            return histories;
        }
        public void UpdateConfiguration()
        {
            const int LabelLength = 16;

            PhasorType type;
            AnalogType analogType;
            char phase;
            string label, scale;
            uint scalingValue;
            int order;

            // Define a protocol independent configuration frame
            m_baseConfigurationFrame = new ConfigurationFrame(m_idCode, DateTime.UtcNow.Ticks, (ushort)base.FramesPerSecond);

            // Define configuration cells (i.e., PMU's that will appear in outgoing data stream)
            foreach (DataRow deviceRow in DataSource.Tables["OutputStreamDevices"].Select($"ParentID={ID}", "LoadOrder"))
            {
                try
                {
                    // Get device ID and ID code
                    int deviceID = int.Parse(deviceRow["ID"].ToString());
                    ushort idCode = ushort.Parse(deviceRow["IDCode"].ToString());

                    // If number was never assigned or is invalid, we fall back on unique database record ID
                    if (idCode == 0)
                        idCode = unchecked((ushort)deviceID);

                    // Create a new configuration cell
                    ConfigurationCell cell = new ConfigurationCell(m_baseConfigurationFrame, idCode);

                    // Assign user selected data and coordinate formats, derived classes can change
                    string formatString;

                    formatString = deviceRow["PhasorDataFormat"].ToNonNullString(m_dataFormat.ToString());
                    cell.PhasorDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), string.IsNullOrEmpty(formatString) ? m_dataFormat.ToString() : formatString, true);

                    formatString = deviceRow["FrequencyDataFormat"].ToNonNullString(m_dataFormat.ToString());
                    cell.FrequencyDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), string.IsNullOrEmpty(formatString) ? m_dataFormat.ToString() : formatString, true);

                    formatString = deviceRow["AnalogDataFormat"].ToNonNullString(m_dataFormat.ToString());
                    cell.AnalogDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), string.IsNullOrEmpty(formatString) ? m_dataFormat.ToString() : formatString, true);

                    formatString = deviceRow["CoordinateFormat"].ToNonNullString(m_coordinateFormat.ToString());
                    cell.PhasorCoordinateFormat = (CoordinateFormat)Enum.Parse(typeof(CoordinateFormat), string.IsNullOrEmpty(formatString) ? m_coordinateFormat.ToString() : formatString, true);

                    // Assign device identification labels
                    cell.IDLabel = deviceRow["Name"].ToString().TruncateRight(cell.IDLabelLength).Trim();
                    label = deviceRow["Acronym"].ToString().TruncateRight(cell.MaximumStationNameLength).Trim();

                    // Station name is serialized to configuration frame
                    cell.StationName = label;

                    // Define all the phasors configured for this device
                    foreach (DataRow phasorRow in DataSource.Tables["OutputStreamDevicePhasors"].Select($"OutputStreamDeviceID={deviceID}", "LoadOrder"))
                    {
                        order = int.Parse(phasorRow["LoadOrder"].ToNonNullString("0"));
                        label = phasorRow["Label"].ToNonNullString("Phasor " + order).Trim().TruncateRight(LabelLength);
                        type = phasorRow["Type"].ToNonNullString("V").Trim().ToUpper().StartsWith("V") ? PhasorType.Voltage : PhasorType.Current;
                        phase = phasorRow["Phase"].ToNonNullString("+").Trim().ToUpper()[0];
                        scale = phasorRow["ScalingValue"].ToNonNullString("0");

                        if (m_replaceWithSpaceChar != Char.MinValue)
                            label = label.Replace(m_replaceWithSpaceChar, ' ');

                        // Scale can be defined as a negative value in database, so check both formatting styles
                        if (!uint.TryParse(scale, out scalingValue))
                            scalingValue = unchecked((uint)int.Parse(scale));

                        // Choose stream defined default value if no scaling value was defined
                        if (scalingValue == 0)
                            scalingValue = (type == PhasorType.Voltage ? m_voltageScalingValue : m_currentScalingValue);

                        cell.PhasorDefinitions.Add(new PhasorDefinition(
                            cell,
                            GeneratePhasorLabel(label, phase, type),
                            scalingValue,
                            type,
                            null));
                    }

                    // Add frequency definition
                    label = $"{cell.IDLabel.TruncateRight(LabelLength - 5)} Freq".Trim();
                    cell.FrequencyDefinition = new FrequencyDefinition(cell, label);

                    // Optionally define all the analogs configured for this device
                    if (DataSource.Tables.Contains("OutputStreamDeviceAnalogs"))
                    {
                        foreach (DataRow analogRow in DataSource.Tables["OutputStreamDeviceAnalogs"].Select($"OutputStreamDeviceID={deviceID}", "LoadOrder"))
                        {
                            order = int.Parse(analogRow["LoadOrder"].ToNonNullString("0"));
                            label = analogRow["Label"].ToNonNullString("Analog " + order).Trim().TruncateRight(LabelLength);
                            analogType = (AnalogType)int.Parse(analogRow["Type"].ToNonNullString("0"));
                            scale = analogRow["ScalingValue"].ToNonNullString("0");

                            if (m_replaceWithSpaceChar != Char.MinValue)
                                label = label.Replace(m_replaceWithSpaceChar, ' ');

                            // Scale can be defined as a negative value in database, so check both formatting styles
                            if (!uint.TryParse(scale, out scalingValue))
                                scalingValue = unchecked((uint)int.Parse(scale));

                            cell.AnalogDefinitions.Add(new AnalogDefinition(
                                cell,
                                label,
                                scalingValue == 0 ? m_analogScalingValue : scalingValue,
                                analogType));
                        }
                    }

                    // Optionally define all the digitals configured for this device
                    if (DataSource.Tables.Contains("OutputStreamDeviceDigitals"))
                    {
                        foreach (DataRow digitalRow in DataSource.Tables["OutputStreamDeviceDigitals"].Select($"OutputStreamDeviceID={deviceID}", "LoadOrder"))
                        {
                            order = int.Parse(digitalRow["LoadOrder"].ToNonNullString("0"));
                            scale = digitalRow["MaskValue"].ToNonNullString("0");

                            // IEEE C37.118 digital labels are defined with all 16-labels (one for each bit) in one large formatted string
                            label = digitalRow["Label"].ToNonNullString("Digital " + order).Trim().TruncateRight(LabelLength * 16);

                            if (m_replaceWithSpaceChar != Char.MinValue)
                                label = label.Replace(m_replaceWithSpaceChar, ' ');

                            // Mask can be defined as a negative value in database, so check both formatting styles
                            if (!uint.TryParse(scale, out scalingValue))
                                scalingValue = unchecked((uint)int.Parse(scale));

                            cell.DigitalDefinitions.Add(new DigitalDefinition(
                                cell,
                                label,
                                scalingValue == 0 ? m_digitalMaskValue : scalingValue));
                        }
                    }

                    m_baseConfigurationFrame.Cells.Add(cell);
                }
                catch (Exception ex)
                {
                    OnProcessException(MessageLevel.Warning, new InvalidOperationException($"Failed to define output stream device \"{deviceRow["Acronym"].ToString().Trim()}\" due to exception: {ex.Message}", ex));
                }
            }

            OnStatusMessage(MessageLevel.Info, $"Defined {m_baseConfigurationFrame.Cells.Count:N0} output stream devices...");

            // Create new lookup table for signal references
            Dictionary<MeasurementKey, SignalReference[]> signalReferences = new Dictionary<MeasurementKey, SignalReference[]>();

            Dictionary<string, int> signalCellIndexes = new Dictionary<string, int>();
            SignalReference signal;
            SignalReference lastSignal = new SignalReference("__-UNKNOWN");
            MeasurementKey measurementKey;
            bool foundQualityFlagsMeasurement = false;
            bool isQualityFlagsMeasurement;

            IEnumerable<DataRow> measurementRows = DataSource.Tables["OutputStreamMeasurements"]
                .Select($"AdapterID={ID}")
                .Select(row => new { Row = row, SigRef = new SignalReference(row["SignalReference"].ToString()) })
                .OrderBy(obj => obj.SigRef.Acronym)
                .ThenBy(obj => obj.SigRef.Kind)
                .ThenBy(obj => obj.SigRef.Index)
                .Select(obj => obj.Row);

            // Define measurement to signals cross reference dictionary
            foreach (DataRow measurementRow in measurementRows)
            {
                isQualityFlagsMeasurement = false;

                try
                {
                    // Create a new signal reference
                    signal = new SignalReference(measurementRow["SignalReference"].ToString());

                    // See if this is the quality flags designation for this output stream 
                    if (signal.Kind == SignalKind.Quality)
                    {
                        if (Name.Equals(signal.Acronym, StringComparison.OrdinalIgnoreCase))
                        {
                            if (foundQualityFlagsMeasurement)
                                throw new Exception("Only one quality flags measurement can be assigned to an output stream - additional quality flags will be ignored.");

                            foundQualityFlagsMeasurement = true;
                            isQualityFlagsMeasurement = true;
                        }
                        else
                        {
                            throw new Exception($"Unexpected quality flags measurement assignment to \"{signal.Acronym}\". A single quality flags measurement can be assigned to output stream \"{Name}\".");
                        }
                    }
                    else
                    {
                        // Lookup cell index by acronym - doing this work upfront will save a huge amount of work during primary measurement sorting
                        if (!signalCellIndexes.TryGetValue(signal.Acronym, out signal.CellIndex))
                        {
                            // We cache these indices locally to speed up initialization as we'll be
                            // requesting them for the same devices over and over
                            signal.CellIndex = m_baseConfigurationFrame.Cells.IndexOfStationName(signal.Acronym);
                            signalCellIndexes.Add(signal.Acronym, signal.CellIndex);
                        }
                    }

                    // No need to define this measurement for sorting unless it has a destination in the outgoing frame
                    if (signal.CellIndex > -1 || isQualityFlagsMeasurement)
                    {
                        // Get historian field
                        string historian = measurementRow["Historian"].ToNonNullString();
                        string pointID = measurementRow["PointID"].ToString();

                        // Define measurement key
                        if (!string.IsNullOrEmpty(historian))
                        {
                            measurementKey = MeasurementKey.LookUpOrCreate(historian, uint.Parse(pointID));
                        }
                        else
                        {
                            DataTable activeMeasurements = DataSource.Tables["ActiveMeasurements"];
                            DataRow[] activeMeasurementRows = new DataRow[0];

                            object activeMeasurementSignalID = null;
                            object activeMeasurementID = null;

                            // OPTIMIZE: This select query will be slow on very large ActiveMeasurement implementations, consider optimization.
                            if ((object)activeMeasurements != null)
                                activeMeasurementRows = activeMeasurements.Select($"ID LIKE '*:{pointID}'");

                            if (activeMeasurementRows.Length == 1)
                            {
                                activeMeasurementSignalID = activeMeasurementRows[0]["SignalID"];
                                activeMeasurementID = activeMeasurementRows[0]["ID"];
                            }

                            // If we still can't find the measurement key, now is the time to give up
                            if ((object)activeMeasurementSignalID == null && (object)activeMeasurementID == null)
                                throw new Exception($"Cannot find measurement key for measurement with pointID {pointID}");

                            measurementKey = MeasurementKey.LookUpOrCreate(Guid.Parse(activeMeasurementRows[0]["SignalID"].ToString()), activeMeasurementID.ToString());
                        }

                        // Re-index signals at runtime in the
                        // same way phasors are indexed at runtime
                        if (signal.Index >= 1)
                        {
                            if (signal.Kind == lastSignal.Kind && signal.Acronym == lastSignal.Acronym)
                                signal.Index = lastSignal.Index + 1;
                            else
                                signal.Index = 1;
                        }

                        lastSignal = signal;

                        // It is possible, but not as common, that a single measurement will have multiple destinations
                        // within an outgoing data stream frame, hence the following
                        signalReferences.AddOrUpdate(measurementKey, key => new[] { signal }, (key, signals) =>
                        {
                            // Add a new signal to existing collection
                            Array.Resize(ref signals, signals.Length + 1);
                            signals[signals.Length - 1] = signal;
                            return signals;
                        });
                    }
                }
                catch (Exception ex)
                {
                    OnProcessException(MessageLevel.Warning, new InvalidOperationException($"Failed to associate measurement key to signal reference \"{measurementRow["SignalReference"].ToNonNullString()}\" due to exception: {ex.Message}", ex));
                }
            }

            // Update the m_signalReferences member variable so that configuration changes will begin to take effect
            Interlocked.Exchange(ref m_signalReferences, signalReferences);

            // Assign action adapter input measurement keys - this assigns the expected measurements per frame needed
            // by the concentration engine for preemptive publication 
            InputMeasurementKeys = signalReferences.Keys.ToArray();

            // Allow for spaces in output stream device names if a replacement character has been defined for spaces
            if (m_replaceWithSpaceChar != char.MinValue)
            {
                foreach (IConfigurationCell cell in m_baseConfigurationFrame.Cells)
                    cell.StationName = cell.StationName.Replace(m_replaceWithSpaceChar, ' ');
            }

            // Create a new protocol specific configuration frame
            m_configurationFrame = CreateNewConfigurationFrame(m_baseConfigurationFrame);

            // Cache new protocol specific configuration frame
            CacheConfigurationFrame(m_configurationFrame, Name);
        }
Esempio n. 30
0
        void CollectThemeInfo()
        {
            var result = new Dictionary<string, object>();

            System.Windows.Media.Color accentColor = Colors.White;

            //if (Config.ShouldUseVisualStudioTheme)
            {
                var theme_color = ThemeInfo.GetThemeColor();

                accentColor = theme_color;

                result.AddOrUpdate(KnownProperties.AccentColor, accentColor);
            }

            CurrentThemeInfo.Clear();
            CurrentThemeInfo.AddOrUpdateFrom((IDictionary<string,object>)result);
        }
Esempio n. 31
0
        public override void Write(byte[] buffer, int offset, int count)
        {
            var bodyStart = 0;

            if (!_headersRead)
            {
                var streamData = Encoding.UTF8.GetString(buffer, 0, count);
                _headerData += streamData;
                bodyStart = _headerData.IndexOf(CrLf + CrLf, StringComparison.Ordinal);
                if (bodyStart >= 0)
                {
                    _headersRead = true;
                    _headerData = _headerData.Substring(0, bodyStart);
                }
            }

            if (_headersRead)
            {
                var httpLines = _headerData.Split(new[] { CrLf }, StringSplitOptions.None);
                if (httpLines.Length > 0)
                {
                    var requestLine = httpLines[0];
                    var splitRequest = requestLine.Split(' ');

                    Method = splitRequest.Length > 0 ? splitRequest[0] : string.Empty;
                    Uri = splitRequest.Length > 1 ? splitRequest[1] : string.Empty;
                    HttpVersion = splitRequest.Length > 2 ? splitRequest[2] : string.Empty;
                }

                if (httpLines.Length > 1)
                {
                    Headers = new Dictionary<string, string>(StringComparer.Ordinal);

                    for (int headerLineIndex = 1; headerLineIndex < httpLines.Length; headerLineIndex++)
                    {
                        if (string.IsNullOrEmpty(httpLines[headerLineIndex])) // The start of the body
                            break;

                        var header = httpLines[headerLineIndex];

                        Headers.AddOrUpdate(
                            header.Split(':')[0],
                            header.Split(':')[1].Trim());
                    }
                }
            }

            if (bodyStart >= 0 && count - (bodyStart + 4) > 0)
            {
                _bodyStream.Write(buffer, (bodyStart + 4), count - (bodyStart + 4));
            }
        }
Esempio n. 32
0
    static private Dictionary<BoxedExpression, List<ProofObligation>> RemoveCoveringPremises(Dictionary<BoxedExpression, List<ProofObligation>> original)
    {
      Contract.Requires(original != null);
      Contract.Ensures(Contract.Result<Dictionary<BoxedExpression, List<ProofObligation>>>() != null);

      var result = new Dictionary<BoxedExpression, List<ProofObligation>>();

      // we look for premise ==> cond
      // so the dictionary contains cond --> (premise ==> cond)
      var cached = new Dictionary<BoxedExpression, Tuple<BoxedExpression, List<ProofObligation>>>(original.Count);

      foreach (var pair in original)
      {
        BinaryOperator bop;
        BoxedExpression premise, cond;
        if (pair.Key.IsBinaryExpression(out bop, out premise, out cond) && bop == BinaryOperator.LogicalOr)
        {
          Tuple<BoxedExpression, List<ProofObligation>> prev;
          if (cached.TryGetValue(cond, out prev))
          {
            Contract.Assume(prev != null);
            BoxedExpression prevPremise, prevCond;
            if (prev.Item1.IsBinaryExpression(out bop, out prevPremise, out prevCond) && bop == BinaryOperator.LogicalOr)
            {
              Contract.Assume(prevCond.Equals(cond));

              cached.Remove(cond);

              if (premise.Negate().Equals(prevPremise))
              {
                result.AddOrUpdate(cond, pair.Value);
              }
              else
              {
                result.AddOrUpdate(pair.Key, pair.Value);
                result.AddOrUpdate(prev.Item1, prev.Item2);
              }
            }
            else
            {
              Contract.Assume(false);
            }
          }
          else
          {
            cached[cond] = new Tuple<BoxedExpression,List<ProofObligation>>(pair.Key, pair.Value);
          }
        }
        else
        {
          result.AddOrUpdate(pair.Key, pair.Value);
        }
      }

      foreach (var pairs in cached)
      {
        result.AddOrUpdate(pairs.Value.Item1, pairs.Value.Item2);
      }

      return result;
    }
Esempio n. 33
0
        private static Dictionary<string, DataRow> InitializeSignalTypes()
        {
            Dictionary<string, DataRow> signalTypes;

            // It is expected that when a point tag is needing to be created that the database will be available
            using (AdoDataConnection database = new AdoDataConnection("systemSettings"))
            {
                signalTypes = new Dictionary<string, DataRow>(StringComparer.OrdinalIgnoreCase);

                foreach (DataRow row in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM SignalType").AsEnumerable())
                {
                    signalTypes.AddOrUpdate(row["Acronym"].ToString(), row);
                }
            }

            return signalTypes;
        }
 public WebSocketUrlBuilder SetVersion(int version)
 {
     _arguments.AddOrUpdate("v", version);
     return(this);
 }
Esempio n. 35
0
        public override List <Card> HandleMulligan(List <Card> Choices, CClass opponentClass, CClass ownClass)
        {
            bool hasCoin  = Choices.Count > 3;
            bool has2drop = false;
            bool lazyFlag = false;

            #region Default Mulligan

            _whiteList.AddOrUpdate(_abusiveSergeant, false);
            _whiteList.AddOrUpdate(_argentSquire, true);
            _whiteList.AddOrUpdate(_coin, true); // Would be nice to keep double
            if (!antiControlBETA || (opponentClass != CClass.WARRIOR))
            {
                _whiteList.AddOrUpdate(_hauntedCreeper, true);
            }
            _whiteList.AddOrUpdate(_knifeJuggler, false);
            _whiteList.AddOrUpdate(_leperGnome, true);
            _whiteList.AddOrUpdate(_madScientist, true);
            _whiteList.AddOrUpdate(_secretkeeper, true);
            _whiteList.AddOrUpdate(_shieldedMinibot, true);
            _whiteList.AddOrUpdate(_zombieChow, true);



            #endregion Default Mulligan

            #region Class Specific Mulligan
            if ((Choices.Any(c => c.Name == _harvestGolem) ||
                 Choices.Any(c => c.Name == _shieldedMinibot) ||
                 Choices.Any(c => c.Name == _madScientist) ||
                 Choices.Any(c => c.Name == _knifeJuggler)
                 ))
            {
                has2drop = true;
            }
            if (midrangeSecretPaladin && hasCoin && has2drop)
            {
                _whiteList.AddOrUpdate(_pilotedShredder, false);
            }

            if (midrangeSecretPaladin)
            {
                _whiteList.AddOrUpdate(_avenge, false);
            }

            switch (opponentClass)
            {
            case CClass.DRUID:
            {
                if (hasCoin)
                {
                    lazyFlag = true;
                }
                _whiteList.AddOrUpdate(_musterForBattle, false);
                if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_pilotedShredder, false);
                }

                break;
            }

            case CClass.HUNTER:
            {
                if (coghammerLogic && has2drop)
                {
                    _whiteList.AddOrUpdate(_coghammer, false);
                }
                _whiteList.AddOrUpdate(_annoyatron, false);
                if (midrangeSecretPaladin && hasCoin)
                {
                    _whiteList.AddOrUpdate(_consecration, false);
                }
                else if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_consecration, false);
                }
                break;
            }

            case CClass.MAGE:
            {
                if (hasCoin)
                {
                    lazyFlag = true;
                }
                _whiteList.AddOrUpdate(_musterForBattle, false);
                if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_mysteriousChallenger, false);
                }
                else
                {
                    _whiteList.AddOrUpdate(_nobleSacrifice, false);
                }

                if (midrangeSecretPaladin && hasCoin)
                {
                    _whiteList.AddOrUpdate(_consecration, false);
                }
                else if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_consecration, false);
                }
                break;
            }

            case CClass.PALADIN:
            {
                if (hasCoin || has2drop)
                {
                    _whiteList.AddOrUpdate(_bloodKnight, false);
                    _whiteList.AddOrUpdate(_ironbeakOwl, false);
                }
                _whiteList.AddOrUpdate(_annoyatron, false);
                _whiteList.AddOrUpdate(_consecration, false);

                if (midrangeSecretPaladin && hasCoin)
                {
                    _whiteList.AddOrUpdate(_consecration, false);
                }
                else if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_consecration, false);
                }

                _whiteList.AddOrUpdate(_musterForBattle, false);
                if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_mysteriousChallenger, false);
                }
                break;
            }

            case CClass.PRIEST:
            {
                if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_mysteriousChallenger, false);
                }
                _whiteList.AddOrUpdate(_pilotedShredder, false);

                break;
            }

            case CClass.ROGUE:
            {
                if (hasCoin)
                {
                    lazyFlag = true;
                }
                _whiteList.AddOrUpdate(_musterForBattle, false);
                if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_mysteriousChallenger, false);
                }
                _whiteList.AddOrUpdate(_pilotedShredder, false);

                break;
            }

            case CClass.SHAMAN:
            {
                _whiteList.AddOrUpdate(_musterForBattle, false);
                if (!midrangeSecretPaladin)
                {
                    _whiteList.AddOrUpdate(_mysteriousChallenger, false);
                }
                _whiteList.AddOrUpdate(_pilotedShredder, false);
                break;
            }

            case CClass.WARLOCK:
            {
                _whiteList.AddOrUpdate(_consecration, false);
                _whiteList.AddOrUpdate(_musterForBattle, false);
                break;
            }

            case CClass.WARRIOR:
            {
                _whiteList.AddOrUpdate(_annoyatron, false);
                _whiteList.AddOrUpdate(_musterForBattle, false);
                if (!midrangeSecretPaladin && hasCoin)
                {
                    _whiteList.AddOrUpdate(_mysteriousChallenger, false);
                }

                if (antiControlBETA && hasCoin)
                {
                    _whiteList.AddOrUpdate(_pilotedShredder, true);
                }
                else
                {
                    _whiteList.AddOrUpdate(_pilotedShredder, false);
                }

                break;
            }
            }
            if (mysteriousChallenger_forever)
            {
                _whiteList.AddOrUpdate(_mysteriousChallenger, false);
            }

            if ((Choices.Any(c => c.Name == _coghammer) && (coghammerLogic && has2drop) && (opponentClass != CClass.WARRIOR)))
            {
                _whiteList.AddOrUpdate(_coghammer, false);
            }
            else if ((opponentClass == CClass.WARRIOR) || (opponentClass == CClass.PRIEST) || (opponentClass == CClass.ROGUE) || (opponentClass == CClass.DRUID))
            {
                _whiteList.AddOrUpdate(_truesilverChamption, false);
            }

            if ((competitiveMustard && lazyFlag) && (Choices.Any(c => c.Name == _competitiveSpirit) && Choices.Any(c => c.Name == _musterForBattle)))
            {
                _whiteList.AddOrUpdate(_musterForBattle, false);
                _whiteList.AddOrUpdate(_competitiveSpirit, false);
            }

            //Keep Mysterious Challenger on coin
            if (hasCoin && !midrangeSecretPaladin)
            {
                _whiteList.AddOrUpdate(_annoyatron, false);
                _whiteList.AddOrUpdate(_mysteriousChallenger, false);
            }

            // Redemption and Harvest Golem are kept if you have both.
            if (redeeming2Drops &&
                (Choices.Any(c => c.Name == _harvestGolem) ||
                 Choices.Any(c => c.Name == _shieldedMinibot)
                ))
            {
                _whiteList.AddOrUpdate(_harvestGolem, false);
                _whiteList.AddOrUpdate(_redemption, false);
                // has2drop = true;
            }

            if ((opponentClass == CClass.ROGUE) || (opponentClass == CClass.DRUID)) //These classes can kill Defender if it's played on turn 1.
            {
                nobleJuggler = false;
            }

            // Noble Sacrifice is kept if you have Knife Juggler.
            if (nobleJuggler && (Choices.Any(c => c.Name == _knifeJuggler)))
            {
                _whiteList.AddOrUpdate(_nobleSacrifice, false);
            }


            // Tech choice with blood knight
            if (keepBloodKnight_onCurve &&
                (Choices.Any(c => c.Name == _argentSquire) && (Choices.Any(c => c.Name == _shieldedMinibot) || Choices.Any(c => c.Name == _annoyatron))))
            {
                _whiteList.AddOrUpdate(_annoyatron, false);
                _whiteList.AddOrUpdate(_bloodKnight, false);
            }
            //Experimental segment that keeps noble sac and avenge with secret keeper.
            if (vengefulSecretKeeper &&
                (Choices.Any(c => c.Name == _avenge) &&
                 (Choices.Any(c => c.Name == _secretkeeper) &&
                  Choices.Any(c => c.Name == _nobleSacrifice))))
            {
                _whiteList.AddOrUpdate(_nobleSacrifice, false);
                _whiteList.AddOrUpdate(_avenge, false);
            }


            #endregion

            foreach (Card s in Choices)
            {
                bool keptOneAlready = false;

                if (_cardsToKeep.Any(c => c.Name == s.Name))
                {
                    keptOneAlready = true;
                }
                if (_whiteList.ContainsKey(s.Name))
                {
                    if (!keptOneAlready | _whiteList[s.Name])
                    {
                        _cardsToKeep.Add(s);
                    }
                }
            }

            return(_cardsToKeep);
        }
Esempio n. 36
0
        public bool LoadModule(Module mod, Entity roid)
        {
            if (mod.Capacity > 0)
            {
                // Module is offline
                if (!mod.IsOnline)
                {
                    EVEFrame.Log("LoadModule: Module offline");
                    return(false);
                }

                // Module is busy - wait
                if (mod.IsReloading || mod.IsActive || mod.IsActivating || mod.IsDeactivating)
                {
                    EVEFrame.Log("LoadModule: Module is busy - wait");
                    return(true);
                }

                if (mod.Charge != null)
                {
                    // Do we already have the correct crystal loaded
                    if (MatchingMiningCrystal(roid).Contains(mod.Charge.TypeID))
                    {
                        return(false);
                    }
                }

                Item matchingCrystal = MyShip.CargoBay.Items.FirstOrDefault(a => MatchingMiningCrystal(roid) != null && MatchingMiningCrystal(roid).Contains(a.TypeID));

                // We're on cooldown from swapping or unloading crystals right now
                if (CrystalSwapCooldown.ContainsKey(mod) && DateTime.Now < CrystalSwapCooldown[mod])
                {
                    EVEFrame.Log("LoadModule: Cooldown");
                    return(true);
                }

                if (!MyShip.CargoBay.IsPrimed)
                {
                    MyShip.CargoBay.Prime();
                    return(true);
                }

                // Cargo is full, can't unload mining crystal
                if (mod.Charge != null && (MyShip.CargoBay.MaxCapacity - MyShip.CargoBay.UsedCapacity) < mod.Charge.Volume)
                {
                    return(false);
                }

                // We have the correct crystal in cargo, load it
                if (matchingCrystal != null)
                {
                    mod.LoadAmmo(matchingCrystal);
                    CrystalSwapCooldown.AddOrUpdate(mod, DateTime.Now.AddSeconds(5));
                    return(true);
                }

                // We don't have the correct crystal in cargo and there's a charge loaded, unload it
                if (mod.Charge != null)
                {
                    mod.UnloadAmmo();
                    CrystalSwapCooldown.AddOrUpdate(mod, DateTime.Now.AddSeconds(5));
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 37
0
 public void AddQueryParameter(string key, string value)
 {
     _queryParameters.AddOrUpdate(key, value);
 }
Esempio n. 38
0
        // Static Methods

        public static List <EventHistoryRecord> ParseRecords(string[] lines, ref int index)
        {
            List <EventHistoryRecord> histories = new List <EventHistoryRecord>();
            EventHistoryRecord        eventHistory;
            string currentLine;

            List <Token> tokens;
            List <Token> headers;
            Dictionary <Token, Token> fields;
            Token fieldHeader;
            Token field;

            int      eventNumber;
            DateTime dateTime;
            double   faultLocation;
            double   current;
            double   frequency;
            int      group;
            int      shot;

            string date;
            string time;

            // Parse header
            headers = Split(lines[index++]);

            // Skip to the next nonblank line
            EventFile.SkipBlanks(lines, ref index);

            while (index < lines.Length)
            {
                currentLine = lines[index];

                // Empty line indicates end of event histories
                if (string.IsNullOrWhiteSpace(currentLine))
                {
                    break;
                }

                // Create a new event history record
                eventHistory = new EventHistoryRecord();

                // Parse fields
                tokens = Split(currentLine);

                // Initialize date and time variables
                date = null;
                time = null;

                fields = new Dictionary <Token, Token>();

                foreach (Token token in tokens)
                {
                    fieldHeader = headers.MinBy(header => token.Distance(header));
                    fields.AddOrUpdate(fieldHeader, token, (key, value) => value.JoinWith(token));
                }

                foreach (Token header in headers)
                {
                    if (fields.TryGetValue(header, out field))
                    {
                        switch (header.Text.ToUpper())
                        {
                        case "#":
                        case "REC_NUM":
                            // Parse the field as an event number
                            if (int.TryParse(field.Text, out eventNumber))
                            {
                                eventHistory.EventNumber = eventNumber;
                            }

                            break;

                        case "DATE":
                            // Parse the field as a date value
                            date = field.Text;

                            // If both date and time have been provided, parse them as a DateTime
                            if ((object)time != null && EventFile.TryParseDateTime(string.Format("{0} {1}", date, time), out dateTime))
                            {
                                eventHistory.Time = dateTime;
                            }

                            break;

                        case "TIME":
                            // Parse the field as a time value
                            time = field.Text;

                            // If both date and time have been provided, parse them as a DateTime
                            if ((object)date != null && EventFile.TryParseDateTime(string.Format("{0} {1}", date, time), out dateTime))
                            {
                                eventHistory.Time = dateTime;
                            }

                            break;

                        case "EVENT":
                            // Parse the field as an event type
                            eventHistory.EventType = field.Text;
                            break;

                        case "LOCAT":
                        case "LOCATION":
                            // Parse the field as a fault location value
                            if (double.TryParse(field.Text, out faultLocation))
                            {
                                eventHistory.FaultLocation = faultLocation;
                            }

                            break;

                        case "CURR":
                            // Parse the field as a current magnitude
                            if (double.TryParse(field.Text, out current))
                            {
                                eventHistory.Current = current;
                            }

                            break;

                        case "FREQ":
                            // Parse the field as a frequency value
                            if (double.TryParse(field.Text, out frequency))
                            {
                                eventHistory.Frequency = frequency;
                            }

                            break;

                        case "GRP":
                        case "GROUP":
                            // Parse the field as a group number
                            if (int.TryParse(field.Text, out group))
                            {
                                eventHistory.Group = group;
                            }

                            break;

                        case "SHOT":
                            // Parse the field as a shot number
                            if (int.TryParse(field.Text, out shot))
                            {
                                eventHistory.Shot = shot;
                            }

                            break;

                        case "TARGETS":
                            // Parse the field as targets
                            eventHistory.Targets = field.Text;
                            break;
                        }
                    }
                }

                // Add history record to the list of histories
                histories.Add(eventHistory);

                // Advance to the next line
                index++;
            }

            return(histories);
        }