Пример #1
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
                tokens.UserId = authInfo.GetValueOrDefault("user_id");

            if (authInfo.ContainsKey("screen_name"))
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");

            try
            {
                if (tokens.UserId != null)
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(tokens.UserId);
                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];
                        tokens.DisplayName = obj.Get("name");
                    }
                }

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(userSession.TwitterUserId), ex);
            }
        }
        /// <summary>
        /// Gets the navigation quick links for the analysis generic index page.
        /// </summary>
        /// <param name="analysisId">The ID of the current analysis.</param>
        /// <param name="count">The dictionary containing the current counts.</param>
        /// <returns>The navigation quick links for the analysis index page.</returns>
        public static IEnumerable <NavigationQuickLinkViewModel> GetContentGenericAnalysisNavigationQuickLinks(string analysisId = null, Dictionary <string, int?> count = null)
        {
            // Check if there is no analysis ID provided.
            if (string.IsNullOrEmpty(analysisId))
            {
                // Assign the empty string to it.
                analysisId = string.Empty;
            }
            // Get the corresponding navigation quick links.
            var analysisNodesNavigationQuickLink    = ContentGenericAnalysisNodesNavigationQuickLink;
            var analysisEdgesNavigationQuickLink    = ContentGenericAnalysisEdgesNavigationQuickLink;
            var analysisUsersNavigationQuickLink    = ContentGenericAnalysisUsersNavigationQuickLink;
            var analysisNetworksNavigationQuickLink = ContentGenericAnalysisNetworksNavigationQuickLink;

            // Update the count and the route ID.
            analysisNodesNavigationQuickLink.ItemCount    = count?.GetValueOrDefault("Nodes", null);
            analysisNodesNavigationQuickLink.RouteId      = analysisId;
            analysisEdgesNavigationQuickLink.ItemCount    = count?.GetValueOrDefault("Edges", null);
            analysisEdgesNavigationQuickLink.RouteId      = analysisId;
            analysisUsersNavigationQuickLink.ItemCount    = count?.GetValueOrDefault("Users", null);
            analysisUsersNavigationQuickLink.RouteId      = analysisId;
            analysisNetworksNavigationQuickLink.ItemCount = count?.GetValueOrDefault("Networks", null);
            analysisNetworksNavigationQuickLink.RouteId   = analysisId;
            // Return the navigation quick links.
            return(new List <NavigationQuickLinkViewModel>
            {
                analysisNodesNavigationQuickLink,
                analysisEdgesNavigationQuickLink,
                analysisUsersNavigationQuickLink,
                analysisNetworksNavigationQuickLink
            });
        }
        public void TestDictionary()
        {
            var d = new Dictionary<int, string> {{1, "one"}};
            Assert.AreEqual("one", d.GetValueOrDefault(1));
            Assert.AreEqual(null, d.GetValueOrDefault(2));

        }
Пример #4
0
 public Release(Dictionary<string,string> properties, DateTime date)
 {
     Title = properties.GetValueOrDefault("Title");
     ReleaseName = properties.GetValueOrDefault("Rlsname");
     Group = properties.GetValueOrDefault("Group");
     Tags = properties.GetValueOrDefault("Tags", string.Empty).Split(new char[] {','}).Select(str => str.Trim()).ToArray();
     Date = date;
 }
Пример #5
0
 public void GetValueOrDefaultReturnsValueFromDictionary()
 {
     var dictionary = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };
     foreach (var pair in dictionary)
     {
         Assert.AreEqual(pair.Value, dictionary.GetValueOrDefault(pair.Key));
         Assert.AreEqual(pair.Value, dictionary.GetValueOrDefault(pair.Key, -1));
     }
 }
Пример #6
0
        public override void ProcessStartElement(string name, Dictionary<string, string> attributes)
        {
            base.ProcessStartElement(name, attributes);

              int port;
              Int32.TryParse(attributes.GetValueOrDefault("Port", String.Empty), out port);
              var newSmtpServer = new SmtpServer(attributes.GetValueOrDefault("Name", null), attributes.GetValueOrDefault("Host", null), port);
              MailManager.Instance.RegisterMailServer(newSmtpServer);
        }
Пример #7
0
        public void GetValueOrDefaultReturnsExpectedDefault()
        {
            var colors = new Dictionary<ConsoleColor, string> { { ConsoleColor.Red, "Red" }, { ConsoleColor.Green, "Green" }, { ConsoleColor.Blue, "Blue" } };
            Assert.AreEqual(null, colors.GetValueOrDefault(ConsoleColor.DarkMagenta));
            Assert.AreEqual("not found!", colors.GetValueOrDefault(ConsoleColor.Magenta) ?? "not found!");

            var numbers = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };
            Assert.AreEqual(0, numbers.GetValueOrDefault("four"));
            Assert.AreEqual(-1, numbers.GetValueOrDefault("five", -1));
        }
Пример #8
0
 public override void Init(Dictionary<string, string> data)
 {
     if (data.ContainsKey("art"))
     {
         byte[] artfile = ObjectHelper.OpenArtFile(data["art"], (Compression.CompressionType)Enum.Parse(typeof(Compression.CompressionType), data.GetValueOrDefault("artcmp", "Nemesis")));
         if (data.ContainsKey("map"))
             img = ObjectHelper.MapToBmp(artfile, Compression.Decompress(data["map"], (Compression.CompressionType)Enum.Parse(typeof(Compression.CompressionType), data.GetValueOrDefault("mapcmp", "Uncompressed"))), int.Parse(data["frame"], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture), int.Parse(data.GetValueOrDefault("pal", "0"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture));
         else if (data.ContainsKey("mapasm"))
             img = ObjectHelper.MapASMToBmp(artfile, data["mapasm"], data["mapasmlbl"], int.Parse(data.GetValueOrDefault("pal", "0"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture));
     }
     spacing = int.Parse(data.GetValueOrDefault("spacing", "24"), System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo);
 }
Пример #9
0
        public void TestGetValueOrDefault()
        {
            // Arrange.
            var dictionary = new Dictionary<string, int>();
            dictionary.Add("one", 1);

            // Assert.
            Assert.AreEqual(1, dictionary.GetValueOrDefault("one", 0));

            Assert.AreEqual(0, dictionary.GetValueOrDefault("two"));
            Assert.AreEqual(0, dictionary.GetValueOrDefault("two", 0));
        }
        public override void ProcessStartElement(string name, Dictionary<string, string> attributes)
        {
            base.ProcessStartElement(name, attributes);

              var tokenName = '#' + attributes.GetValueOrDefault("TokenName", string.Empty) + '#';
              var value = attributes.GetValueOrDefault("Value", string.Empty);
              var regExPattern = attributes.GetValueOrDefault("RegExPattern", string.Empty);
              if (string.IsNullOrEmpty(tokenName))
              {
            log.Warn(string.Format("No 'TokenName' was specified for {0}", name));
            return;
              }

              if (string.IsNullOrEmpty(value))
              {
            log.Warn(string.Format("No 'Value' was specified for {0}", name));
            return;
              }

              if (string.IsNullOrEmpty(regExPattern))
              {
            RepositoryInfoHub.Instance.AddToken(tokenName, () =>
              {
            log.DebugFormat("Setting custom replacement token {0} to [{1}]", tokenName, value);
            return value;
              });
              }
              else
              {
            var regex = new Regex(regExPattern, RegexOptions.Compiled);
            RepositoryInfoHub.Instance.AddToken(tokenName, () =>
              {
            var input = RepositoryInfoHub.Instance.ParseTokens(value);
            log.DebugFormat("Preparing custom replacement token {0}", tokenName);
            log.DebugFormat("Value: [{0}]", value);
            log.DebugFormat("Processses value: [{0}]", input);
            var match = regex.Match(input);
            if (match != null)
            {
              log.DebugFormat("RegEx group count: {0}", match.Groups.Count);
              if (match.Groups.Count > 1)
              {
                log.DebugFormat("Setting custom replacement token {0} to [{1}]", tokenName, match.Groups[1].Value);
                return match.Groups[1].Value;
              }
            }

            return string.Empty;
              });
              }
        }
        /// <summary>
        /// Gets the navigation quick links for the administration index page.
        /// </summary>
        /// <param name="count">The dictionary containing the current counts.</param>
        /// <returns>The navigation quick links for the content index page.</returns>
        public static IEnumerable <NavigationQuickLinkViewModel> GetAdministrationNavigationQuickLinks(Dictionary <string, int?> count = null)
        {
            // Get the corresponding navigation quick links.
            var administrationUsersNavigationQuickLink           = AdministrationUsersNavigationQuickLink;
            var administrationRolesNavigationQuickLink           = AdministrationRolesNavigationQuickLink;
            var administrationDatabasesNavigationQuickLink       = AdministrationDatabasesNavigationQuickLink;
            var administrationNodeCollectionsNavigationQuickLink = AdministrationNodeCollectionsNavigationQuickLink;
            var administrationNodesNavigationQuickLink           = AdministrationNodesNavigationQuickLink;
            var administrationEdgesNavigationQuickLink           = AdministrationEdgesNavigationQuickLink;
            var administrationNetworksNavigationQuickLink        = AdministrationNetworksNavigationQuickLink;
            var administrationAnalysesNavigationQuickLink        = AdministrationAnalysesNavigationQuickLink;

            // Update the count and the route ID.
            administrationUsersNavigationQuickLink.ItemCount           = count?.GetValueOrDefault("Users", null);
            administrationRolesNavigationQuickLink.ItemCount           = count?.GetValueOrDefault("Roles", null);
            administrationDatabasesNavigationQuickLink.ItemCount       = count?.GetValueOrDefault("Databases", null);
            administrationNodeCollectionsNavigationQuickLink.ItemCount = count?.GetValueOrDefault("NodeCollections", null);
            administrationNodesNavigationQuickLink.ItemCount           = count?.GetValueOrDefault("Nodes", null);
            administrationEdgesNavigationQuickLink.ItemCount           = count?.GetValueOrDefault("Edges", null);
            administrationNetworksNavigationQuickLink.ItemCount        = count?.GetValueOrDefault("Networks", null);
            administrationAnalysesNavigationQuickLink.ItemCount        = count?.GetValueOrDefault("Analyses", null);
            // Return the navigation quick links.
            return(new List <NavigationQuickLinkViewModel>
            {
                administrationUsersNavigationQuickLink,
                administrationRolesNavigationQuickLink,
                administrationDatabasesNavigationQuickLink,
                administrationNodeCollectionsNavigationQuickLink,
                administrationNodesNavigationQuickLink,
                administrationEdgesNavigationQuickLink,
                administrationNetworksNavigationQuickLink,
                administrationAnalysesNavigationQuickLink
            });
        }
        /// <summary>
        /// Gets the navigation quick links for the content PPI index page.
        /// </summary>
        /// <param name="count">The dictionary containing the current counts.</param>
        /// <returns>The navigation quick links for the content index page.</returns>
        public static IEnumerable <NavigationQuickLinkViewModel> GetContentPPINavigationQuickLinks(Dictionary <string, int?> count = null)
        {
            // Get the corresponding navigation quick links.
            var contentPPINetworksNavigationQuickLink = ContentPPINetworksNavigationQuickLink;
            var contentPPIAnalysesNavigationQuickLink = ContentPPIAnalysesNavigationQuickLink;

            // Update the count and the route ID.
            contentPPINetworksNavigationQuickLink.ItemCount = count?.GetValueOrDefault("Networks", null);
            contentPPIAnalysesNavigationQuickLink.ItemCount = count?.GetValueOrDefault("Analyses", null);
            // Return the navigation quick links.
            return(new List <NavigationQuickLinkViewModel>
            {
                contentPPINetworksNavigationQuickLink,
                contentPPIAnalysesNavigationQuickLink
            });
        }
 public void TestGetValueOrDefaultInexisting()
 {
     Dictionary<string, int> dictionary = new Dictionary<string, int>();
     dictionary["Dummy"] = 1;
     int result = dictionary.GetValueOrDefault("Dummy2");
     Assert.AreEqual(default(int), result);
 }
Пример #14
0
        private static ReviewInfo ToReviewInfo(ExerciseCodeReview r, bool isUlearnBot,
                                               [CanBeNull] Dictionary <int, IEnumerable <ExerciseCodeReviewComment> > reviewId2Comments)
        {
            var comments = reviewId2Comments?.GetValueOrDefault(r.Id);

            return(ReviewInfo.Build(r, comments, isUlearnBot));
        }
        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;
        }
Пример #16
0
        protected Object PreProcessValue(Object value, String key, IDictionary <String, String> values, Dictionary <String, Dictionary <string, string> > resultMap)
        {
            if (values != null)
            {
                values[key] = resultMap?.GetValueOrDefault(key)?.GetValueOrDefault(value.ToString()) ?? value?.ToString();
            }

            return(value);
        }
 public void GetValueOrDefault_NonEmptyDictionaryWithoutKey_ReturnsDefault()
 {
     IDictionary<object, object> dict = new Dictionary<object, object>
     {
         { "key", "value" }
     };
     object value = dict.GetValueOrDefault("anotherKey", "fallback");
     Assert.Equal("fallback", value);
 }
        public async Task <Cryptocurrency> Resolve(string symbol)
        {
            // refresh the dictionary if the symbol was not found in it
            if (_nameToCryptocurrencyDictionary?.GetValueOrDefault(symbol) == null)
            {
                await Refresh();
            }

            return(_nameToCryptocurrencyDictionary.GetValueOrDefault(symbol, null));
        }
Пример #19
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
                tokens.UserId = authInfo.GetValueOrDefault("user_id");

            if (authInfo.ContainsKey("screen_name"))
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");

            try
            {
                if (tokens.UserId != null)
                {
                    var oauthToken = new OAuthAccessToken
                    {
                        OAuthProvider = this,
                        AccessToken = tokens.AccessToken,
                        AccessTokenSecret = tokens.AccessTokenSecret,
                    };
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(oauthToken, tokens.UserId);
                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];
                        tokens.DisplayName = obj.Get("name");

                        string profileUrl;
                        if (obj.TryGetValue("profile_image_url", out profileUrl))
                            tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;

                        if (SaveExtendedUserInfo)
                        {
                            obj.Each(x => authInfo[x.Key] = x.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve twitter user info for '{userSession.TwitterUserId}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
        public static CommandLineArgs Parse(string[] args)
        {
            var dictionary = new Dictionary<string, string>();

            foreach (var a in args)
            {
                var keyValue = a.Split('=');
                var key = keyValue[0].Trim().ToLowerInvariant();
                var value = keyValue[1].Trim();

                dictionary.Add(key, value);
            }

            return new CommandLineArgs
            {
                MarkdownPath = dictionary.GetValueOrDefault("-output", "output.md"),
                DllPath = dictionary.GetValueOrDefault("-input", "."),
                UrlStringFormat = dictionary.GetValueOrDefault("-urlformat", "https://msdn.microsoft.com/en-us/library/{0}.aspx")
            };
        }
Пример #21
0
        public HttpControllerDescriptor Process(IDictionary <string, object> values, string[] segments, int i)
        {
            values.Add("controller", ControllerDescriptor.ControllerName);
            //values.Add("controllerDescriptor", ControllerDescriptor);

            if (segments.Length <= i)
            {
                if (_itemsStore == null)
                {
                    return(null);
                }
                values.Add("action", "items");
                values.Add("actionStore", _itemsStore);
                return(ControllerDescriptor);
            }

            var id = segments[i];

            i++;
            if (segments.Length > i)
            {
                if (_itemActionStores == null || segments.Length > i + 1)
                {
                    return(null);
                }
                var action          = segments[i];
                var itemActionStore = _itemActionStores.GetValueOrDefault(action);
                if (itemActionStore == null)
                {
                    return(null);
                }
                values.Add("action", action);
                values.Add("id", id);
                values.Add("actionStore", itemActionStore);
                return(ControllerDescriptor);
            }

            var nonItemActionStore = _nonItemActionStores?.GetValueOrDefault(id);

            if (nonItemActionStore != null)
            {
                values.Add("action", id);
                values.Add("actionStore", nonItemActionStore);
                return(ControllerDescriptor);
            }
            if (_itemStore != null)
            {
                values.Add("action", "item");
                values.Add("id", id);
                values.Add("actionStore", _itemStore);
                return(ControllerDescriptor);
            }
            return(null);
        }
Пример #22
0
 public void GetValueOrDefault()
 {
     #region GetValueOrDefault
     var dict = new Dictionary<string, int> () {
         { "a", 1 },
     };
     Assert.AreEqual (1, dict.GetValueOrDefault ("a"));
     Assert.AreEqual (0, dict.GetValueOrDefault ("c"));
     Assert.AreEqual (3, dict.GetValueOrDefault ("c", 3));
     #endregion
 }
 protected override Instruction CreateInstruction(Dictionary<string, string> attributes)
 {
     var mailInstruction = new MailInstruction();
       mailInstruction.Body = attributes.GetValueOrDefault("Body", String.Empty);
       mailInstruction.BodyTemplateFile = attributes.GetValueOrDefault("BodyTemplateFile", String.Empty);
       mailInstruction.BccMailAddresses = attributes.GetValueOrDefault("BccMailAddresses", String.Empty);
       mailInstruction.CcMailAddresses = attributes.GetValueOrDefault("CcMailAddresses", String.Empty);
       mailInstruction.FromMailAddress = attributes.GetValueOrDefault("FromMailAddress", String.Empty);
       mailInstruction.ReplyToMailAddress = attributes.GetValueOrDefault("ReplyToMailAddress", String.Empty);
       mailInstruction.Subject = attributes.GetValueOrDefault("Subject", String.Empty);
       mailInstruction.ToMailAddresses = attributes.GetValueOrDefault("ToMailAddresses", String.Empty);
       return mailInstruction;
 }
        public ProcessResult Process(ElementNode node, ProcessContext context = null,
                                     Dictionary <string, object> settings     = null)
        {
            var processResult = new ProcessResult();

            if (string.IsNullOrEmpty(node?.Value?.ToString()))
            {
                return(processResult);
            }

            // prefix the domain, if set
            var domainPrefix = settings?.GetValueOrDefault("domain-prefix", string.Empty);

            var domain = settings?
                         .GetValueOrDefault("domain", null)?
                         .ToString();

            var input = node.Value.ToString();

            // Pseudonymize the id part for "Reference.reference" node and
            // pseudonymize whole input for other node types
            if (node.IsReferenceStringNode() || IsReferenceUriNode(node, input))
            {
                // if the domain setting is not set,
                // create a domain from the reference, ie "Patient/123" -> "Patient"
                domain ??= ReferenceUtility
                .GetReferencePrefix(input)
                .TrimEnd('/');

                node.Value = ReferenceUtility.TransformReferenceId(
                    input,
                    x => GetOrCreatePseudonym(x, domainPrefix + domain));
            }
            else
            {
                node.Value = GetOrCreatePseudonym(input, domainPrefix + domain);
            }

            processResult.AddProcessRecord(AnonymizationOperations.Pseudonymize, node);
            return(processResult);
        }
Пример #25
0
        public void cachedobject_is_working_with_dict()
        {
            var dict = new Dictionary<string, string>();
            var cachedObject = new CachedObject<string>(() => dict.Add(Key, Value), () => dict.GetValueOrDefault(Key));

            dict.Count.ShouldEqual(0);
            cachedObject.Get().ShouldEqual(Value);
            dict.Count.ShouldEqual(1);

            cachedObject.Get().ShouldEqual(Value);
            dict.Count.ShouldEqual(1);
        }
        public static TValue GetValueOrNull <TKey, TValue>(this Dictionary <TKey, TValue> dict, TKey key)
            where TKey : class
            where TValue : class
        {
            if (dict == null ||
                key == null)
            {
                return(null);
            }

            return(dict?.GetValueOrDefault(key));
        }
        protected override Instruction CreateInstruction(Dictionary<string, string> attributes)
        {
            this.executeInstruction = new CommandLineInstruction();
              this.executeInstruction.FileName = attributes.GetValueOrDefault("FileName", string.Empty);
              this.executeInstruction.Arguments = attributes.GetValueOrDefault("Arguments", string.Empty);
              this.executeInstruction.NewLineReplacement = attributes.GetValueOrDefault("NewLineReplacement", string.Empty);

              int timeoutInMilliseconds;
              if (int.TryParse(attributes.GetValueOrDefault("TimeoutInMilliseconds", string.Empty), out timeoutInMilliseconds))
              {
            this.executeInstruction.TimeoutInMilliseconds = timeoutInMilliseconds;
              }

              int expectedExitCode;
              if (int.TryParse(attributes.GetValueOrDefault("ExpectedExitCode", string.Empty), out expectedExitCode))
              {
            this.executeInstruction.ExpectedExitCode = expectedExitCode;
              }

              return this.executeInstruction;
        }
        public static TValue?GetValueOrNull <TKey, TValue>(this Dictionary <TKey?, TValue?> dict, TKey?key)
            where TKey : struct
            where TValue : struct
        {
            if (dict == null ||
                key.GetValueOrNull() == null)
            {
                return(null);
            }

            return(dict?.GetValueOrDefault(key));
        }
Пример #29
0
        private void AddGenericTheory(Dictionary<IAstTypeReference, ISet<IAstTypeReference>> genericTheories, IAstTypeReference genericType, IAstTypeReference argumentType)
        {
            if (argumentType is AstGenericPlaceholderType || argumentType.IsImplicit())
                return;

            var set = genericTheories.GetValueOrDefault(genericType);
            if (set == null) {
                genericTheories.Add(genericType, new HashSet<IAstTypeReference> { argumentType });
                return;
            }

            set.Add(argumentType);
        }
        public void GetValueOrDefault()
        {
            var dictionary = new Dictionary<int, string>();

            dictionary.GetValueOrDefault(0).ShouldBe(null);
            dictionary.GetValueOrDefault(0, "default").ShouldBe("default");
            dictionary.GetValueOrDefault(0, () => "default").ShouldBe("default");

            dictionary.Add(0, "zero");

            dictionary.GetValueOrDefault(0).ShouldBe("zero");
            dictionary.GetValueOrDefault(0, "default").ShouldBe("zero");
            dictionary.GetValueOrDefault(0, () => "default").ShouldBe("zero");
        }
Пример #31
0
            public ExportRow ToExportRow(Dictionary <int, string> accountNames)
            {
                return(new ExportRow {
                    Supplier = CompanyName,
                    Amount = Amount,
                    AccountId = AccountId ?? 0,
                    AccountName = accountNames?.GetValueOrDefault(AccountId ?? 0, "") ?? "",
                    Comments = Comment,
                    CurrencyDate = PaymentDate,
                    Date = SortDate,
                    InvoiceLink = Link,

                    InvoiceId = SLR?.Id,
                    ReceiptId = Receipt?.Information,
                    TransactionRef = "",
                    TransactionText = "",
                    Missing = Missing,
                    //AccountChange
                });
            }
Пример #32
0
        public void Write <T>(IEnumerable <T> rows)
        {
            if (typeof(T).IsPrimitive || typeof(T) == typeof(string))
            {
                throw new Exception("Table.Write<T> does not support primitive types or strings.  Use Write(IEnumerable<IEnumerable<object>> rows)");
            }

            var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            Column?GetOverriden(PropertyInfo property) =>
            _columnsByProperty?.GetValueOrDefault(property.Name);

            if (Count == 0)
            {
                AddRange(properties.Select(p =>
                                           GetOverriden(p) ?? BuildColumn(p.Name, p.PropertyType)));
            }

            Write(rows.Select(row => properties.Select(p => p.GetValue(row))));
        }
        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;
        }
		public RegistrationSettings(Dictionary<string, string> settings): this()
		{
            RandomPassword = settings.GetValueOrDefault("Registration_RandomPassword", RandomPassword);
            RedirectAfterRegistration = settings.GetValueOrDefault("Redirect_AfterRegistration", RedirectAfterRegistration);
            RedirectAfterLogout = settings.GetValueOrDefault("Redirect_AfterLogout", RedirectAfterLogout);
            RedirectAfterLogin = settings.GetValueOrDefault("Redirect_AfterLogin", RedirectAfterLogin);
            RegistrationFields = settings.GetValueOrDefault("Registration_RegistrationFields", RegistrationFields);
            ExcludeTerms = settings.GetValueOrDefault("Registration_ExcludeTerms", ExcludeTerms);
            RegistrationFormType = settings.GetValueOrDefault("Registration_RegistrationFormType", RegistrationFormType);
            RequirePasswordConfirm = settings.GetValueOrDefault("Registration_RequireConfirmPassword", RequirePasswordConfirm);
            RequireUniqueDisplayName = settings.GetValueOrDefault("Registration_RequireUniqueDisplayName", RequireUniqueDisplayName);
            UseAuthProviders = settings.GetValueOrDefault("Registration_UseAuthProviders", UseAuthProviders);
            UseEmailAsUserName = settings.GetValueOrDefault("Registration_UseEmailAsUserName", UseEmailAsUserName);
            UseProfanityFilter = settings.GetValueOrDefault("Registration_UseProfanityFilter", UseProfanityFilter);
            RequireValidProfile = settings.GetValueOrDefault("Security_RequireValidProfile", RequireValidProfile);
            RequireValidProfileAtLogin = settings.GetValueOrDefault("Security_RequireValidProfileAtLogin", RequireValidProfileAtLogin);
            UseCaptcha = settings.GetValueOrDefault("Security_CaptchaRegister", UseCaptcha);
            UserNameValidator = settings.GetValueOrDefault("Security_UserNameValidation", UserNameValidator);
            DisplayNameFormat = settings.GetValueOrDefault("Security_DisplayNameFormat", DisplayNameFormat);
            EmailValidator = settings.GetValueOrDefault("Security_EmailValidation", EmailValidator);

			ExcludeTermsRegex = "^(?:(?!" + ExcludeTerms.Replace(" ", "").Replace(",", "|") + ").)*$\\r?\\n?";
		}
        /// <summary>
        /// Gets the navigation quick links for the PPI network index page.
        /// </summary>
        /// <param name="networkId">The ID of the current network.</param>
        /// <param name="count">The dictionary containing the current counts.</param>
        /// <returns>The navigation quick links for the network index page.</returns>
        public static IEnumerable <NavigationQuickLinkViewModel> GetContentPPINetworkNavigationQuickLinks(string networkId = null, Dictionary <string, int?> count = null)
        {
            // Check if there is no network ID provided.
            if (string.IsNullOrEmpty(networkId))
            {
                // Assign the empty string to it.
                networkId = string.Empty;
            }
            // Get the corresponding navigation quick links.
            var networkNodesNavigationQuickLink           = ContentPPINetworkNodesNavigationQuickLink;
            var networkEdgesNavigationQuickLink           = ContentPPINetworkEdgesNavigationQuickLink;
            var networkDatabasesNavigationQuickLink       = ContentPPINetworkDatabasesNavigationQuickLink;
            var networkNodeCollectionsNavigationQuickLink = ContentPPINetworkNodeCollectionsNavigationQuickLink;
            var networkUsersNavigationQuickLink           = ContentPPINetworkUsersNavigationQuickLink;
            var networkAnalysesNavigationQuickLink        = ContentPPINetworkAnalysesNavigationQuickLink;

            // Update the count and the route ID.
            networkNodesNavigationQuickLink.ItemCount           = count?.GetValueOrDefault("Nodes", null);
            networkNodesNavigationQuickLink.RouteId             = networkId;
            networkEdgesNavigationQuickLink.ItemCount           = count?.GetValueOrDefault("Edges", null);
            networkEdgesNavigationQuickLink.RouteId             = networkId;
            networkDatabasesNavigationQuickLink.ItemCount       = count?.GetValueOrDefault("Databases", null);
            networkDatabasesNavigationQuickLink.RouteId         = networkId;
            networkNodeCollectionsNavigationQuickLink.ItemCount = count?.GetValueOrDefault("NodeCollections", null);
            networkNodeCollectionsNavigationQuickLink.RouteId   = networkId;
            networkUsersNavigationQuickLink.ItemCount           = count?.GetValueOrDefault("Users", null);
            networkUsersNavigationQuickLink.RouteId             = networkId;
            networkAnalysesNavigationQuickLink.ItemCount        = count?.GetValueOrDefault("Analyses", null);
            networkAnalysesNavigationQuickLink.RouteId          = networkId;
            // Return the navigation quick links.
            return(new List <NavigationQuickLinkViewModel>
            {
                networkNodesNavigationQuickLink,
                networkEdgesNavigationQuickLink,
                networkDatabasesNavigationQuickLink,
                networkNodeCollectionsNavigationQuickLink,
                networkUsersNavigationQuickLink,
                networkAnalysesNavigationQuickLink
            });
        }
Пример #36
0
        private void Run(object obj)
        {
            Dictionary<string, string> updatedSubmodules = new Dictionary<string, string>();

            while (!m_token.IsCancellationRequested)
            {
                // check for changes to the build repo itself (and reload the submodules if so)
                string commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch, m_updatingSubmodulesFailed);
                if (commitId == null)
                {
                    Log.Info("Getting last commit ID failed; assuming branch doesn't exist.");
                    commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, "master");
                    if (commitId == null)
                    {
                        Log.Error("Getting commit ID for 'master' failed; will stop monitoring project.");
                        break;
                    }

                    GitReference reference = m_gitHubClient.CreateReference(m_user, m_repo, m_branch, commitId);
                    if (reference == null)
                    {
                        Log.Error("Failed to create new branch '{0}' (based on master = {1}); will stop monitoring project.", m_branch, commitId);
                        break;
                    }

                    Log.Info("Sleeping for five seconds to allow GitHub API time to learn about the new branch.");
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }

                if (commitId != m_lastBuildCommitId)
                {
                    if (m_lastBuildCommitId != null)
                    {
                        Log.Info("Build repo commit ID has changed from {0} to {1}; reloading submodules.", m_lastBuildCommitId, commitId);
                        StartBuild();
                    }

                    try
                    {
                        GetSubmodules();
                    }
                    catch (WatcherException ex)
                    {
                        Log.Error("Getting submodules failed; will stop monitoring project.", ex);
                        break;
                    }
                    updatedSubmodules.Clear();
                }
                else
                {
                    // check for changes in the submodules
                    bool submoduleChanged = false;
                    bool submoduleHasError = false;
                    foreach (var pair in m_submodules)
                    {
                        Submodule submodule = pair.Value;
                        commitId = m_gitHubClient.GetLatestCommitId(submodule.User, submodule.Repo, submodule.Branch, m_updatingSubmodulesFailed);
                        if (commitId == null)
                        {
                            Log.Error("Submodule '{0}' doesn't have a latest commit for branch '{1}'; will stop monitoring project.", pair.Key, submodule.Branch);
                            submoduleHasError = true;
                        }
                        else if (commitId != submodule.LatestCommitId && commitId != updatedSubmodules.GetValueOrDefault(pair.Key))
                        {
                            Log.Info("Submodule '{0}' has changed from {1} to {2}; waiting for more changes.", pair.Key, submodule.LatestCommitId.Substring(0, 8), commitId.Substring(0, 8));
                            updatedSubmodules[pair.Key] = commitId;
                            submoduleChanged = true;
                        }
                    }

                    // abort if there were errors
                    if (submoduleHasError)
                        break;

                    // pause for five seconds between each check
                    m_token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

                    // if any submodule changed, loop again (to allow changes to multiple submodules to be batched)
                    if (submoduleChanged)
                        continue;

                    // if there were updated submodules, create a new commit
                    m_updatingSubmodulesFailed = false;
                    if (updatedSubmodules.Count != 0)
                    {
                        try
                        {
                            if (UpdateSubmodules(updatedSubmodules))
                            {
                                m_retryDelay = TimeSpan.FromSeconds(15);
                            }
                            else
                            {
                                m_updatingSubmodulesFailed = true;
                                m_retryDelay = m_retryDelay + m_retryDelay;
                                TimeSpan maximumRetryDelay = TimeSpan.FromMinutes(30);
                                if (m_retryDelay > maximumRetryDelay)
                                    m_retryDelay = maximumRetryDelay;
                                Log.Info("Failed to update submodules; will wait {0} before trying again.", m_retryDelay);
                            }
                            updatedSubmodules.Clear();

                            // wait for the build to start, and/or for gitdata to be updated with the new commit data
                            m_token.WaitHandle.WaitOne(m_retryDelay);
                        }
                        catch (WatcherException ex)
                        {
                            Log.Error("Updating submodules failed; will stop monitoring project.", ex);
                            break;
                        }
                    }
                }
            }
        }
Пример #37
0
        static void Main(string[] args)
        {
            string       inputFile = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName + @"\in.txt";
            StreamReader cin       = new StreamReader(inputFile);

            List <int> jolts = new List <int>();

            jolts.Add(0);

            int adapter, MaxAdapter = 0;

            while (!cin.EndOfStream)
            {
                adapter    = int.Parse(cin.ReadLine());
                MaxAdapter = Math.Max(MaxAdapter, adapter);
                jolts.Add(adapter);
            }

            jolts.Add(MaxAdapter + 3);
            jolts.Sort();

            int oneJoltDiff = 0, threeJoltsDiff = 0;

            for (int i = 1; i < jolts.Count; i++)
            {
                if (jolts[i] - jolts[i - 1] == 1)
                {
                    oneJoltDiff++;
                }
                else if (jolts[i] - jolts[i - 1] <= 3)
                {
                    threeJoltsDiff++;
                }
            }

            Console.WriteLine("Part 1: " + oneJoltDiff * threeJoltsDiff);

            jolts.Add(jolts[jolts.Count - 1] + 3);

            //number of distinct ways you can arrange the adapters
            Dictionary <int, long> numberOfDistinctWays = new Dictionary <int, long>();

            numberOfDistinctWays[0] = 1;

            for (int i = 0; i < jolts.Count; i++)
            {
                for (int j = i + 1; j < jolts.Count && jolts[j] - jolts[i] <= 3; j++)
                {
                    if (numberOfDistinctWays.ContainsKey(j))
                    {
                        numberOfDistinctWays[j] += numberOfDistinctWays[i];
                    }
                    else
                    {
                        numberOfDistinctWays.Add(j, numberOfDistinctWays.GetValueOrDefault(i, 0));
                    }
                }
            }

            Console.WriteLine("Part 2: " + numberOfDistinctWays[jolts.Count - 1]);
        }
Пример #38
0
 public MyOsdMenu EndSubMenu()
 {
     CurrentMenu   = ParentMenusDictionary.GetValueOrDefault(CurrentMenu, null);
     CurrentOption = MenuCurrentOptionsDictionary.GetValueOrDefault(CurrentMenu, null);
     return(this);
 }
 public ITSNamedCodePart?FindNamedPart(string name) => _namedParts?.GetValueOrDefault(name);
Пример #40
0
        public static IEnumerable <string> GetRelevantCompletionItems(
            string words,
            IDictionary <string, string[]> completionItems)
        {
            completionItems = new Dictionary <string, string[]>(completionItems, StringComparer.OrdinalIgnoreCase);
            var suggestedItems = new List <string>();

            var parts         = words.Split(separator: ' ');
            var currentWord   = parts.Last() != string.Empty ? parts.Last() : null;
            var parameters    = parts.Where(ParameterService.IsParameter).Select(ParameterService.GetParameterMemberName).ToList();
            var lastParameter = parameters.LastOrDefault();

            void AddParameters()
            {
                var useDashes = currentWord == null ||
                                currentWord.TrimStart('-').Length == 0 ||
                                currentWord.StartsWith("--");
                var items = completionItems.Keys
                            .Except(parameters, StringComparer.InvariantCultureIgnoreCase)
                            .Select(x => useDashes
                        ? $"--{ParameterService.GetParameterDashedName(x)}"
                        : $"-{x}");

                AddItems(items);
            }

            void AddTargetsOrValues(string parameter)
            {
                var passedItems = parts
                                  .Reverse()
                                  .TakeWhile(x => !ParameterService.IsParameter(x))
                                  .Select(ParameterService.GetParameterMemberName);

                var items = completionItems.GetValueOrDefault(parameter)?.Except(passedItems, StringComparer.OrdinalIgnoreCase) ??
                            new string[0];

                if (parameter.EqualsOrdinalIgnoreCase(Constants.InvokedTargetsParameterName))
                {
                    items = items.Select(x => x.SplitCamelHumpsWithSeparator("-", Constants.KnownWords));
                }

                AddItems(items);
            }

            void AddItems(IEnumerable <string> items)
            {
                foreach (var item in items)
                {
                    if (currentWord == null)
                    {
                        suggestedItems.Add(item);
                    }
                    else if (item.StartsWithOrdinalIgnoreCase(currentWord))
                    {
                        var normalizedItem = item.ReplaceRegex(currentWord, x => currentWord, RegexOptions.IgnoreCase);
                        if (normalizedItem != item)
                        {
                            var letters = currentWord.Where(char.IsLetter).ToList();
                            if (letters.All(char.IsUpper))
                            {
                                normalizedItem = normalizedItem.ToUpperInvariant();
                            }
                            else if (letters.All(char.IsLower))
                            {
                                normalizedItem = normalizedItem.ToLowerInvariant();
                            }
                        }

                        suggestedItems.Add(normalizedItem);
                    }
                }
            }

            if (lastParameter == null)
            {
                AddTargetsOrValues(Constants.InvokedTargetsParameterName);
            }
            else if (currentWord != lastParameter)
            {
                AddTargetsOrValues(lastParameter);
            }

            if (currentWord == null || ParameterService.IsParameter(currentWord))
            {
                AddParameters();
            }

            return(suggestedItems);
        }
Пример #41
0
        private IEnumerable<WatchFolderItem> GetDownloadItems(string watchFolder, Dictionary<string, WatchFolderItem> lastWatchItems, TimeSpan waitPeriod)
        {
            foreach (var folder in _diskProvider.GetDirectories(watchFolder))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(folder));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(folder) + "_" + _diskProvider.FolderGetCreationTime(folder).Ticks,
                    Title = title,

                    OutputPath = new OsPath(folder),

                    Status = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    var files = _diskProvider.GetFiles(folder, SearchOption.AllDirectories);

                    newWatchItem.TotalSize = files.Select(_diskProvider.GetFileSize).Sum();
                    newWatchItem.Hash = GetHash(folder, files);

                    if (files.Any(_diskProvider.IsFileLocked))
                    {
                        newWatchItem.Status = DownloadItemStatus.Downloading;
                        newWatchItem.RemainingTime = null;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return newWatchItem;
            }

            foreach (var videoFile in _diskScanService.GetVideoFiles(watchFolder, false))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(videoFile));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(videoFile) + "_" + _diskProvider.FileGetLastWrite(videoFile).Ticks,
                    Title = title,

                    OutputPath = new OsPath(videoFile),

                    Status = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    newWatchItem.TotalSize = _diskProvider.GetFileSize(videoFile);
                    newWatchItem.Hash = GetHash(videoFile);

                    if (_diskProvider.IsFileLocked(videoFile))
                    {
                        newWatchItem.Status = DownloadItemStatus.Downloading;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return newWatchItem;
            }
        }
Пример #42
0
 public IReadOnlyDictionary <MyStringId, SetInstruction> InstructionsForState(MyStringHash state)
 {
     return(_states.GetValueOrDefault(state));
 }
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
                tokens.UserId = authInfo.GetValueOrDefault("user_id");

            if (authInfo.ContainsKey("name"))
                tokens.DisplayName = authInfo.GetValueOrDefault("name");

            if (authInfo.ContainsKey("FullName"))
            {
                tokens.FullName = authInfo.GetValueOrDefault("FullName");
                if (tokens.DisplayName.IsNullOrEmpty())
                    tokens.DisplayName = tokens.FullName;
            }

            if (authInfo.ContainsKey("Email"))
                tokens.Email = authInfo.GetValueOrDefault("Email");

            if (authInfo.ContainsKey("BirthDate"))
                tokens.BirthDate = authInfo.GetValueOrDefault("BirthDate").FromJsv<DateTime?>();

            if (authInfo.ContainsKey("BirthDateRaw"))
                tokens.BirthDateRaw = authInfo.GetValueOrDefault("BirthDateRaw");

            if (authInfo.ContainsKey("Country"))
                tokens.Country = authInfo.GetValueOrDefault("Country");

            if (authInfo.ContainsKey("Culture"))
                tokens.Culture = authInfo.GetValueOrDefault("Culture");

            if (authInfo.ContainsKey("Gender"))
                tokens.Gender = authInfo.GetValueOrDefault("Gender");

            if (authInfo.ContainsKey("MailAddress"))
                tokens.MailAddress = authInfo.GetValueOrDefault("MailAddress");

            if (authInfo.ContainsKey("Nickname"))
                tokens.Nickname = authInfo.GetValueOrDefault("Nickname");

            if (authInfo.ContainsKey("PostalCode"))
                tokens.PostalCode = authInfo.GetValueOrDefault("PostalCode");

            if (authInfo.ContainsKey("TimeZone"))
                tokens.TimeZone = authInfo.GetValueOrDefault("TimeZone");

            LoadUserOAuthProvider(userSession, tokens);
        }
Пример #44
0
 public T Get <T>() where T : class
 {
     return((T)_table?.GetValueOrDefault(typeof(T)));
 }
Пример #45
0
        private NativeStyle BuildNativeStyle()
        {
            var targetType = Style.TargetType ?? typeof(FrameworkElement);

            var nativeStyle = new NativeStyle
            {
                TargetType = targetType
            };

#if !SILVERLIGHT
            foreach (var baseStyle in Style.EnumerateBaseStylesAndSelf().OfType <Style>())
            {
                if (baseStyle.Resources.Count == 0)
                {
                    continue;
                }

                foreach (var resourceKey in baseStyle.Resources.Keys)
                {
                    if (nativeStyle.Resources.Contains(resourceKey) == false)
                    {
                        nativeStyle.Resources.Add(resourceKey, baseStyle.Resources[resourceKey]);
                    }
                }
            }
#endif

            Triggers.AddRange(Style.ActualTriggers);

            var flatSetters = Style.ActualSetters.OfType <Setter>().Select(s => s.DeepClone <Setter>()).ToList();

            Dictionary <DependencyProperty, DependencyProperty> dynamicProperties = null;

            foreach (var setter in flatSetters)
            {
                if (string.IsNullOrEmpty(setter.ExpandoProperty) == false || string.IsNullOrEmpty(setter.VisualState))
                {
                    continue;
                }

                var property = setter.ResolveProperty(targetType);

                if (property == null)
                {
                    LogService.LogWarning($"Unable resolve property for setter: {setter}");
                    continue;
                }

                dynamicProperties ??= new Dictionary <DependencyProperty, DependencyProperty>();

                dynamicProperties.GetValueOrCreate(property, GetDynamicProperty);
            }

            if (dynamicProperties != null)
            {
                foreach (var kv in dynamicProperties)
                {
                    nativeStyle.Setters.Add(new NativeSetter {
                        Property = kv.Key, Value = new Binding {
                            Path = new PropertyPath(kv.Value), RelativeSource = XamlConstants.Self
                        }
                    });
                }
            }

            foreach (var setter in flatSetters)
            {
                if (string.IsNullOrEmpty(setter.ExpandoProperty) == false)
                {
                    Setters.Add(setter.Optimize());
                    continue;
                }

                var dependencyProperty = setter.ResolveProperty(targetType);
                var dynamicProperty    = dependencyProperty != null?dynamicProperties?.GetValueOrDefault(dependencyProperty) : null;

                if (dynamicProperty != null)
                {
                    setter.Property = dynamicProperty;
                    Setters.Add(setter.Optimize());
                    continue;
                }

                var nativeSetter = setter.CreateNativeStyleSetter(targetType);

                if (nativeSetter != null)
                {
                    nativeStyle.Setters.Add(nativeSetter);
                }
                else
                {
                    Setters.Add(setter.Optimize());
                }
            }

            nativeStyle.Setters.Add(new NativeSetter(InstanceProperty, this));

            return(nativeStyle);
        }
Пример #46
0
 public bool?process(IDictionary <string, string> subject, Object controller, IDictionary <string, string> configs = null)
 {
     try
     {
         var queryTemplate = configs[PSTconfigsEnum.template.ToString()];
         if (String.IsNullOrWhiteSpace(queryTemplate) || subject == null || !subject.Keys.Any())
         {
             return(false);
         }
         handle.WriteLine(subject.Aggregate(queryTemplate, (c, v) => c.Replace($"@'{v.Key}'@", MySQLHelper.sanitizeQuery(fflds?.GetValueOrDefault("date")?.Any(f => f.Equals(v.Key, StringComparison.OrdinalIgnoreCase)) == true ? DateTime.Parse(v.Value).ToString("MM/dd/yyyy") : v.Value))) + ";");
         return(true);
     }
     catch (Exception ex)
     {
         Logger.Log(ex);
         return(false);
     }
 }
Пример #47
0
 public string Answer(int index) => surveyResponses?.GetValueOrDefault(index) ?? "No Answer";
Пример #48
0
 public static Delegate CreateRoutedEventHandler(RoutedEvent routedEvent, RoutedEventHandler underlyingDelegate)
 {
     return(HandlerFactoryDict.GetValueOrDefault(routedEvent)?.Invoke(underlyingDelegate) ?? underlyingDelegate);
 }
Пример #49
0
        public static Metadata LoadMetadata(string target)
        {
            var types = new Dictionary<string, MetadataType>();
            var typeDefs = new Dictionary<MetadataType, TypeDef>();
            var metadata = new Metadata();

            // add easilly the bool type and other types in the future like Brushes posiibly
            var td = new CustomEnumTypeDef(typeof(bool).FullName, new[] { "True", "False" });
            types.Add(typeof(bool).FullName, new MetadataType() { Name = typeof(bool).FullName });
            typeDefs.Add(types[typeof(bool).FullName], td);

            foreach (var asm in LoadAssemblies(target))
            {
                var aliases = new Dictionary<string, string>();
                foreach (var attr in asm.CustomAttributes.FindAll("Avalonia.Metadata.XmlnsDefinitionAttribute"))
                    aliases[attr.ConstructorArguments[1].Value.ToString()] =
                        attr.ConstructorArguments[0].Value.ToString();

                foreach (var type in asm.Modules.SelectMany(m => m.GetTypes()).Where(x => !x.IsInterface && x.IsPublic))
                {
                    var mt = types[type.FullName] = new MetadataType
                    {
                        Name = type.Name,
                        IsStatic = type.IsSealed && type.IsAbstract,
                        IsMarkupExtension = IsMarkupExtensions(type)
                    };
                    typeDefs[mt] = type;
                    metadata.AddType("clr-namespace:" + type.Namespace + ";assembly=" + asm.Name, mt);
                    string alias = null;
                    if (aliases.TryGetValue(type.Namespace, out alias))
                        metadata.AddType(alias, mt);
                }
            }

            foreach (var type in types.Values)
            {
                var typeDef = typeDefs[type];
                while (typeDef != null)
                {
                    foreach (var prop in typeDef.Properties)
                    {
                        var setMethod = prop.SetMethod;
                        if (setMethod == null || setMethod.IsStatic || !setMethod.IsPublic)
                            continue;

                        var p = new MetadataProperty { Name = prop.Name };

                        if (setMethod.Parameters.Count == 2)
                        {
                            //1 param this, 2 param prop value
                            var mt = types.GetValueOrDefault(setMethod.Parameters[1].Type.FullName);

                            if (mt != null)
                                ResolvePropertyType(typeDefs[mt], p);
                        }

                        type.Properties.Add(p);
                    }
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name.StartsWith("Set") && methodDef.IsStatic && methodDef.IsPublic
                            && methodDef.Parameters.Count == 2)
                        {
                            var p = new MetadataProperty() { Name = methodDef.Name.Substring(3), IsAttached = true };
                            var mt = types.GetValueOrDefault(methodDef.Parameters[1].Type.FullName);
                            if (mt != null)
                                ResolvePropertyType(typeDefs[mt], p);
                            type.Properties.Add(p);
                        }
                    }
                    typeDef = typeDef.GetBaseType().ResolveTypeDef();
                }
                type.HasAttachedProperties = type.Properties.Any(p => p.IsAttached);
            }

            return metadata;
        }
Пример #50
0
        public void CreatePackage(ServiceDefinition definition, 
            CloudProjectPathInfo paths, 
            DevEnv type,
            string azureSdkBinDirectory,
            out string standardOutput, 
            out string standardError)
        {
            if (definition == null)
            {
                throw new ArgumentNullException(
                    "definition",
                    string.Format(Resources.InvalidOrEmptyArgumentMessage, "Service definition"));
            }
            if (string.IsNullOrEmpty(paths.RootPath))
            {
                throw new ArgumentException(Resources.InvalidRootNameMessage, "rootPath");
            }

            // Track the directories that are created by GetOrCreateCleanPath
            // to avoid publishing iisnode log files so we can delete the temp
            // copies when we're finished packaging
            Dictionary<string, string> tempDirectories = new Dictionary<string, string>();
            try
            {
                string roles =
                    // Get the names of all web and worker roles
                    Enumerable.Concat(
                        definition.WebRole.NonNull().Select(role => role.name),
                        definition.WorkerRole.NonNull().Select(role => role.name))
                    // Get the name and safe path for each role (i.e., if the
                    // role has files that shouldn't be packaged, it'll be
                    // copied to a temp location without those files)
                    .Select(name => GetOrCreateCleanPath(paths.RolesPath, name, tempDirectories, type))
                    // Format the role name and path as a role argument
                    .Select(nameAndPath => string.Format(Resources.RoleArgTemplate, nameAndPath.Key, nameAndPath.Value))
                    // Join all the role arguments together into one
                    .DefaultIfEmpty(string.Empty)
                    .Aggregate(string.Concat);

                string sites =
                    // Get all of the web roles
                    definition.WebRole.NonNull()
                    // Get all the sites in each role and format them all as
                    // site arguments
                    .SelectMany(role =>
                        // Format each site as a site argument
                        role.Sites.Site.Select(site =>
                            string.Format(
                                Resources.SitesArgTemplate,
                                role.name,
                                site.name,
                                tempDirectories.GetValueOrDefault(role.name, paths.RolesPath))))
                    // Join all the site arguments together into one
                    .DefaultIfEmpty(string.Empty)
                    .Aggregate(string.Concat);

                string args = string.Format(
                    type == DevEnv.Local ? Resources.CsPackLocalArg : Resources.CsPackCloudArg,
                    paths.RootPath,
                    roles,
                    sites);

                // Run CsPack to generate the package
                ProcessHelper.StartAndWaitForProcess(
                    new ProcessStartInfo(
                        Path.Combine(azureSdkBinDirectory, Resources.CsPackExe),
                        args),
                    out standardOutput,
                    out standardError);
            }
            finally
            {
                // Cleanup any temp directories
                tempDirectories.Values.ForEach(dir => Directory.Delete(dir, true));
            }
        }
        public virtual void OnAuthenticated(IServiceBase oAuthService, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var provider = tokens.Provider;
            var authProvider = oAuthService.TryResolve<IUserAuthRepository>();
            if (authProvider != null)
                authProvider.LoadUserAuth(this, tokens);

            if (provider == TwitterAuthConfig.Name)
            {
                if (authInfo.ContainsKey("user_id"))
                    tokens.UserId = this.TwitterUserId = authInfo.GetValueOrDefault("user_id");

                if (authInfo.ContainsKey("screen_name"))
                    tokens.UserName = this.TwitterScreenName = authInfo.GetValueOrDefault("screen_name");

                try
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(this.TwitterUserId);
                    var obj = JsonObject.Parse(json);
                    tokens.DisplayName = obj.Get("name");
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(TwitterUserId), ex);
                }
            }
            else if (provider == FacebookAuthConfig.Name)
            {
                try
                {
                    var json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret);
                    var obj = JsonObject.Parse(json);
                    tokens.UserId = obj.Get("id");
                    tokens.UserName = obj.Get("username");
                    tokens.DisplayName = obj.Get("name");
                    tokens.FirstName = obj.Get("first_name");
                    tokens.LastName = obj.Get("last_name");
                    tokens.Email = obj.Get("email");

                    this.FacebookUserId = tokens.UserId ?? this.FacebookUserId;
                    this.FacebookUserName = tokens.UserName ?? this.FacebookUserName;
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                    this.FirstName = tokens.FirstName ?? this.FirstName;
                    this.LastName = tokens.LastName ?? this.LastName;
                    this.Email = tokens.Email ?? this.Email;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex);
                }
            }

            authInfo.ForEach((x, y) => tokens.Items[x] = y);

            SaveUserAuth(oAuthService.TryResolve<IUserAuthRepository>(), tokens);
            OnSaveUserAuth(oAuthService, this.UserAuthId);
        }
Пример #52
0
        public static List <SourceFileAnalysisResult> AnalyzeResults(
            Dictionary <string, List <CodeEntityDetails> > sourceFileToCodeEntities,
            Dictionary <PackageVersionPair, Task <PackageDetails> > packageResults,
            Dictionary <string, Task <RecommendationDetails> > recommendationResults,
            Dictionary <string, List <RecommendedAction> > portingActionResults,
            string targetFramework = "net6.0",
            bool compatibleOnly    = false
            )
        {
            var packageDetailsWithIndicesResults = ApiCompatiblity.PreProcessPackageDetails(packageResults);

            return(sourceFileToCodeEntities.Select(sourceFile =>
            {
                return new SourceFileAnalysisResult
                {
                    SourceFileName = Path.GetFileName(sourceFile.Key),
                    SourceFilePath = sourceFile.Key,
                    RecommendedActions = portingActionResults?.GetValueOrDefault(sourceFile.Key, new List <RecommendedAction>()),
                    ApiAnalysisResults = sourceFile.Value.Select(codeEntity =>
                    {
                        var package = codeEntity.Package;

                        //A code entity with no reference data. This can be any error in the code
                        if (package == null)
                        {
                            return new ApiAnalysisResult
                            {
                                CodeEntityDetails = codeEntity,
                                CompatibilityResults = new Dictionary <string, CompatibilityResult>
                                {
                                    {
                                        targetFramework, new CompatibilityResult()
                                        {
                                            Compatibility = Compatibility.UNKNOWN
                                        }
                                    }
                                },
                                Recommendations = new Model.Recommendations
                                {
                                    RecommendedActions = new List <RecommendedAction>()
                                }
                            };
                        }
                        var sdkpackage = new PackageVersionPair {
                            PackageId = codeEntity.Namespace, Version = "0.0.0", PackageSourceType = PackageSourceType.SDK
                        };

                        // check result with nuget package
                        var packageDetails = packageDetailsWithIndicesResults.GetValueOrDefault(package, null);
                        var compatibilityResultWithPackage = ApiCompatiblity.GetCompatibilityResult(packageDetails, codeEntity, targetFramework);

                        // potential check with namespace
                        var sdkpackageDetails = packageDetailsWithIndicesResults.GetValueOrDefault(sdkpackage, null);
                        var compatibilityResultWithSdk = ApiCompatiblity.GetCompatibilityResult(sdkpackageDetails, codeEntity, targetFramework);
                        var compatibilityResult = GetCompatibilityResult(compatibilityResultWithPackage, compatibilityResultWithSdk);

                        if (compatibleOnly)
                        {
                            if (!(compatibilityResult.Compatibility == Compatibility.INCOMPATIBLE))
                            {
                                return null;
                            }
                        }

                        var recommendationDetails = recommendationResults.GetValueOrDefault(codeEntity.Namespace, null);
                        var apiRecommendation = ApiCompatiblity.UpgradeStrategy(compatibilityResult, codeEntity.OriginalDefinition, recommendationDetails, targetFramework);

                        return new ApiAnalysisResult
                        {
                            CodeEntityDetails = codeEntity,
                            CompatibilityResults = new Dictionary <string, CompatibilityResult>
                            {
                                { targetFramework, compatibilityResult }
                            },
                            Recommendations = new Model.Recommendations
                            {
                                RecommendedActions = new List <RecommendedAction>
                                {
                                    apiRecommendation
                                }
                            }
                        };
                    }).Where(codeEntity => codeEntity != null)
                                         .ToList()
                };
            }
                                                   ).ToList());
        }
Пример #53
0
        private string ReplaceToken(Match match, Dictionary<string, Func<TokenMatch, string>> tokenHandlers, NamingConfig namingConfig)
        {
            var tokenMatch = new TokenMatch
            {
                RegexMatch = match,
                Prefix = match.Groups["prefix"].Value,
                Separator = match.Groups["separator"].Value,
                Suffix = match.Groups["suffix"].Value,
                Token = match.Groups["token"].Value,
                CustomFormat = match.Groups["customFormat"].Value
            };

            if (tokenMatch.CustomFormat.IsNullOrWhiteSpace())
            {
                tokenMatch.CustomFormat = null;
            }

            var tokenHandler = tokenHandlers.GetValueOrDefault(tokenMatch.Token, m => string.Empty);

            var replacementText = tokenHandler(tokenMatch).Trim();

            if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsLower(t)))
            {
                replacementText = replacementText.ToLower();
            }
            else if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsUpper(t)))
            {
                replacementText = replacementText.ToUpper();
            }

            if (!tokenMatch.Separator.IsNullOrWhiteSpace())
            {
                replacementText = replacementText.Replace(" ", tokenMatch.Separator);
            }

            replacementText = CleanFileName(replacementText, namingConfig.ReplaceIllegalCharacters);

            if (!replacementText.IsNullOrWhiteSpace())
            {
                replacementText = tokenMatch.Prefix + replacementText + tokenMatch.Suffix;
            }

            return replacementText;
        }
 public override Hotel GetFromId(int id)
 {
     return(hotels.GetValueOrDefault(id));
 }
Пример #55
0
        private static Dictionary <Variable <TK, TD>, int> Ac3(CspProblem <TK, TD> problem, out bool isConsistent)
        {
            var queue           = new LinkedList <BinaryConstraint <TK, TD> >(problem.Constraints);
            var removalsCounter = new Dictionary <Variable <TK, TD>, int>();

            while (queue.Any())
            {
                var con = queue.First?.Value;
                queue.RemoveFirst();

                if (!RemoveInconsistentValues(con, out var emptyFound))
                {
                    continue;
                }

                if (emptyFound)
                {
                    isConsistent = false;
                    return(removalsCounter);
                }

                Debug.Assert(con?.VariableOne.Constraints != null, "con?.VariableOne.Constraints != null");
                foreach (var c in con.VariableOne.Constraints)
                {
                    queue.AddLast(c);
                }
            }

            isConsistent = true;
            return(removalsCounter);

            bool RemoveInconsistentValues(BinaryConstraint <TK, TD> c, out bool emptyDomainFound)
            {
                var(v1, v2) = (c.VariableOne, c.VariableTwo);

                if (v1.Assigned)
                {
                    emptyDomainFound = false;
                    return(false);
                }

                var removed  = false;
                var toRemove = new LinkedList <TD>();

                foreach (var d in v1.Domain)
                {
                    if (v2.Domain.Any(d2 => c.Test(d, d2)))
                    {
                        continue;
                    }
                    toRemove.AddLast(d);
                    removed = true;
                }

                if (!removed)
                {
                    emptyDomainFound = false;
                    return(false);
                }

                v1.RemoveFromDomain(toRemove);
                emptyDomainFound    = !v1.Domain.Any();
                removalsCounter[v1] = removalsCounter.GetValueOrDefault(v1, 0) + 1;
                return(true);
            }
        }
Пример #56
0
        public List <int> slidingWindowTemplateByHarryChaoyangHe(string s, string t)
        {
            //init a collection or int value to save the result according the question.
            List <int> result = new List <int>();

            if (t.Length > s.Length)
            {
                return(result);
            }

            //create a hashmap to save the Characters of the target substring.
            //(K, V) = (Character, Frequence of the Characters)
            Dictionary <char, int> map = new Dictionary <char, int>();

            foreach (char c in t.ToCharArray())
            {
                map.Add(c, map.GetValueOrDefault(c, 0) + 1);
            }
            //maintain a counter to check whether match the target string.
            int counter = map.Count;//must be the map size, NOT the string size because the char may be duplicate.

            //Two Pointers: begin - left pointer of the window; end - right pointer of the window
            int begin = 0, end = 0;

            //the length of the substring which match the target string.
            // int len = int.MaxValue;

            //loop at the begining of the source string
            while (end < s.Length)
            {
                char c = s[end];//get a character

                if (map.ContainsKey(c))
                {
                    map.Add(c, map[c] - 1);// plus or minus one
                    if (map[c] == 0)
                    {
                        counter--;             //modify the counter according the requirement(different condition).
                    }
                }
                end++;

                //increase begin pointer to make it invalid/valid again
                while (counter == 0)       /* counter condition. different question may have different condition */
                {
                    char tempc = s[begin]; //***be careful here: choose the char at begin pointer, NOT the end pointer
                    if (map.ContainsKey(tempc))
                    {
                        map.Add(tempc, map[tempc] + 1);//plus or minus one
                        if (map[tempc] > 0)
                        {
                            counter++;                //modify the counter according the requirement(different condition).
                        }
                    }

                    /* save / update(min/max) the result if find a target*/
                    // result collections or result int value

                    begin++;
                }
            }
            return(result);
        }
Пример #57
0
        private void Run(object obj)
        {
            Dictionary<string, string> updatedSubmodules = new Dictionary<string, string>();

            while (!m_token.IsCancellationRequested)
            {
                // check for changes to the build repo itself (and reload the submodules if so)
                string commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch);
                if (commitId == null)
                {
                    Log.Error("Getting last commit ID failed; will stop monitoring project.");
                    break;
                }

                if (commitId != m_lastBuildCommitId)
                {
                    if (m_lastBuildCommitId != null)
                    {
                        Log.Info("Build repo commit ID has changed from {0} to {1}; reloading submodules.", m_lastBuildCommitId, commitId);
                        StartBuild();
                    }

                    try
                    {
                        GetSubmodules();
                    }
                    catch (WatcherException ex)
                    {
                        Log.Error("Getting submodules failed; will stop monitoring project.", ex);
                        break;
                    }
                    updatedSubmodules.Clear();
                }
                else
                {
                    // check for changes in the submodules
                    bool submoduleChanged = false;
                    bool submoduleHasError = false;
                    foreach (var pair in m_submodules)
                    {
                        Submodule submodule = pair.Value;
                        commitId = m_gitHubClient.GetLatestCommitId(submodule.User, submodule.Repo, submodule.Branch);
                        if (commitId == null)
                        {
                            Log.Error("Submodule '{0}' doesn't have a latest commit for branch '{1}'; will stop monitoring project.", pair.Key, submodule.Branch);
                            submoduleHasError = true;
                        }
                        else if (commitId != submodule.LatestCommitId && commitId != updatedSubmodules.GetValueOrDefault(pair.Key))
                        {
                            Log.Info("Submodule '{0}' has changed from {1} to {2}; waiting for more changes.", pair.Key, submodule.LatestCommitId.Substring(0, 8), commitId.Substring(0, 8));
                            updatedSubmodules[pair.Key] = commitId;
                            submoduleChanged = true;
                        }
                    }

                    // abort if there were errors
                    if (submoduleHasError)
                        break;

                    // pause for five seconds between each check
                    m_token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

                    // if any submodule changed, loop again (to allow changes to multiple submodules to be batched)
                    if (submoduleChanged)
                        continue;

                    // if there were updated submodules, create a new commit
                    if (updatedSubmodules.Count != 0)
                    {
                        try
                        {
                            UpdateSubmodules(updatedSubmodules);
                            updatedSubmodules.Clear();
                        }
                        catch (WatcherException ex)
                        {
                            Log.Error("Updating submodules failed; will stop monitoring project.", ex);
                            break;
                        }
                    }
                }
            }
        }
 public static ItemExtractionMetadata GetMetadata(int itemId)
 {
     return(map.GetValueOrDefault(itemId));
 }
        // Generate an instance of the correct implementation for the provided client on request
        public IExampleService GetInstance(string client, IServiceProvider provider)
        {
            var implType = _dict.GetValueOrDefault(client);

            return((IExampleService)provider.GetRequiredService(implType));
        }
Пример #60
0
 public static ICommand Get(BigInteger key)
 => Values?.GetValueOrDefault((Command)((int)key)) ?? throw new ArgumentNullException(nameof(key));