Beispiel #1
0
        public string ToJson()
        {
            var values = new Dictionary
                         <string, string>(this);

            values.AddOrSet("mp_source", _source);
            values.AddOrSet("token", ApiKeys.MIXPANEL_TOKEN);

            var settings = AppSettings.Instance;

            values.AddOrSet("distinct_id",
                            settings.InstanceID);

            var properties = values.Select(x =>
                                           new JProperty(x.Key, x.Value))
                             .ToArray();

            var json = new JObject(
                new JProperty("event", _eventName),
                new JProperty("properties",
                              new JObject(properties)));

            return(Convert.ToBase64String(
                       Encoding.UTF8.GetBytes(json.ToString())));
        }
Beispiel #2
0
        public string GetDigest(string uri, string method)
        {
            _nc++;

            var values = new Dictionary<string, string>(_values)
            {
                {"uri", uri},
                {"method", method},
                {"nc", _nc.ToString("00000000")},
            };

            var a1 = GetHash(GetKeys(values,
                "username", "realm", "password"));
            values.AddOrSet("a1", a1);

            var a2 = GetHash(GetKeys(
                values, "method", "uri"));
            values.AddOrSet("a2", a2);

            var response = GetHash(GetKeys(values,
                "a1", "nonce", "nc", "cnonce", "qop", "a2"));
            values.AddOrSet("response", response);

            return GetDigest(values,
                "username", "realm", "nonce", "uri",
                "response", "opaque", "qop", "nc", "cnonce");
        }
Beispiel #3
0
        public string GetDigest(string uri, string method)
        {
            _nc++;

            var values = new Dictionary <string, string>(_values)
            {
                { "uri", uri },
                { "method", method },
                { "nc", _nc.ToString("00000000") },
            };

            var a1 = GetHash(GetKeys(values,
                                     "username", "realm", "password"));

            values.AddOrSet("a1", a1);

            var a2 = GetHash(GetKeys(
                                 values, "method", "uri"));

            values.AddOrSet("a2", a2);

            var response = GetHash(GetKeys(values,
                                           "a1", "nonce", "nc", "cnonce", "qop", "a2"));

            values.AddOrSet("response", response);

            return(GetDigest(values,
                             "username", "realm", "nonce", "uri",
                             "response", "opaque", "qop", "nc", "cnonce"));
        }
Beispiel #4
0
        public int OtherSolution(int[] num)
        {
            int res = 0;
            Dictionary <int, int> map = new Dictionary <int, int>();

            foreach (int n in num)
            {
                if (!map.ContainsKey(n))//仅处理未在区域内的值 即记录的值
                {
                    int left  = (map.ContainsKey(n - 1)) ? map.Get(n - 1) : 0;
                    int right = (map.ContainsKey(n + 1)) ? map.Get(n + 1) : 0;
                    // sum: length of the sequence n is in
                    int sum = left + right + 1;
                    map.Add(n, sum);

                    // keep track of the max length
                    res = Math.Max(res, sum);

                    // extend the length to the boundary(s)
                    // of the sequence
                    // will do nothing if n has no neighbors
                    map.AddOrSet(n - left, sum);  //设置左边界值
                    map.AddOrSet(n + right, sum); //设置右边界值
                }
            }
            return(res);
        }
Beispiel #5
0
        public PowerShellProviderBase(DynamicPowershell ps, PSModuleInfo module)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }

            _powershell = ps;
            _module     = module;

            // combine all the cmdinfos we care about
            // but normalize the keys as we go (remove any '-' '_' chars)
            foreach (var k in _module.ExportedAliases.Keys)
            {
                _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedAliases[k]);
            }
            foreach (var k in _module.ExportedCmdlets.Keys)
            {
                _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedCmdlets[k]);
            }
            foreach (var k in _module.ExportedFunctions.Keys)
            {
                _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedFunctions[k]);
            }
        }
Beispiel #6
0
 public void Reload()
 {
     m_EnabledAddons.Clear();
     if (System.IO.File.Exists(CharacterAddonFilePath) == true)
     {
         m_LoadDateTime = DateTime.Now;
         m_Changed      = false;
         string[] configLines = System.IO.File.ReadAllLines(CharacterAddonFilePath);
         foreach (string configLine in configLines)
         {
             string[] addonNameAndConfig = configLine.Split(new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries);
             if (addonNameAndConfig.Length == 2)
             {
                 AddonStatus.Enum addonEnabled = AddonStatus.Enum.Default;
                 if (addonNameAndConfig[1] == "enabled")
                 {
                     addonEnabled = AddonStatus.Enum.Enabled;
                 }
                 else if (addonNameAndConfig[1] == "disabled")
                 {
                     addonEnabled = AddonStatus.Enum.Disabled;
                 }
                 else
                 {
                     Logger.ConsoleWriteLine("Unexpected Addon Config State: " + addonNameAndConfig[1], ConsoleColor.Red);
                     continue;
                 }
                 m_EnabledAddons.AddOrSet(addonNameAndConfig[0], addonEnabled);
             }
         }
     }
 }
Beispiel #7
0
        public static bool Update(string key, string value, LocaleType type)
        {
            LocaleItem li;

            if (!Exists(key))
            {
                string path;
                switch (type)
                {
                case LocaleType.VictoryPointName: {
                    path = @$ "{basePath}{localeFileLocation}\ttr_victory_points_l_english.yml";
                    break;
                }

                case LocaleType.StateName: {
                    path = @$ "{basePath}{localeFileLocation}\ttr_state_names_l_english.yml";
                    break;
                }

                default: {
                    path = @$ "{basePath}{localeFileLocation}\ttr_misc_l_english.yml";
                    break;
                }
                }
                li = new LocaleItem(value, path, true);
                dict.AddOrSet(key, li);
                return(true);
            }

            if (IsLocaleVanilla(dict[key]))
            {
                string path;
                switch (type)
                {
                case LocaleType.VictoryPointName: {
                    path = @$ "{basePath}{localeFileLocation}\replace\ttr_victory_points_replace_l_english.yml";
                    break;
                }

                case LocaleType.StateName: {
                    path = @$ "{basePath}{localeFileLocation}\replace\ttr_state_names_replace_l_english.yml";
                    break;
                }

                default: {
                    path = @$ "{basePath}{localeFileLocation}\replace\ttr_misc_replace_l_english.yml";
                    break;
                }
                }
                li = new LocaleItem(value, path, true);
                dict.AddOrSet(key, li);
                return(true);
            }

            li        = new LocaleItem(value, dict[key].Source, true);
            dict[key] = li;
            return(true);
        }
Beispiel #8
0
 private void _SetConfigString(string _ConfigName, string _Value)
 {
     ConfigValues.AddOrSet(_ConfigName, Tuple.Create(_Value, true));
     if (ConfigValuesChanged != null)
     {
         ConfigValuesChanged(_ConfigName, _Value);
     }
     Logger.LogText("Changed Setting \"" + _ConfigName + "\" to value \"" + _Value + "\"");
 }
Beispiel #9
0
 protected IEnumerable <SoftwareIdentity> ProcessProvider(PackageProvider provider)
 {
     using (var packages = provider.GetInstalledPackages("", this).CancelWhen(_cancellationEvent.Token)) {
         foreach (var p in packages)
         {
             _providersProcessed.AddOrSet(provider.ProviderName, true);
             yield return(p);
         }
     }
 }
        public override bool VisitRegularField(EntityTemplateParser.RegularFieldContext context)
        {
            _doubleFieldCount.AddOrSet($"{string.Join(".",_embeddedObjectContext)}.{context.key.Text.Trim(1,1)}", existing => ++ existing);

            if (context.value().@object() == null && _embeddedObjectContext.Count == 1)
            {
                _nonObjectFieldKeys.Add(context.key.Text.Trim(1, 1));
            }

            return(base.VisitRegularField(context));
        }
Beispiel #11
0
        public void push(int x)
        {
            int f = freq.Get(x, 0) + 1;

            freq.AddOrSet(x, f);
            maxfreq = Math.Max(maxfreq, f);
            if (!m.ContainsKey(f))
            {
                m.Add(f, new Stack <int>());
            }
            m[f].Push(x);
        }
Beispiel #12
0
 /// <summary>
 /// Marking an endpoint as failed means that we will not try to connect to the remote system within
 /// the gated period but it is ok for the remote system to try to connect with us (inbound-only.)
 /// </summary>
 public void MarkAsFailed(ActorRef endpoint, Deadline timeOfRelease)
 {
     if (IsWritable(endpoint))
     {
         addressToWritable.AddOrSet(writableToAddress[endpoint], new EndpointManager.Gated(timeOfRelease));
         writableToAddress.Remove(endpoint);
     }
     else if (IsReadOnly(endpoint))
     {
         addressToReadonly.Remove(readonlyToAddress[endpoint]);
         readonlyToAddress.Remove(endpoint);
     }
 }
 private void HandleCalculationResult(CalculationResultMessage resultMessage)
 {
     if (resultMessage.command is AddMessage)
     {
         var addMessage = resultMessage.command as AddMessage;
         var key        = $"add_{addMessage.Summand1}_{addMessage.Summand2}";
         cachedResults.AddOrSet(key, resultMessage.Result);
     }
     if (resultMessage.command is UltimateQuestion)
     {
         var key = $"ultimateQuestion";
         cachedResults.AddOrSet(key, resultMessage.Result);
     }
 }
 public ActorRef RegisterWritableEndpoint(Address address, ActorRef endpoint, int?uid = null)
 {
     EndpointManager.EndpointPolicy existing;
     if (addressToWritable.TryGetValue(address, out existing))
     {
         var gated = existing as EndpointManager.Gated;
         if (gated != null && !gated.TimeOfRelease.IsOverdue) //don't throw if the prune timer didn't get a chance to run first
         {
             throw new ArgumentException("Attempting to overwrite existing endpoint " + existing + " with " + endpoint);
         }
     }
     addressToWritable.AddOrSet(address, new EndpointManager.Pass(endpoint, uid));
     writableToAddress.AddOrSet(endpoint, address);
     return(endpoint);
 }
Beispiel #15
0
        /// <summary>
        /// https://leetcode.com/problems/judge-route-circle/description/
        /// </summary>
        /// <param name="moves"></param>
        /// <returns></returns>
        public static bool JudgeCircle(string moves)
        {
            var dict = new Dictionary <char, int>();

            dict.AddOrSet('U', 0);
            dict.AddOrSet('D', 0);
            dict.AddOrSet('L', 0);
            dict.AddOrSet('R', 0);
            for (int i = 0; i < moves.Length; i++)
            {
                dict.AddOrSet(moves[i], (cur) => ++ cur);
            }

            return((dict['U'] == dict['D']) && (dict['L'] == dict['R']));
        }
Beispiel #16
0
        /// <summary>
        /// https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
        /// cbaebabacd
        /// abc
        /// </summary>
        /// <param name="s"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static IList <int> FindAnagrams(string s, string p)
        {
            var ret       = new List <int>();
            var stillNeed = new Dictionary <char, int>(); //Meaning if you want to establish an anagram of string p, you still need how many characters

            foreach (var c in p)
            {
                stillNeed.AddOrSet(c, stillNeed.GetValueOrDefault(c, 0) + 1);
            }

            int counter = stillNeed.Count; // number of unique characters in p

            //start at the beginning
            int start = 0, end = 0;

            while (end < s.Length)
            {
                var endChar = s[end];
                if (stillNeed.ContainsKey(endChar))
                {
                    stillNeed[endChar]--;
                    if (stillNeed[endChar] == 0)
                    {
                        counter--;
                    }
                }
                end++;
                while (counter == 0)
                {
                    var startChar = s[start];
                    if (stillNeed.ContainsKey(s[start]))
                    {
                        stillNeed.AddOrSet(startChar, stillNeed.GetValueOrDefault(startChar, 0) + 1);
                        if (stillNeed[startChar] > 0)
                        {
                            counter++;
                        }
                    }
                    if (end - start == p.Length)
                    {
                        ret.Add(start);
                    }
                    start++;
                }
            }

            return(ret);
        }
Beispiel #17
0
        public static Dictionary <TKey, TElement> ToDictionaryNicely <TSource, TKey, TElement>(
            this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, Func <TSource, TElement> elementSelector,
            IEqualityComparer <TKey> comparer)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (keySelector == null)
            {
                throw new ArgumentNullException(nameof(keySelector));
            }
            if (elementSelector == null)
            {
                throw new ArgumentNullException(nameof(elementSelector));
            }

            var dictionary = new Dictionary <TKey, TElement>(comparer);

            foreach (var element in source)
            {
                dictionary.AddOrSet(keySelector(element), elementSelector(element));
            }
            return(dictionary);
        }
Beispiel #18
0
        static MsBuildMap()
        {
            TaskClasses = new AsyncLazy <Dictionary <string, MSBuildTaskType> >(() => {
                var _taskClasses = new Dictionary <string, MSBuildTaskType>();

                // ensure a few assemblies are loaded.
                AppDomain.CurrentDomain.Load(new AssemblyName("Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"));
                AppDomain.CurrentDomain.Load(new AssemblyName("Microsoft.Build.Utilities.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"));
                AppDomain.CurrentDomain.Load(new AssemblyName("Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"));

                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (var asm in assemblies)
                {
                    try {
                        var tasks = asm.GetTypes().Where(each => each.GetInterfaces().Contains(typeof(ITask))).Where(each => each.IsPublic);
                        foreach (var t in tasks)
                        {
                            var properties = t.GetProperties().Where(each => !_ignoreProperties.Contains(each.Name)).ToArray();
                            if (!_taskClasses.ContainsKey(t.Name))
                            {
                                _taskClasses.AddOrSet(t.Name.ToLower(), new MSBuildTaskType {
                                    TaskClass      = t,
                                    Outputs        = properties.Where(each => each.GetCustomAttributes(true).Any(attr => attr.GetType().Name == "OutputAttribute")).Select(each => each.Name).ToArray(),
                                    RequiredInputs = properties.Where(each => each.GetCustomAttributes(true).Any(attr => attr.GetType().Name == "RequiredAttribute")).Select(each => each.Name).ToArray(),
                                    OptionalInputs = properties.Where(each => each.GetCustomAttributes(true).All(attr => attr.GetType().Name != "OutputAttribute" && attr.GetType().Name != "RequiredAttribute")).Select(each => each.Name).ToArray()
                                });
                            }
                        }
                    } catch (Exception) {
                        // skip any troublesome assemblies.
                    }
                }
                return(_taskClasses);
            });
        }
        private IEnumerable <GachaLogNode> BuildView(IEnumerable <GachaLogItem> pool)
        {
            IEnumerable <GachaLogItem> rank5 = pool.Where(i => i.Rank == "5");
            IEnumerable <GachaLogItem> rank4 = pool.Where(i => i.Rank == "4");
            IEnumerable <GachaLogItem> rank3 = pool.Where(i => i.Rank == "3");

            Dictionary <string, int> countOfRank5 = new Dictionary <string, int>();

            foreach (GachaLogItem item in rank5)
            {
                countOfRank5.AddOrSet(item.Name, v => ++ v);
            }
            Dictionary <string, int> countOfRank4 = new Dictionary <string, int>();

            foreach (GachaLogItem item in rank4)
            {
                countOfRank4.AddOrSet(item.Name, v => ++ v);
            }
            Dictionary <string, int> countOfRank3 = new Dictionary <string, int>();

            foreach (GachaLogItem item in rank3)
            {
                countOfRank3.AddOrSet(item.Name, v => ++ v);
            }

            IEnumerable <GachaLogNode> gachaLogNodes = new List <GachaLogNode>()
            {
                new GachaLogNode("五星", rank5.Count(), countOfRank5.Select(i => new GachaLogNode(i.Key, i.Value, null)).OrderByDescending(i => i.Count)),
                new GachaLogNode("四星", rank4.Count(), countOfRank4.Select(i => new GachaLogNode(i.Key, i.Value, null)).OrderByDescending(i => i.Count)),
                new GachaLogNode("三星", rank3.Count(), countOfRank3.Select(i => new GachaLogNode(i.Key, i.Value, null)).OrderByDescending(i => i.Count))
            };

            return(gachaLogNodes);
        }
Beispiel #20
0
        public void InitializeProvider(RequestImpl requestImpl)
        {
            if (requestImpl == null)
            {
                throw new ArgumentNullException("requestImpl");
            }

            var req = requestImpl.As <Request>();

            req.Debug("Initializing PowerShell MetaProvider");

            // to do : get modules to load (from configuration ?)
            var modules = ScanForModules(req).ToArray();

            req.Debug("Scanned for PowerShell Provider Modules ");

            // try to create each module at least once.
            Parallel.ForEach(modules, modulePath => {
                var provider = Create(modulePath);
                if (provider != null)
                {
                    if (provider.GetPackageProviderName() != null)
                    {
                        // looks good to me, let's add this to the list of moduels this meta provider can create.
                        _packageProviders.AddOrSet(provider.GetPackageProviderName(), provider);
                    }
                    else
                    {
                        provider.Dispose();
                        provider = null;
                    }
                }
            });
            req.Debug("Loaded PowerShell Provider Modules ");
        }
Beispiel #21
0
        public static int helper(TreeNode root, int currSum, int target, Dictionary <int, int> preSum)
        {
            if (root == null)
            {
                return(0);
            }

            currSum += root.val;
            int res = preSum.GetValueOrDefault(currSum - target, 0);

            preSum.AddOrSet(currSum, preSum.GetValueOrDefault(currSum, 0) + 1);

            res += helper(root.left, currSum, target, preSum) + helper(root.right, currSum, target, preSum);
            preSum.AddOrSet(currSum, preSum[currSum] - 1);
            return(res);
        }
        private void UpdatePreliminaryPrice(UpdatePreliminaryPriceMessage message)
        {
            var currentDayPrice = _trangselskattCalculator.CalculateDayPrice(message.DateToUpdate, _vehicle, _passageTimes.AsReadOnly());

            _daySumMap.AddOrSet(message.DateToUpdate.Date, currentDayPrice);
            Log.Info($"[{_vehicle.RegistrationNumber} - {message.DateToUpdate}] New day total: {currentDayPrice}");
        }
Beispiel #23
0
        public void InitializeProvider(PsRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug("Initializing PowerShell MetaProvider");

            // to do : get modules to load (from configuration ?)
            var modules = ScanForModules(request).Distinct().ToArray();

            // try to create each module at least once.
            modules.ParallelForEach(modulePath => {
                request.Debug("Attempting to load PowerShell Provider Module [{0}]", modulePath);
                var provider = Create(request, modulePath);
                if (provider != null)
                {
                    if (provider.GetPackageProviderName() != null)
                    {
                        request.Debug("Loaded PowerShell Package Provider Module: [{0}]", modulePath);
                        // looks good to me, let's add this to the list of moduels this meta provider can create.
                        _packageProviders.AddOrSet(provider.GetPackageProviderName(), provider);
                    }
                    else
                    {
                        provider.Dispose();
                        provider = null;
                    }
                }
            });

            request.Debug("Loaded PowerShell Provider Modules ");
        }
        public static Dictionary <string, Dictionary <string, string> > Import(GoogleSpreadsheetDocumentPageDBEntry page)
        {
            ServicePointManager.ServerCertificateValidationCallback += allowCertificate;
            string docFormat        = "csv";
            string gDocsDownloadURL = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key={0}&gid={1}&exportFormat={2}";
            string downloadUrl      = string.Format(gDocsDownloadURL, page.document.documentId, page.pageId, docFormat);

            Debug.Log(downloadUrl);

            HttpWebRequest  aRequest  = (HttpWebRequest)WebRequest.Create(downloadUrl);
            HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();

            WebHeaderCollection header = aResponse.Headers;

            var encoding = ASCIIEncoding.UTF8;

            var parsedPage = new Dictionary <string, Dictionary <string, string> >();

            using (var reader = new StreamReader(aResponse.GetResponseStream(), encoding)) {
                string localizationsString = reader.ReadToEnd();

                var stringRows = localizationsString.Split('\r', '\n');


                Debug.Log(localizationsString);
                Debug.Log(stringRows.ToPlainString());

                string[] keyColumns = null;
                for (int r = 0; r < stringRows.Length; r++)
                {
                    var row        = stringRows[r];
                    var stringCols = row.Split(',');
                    if (r == 0)
                    {
                        keyColumns = stringCols;
                        Debug.Log(keyColumns.ToPlainString());
                        for (int l = 1; l < keyColumns.Length; l++)
                        {
                            var lang = keyColumns[l];
                            if (!string.IsNullOrEmpty(lang))
                            {
                                parsedPage.AddOrSet(lang, new Dictionary <string, string>());
                            }
                        }
                    }
                    else
                    {
                        for (int c = 1; c < stringCols.Length; c++)
                        {
                            parsedPage[keyColumns[c]].AddOrSet(stringCols[0], stringCols[c]);
                        }
                    }
                }
            }

            ServicePointManager.ServerCertificateValidationCallback -= allowCertificate;

            Debug.Log(JSONUtuls.Serialize(parsedPage));
            return(parsedPage);
        }
Beispiel #25
0
        protected void ScanMessage(Dictionary <string, object> logEvent, string input)
        {
            var match = _regex.Match(input);

            if (!match.Success)
            {
                logEvent.AddTag(FailedGrok);
            }

            foreach (var groupName in _groupNames)
            {
                var key = match.Groups[groupName];
                if (!key.Success)
                {
                    continue;
                }

                if (Overwrite)
                {
                    logEvent[groupName] = key.Value;
                }
                else
                {
                    logEvent.AddOrSet(groupName, key.Value);
                }
            }
        }
Beispiel #26
0
        public static NetBroadcast.BroadcastData      GetBroadcastDataFromRow(TableRow row)
        {
            string fromAddress = "";
            Dictionary <string, string> dict = new Dictionary <string, string> ();

            TableEntry entryIP = row.FindEntryByColumnName("IP");

            if (entryIP)
            {
                fromAddress = entryIP.entryText;
            }

            for (int i = 0; i < row.Table.columns.Count; i++)
            {
                var column = row.Table.columns [i];
                if (column.columnName == "IP")
                {
                    continue;
                }
                var entry = row.Entries [i];
                dict.AddOrSet(column.columnName, entry.entryText);
            }


            var broadcastData = new NetBroadcast.BroadcastData(fromAddress, dict);

            return(broadcastData);
        }
Beispiel #27
0
        private void GetMsiInstalledPackage(string name, PackageJson package, string requiredVersion, string minimumVersion, string maximumVersion, PackageSourceListRequest request)
        {
            request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "GetMsiInstalledPackage' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion));

            var provider = PackageSourceListRequest.FindProvider(request, package.Type, request);

            if (provider != null)
            {
                var packagesInstalled = provider.GetInstalledPackages(package.Name, requiredVersion, minimumVersion, maximumVersion, request);

                if (!packagesInstalled.Any())
                {
                    packagesInstalled = provider.GetInstalledPackages(package.DisplayName, requiredVersion, minimumVersion, maximumVersion, request);
                }
                foreach (var i in packagesInstalled)
                {
                    request.Debug("found a package '{0}.{1}' installed from '{2}'", i.Name, i.Version, i.Source);

                    var info = PackageSourceListRequest.MakeFastPathComplex(i.Source, name, (package.DisplayName ?? ""), i.Version, i.FastPackageReference);

                    _fastPackReftable.AddOrSet(i.FastPackageReference, i);

                    // check if the installed version matches with the one specified in the PSL.json.
                    // If so, we choose PSL.json.
                    var version = i.Version.CompareVersion(package.Version) ? package.Version : i.Version;
                    //we use displayname here because msi provider uses the displayname.
                    request.YieldSoftwareIdentity(info, package.DisplayName, version, i.VersionScheme, i.Summary, package.Source, i.SearchKey, i.FullPath, i.PackageFilename);
                    return;
                }
            }
        }
Beispiel #28
0
        private void ProcessValueAndStore(Dictionary <string, object> logEvent, string key, string value)
        {
            if (Recursive)
            {
                var innerEvent = new Dictionary <string, object>();
                ScanMessage(innerEvent, value);

                if (innerEvent.Count > 0)
                {
                    logEvent.AddOrSet(key, innerEvent);
                    return;
                }
            }

            logEvent.AddOrSet(key, value);
        }
Beispiel #29
0
        public static Dictionary <TKey, TElement> ToDictionaryNicely <TSource, TKey, TElement>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, Func <TSource, TElement> elementSelector, IEqualityComparer <TKey> comparer)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (keySelector == null)
            {
                throw new ArgumentNullException("keySelector");
            }
            if (elementSelector == null)
            {
                throw new ArgumentNullException("elementSelector");
            }

            var d = new Dictionary <TKey, TElement>(comparer);

            foreach (var element in source)
            {
                var key = keySelector(element);
                if (key != null)
                {
                    d.AddOrSet(key, elementSelector(element));
                }
            }

            return(d);
        }
Beispiel #30
0
        public override bool ProcessRecordAsync()
        {
            // keep track of what package names the user asked for.
            if (!Name.IsNullOrEmpty())
            {
                foreach (var name in Name)
                {
                    _namesProcessed.GetOrAdd(name, () => false);
                }
            }

            var requests = (Name.IsNullOrEmpty() ?

                            // if the user didn't specify any names
                            SelectedProviders.Select(pv => new {
                query = "?",
                packages = pv.GetInstalledPackages("", this.ProviderSpecific(pv)).CancelWhen(_cancellationEvent.Token)
            }) :

                            // if the user specified a name,
                            SelectedProviders.SelectMany(pv => {
                // for a given provider, if we get an error, we want just that provider to stop.
                var host = this.ProviderSpecific(pv);

                return(Name.Select(name => new {
                    query = name,
                    packages = pv.GetInstalledPackages(name, host).CancelWhen(_cancellationEvent.Token)
                }));
            })).ToArray();

            while (WaitForActivity(requests.Select(each => each.packages)))
            {
                // keep processing while any of the the queries is still going.

                foreach (var result in requests.Where(each => each.packages.HasData))
                {
                    // look only at requests that have data waiting.

                    foreach (var package in result.packages.GetConsumingEnumerable())
                    {
                        // process the results for that set.

                        if (IsPackageInVersionRange(package))
                        {
                            // it only counts if the package is in the range we're looking for.

                            // mark down that we found something for that query
                            _namesProcessed.AddOrSet(result.query, true);

                            ProcessPackage(result.query, package);
                        }
                    }
                }

                // just work with whatever is not yet consumed
                requests = requests.FilterWithFinalizer(each => each.packages.IsConsumed, each => each.packages.Dispose()).ToArray();
            }
            return(true);
        }
Beispiel #31
0
        public IActorRef RegisterWritableEndpoint(Address address, IActorRef endpoint, int?uid, int?refuseUid)
        {
            EndpointManager.EndpointPolicy existing;
            _addressToWritable.TryGetValue(address, out existing);

            var pass = existing as EndpointManager.Pass;

            if (pass != null) // if we already have a writable endpoint....
            {
                var e = pass.Endpoint;
                throw new ArgumentException("Attempting to overwrite existing endpoint " + e + " with " + endpoint);
            }

            _addressToWritable.AddOrSet(address, new EndpointManager.Pass(endpoint, uid, refuseUid));
            _writableToAddress.AddOrSet(endpoint, address);
            return(endpoint);
        }
Beispiel #32
0
        public void PrepareEvent(Dictionary<string, object> logEvent)
        {
            var key = _key.Format(logEvent);
            var value = _value.Format(logEvent);

            if (Overwrite)
            {
                logEvent[key] = value;
            }
            else
            {
                logEvent.AddOrSet(key, value);
            }
        }
Beispiel #33
0
        internal static void GeInstalledNuGetPackages(PackageJson package, string requiredVersion, string minimumVersion, string maximumVersion, Dictionary<string, SoftwareIdentity> fastPackReftable, PackageSourceListRequest request)
        { 
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "GeInstalledNuGetPackages' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", package.Name, requiredVersion, minimumVersion, maximumVersion));

            //clone the request
            //nuget provider may not know the location of the package gets installed.
            //we need to pass around the destination path to nuget provider
            var installedRequest = PackageSourceListRequest.ExtendRequest(
                   new Dictionary<string, string[]> {
                        {"Destination", new[] { package.Destination ?? ""}}
                   }, null, package.IsTrustedSource, request);

            var provider = PackageSourceListRequest.FindProvider(request, package.Type, request);
            if (provider != null)
            {
                //calling NuGet provider
                var packagesInstalled = provider.GetInstalledPackages(package.Name, requiredVersion, minimumVersion, maximumVersion, installedRequest);
                if (packagesInstalled != null)
                {
                    foreach (var i in packagesInstalled)
                    {
                        request.Debug("Found an installed package '{0}.{1} from {2}' ", i.Name, i.Version, i.Source);
                        var info = PackageSourceListRequest.MakeFastPathComplex(i.Source, i.Name, "", i.Version, "");

                        fastPackReftable.AddOrSet(info, i);

                        // make it semver because in find-package we use semver
                        var version = i.Version.CompareVersion(package.Version) ? package.Version : i.Version;
                        request.YieldSoftwareIdentity(info, i.Name, version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename);

                    }
                }
            }
        }
Beispiel #34
0
        protected void ScanMessage(Dictionary<string, object> logEvent, string input)
        {
            var match = _regex.Match(input);
            
            if (!match.Success)
            {
                logEvent.AddTag(FailedGrok);
            }

            foreach (var groupName in _groupNames)
            {
                var key = match.Groups[groupName];
                if (!key.Success) continue;

                if (Overwrite)
                {
                    logEvent[groupName] = key.Value;
                }
                else
                {
                    logEvent.AddOrSet(groupName, key.Value);
                }
            }
        }
Beispiel #35
0
            public Cache(ImmutableList<Record> records)
            {
                if (records.IsEmpty)
                {
                    _observerRowsMap = ImmutableDictionary.Create<UniqueAddress, ImmutableDictionary<UniqueAddress, Record>>();
                    _allTerminated = ImmutableHashSet.Create<UniqueAddress>();
                    _allUnreachable = ImmutableHashSet.Create<UniqueAddress>();
                }
                else
                {
                    var mapBuilder = new Dictionary<UniqueAddress, ImmutableDictionary<UniqueAddress, Record>>();
                    var terminatedBuilder = ImmutableHashSet.CreateBuilder<UniqueAddress>();
                    var unreachableBuilder = ImmutableHashSet.CreateBuilder<UniqueAddress>();

                    foreach (var r in records)
                    {
                        ImmutableDictionary<UniqueAddress, Record> m;
                        if(mapBuilder.TryGetValue(r.Observer, out m))
                        {
                            m = m.SetItem(r.Subject, r);                            
                        }
                        else
                        {
                            //TODO: Other collections take items for Create. Create unnecessary array here
                            m = ImmutableDictionary.CreateRange(new[] { new KeyValuePair<UniqueAddress, Record>(r.Subject, r) });
                        }
                        mapBuilder.AddOrSet(r.Observer, m);

                        if (r.Status == ReachabilityStatus.Unreachable) unreachableBuilder.Add(r.Subject);
                        else if (r.Status == ReachabilityStatus.Terminated) terminatedBuilder.Add(r.Subject);
                    }

                    _observerRowsMap = ImmutableDictionary.CreateRange(mapBuilder);
                    _allTerminated = terminatedBuilder.ToImmutable();
                    _allUnreachable = unreachableBuilder.ToImmutable().Except(AllTerminated);
                }

                _allUnreachableOrTerminated = _allTerminated.IsEmpty
                    ? AllUnreachable
                    : AllUnreachable.Union(AllTerminated);
            }
Beispiel #36
0
        private void ProcessValueAndStore(Dictionary<string, object> logEvent, string key, string value)
        {   
            if (Recursive)
            {
                var innerEvent = new Dictionary<string, object>();
                ScanMessage(innerEvent, value);

                if (innerEvent.Count > 0)
                {
                    logEvent.AddOrSet(key, innerEvent);
                    return;
                }
            }

            logEvent.AddOrSet(key, value);
        }
        internal static void GeInstalledPowershellArtifacts(PackageJson package, string requiredVersion, string minimumVersion, string maximumVersion, Dictionary<string, SoftwareIdentity> fastPackReftable, PackageSourceListRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "GeInstalledPowershellArtifacts' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", package.Name, requiredVersion, minimumVersion, maximumVersion));

            var provider = PackageSourceListRequest.FindProvider(request, package.Type, request);
            if (provider == null) return;

            //calling the PowerShellGet provider
            request.Debug("Calling '{0}' provider to get installed packages '{1}.{2}'", provider.Name, package.Name, package.Version);

            var packagesInstalled = provider.GetInstalledPackages(package.Name, requiredVersion, minimumVersion, maximumVersion, request).ToArray();

            if (packagesInstalled == null || !packagesInstalled.Any())
            {
                request.Verbose(Resources.Messages.NumberOfPackagesRecevied, 0, provider.Name, "GetInstalledPackages");
                return;
            }          
            
            foreach (var i in packagesInstalled)
            {
                request.Debug("Found an installed package '{0}.{1} from {2}' ", i.Name, i.Version, i.Source);
                var info = PackageSourceListRequest.MakeFastPathComplex(i.Source, i.Name, "", i.Version, "");

                fastPackReftable.AddOrSet(info, i);

                // check if the installed version matches with the one specified in the PSL.json.
                // If so, we choose PSL.json.
                var version = i.Version.CompareVersion(package.Version) ? package.Version : i.Version;
                request.YieldSoftwareIdentity(info, i.Name, version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename);
            }                       
        }
Beispiel #38
0
        static void Main(string[] args)
        {
            var test = ConfigurationManager.GetSection("akka");
            var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka");
            _clusterConfig = section.AkkaConfig;

            Console.WriteLine(_instructions);

            var backendNodes = new Dictionary<string, ActorSystem>();
            var frontendNodes = new Dictionary<string, ActorSystem>();

            while (true)
            {
                var line = Console.ReadLine();
                var command = line.Split(' ')[0];
                var arguments = line.Split(' ').Drop(1);
                var quit = false;
                var port = "0";
                if(arguments.Count() >= 0)
                    port = arguments.Head();

                switch (command)
                {
                    case "help":
                        Console.WriteLine(_instructions);
                        break;
                    case "quit":
                        quit = true;
                        break;
                    case "start-back":
                        if (backendNodes.ContainsKey(port))
                        {
                            backendNodes[port].AwaitTermination();
                        }
                        backendNodes.AddOrSet(port, LaunchBackend(port));
                        break;
                    case "start-front":
                        if (frontendNodes.ContainsKey(port))
                        {
                            frontendNodes[port].AwaitTermination();
                        }
                        frontendNodes.AddOrSet(port, LaunchFrontend(port));
                        break;
                    case "stop-back":
                        if (backendNodes.ContainsKey(port))
                        {
                            backendNodes[port].Shutdown();
                            backendNodes.Remove(port);
                        }
                        break;
                    case "stop-front":
                        if (frontendNodes.ContainsKey(port))
                        {
                            frontendNodes[port].Shutdown();
                            frontendNodes.Remove(port);
                        }
                        break;
                    case "stop-all":
                        backendNodes.Values.ForEach(node => node.Shutdown());
                        frontendNodes.Values.ForEach(node => node.Shutdown());

                        backendNodes = new Dictionary<string, ActorSystem>();
                        frontendNodes = new Dictionary<string, ActorSystem>();
                        break;
                    case "status":
                        ActorSystem statusNode = null;
                        if (backendNodes.ContainsKey(port))
                        {
                            statusNode = backendNodes[port];
                            Console.WriteLine("node on port {0} is of backend type", port);
                        }
                        else if (frontendNodes.ContainsKey(port))
                        {
                            statusNode = frontendNodes[port];
                            Console.WriteLine("node on port {0} is of frontend type", port);
                        }
                        if (statusNode == null)
                        {
                            Console.WriteLine("No node with such a port");
                        }
                        else
                        {
                            Console.WriteLine("Node - ActorSystem: {0}", statusNode);
                            Console.WriteLine("Name: {0}", statusNode.Name);
                        }
                        break;
                    default:
                        Console.WriteLine("Unknown instruction, type 'help' to display instructions");
                        break;
                }

                if (quit)
                    break;
            }

            backendNodes.Values.ForEach(node => node.Shutdown());
            frontendNodes.Values.ForEach(node => node.Shutdown());

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }