Пример #1
0
        /* ***************INSTRUCTIONS***************
         * Create a total ownership report that computes the total value of each stock that you have purchased. This is the basic relational database
         * join algorithm between two tables.
         *
         * Define a new Dictionary to hold the aggregated purchase information. - The key should be a string that is the full company name. -
         * The value will be the valuation of each stock (price*amount) { "General Electric": 35900, "AAPL": 8445, ... }
         * Iterate over the purchases and update the valuation for each stock
         * foreach ((string ticker, int shares, double price) purchase in purchases)
         * {Does the company name key already exist in the report dictionary?
         * If it does, update the total valuation
         * If not, add the new key and set its value
         * }
         */

        static void Main(string[] args)
        {
            Dictionary <string, string> stocks = new Dictionary <string, string>();

            stocks.Add("NKE", "Nike");
            stocks.Add("AAPL", "Apple");
            stocks.Add("TWTR", "Twitter");
            stocks.Add("SNAP", "Snapchat");
            stocks.Add("GOOGL", "Google");

            List <(string ticker, int shares, double price)> purchases = new List <(string, int, double)>();

            purchases.Add((ticker: "NKE", shares: 50, price: 89.87));
            purchases.Add((ticker: "NKE", shares: 123, price: 79.89));
            purchases.Add((ticker: "NKE", shares: 13, price: 83.23));
            purchases.Add((ticker: "AAPL", shares: 414, price: 183.73));
            purchases.Add((ticker: "AAPL", shares: 63, price: 185.13));
            purchases.Add((ticker: "AAPL", shares: 27, price: 187.11));
            purchases.Add((ticker: "TWTR", shares: 223, price: 31.03));
            purchases.Add((ticker: "TWTR", shares: 77, price: 33.89));
            purchases.Add((ticker: "SNAP", shares: 90, price: 11.28));
            purchases.Add((ticker: "SNAP", shares: 303, price: 12.54));
            purchases.Add((ticker: "GOOGL", shares: 19, price: 1192.53));
            purchases.Add((ticker: "GOOGL", shares: 36, price: 1189.09));

            Dictionary <string, double> ownershipReport = new Dictionary <string, double>();

            var allStocks = stocks.Join(purchases,
                                        stock => stock.Key,
                                        purchase => purchase.ticker,
                                        (s, p) => new { Ticker = s.Value, Shares = p.shares, Price = p.price });

            foreach (var stock in allStocks)
            {
                // { Does the company name key already exist in the report dictionary?
                // If it does, update the total valuation
                if (ownershipReport.ContainsKey(stock.Ticker))
                {
                    ownershipReport[stock.Ticker] = ownershipReport[stock.Ticker] + (stock.Shares * stock.Price);
                }
                // If not, add the new key and set its value
                else
                {
                    ownershipReport.Add(stock.Ticker, (stock.Shares * stock.Price));
                }
            }

            foreach (var stock in ownershipReport)
            {
                Console.WriteLine($"Company: {stock.Key} \t\t Total Amount Invested: ${stock.Value}");
            }

            Console.ReadLine();
        }
Пример #2
0
 public List <Entity> GetEntities(List <NitroxId> ids)
 {
     lock (entitiesById)
     {
         return(entitiesById.Join(ids,
                                  entity => entity.Value.Id,
                                  id => id,
                                  (entity, id) => entity.Value)
                .ToList());
     }
 }
Пример #3
0
 public IEnumerable <UpdateSkuInventoryRequest> GetUpdateRequests(Dictionary <string, int> updatedSkusQuantities, IEnumerable <SellbriteProductInventory> sellbriteInventory, string warehouseId)
 {
     return(updatedSkusQuantities.Join(sellbriteInventory, sq => sq.Key.ToUpperInvariant(), si => si.Sku.ToUpperInvariant(), (sq, si) =>
     {
         return new UpdateSkuInventoryRequest()
         {
             Sku = si.Sku,
             WarehouseUuid = warehouseId,
             Available = sq.Value
         };
     }).ToList());
 }
Пример #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Dictionary <string, string> stocks = new Dictionary <string, string>();

            stocks.Add("AMZN", "Amazon");
            stocks.Add("TSLA", "Tesla");
            stocks.Add("SHOP", "Shopify");
            stocks.Add("FB", "Facebook");
            stocks.Add("SPOT", "Spotify");
            stocks.Add("TWLO", "Twilio");
            stocks.Add("IPOA", "Social Capital Hedosophia");
            stocks.Add("MJ", "ETFMG Alternative Harvest");

            // Creating a list of ValueTypes that represent stock purchases
            // The properties are ticker, shares and price.
            List <(string ticker, int shares, double price)> purchases = new List <(string, int, double)>();

            purchases.Add((ticker: "AMZN", shares: 1, price: 1778.44));
            purchases.Add((ticker: "TSLA", shares: 1, price: 277.60));
            purchases.Add((ticker: "SHOP", shares: 1, price: 207.25));
            purchases.Add((ticker: "FB", shares: 1, price: 165.73));
            purchases.Add((ticker: "SPOT", shares: 1, price: 138.87));
            purchases.Add((ticker: "TWLO", shares: 2, price: 128.95));
            purchases.Add((ticker: "IPOA", shares: 1, price: 10.19));
            purchases.Add((ticker: "MJ", shares: 2, price: 36.36));
            purchases.Add((ticker: "SHOP", shares: 2, price: 175.90));
            purchases.Add((ticker: "SHOP", shares: 2, price: 175.90));

            Dictionary <string, double> TotalHoldings = new Dictionary <string, double>();

            var CombinedData = stocks.Join(purchases,
                                           s => s.Key,
                                           p => p.ticker,
                                           (s, p) => new { CompName = s.Value, CompOwn = p.shares, CompPrice = p.price }
                                           );

            foreach (var equity in CombinedData)
            {
                if (TotalHoldings.ContainsKey(equity.CompName))
                {
                    TotalHoldings[equity.CompName] = TotalHoldings[equity.CompName] + (equity.CompOwn * equity.CompPrice);
                }
                else
                {
                    TotalHoldings.Add(equity.CompName, (equity.CompOwn * equity.CompPrice));
                }
                Console.WriteLine($"Man I'm glad I purchased {equity.CompName} on the dip");
                Console.ReadKey();
            }
        }
Пример #5
0
        static void Main(string[] args)
        {
            Dictionary <string, string> stocks = new Dictionary <string, string>();
            List <(string ticker, double shares, double price)> purchases = new List <(string, double, double)>();
            Dictionary <string, double> aggregatedPurchases = new Dictionary <string, double>();
            double updatedValuation = 0;

            stocks.Add("CBRL", "Cracker Barrel");
            stocks.Add("HD", "Home Depot");
            stocks.Add("UA", "Under Armour");
            stocks.Add("GOOGL", "Google");
            stocks.Add("NFLX", "Netflix");

            purchases.Add((ticker: "CBRL", shares: 225, price: 156.49));
            purchases.Add((ticker: "CBRL", shares: 45, price: 157.36));
            purchases.Add((ticker: "CBRL", shares: 110, price: 156.45));
            purchases.Add((ticker: "HD", shares: 75, price: 183.42));
            purchases.Add((ticker: "HD", shares: 256, price: 183.79));
            purchases.Add((ticker: "HD", shares: 189, price: 187.45));
            purchases.Add((ticker: "GOOGL", shares: 95, price: 1188.55));
            purchases.Add((ticker: "GOOGL", shares: 22, price: 1189.23));
            purchases.Add((ticker: "GOOGL", shares: 73, price: 1190.04));
            purchases.Add((ticker: "NFLX", shares: 10, price: 363.44));
            purchases.Add((ticker: "NFLX", shares: 45, price: 363.79));
            purchases.Add((ticker: "NFLX", shares: 79, price: 364.23));
            purchases.Add((ticker: "UA", shares: 43, price: 19.85));
            purchases.Add((ticker: "UA", shares: 35, price: 20.15));
            purchases.Add((ticker: "UA", shares: 45, price: 19.06));

            var ownershipReport =
                stocks.Join(purchases, (stock => stock.Key), (purchase => purchase.ticker),
                            ((stock, purchase) => new { Name = stock.Value, Valuation = (purchase.shares * purchase.price) }));

            foreach (var stock in ownershipReport)
            {
                if (aggregatedPurchases.ContainsKey(stock.Name))
                {
                    aggregatedPurchases[stock.Name] = aggregatedPurchases[stock.Name] + (stock.Valuation);
                }
                else
                {
                    aggregatedPurchases.Add(stock.Name, stock.Valuation);
                }
            }

            foreach (var stock in aggregatedPurchases)
            {
                Console.WriteLine($"You own ${stock.Value} of {stock.Key}.");
            }

            Console.ReadKey();
        }
Пример #6
0
        private bool AllFieldsAreValid2(Passport passport)
        {
            if (!AllFieldsAreValid1(passport))
            {
                return(false);
            }

            return(passportFieldsNamesValidation
                   .Join(passport.Fields,
                         fnv => fnv.Key,
                         f => f.Field,
                         (fnv, f) => fnv.Value(f.Value))
                   .All(v => v));
        }
Пример #7
0
        public void JoinExcersize()
        {
            Dictionary <string, string> klienci = new Dictionary <string, string>
            {
                { "3010201231231232", "Mateusz" },
                { "1210501231231312", "Ewa" },
                { "3210303123131231", "Florian " },
                { "3210501231231312", "Daria" },
                { "1210403123123132", "Michal" },
            };
            Dictionary <string, string> banki = new Dictionary <string, string>
            {
                { "1020", "PKO" },
                { "1030", "Ing" },
                { "1040", "mBank" },
            };

            banki.Add("1060", "bzwbk");
            // nr konta, nazwa banku, klient
            //TODO to samo ale do obiektu Klient z property

            var wynik = klienci.Join(
                banki,
                klienciSelector => klienciSelector.Key.Substring(2, 4),
                bankiSelector => bankiSelector.Key,
                (klient, bank) => new BankTransfer {
                AccountNumber = klient.Key, BankName = bank.Value, BankCode = bank.Key, ClientName = klient.Value
            });

            var wynik2 = klienci.Join(
                banki,
                klienciSelector => klienciSelector.Key.Substring(2, 3),
                bankiSelector => bankiSelector.Key.Substring(0, 3),
                (klient, bank) => new BankTransfer {
                AccountNumber = klient.Key, BankName = bank.Value, BankCode = bank.Key, ClientName = klient.Value
            });
        }
Пример #8
0
    private Dictionary <DebugMessageType, DebugMessage> MapToMessages(Dictionary <DebugMessageType, KeyValuePair <string, string> > mapping)
    {
        var textList   = GameObject.FindObjectsOfType <Text>().ToList();
        var fieldNames = new List <string> {
            "debugModeText", "skipLevelText", "collisionsOffText"
        };
        var messages = mapping.Join(
            textList,
            f => f.Value.Key,
            tn => tn.name,
            (fn, tn) => new DebugMessage(fn.Key, tn, fn.Value.Value)
            );

        return(messages.ToDictionary(m => m.Type));
    }
        public bool GetTeamColorTileData(IEnumerable <string> searchTilesets, string name, int shape, TeamColor teamColor, out int fps, out Tile[] tiles)
        {
            fps   = 0;
            tiles = null;

            foreach (var tileset in tilesets.Join(searchTilesets, x => x.Key, y => y, (x, y) => x.Value))
            {
                if (tileset.GetTileData(name, shape, teamColor, out fps, out tiles))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #10
0
 internal void Dump(TextWriter tw)
 {
     tw.WriteLine("Game: ");
     tw.WriteLine("  Settings={0}", PropertyLookup.Join(","));
     tw.WriteLine("  Players={0}", PlayerLookup.Join(","));
     tw.WriteLine("  TurnOrders={0}", TurnOrders.Join(","));
     tw.WriteLine("  MovePriorities={0}", MovePriorities.Join(","));
     tw.WriteLine("  Setups={0}", SetupItems.Join(","));
     tw.WriteLine("  Goals={0}", Goals.Join(","));
     tw.WriteLine("  Pieces={0}", PieceLookup.Values.Join(","));
     tw.WriteLine("");
     Board.Dump(tw);
     Code.Dump(tw);
     // nice idea but no data?
     //foreach (var piece in PieceLookup.Values) piece.Dump(tw);
 }
Пример #11
0
        /// <summary>
        /// Removes all the plugins related to the given plugin files.
        /// </summary>
        /// <param name="deletedFiles">The collection of plugin file paths that were removed.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="deletedFiles"/> is <see langword="null" />.
        /// </exception>
        public void RemovePlugins(IEnumerable <string> deletedFiles)
        {
            {
                Lokad.Enforce.Argument(() => deletedFiles);
            }

            lock (m_Lock)
            {
                var filesToDelete = m_PluginFiles
                                    .Join(
                    deletedFiles,
                    pluginFile => pluginFile.Path,
                    filePath => filePath,
                    (pluginFile, filePath) => pluginFile)
                                    .ToList();
                foreach (var file in filesToDelete)
                {
                    m_PluginFiles.Remove(file);
                }

                var groupsToDelete = m_Groups
                                     .Join(
                    filesToDelete,
                    p => p.Value.Item2,
                    file => file,
                    (pair, file) => pair.Key)
                                     .ToList();
                foreach (var group in groupsToDelete)
                {
                    m_Groups.Remove(group);
                }

                var typesToDelete = m_Parts
                                    .Join(
                    filesToDelete,
                    p => p.Value.Item2,
                    file => file,
                    (pair, file) => pair.Key)
                                    .ToList();
                foreach (var type in typesToDelete)
                {
                    m_Parts.Remove(type);
                    m_Types.Remove(type);
                    m_TypeGraph.RemoveVertex(type);
                }
            }
        }
Пример #12
0
        public static IEnumerable <GetTrainingCourseProviderListItem> OrderByProviderScore(
            this IEnumerable <GetTrainingCourseProviderListItem> source, List <DeliveryModeType> requestDeliveryModes = null)
        {
            _providerScores = new Dictionary <int, decimal>();

            var getTrainingCourseProviderListItems = source.ToList();

            AddFeedbackRateScore(getTrainingCourseProviderListItems);

            AddAchievementRateScore(getTrainingCourseProviderListItems);

            var scoredAndSortedProviders =
                _providerScores.Join(getTrainingCourseProviderListItems,
                                     achievementRateScore => achievementRateScore.Key,
                                     getTrainingCourseProviderListItem => getTrainingCourseProviderListItem.ProviderId,
                                     (achievementRateScore, getTrainingCourseProviderListItem) =>
                                     new { achievementRateScore, getTrainingCourseProviderListItem })
                .OrderByDescending(t => t.achievementRateScore.Value)
                .Select(c =>
            {
                var getTrainingCourseProviderListItem   = c.getTrainingCourseProviderListItem;
                getTrainingCourseProviderListItem.Score = c.achievementRateScore.Value;
                return(getTrainingCourseProviderListItem);
            })
                .OrderByDescending(c => c.Score)
                .ThenByDescending(c => c.OverallAchievementRate)
                .ThenByDescending(c => c.OverallCohort)
                .ThenByDescending(c => c.EmployerFeedback.TotalEmployerResponses)
                .ThenByDescending(c => c.ApprenticeFeedback.TotalApprenticeResponses)
                .ThenBy(c => c.Name)
                .ToList();

            _filteredDeliveryMode = DeliveryModeType.NotFound;
            if (requestDeliveryModes != null && requestDeliveryModes.Count(c => c != DeliveryModeType.National) == 1) //TODO need to exclude national
            {
                _filteredDeliveryMode = requestDeliveryModes.First(c => c != DeliveryModeType.National);
            }

            if (!getTrainingCourseProviderListItems.All(c => c.HasLocation) ||
                getTrainingCourseProviderListItems.All(c => c.DeliveryModes.All(x => x.DeliveryModeType == DeliveryModeType.Workplace)) ||
                _filteredDeliveryMode == DeliveryModeType.Workplace)
            {
                return(scoredAndSortedProviders);
            }

            return(scoredAndSortedProviders.OrderByScoreAndDistance(_filteredDeliveryMode));
        }
Пример #13
0
        public PropertyToValueCorrelation[] GetPropertiesValues(string rawData)
        {
            Dictionary <string, string> mailPairs = DefaultRawStringParser.ParseWithLinq(rawData: rawData, pairDelimiter: Environment.NewLine);
            var mapSchemas =
                _mapSchemas
                .Where(x => x.EntityName.ToUpperInvariant() == _typeNameInUpperCaseInvariant)
                .Select(x => new { x.Key, x.Property })
                .ToArray();

            return
                (mailPairs
                 .Join(mapSchemas, x => x.Key, x => x.Key,
                       (x, y) => new PropertyToValueCorrelation {
                PropertyName = y.Property, Value = x.Value
            })
                 .ToArray());
        }
Пример #14
0
        public async Task <ApiResponse> PostAsync(string api, Dictionary <string, object> formData, Func <ApiRequest, WebRequest, WebRequest> requestInitializer, CancellationToken token)
        {
            var result = new ApiResponse();

            try
            {
                var postData = formData.Join("&");
                var body     = Encoding.UTF8.GetBytes(postData);

                result = await InvokeAsync(new ApiRequest { Api = api, ContentType = "application/x-www-form-urlencoded", Body = body, Method = HttpMethod.Post }, PrepareRequestInitializer(requestInitializer, false), token);
            }
            catch (Exception e)
            {
                result.Failed(e);
            }

            return(result);
        }
Пример #15
0
        static void Main(string[] args)
        {
            //排序复杂时,用linq语句会更方便


            //linq语句语法
            var list1 = new Dictionary <string, string> {
                { "1", "张三" }, { "2", "李四" }, { "3", "张三" }, { "4", "张三" }
            };
            var list2 = new Dictionary <string, string> {
                { "1", "张三" }, { "2", "李四" }, { "3", "李四" }, { "4", "张三" }
            };

            var query1 = from l1 in list1
                         join l2 in list2
                         on l1.Key equals l2.Key
                         orderby l1.Key, l2.Key descending
                select new { l1, l2 };
            ///提交到数据库执行,并获取结果
            var result1 = query1.ToList();

            foreach (var res1 in result1)
            {
                Console.WriteLine("列表1{0}", res1.l1);
                Console.WriteLine("列表2{0}", res1.l2);
            }

            //lmabda语句表达
            var query2 = list1.Join(list2, l1 => l1.Key, l2 => l2.Key, (l1, l2) => new { l1, l2 })
                         .OrderBy(lll => lll.l1.Key)
                         .ThenByDescending(lll => lll.l2.Key)
                         .Select(t => new { t.l1, t.l2 });

            var resutl2 = query2.ToList();

            foreach (var res2 in resutl2)
            {
                Console.WriteLine(res2.l1);
                Console.WriteLine(res2.l2);
            }
        }
Пример #16
0
        public List <Contact> addContacts(Dictionary <String, String> extUserIDs_nameContacts, int extServiceID)
        {
            List <Contact> alreadyIn = null;
            List <Contact> toInsert;

            try
            {
                alreadyIn = context.Contact.Where(c => c.externalServiceID == extServiceID).ToList().Join(extUserIDs_nameContacts.Keys, c => c.externalUserID, k => k.ToUpper(), (c, k) => c).ToList();
                if (alreadyIn.Count == extUserIDs_nameContacts.Count)
                {
                    return(alreadyIn);                                                                                                           // All contacts are already in the DB
                }
                var duplicates = extUserIDs_nameContacts.Join(alreadyIn, oK => oK.Key.ToUpper(), iK => iK.externalUserID, (o, i) => o).ToList(); //nameContact is not Unique (DB costr)!!
                extUserIDs_nameContacts = extUserIDs_nameContacts.Except(duplicates).ToDictionary(c => c.Key, c => c.Value);
            }
            catch (Exception) { }
            toInsert = extUserIDs_nameContacts.Select(c => new Contact()
            {
                externalUserID = c.Key.ToUpper(), nameContact = c.Value, externalServiceID = extServiceID
            }).ToList();
            return(AddEntityAndUnion(toInsert, alreadyIn));
        }
Пример #17
0
        public static IDictionary <string, int> StringValuesAndEnumInts(this Enum value)
        {
            IDictionary <string, int> ret = new Dictionary <string, int>();

            Type type = value.GetType();
            IDictionary <string, string> valuesText = new Dictionary <string, string>();

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in type.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                {
                    valuesText.Add(attrs[0].StringValue, fi.Name);
                }
            }

            IDictionary <string, int> valuesInt = new Dictionary <string, int>();

            foreach (var ttt in Enum.GetValues(type))
            {
                valuesInt.Add(ttt.ToString(), ((int)ttt));
            }

            var items = valuesText.Join(valuesInt,
                                        (x) => { return(x.Value); },
                                        (x) => { return(x.Key); },
                                        (outer, inner) => { return(new KeyValuePair <string, int>(outer.Key, inner.Value)); }

                                        );

            foreach (var item in items)
            {
                ret.Add(item);
            }

            return(ret);
        }
Пример #18
0
        private static void Postfix()
        {
            if (!GameplayManager.IsDedicatedServer())
            {
                return;
            }
            Debug.Log("MPTweaksLoadScene");
            RobotManager.ReadMultiplayerModeFile();
            Debug.Log("MPTweaks loaded mode file");
            bool nobodySupportsProj = !NetworkMatch.m_players.Keys.Any(connId =>
                                                                       MPTweaks.ClientInfos.TryGetValue(connId, out var clientInfo) &&
                                                                       clientInfo.SupportsTweaks.Contains("proj"));
            var tweaks = new Dictionary <string, string>()
            {
            };

            if (nobodySupportsProj) // use stock hunters for all stock client match
            {
                Debug.LogFormat("MPTweaks: not tweaking hunter: unsupported by all clients");
            }
            else
            {
                tweaks.Add("proj.missile_hunter.m_init_speed_min", "17.5");
            }
            if (NetworkMatch.GetMode() == CTF.MatchModeCTF)
            {
                tweaks.Add("ctf.returntimer", CTF.ReturnTimeAmountDefault.ToStringInvariantCulture());
            }
            if (!MPCustomModeFile.PickupCheck)
            {
                tweaks.Add("item.pickupcheck", Boolean.FalseString);
            }
            if (tweaks.Any())
            {
                Debug.LogFormat("MPTweaks: sending tweaks {0}", tweaks.Join());
                MPTweaks.Set(tweaks);
                MPTweaks.Send();
            }
        }
Пример #19
0
        /// <summary>
        /// Sends the specified request URI string.
        /// </summary>
        /// <param name="requestUriString">The request URI string.</param>
        /// <param name="method">The method.</param>
        /// <param name="queryStringData">The query string data.</param>
        /// <param name="formData">The form data.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static WebResponse Send(string requestUriString, string method, Dictionary <string, string> queryStringData, Dictionary <string, string> formData)
        {
            string uri = requestUriString;

            if (queryStringData != null)
            {
                string parms = queryStringData.Join("&");
                if (parms.Trim() != string.Empty)
                {
                    uri += (uri.Contains("?") ? "&" : "?") + parms;
                }
            }

            HttpWebRequest request = ( HttpWebRequest )HttpWebRequest.Create(uri);

            request.Method = method;

            if (formData != null && formData.Count > 0)
            {
                byte[] postData = ASCIIEncoding.ASCII.GetBytes(formData.Join("&"));

                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postData, 0, postData.Length);
                requestStream.Close();
            }

            try
            {
                HttpWebResponse response = ( HttpWebResponse )request.GetResponse();
                return(new WebResponse(response.StatusCode, GetResponseString(response.GetResponseStream())));
            }
            catch (WebException webException)
            {
                string message = GetResponseString(webException.Response.GetResponseStream());
                throw new Exception(webException.Message + " - " + message);
            }
        }
Пример #20
0
        /// <summary>
        /// Sends the specified request URI string.
        /// </summary>
        /// <param name="requestUriString">The request URI string.</param>
        /// <param name="method">The method.</param>
        /// <param name="queryStringData">The query string data.</param>
        /// <param name="formData">The form data.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static RockWebResponse Send( string requestUriString, string method, Dictionary<string, string> queryStringData, Dictionary<string, string> formData )
        {
            string uri = requestUriString;

            if ( queryStringData != null )
            {
                string parms = queryStringData.Join( "&" );
                if ( parms.Trim() != string.Empty )
                    uri += ( uri.Contains( "?" ) ? "&" : "?" ) + parms;
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( uri );

            request.Method = method;

            if ( formData != null && formData.Count > 0 )
            {
                byte[] postData = ASCIIEncoding.ASCII.GetBytes( formData.Join( "&" ) );

                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write( postData, 0, postData.Length );
                requestStream.Close();
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                return new RockWebResponse( response.StatusCode, GetResponseString( response.GetResponseStream() ) );
            }
            catch ( WebException webException )
            {
                string message = GetResponseString( webException.Response.GetResponseStream() );
                throw new Exception( webException.Message + " - " + message );
            }
        }
Пример #21
0
        /// <summary>
        /// Binds the registrations grid.
        /// </summary>
        private void BindRegistrationsGrid()
        {
            int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull();
            if ( instanceId.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) );

                    var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value );
                    _instanceHasCost = instance != null && instance.RegistrationTemplate.Cost > 0.0m;

                    var qry = new RegistrationService( rockContext )
                        .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" )
                        .AsNoTracking()
                        .Where( r => r.RegistrationInstanceId == instanceId.Value );

                    if ( drpRegistrationDateRange.LowerValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value );
                    }
                    if ( drpRegistrationDateRange.UpperValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) )
                    {
                        string pfname = tbRegistrationRegisteredByFirstName.Text;
                        qry = qry.Where( r =>
                            r.FirstName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.NickName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.FirstName.StartsWith( pfname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) )
                    {
                        string plname = tbRegistrationRegisteredByLastName.Text;
                        qry = qry.Where( r =>
                            r.LastName.StartsWith( plname ) ||
                            r.PersonAlias.Person.LastName.StartsWith( plname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) )
                    {
                        string rfname = tbRegistrationRegistrantFirstName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.NickName.StartsWith( rfname ) ||
                                p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) )
                    {
                        string rlname = tbRegistrationRegistrantLastName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.LastName.StartsWith( rlname ) ) );
                    }

                    // If filtering on payment status, need to do some sub-querying...
                    if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null )
                    {
                        // Get all the registrant costs
                        var rCosts = new Dictionary<int, decimal>();
                        qry
                            .Select( r => new
                            {
                                RegistrationId = r.Id,
                                Costs = r.Registrants.Sum( p => p.Cost ),
                                Fees = r.Registrants.SelectMany( p => p.Fees ).Sum( f => f.Cost )
                            } ).ToList()
                            .ForEach( c =>
                                rCosts.AddOrReplace( c.RegistrationId, c.Costs + c.Fees ) );

                        var rPayments = new Dictionary<int, decimal>();
                        new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                rCosts.Keys.Contains( d.EntityId.Value ) )
                            .Select( d => new
                            {
                                RegistrationId = d.EntityId.Value,
                                Payment = d.Amount
                            } )
                            .ToList()
                            .GroupBy( d => d.RegistrationId )
                            .Select( d => new
                            {
                                RegistrationId = d.Key,
                                Payments = d.Sum( p => p.Payment )
                            } )
                            .ToList()
                            .ForEach( p =>
                                rPayments.AddOrReplace( p.RegistrationId, p.Payments ) );

                        var rPmtSummary = rCosts
                            .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new
                            {
                                RegistrationId = c.Key,
                                Costs = c.Value,
                                Payments = p.Value
                            } )
                            .ToList();

                        var ids = new List<int>();

                        if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" )
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs <= r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }
                        else
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs > r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }

                        qry = qry.Where( r => ids.Contains( r.Id ) );
                    }

                    IOrderedQueryable<Registration> orderedQry = null;
                    SortProperty sortProperty = gRegistrations.SortProperty;
                    if ( sortProperty != null )
                    {
                        orderedQry = qry.Sort( sortProperty );
                    }
                    else
                    {
                        orderedQry = qry.OrderByDescending( r => r.CreatedDateTime );
                    }

                    gRegistrations.SetLinqDataSource( orderedQry );

                    // Get all the payments for any registrations being displayed on the current page.
                    // This is used in the RowDataBound event but queried now so that each row does
                    // not have to query for the data.
                    var currentPageRegistrations = gRegistrations.DataSource as List<Registration>;
                    if ( currentPageRegistrations != null && registrationEntityType != null )
                    {
                        var registrationIds = currentPageRegistrations
                            .Select( r => r.Id )
                            .ToList();

                        RegistrationPayments = new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                registrationIds.Contains( d.EntityId.Value ) )
                            .ToList();
                    }

                    gRegistrations.DataBind();
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Binds the registrations grid.
        /// </summary>
        private void BindRegistrationsGrid()
        {
            int?instanceId = this.RegistrationInstanceId;

            if (instanceId.HasValue && instanceId > 0)
            {
                using (var rockContext = new RockContext())
                {
                    var registrationEntityType = EntityTypeCache.Get(typeof(Rock.Model.Registration));

                    var instance = new RegistrationInstanceService(rockContext).Get(instanceId.Value);
                    if (instance != null)
                    {
                        decimal cost = instance.RegistrationTemplate.Cost;
                        if (instance.RegistrationTemplate.SetCostOnInstance ?? false)
                        {
                            cost = instance.Cost ?? 0.0m;
                        }

                        _instanceHasCost = cost > 0.0m;
                    }

                    var qry = new RegistrationService(rockContext)
                              .Queryable("PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee")
                              .AsNoTracking()
                              .Where(r =>
                                     r.RegistrationInstanceId == instanceId.Value &&
                                     !r.IsTemporary);

                    var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(sdrpRegistrationDateRange.DelimitedValues);

                    if (dateRange.Start.HasValue)
                    {
                        qry = qry.Where(r =>
                                        r.CreatedDateTime.HasValue &&
                                        r.CreatedDateTime.Value >= dateRange.Start.Value);
                    }

                    if (dateRange.End.HasValue)
                    {
                        qry = qry.Where(r =>
                                        r.CreatedDateTime.HasValue &&
                                        r.CreatedDateTime.Value < dateRange.End.Value);
                    }

                    if (!string.IsNullOrWhiteSpace(tbRegistrationRegisteredByFirstName.Text))
                    {
                        string pfname = tbRegistrationRegisteredByFirstName.Text;
                        qry = qry.Where(r =>
                                        r.FirstName.StartsWith(pfname) ||
                                        r.PersonAlias.Person.NickName.StartsWith(pfname) ||
                                        r.PersonAlias.Person.FirstName.StartsWith(pfname));
                    }

                    if (!string.IsNullOrWhiteSpace(tbRegistrationRegisteredByLastName.Text))
                    {
                        string plname = tbRegistrationRegisteredByLastName.Text;
                        qry = qry.Where(r =>
                                        r.LastName.StartsWith(plname) ||
                                        r.PersonAlias.Person.LastName.StartsWith(plname));
                    }

                    if (!string.IsNullOrWhiteSpace(tbRegistrationRegistrantFirstName.Text))
                    {
                        string rfname = tbRegistrationRegistrantFirstName.Text;
                        qry = qry.Where(r =>
                                        r.Registrants.Any(p =>
                                                          p.PersonAlias.Person.NickName.StartsWith(rfname) ||
                                                          p.PersonAlias.Person.FirstName.StartsWith(rfname)));
                    }

                    if (!string.IsNullOrWhiteSpace(tbRegistrationRegistrantLastName.Text))
                    {
                        string rlname = tbRegistrationRegistrantLastName.Text;
                        qry = qry.Where(r =>
                                        r.Registrants.Any(p =>
                                                          p.PersonAlias.Person.LastName.StartsWith(rlname)));
                    }

                    // If filtering on payment status, need to do some sub-querying...
                    if (ddlRegistrationPaymentStatus.SelectedValue != string.Empty && registrationEntityType != null)
                    {
                        // Get all the registrant costs
                        var rCosts = new Dictionary <int, decimal>();
                        qry.ToList()
                        .Select(r => new
                        {
                            RegistrationId = r.Id,
                            DiscountCosts  = r.Registrants.Sum(p => ( decimal? )p.DiscountedCost(r.DiscountPercentage, r.DiscountAmount)) ?? 0.0m,
                        }).ToList()
                        .ForEach(c =>
                                 rCosts.AddOrReplace(c.RegistrationId, c.DiscountCosts));

                        var rPayments = new Dictionary <int, decimal>();
                        new FinancialTransactionDetailService(rockContext)
                        .Queryable().AsNoTracking()
                        .Where(d =>
                               d.EntityTypeId.HasValue &&
                               d.EntityId.HasValue &&
                               d.EntityTypeId.Value == registrationEntityType.Id &&
                               rCosts.Keys.Contains(d.EntityId.Value))
                        .Select(d => new
                        {
                            RegistrationId = d.EntityId.Value,
                            Payment        = d.Amount
                        })
                        .ToList()
                        .GroupBy(d => d.RegistrationId)
                        .Select(d => new
                        {
                            RegistrationId = d.Key,
                            Payments       = d.Sum(p => p.Payment)
                        })
                        .ToList()
                        .ForEach(p => rPayments.AddOrReplace(p.RegistrationId, p.Payments));

                        var rPmtSummary = rCosts
                                          .Join(
                            rPayments,
                            c => c.Key,
                            p => p.Key,
                            (c, p) => new
                        {
                            RegistrationId = c.Key,
                            Costs          = c.Value,
                            Payments       = p.Value
                        })
                                          .ToList();

                        var ids = new List <int>();

                        if (ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full")
                        {
                            ids = rPmtSummary
                                  .Where(r => r.Costs <= r.Payments)
                                  .Select(r => r.RegistrationId)
                                  .ToList();
                        }
                        else
                        {
                            ids = rPmtSummary
                                  .Where(r => r.Costs > r.Payments)
                                  .Select(r => r.RegistrationId)
                                  .ToList();
                        }

                        qry = qry.Where(r => ids.Contains(r.Id));
                    }

                    SortProperty sortProperty = gRegistrations.SortProperty;
                    if (sortProperty != null)
                    {
                        // If sorting by Total Cost or Balance Due, the database query needs to be run first without ordering,
                        // and then ordering needs to be done in memory since TotalCost and BalanceDue are not database fields.
                        if (sortProperty.Property == "TotalCost")
                        {
                            if (sortProperty.Direction == SortDirection.Ascending)
                            {
                                gRegistrations.SetLinqDataSource(qry.ToList().OrderBy(r => r.TotalCost).AsQueryable());
                            }
                            else
                            {
                                gRegistrations.SetLinqDataSource(qry.ToList().OrderByDescending(r => r.TotalCost).AsQueryable());
                            }
                        }
                        else if (sortProperty.Property == "BalanceDue")
                        {
                            if (sortProperty.Direction == SortDirection.Ascending)
                            {
                                gRegistrations.SetLinqDataSource(qry.ToList().OrderBy(r => r.BalanceDue).AsQueryable());
                            }
                            else
                            {
                                gRegistrations.SetLinqDataSource(qry.ToList().OrderByDescending(r => r.BalanceDue).AsQueryable());
                            }
                        }
                        else if (sortProperty.Property == "RegisteredBy")
                        {
                            // Sort by the Person name if we have it, otherwise the provided first and last name.
                            Func <Registration, string> sortBy = (r) =>
                            {
                                return(r.PersonAlias != null && r.PersonAlias.Person != null ? r.PersonAlias.Person.FullNameReversed : string.Format("{0}, {1}", r.LastName, r.FirstName));
                            };

                            if (sortProperty.Direction == SortDirection.Ascending)
                            {
                                gRegistrations.SetLinqDataSource(qry.ToList().OrderBy(sortBy).AsQueryable());
                            }
                            else
                            {
                                gRegistrations.SetLinqDataSource(qry.ToList().OrderByDescending(sortBy).AsQueryable());
                            }
                        }
                        else
                        {
                            gRegistrations.SetLinqDataSource(qry.Sort(sortProperty));
                        }
                    }
                    else
                    {
                        gRegistrations.SetLinqDataSource(qry.OrderByDescending(r => r.CreatedDateTime));
                    }

                    // Get all the payments for any registrations being displayed on the current page.
                    // This is used in the RowDataBound event but queried now so that each row does
                    // not have to query for the data.
                    var currentPageRegistrations = gRegistrations.DataSource as List <Registration>;
                    if (currentPageRegistrations != null && registrationEntityType != null)
                    {
                        var registrationIds = currentPageRegistrations
                                              .Select(r => r.Id)
                                              .ToList();

                        _registrationPayments = new FinancialTransactionDetailService(rockContext)
                                                .Queryable().AsNoTracking()
                                                .Where(d =>
                                                       d.EntityTypeId.HasValue &&
                                                       d.EntityId.HasValue &&
                                                       d.EntityTypeId.Value == registrationEntityType.Id &&
                                                       registrationIds.Contains(d.EntityId.Value))
                                                .ToList();
                    }

                    var discountCodeHeader = gRegistrations.GetColumnByHeaderText("Discount Code");
                    if (discountCodeHeader != null)
                    {
                        discountCodeHeader.Visible = GetAttributeValue(AttributeKey.DisplayDiscountCodes).AsBoolean();
                    }

                    gRegistrations.DataBind();
                }
            }
        }
Пример #23
0
 public static Dictionary <T1, T2> MERGE <T1, T2>(Dictionary <T1, T2> xs, Dictionary <T1, T2> ys) => xs.Except(xs.Join(ys, z => z.Key, z => z.Key, (a, b) => a)).Concat(ys).ToDictionary(z => z.Key, z => z.Value);
Пример #24
0
        private void WriteCluster(string path, int numClusters, int numRatings, Func<ItemRating, string> fieldSelector,
            bool writeRatingHistogram, string centerPath = "")
        {
            Console.WriteLine("Prepating data for clustering...");

            var items = _dataset.AllSamples.GroupBy(ir => fieldSelector(ir))
                .Select(g => new
                {
                    ItemId = g.Key,
                    RatingVector = g.GroupBy(ir => ir.Rating)
                        .Select(gg => new { Rate = Convert.ToInt32(gg.Key), Count = gg.Count() }).OrderBy(v => v.Rate)
                }).OrderBy(u => u.ItemId).ToList();

            int numItems = items.Count();

            double[,] features = new double[numItems, numRatings];
            Dictionary<string, string> histograms = new Dictionary<string,string>();

            int ix = 0;
            items.ForEach(i =>
            {
                string histLine = "";

                for (int j = 0; j < numRatings; j++)
                {
                    features[ix, j] = i.RatingVector.Where(rv => rv.Rate == (j + 1)).Select(rv => rv.Count).SingleOrDefault();
                    histLine += features[ix, j] + (j != (numRatings - 1) ? "," : "");
                }
                ix++;
                histograms.Add(i.ItemId, histLine);
            });

            var clusters = Cluster(items.Select(u => u.ItemId), features, numClusters, centerPath);
            var output = clusters.Select(c => string.Format("{0},{1}", c.Key, c.Value));
            File.WriteAllLines(path, output);

            if (writeRatingHistogram)
            {
                Console.WriteLine("Writing item histograms...");

                var hist = histograms.Join(clusters, h => h.Key, c => c.Key, (h, c) => new { Hist = h, Cluster = c })
                    .OrderBy(i => i.Cluster.Value);

                var histOutput = hist.Select(h => string.Format("{0},{1},{2}",
                    h.Cluster.Value,
                    h.Hist.Key,
                    h.Hist.Value
                ));

                var header = new string[] { "ClusterId,ItemId,R1,R2,R3,R4,R5" };

                File.WriteAllLines(path + ".hist", header.Concat(histOutput));
            }
        }
Пример #25
0
        /// <summary>
        /// Returns time series of all recoveries, deaths, covid cases for all the locations.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns>Time</returns>
        public async Task <IEnumerable <TimeSeries>?> GetTimeSeriesAsync(CancellationToken cancellationToken = default)
        {
            var results = await LoadDataAsync(cancellationToken).ConfigureAwait(false);

            if (results.Any(r => r.IsFailed))
            {
                var errors = results
                             .Where(r => r.IsFailed)
                             .SelectMany(r => r.Errors);

                throw new CovidClientException(errors);
            }
            ;


            Dictionary <string, Dictionary <DateTime, int?> >?globalConfirmed = Parser
                                                                                .Parse <TimeSeriesRaw, TimeSeriesRawMap>(results[0].Value)
                                                                                .ToDictionary(o => $"{o.CountryOrRegion}-{o.ProvinceOrState}", o => o.Data);

            var globalRecovered = Parser
                                  .Parse <TimeSeriesRaw, TimeSeriesRawMap>(results[1].Value)
                                  .ToDictionary(o => $"{o.CountryOrRegion}-{o.ProvinceOrState}", o => o.Data);

            var globalDeaths = Parser
                               .Parse <TimeSeriesRaw, TimeSeriesRawMap>(results[2].Value)
                               .ToDictionary(o => $"{o.CountryOrRegion}-{o.ProvinceOrState}", o => o.Data);

            IEnumerable <TimeSeries>?combined = globalConfirmed
                                                .Join(
                globalDeaths,
                confirmed => confirmed.Key,
                deaths => deaths.Key,
                (c, d) => new
            {
                Location  = c.Key,
                Confirmed = c.Value,
                Deaths    = d.Value
            }
                )
                                                .Join(
                globalRecovered,
                cmb => cmb.Location,
                recovered => recovered.Key,
                (cmb, rec) =>
            {
                var data = GetDataPoints(cmb.Deaths, cmb.Confirmed, rec.Value);
                return(new TimeSeries
                {
                    Location = cmb.Location,
                    Data = data
                });
            }
                );

            //var usaConfirmed = parser
            //    .Parse<TimeSeries, TimeSeriesMap>(results[3].Value);

            //var usaDeaths = parser
            //    .Parse<TimeSeries, TimeSeriesMap>(results[4].Value)

            return(combined);
        }
Пример #26
0
        public async Task <(IEnumerable <GestorModel>, Dictionary <string, string>)> GestoresPadraoEnvio(int c, int?u, Dictionary <string, string> padrao)
        {
            using (var conn = new SqlConnection(Util.ConnString))
            {
                await conn.OpenAsync();

                try
                {
                    var p = new DynamicParameters();
                    p.Add("ClienteID", c, DbType.Int32, ParameterDirection.Input);
                    p.Add("Padrao", padrao.Select(a => a.Key).Aggregate((a, b) => $"{a.ToUpper()},{b.ToUpper()}"), DbType.String, ParameterDirection.Input);

                    var result = await conn.QueryAsync(@"SELECT G.NOME, G.EMAIL, G.CARTEIRA, G.TELEFONE, PP.CARTEIRAID, PP.TIPOCAMPANHAID, T.TIPOCAMPANHA, PP.PADRAO  FROM PADRAO_POSTAGENS PP 
														JOIN TIPOCAMPANHA T ON PP.TIPOCAMPANHAID=T.CODIGO
														JOIN string_split(@Padrao, ',') S ON PP.PADRAO=S.VALUE
														JOIN GESTORESSMS G ON PP.CARTEIRAID=G.CARTEIRAID AND PP.CLIENTEID=G.CLIENTEID WHERE PP.CLIENTEID=@ClienteID"                                                        , p, commandTimeout : Util.TIMEOUTEXECUTE);

                    if (result != null)
                    {
                        var dados = result.GroupBy(a => new
                        {
                            Nome          = (string)a.NOME,
                            ArquivoPadrao = (string)a.PADRAO
                        },
                                                   (a, b) => new GestorModel()
                        {
                            Nome          = a.Nome,
                            ArquivoPadrao = a.ArquivoPadrao,
                            Carteiras     = b.Where(k => k.CARTEIRA != null).GroupBy(k => new { k.CARTEIRA, k.CARTEIRAID }, (m, n) => new CarteiraModel()
                            {
                                Carteira = m.CARTEIRA, CarteiraID = m.CARTEIRAID
                            }).ToList(),
                            Emails       = b.Where(k => k.EMAIL != null).GroupBy(k => k.EMAIL, (m, n) => (string)m).ToList(),
                            TipoCampanha = b.Where(k => k.TIPOCAMPANHA != null).GroupBy(k => k.TIPOCAMPANHA, (k, n) => new TipoCampanhaModel()
                            {
                                TipoCampanha = k.TIPOCAMPANHA, TipoCampanhaID = k.TIPOCAMPANHA
                            }),
                            Telefones = b.Where(k => k.TELEFONE != null).GroupBy(k => k.TELEFONE, (m, n) => (decimal)m).ToList(),
                        });

                        var _dic = new Dictionary <string, string>();
                        foreach (var item in padrao.Join(dados, a => a.Key, b => b.ArquivoPadrao, (a, b) => new { Key = a.Key, Value = a.Value }))
                        {
                            if (!_dic.ContainsKey(item.Key))
                            {
                                _dic.Add(item.Key, item.Value);
                            }
                        }



                        return(dados, _dic);
                    }



                    return(new GestorModel[] { }, null);
                }
                catch (Exception err)
                {
                    throw err;
                }
                finally
                {
                    conn.Close();
                }
            }
        }
Пример #27
0
        private void ReinitializeSearchContainers(Dictionary<string, List<string>> Containers)
        {
            if (Containers == null)
            {
                // No search restrictions (search entire domain)
                foreach (var domain in this.Domains)
                    domain.UpdateSearchEntireDomain();
            }
            else
            {
                // Restrict search containers
                var searchContainerDomains = Containers.Join(this.Domains, ok => ok.Key, ik => ik.Name, (o, i) => Tuple.Create(o, i), StringComparer.OrdinalIgnoreCase);
                foreach (var domainContainers in searchContainerDomains)
                    domainContainers.Item2.UpdateSearchContainers(domainContainers.Item1.Value);

                // Ignore domains without configured containers
                var unconfiguredContainers = this.Domains.Except(searchContainerDomains.Select(sc => sc.Item2));
                foreach (var domain in unconfiguredContainers)
                    domain.UpdateSearchContainers(new List<string>());
            }
        }
Пример #28
0
        public static void Run()
        {
            BoardRectangle = new Rectangle(0, 0, 400, 400);

            Console.WindowWidth  = 85;
            Console.WindowHeight = 50;
            Console.BufferWidth  = 85;
            Console.BufferHeight = 50;

            ownedAreas = new Dictionary <int, List <Point> >();
            var lines   = File.ReadLines("input.txt");
            var viruses = new Dictionary <int, Virus>();
            int virusId = 1;

            Board board = new Board();

            foreach (var line in lines)
            {
                var parts = line.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                var point = new Point(int.Parse(parts[0]), int.Parse(parts[1]));

                var virus = new Virus {
                    Id = virusId++
                };

                viruses.Add(virus.Id, virus);
                virus.SetOrigin(board, point);
                virus.Open.Push(point);
            }

            bool boardChanged = true;

            int maxChanges = 100000;
            int changes    = 0;

            do
            {
                bool claimedRound          = ClaimRound(viruses, board);
                bool administeredOwnership = AdministerOwnership(board);
                boardChanged = claimedRound || administeredOwnership;
                changes++;

                //Console.Clear();

                //int visualizeWidth = 80;
                //int visualizeHeight = 50;

                //int fromTop = 171;
                //int fromLeft = 222;

                //for (int x = 0 + fromLeft; x < visualizeWidth + fromLeft; x++) {
                //    for (int y = 0 + fromTop; y < visualizeHeight + fromTop; y++) {
                //        Console.SetCursorPosition(x - fromLeft, y - fromTop);
                //        var area = board.GetArea(new Point(x, y));

                //        int n = 0;
                //        if (n < 4 && area.State == Area.AreaState.Start) {
                //            n = 4;
                //        } else if (n < 3 && area.State == Area.AreaState.Owned) {
                //            n = 3;
                //        } else if (n < 2 && area.State == Area.AreaState.Claimed) {
                //            n = 2;
                //        } else if (n < 1 && area.State == Area.AreaState.Equidistant) {
                //            n = 1;
                //        }

                //        Console.Write(n == 0 ? " " : n == 1 ? "." : n == 2 ? "C" : n == 3 ? "o" : "S");
                //    }
                //}


                //Console.SetCursorPosition(0, 0);
                //Console.WriteLine("OwnedAreasCount: " + OwnedAreasCount);

                //var virus = viruses[1];
                //Console.WriteLine("");
                //Console.WriteLine("Virus 1 - IsInfinite: " + virus.IsInfinite.ToString());
                //Console.WriteLine("Virus 1 - Open #: " + virus.Open.Count);
                //Console.WriteLine("Virus 1 - Owned: " + ownedAreas[1].Count);

                //Console.ReadKey(true);
            } while (boardChanged && changes < maxChanges);

            var maxAreaCountObject = ownedAreas.Join(viruses, x => x.Key, x => x.Key, (oa, v) => new { Virus = v.Value, IsInfinite = v.Value.IsInfinite, AreasCount = oa.Value.Count })
                                     .Where(x => x.IsInfinite == false)
                                     .OrderByDescending(x => x.AreasCount).First();

            Console.WriteLine("Max Areas Count: " + maxAreaCountObject.AreasCount);

            if (changes == maxChanges)
            {
                Console.WriteLine("Max Changes met.");
            }
        }
        /// <summary>
        /// Binds the registrations grid.
        /// </summary>
        private void BindRegistrationsGrid()
        {
            int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull();
            if ( instanceId.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) );

                    var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value );
                    decimal cost = instance.RegistrationTemplate.Cost;
                    if ( instance.RegistrationTemplate.SetCostOnInstance ?? false )
                    {
                        cost = instance.Cost ?? 0.0m;
                    }
                    _instanceHasCost = cost > 0.0m;

                    var qry = new RegistrationService( rockContext )
                        .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" )
                        .AsNoTracking()
                        .Where( r =>
                            r.RegistrationInstanceId == instanceId.Value &&
                            !r.IsTemporary );

                    if ( drpRegistrationDateRange.LowerValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value );
                    }
                    if ( drpRegistrationDateRange.UpperValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) )
                    {
                        string pfname = tbRegistrationRegisteredByFirstName.Text;
                        qry = qry.Where( r =>
                            r.FirstName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.NickName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.FirstName.StartsWith( pfname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) )
                    {
                        string plname = tbRegistrationRegisteredByLastName.Text;
                        qry = qry.Where( r =>
                            r.LastName.StartsWith( plname ) ||
                            r.PersonAlias.Person.LastName.StartsWith( plname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) )
                    {
                        string rfname = tbRegistrationRegistrantFirstName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.NickName.StartsWith( rfname ) ||
                                p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) )
                    {
                        string rlname = tbRegistrationRegistrantLastName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.LastName.StartsWith( rlname ) ) );
                    }

                    // If filtering on payment status, need to do some sub-querying...
                    if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null )
                    {
                        // Get all the registrant costs
                        var rCosts = new Dictionary<int, decimal>();
                        qry.ToList()
                            .Select( r => new
                            {
                                RegistrationId = r.Id,
                                DiscountCosts = r.Registrants.Sum( p => (decimal?)( p.DiscountedCost( r.DiscountPercentage, r.DiscountAmount) ) ) ?? 0.0m,
                            } ).ToList()
                            .ForEach( c =>
                                rCosts.AddOrReplace( c.RegistrationId, c.DiscountCosts ) );

                        var rPayments = new Dictionary<int, decimal>();
                        new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                rCosts.Keys.Contains( d.EntityId.Value ) )
                            .Select( d => new
                            {
                                RegistrationId = d.EntityId.Value,
                                Payment = d.Amount
                            } )
                            .ToList()
                            .GroupBy( d => d.RegistrationId )
                            .Select( d => new
                            {
                                RegistrationId = d.Key,
                                Payments = d.Sum( p => p.Payment )
                            } )
                            .ToList()
                            .ForEach( p =>
                                rPayments.AddOrReplace( p.RegistrationId, p.Payments ) );

                        var rPmtSummary = rCosts
                            .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new
                            {
                                RegistrationId = c.Key,
                                Costs = c.Value,
                                Payments = p.Value
                            } )
                            .ToList();

                        var ids = new List<int>();

                        if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" )
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs <= r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }
                        else
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs > r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }

                        qry = qry.Where( r => ids.Contains( r.Id ) );
                    }

                    SortProperty sortProperty = gRegistrations.SortProperty;
                    if ( sortProperty != null )
                    {
                        // If sorting by Total Cost or Balance Due, the database query needs to be run first without ordering,
                        // and then ordering needs to be done in memory since TotalCost and BalanceDue are not databae fields.
                        if ( sortProperty.Property == "TotalCost" )
                        {
                            if ( sortProperty.Direction == SortDirection.Ascending )
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.TotalCost ).AsQueryable() );
                            }
                            else
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.TotalCost ).AsQueryable() );
                            }
                        }
                        else if ( sortProperty.Property == "BalanceDue" )
                        {
                            if ( sortProperty.Direction == SortDirection.Ascending )
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.BalanceDue ).AsQueryable() );
                            }
                            else
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.BalanceDue ).AsQueryable() );
                            }
                        }
                        else
                        {
                            gRegistrations.SetLinqDataSource( qry.Sort( sortProperty ) );
                        }
                    }
                    else
                    {
                        gRegistrations.SetLinqDataSource( qry.OrderByDescending( r => r.CreatedDateTime ) );
                    }

                    // Get all the payments for any registrations being displayed on the current page.
                    // This is used in the RowDataBound event but queried now so that each row does
                    // not have to query for the data.
                    var currentPageRegistrations = gRegistrations.DataSource as List<Registration>;
                    if ( currentPageRegistrations != null && registrationEntityType != null )
                    {
                        var registrationIds = currentPageRegistrations
                            .Select( r => r.Id )
                            .ToList();

                        RegistrationPayments = new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                registrationIds.Contains( d.EntityId.Value ) )
                            .ToList();
                    }

                    var discountCodeHeader = gRegistrations.Columns.GetColumnByHeaderText( "Discount Code" );
                    if ( discountCodeHeader != null )
                    {
                        discountCodeHeader.Visible = GetAttributeValue( "DisplayDiscountCodes" ).AsBoolean();
                    }

                    gRegistrations.DataBind();
                }
            }
        }
Пример #30
0
 private string ConstructBusinessParameters(Dictionary <string, string> parameters)
 {
     return(parameters.Join("", p => string.Format("<{0}>{1}</{0}>", p.Key, p.Value)));
 }
Пример #31
0
        public void RunLinqs()
        {
            IEnumerable<int> tablica = new int[] {2, 4, 3, 5, 2, 3};

            var lista = tablica.ToList(); // gen lista
            // List<int>

            int[] tabOfInts = {1, 2, 3, 1, 5, 4, 3};

            int sum = tabOfInts.Sum(); // 19

            var result = lista.Where(item => item == 3);// 2

            lista.Add(3);
            lista.Add(3);
            lista.Add(3);
            lista.Add(3);
            lista.Add(3);

            var icoteraz = result.ToArray();

            var ile = icoteraz.Length; // 7 !!!!

            lista.Add(3);

            var final = result.ToArray();

            Dictionary<string, string> klienci = new Dictionary<string, string>
            {
                { "30102061274627621478132", "Jas wedrowniczek"},
                { "30105061274627621478132", "Jas fasola"},
                { "30103061274627621478132", "johnny english"},
                { "30107061274627621478132", "jan kowalski"},
            };

            Dictionary<string, string> banki = new Dictionary<string, string>
            {
                { "1020", "Ing"},
                { "1030", "Pko"},
                { "1040", "nordea"},
                { "1050", "mbank"},
            };

            var chosenbank = banki.Where(item => item.Value == "mbank").Select(item => new MyExampleOfHomework());//string.Format("{0} to kod banku {1}", item.Key, item.Value));

            //banki.Add("1020", "dsfsdfasd");
            banki.Add("1060", "bzwbk");

            //IEqualityComparer<string> dsa;

            //dsa.

            var jazda = chosenbank.ToArray();
            //  nr konta , nazwa banku, klient
            var wynik = klienci.Join(
                banki,
                klienciSelector => klienciSelector.Key.Substring(2, 4),
                bankiSelector => bankiSelector.Key,
                (klient, bank) => new BankTransfer {Konto = klient.Key, NazwaBanku = bank.Value, Klient = klient.Value});

            var testhaha = wynik.Count();

            klienci.Add("121111", "szyfrant");
        }
Пример #32
0
        public void BuildRequestTest2(String method, String action, String argKind)
        {
            // 几大类型参数
            Object args = null;

            switch (argKind)
            {
            case "[buffer]":
                args = Rand.NextBytes(16);
                break;

            case "[packet]":
                args = new Packet(Rand.NextBytes(16));
                break;

            case "[object]":
                args = new { name = Rand.NextString(8), code = Rand.Next() };
                break;

            case "[dictionary]":
                var dic = new Dictionary <String, Object>
                {
                    ["aaa"] = Rand.NextString(16),
                    ["bbb"] = Rand.Next(1000, 9999),
                    ["ccc"] = Rand.Next()
                };
                args = dic;
                break;
            }

            // 建立请求
            var md      = new HttpMethod(method);
            var request = ApiHelper.BuildRequest(md, action, args);

            // 无论如何,请求方法不会错
            Assert.NotNull(request);
            Assert.Equal(method, request.Method.Method);

            // Get有url参数,而Post没有
            var uri   = request.RequestUri + "";
            var query = uri.Substring("?");

            switch (method)
            {
            case "Get":
                Assert.NotEqual(action, request.RequestUri + "");
                Assert.NotEmpty(query);
                Assert.Null(request.Content);

                // 对象和字典有特殊处理方式
                if (argKind == "[object]")
                {
                    Assert.Equal(args.ToDictionary().Join("&", k => $"{k.Key}={k.Value}"), query);
                }
                else if (argKind == "[dictionary]" && args is IDictionary <String, Object> dic)
                {
                    Assert.Equal(dic.Join("&", k => $"{k.Key}={k.Value}"), query);
                }
                break;

            case "Post":
            case "Put":
                Assert.Equal(action, request.RequestUri + "");
                Assert.Null(query);
                Assert.NotNull(request.Content);

                // 不同参数类型,有不同的请求内容类型
                var content = request.Content;
                switch (argKind)
                {
                case "[buffer]":
                    Assert.Equal("application/octet-stream", content.Headers.ContentType + "");
                    Assert.Equal((args as Byte[]).ToHex(), content.ReadAsByteArrayAsync().Result.ToHex());
                    break;

                case "[packet]":
                    Assert.Equal("application/octet-stream", request.Content.Headers.ContentType + "");
                    Assert.Equal((args as Packet).ToHex(), content.ReadAsByteArrayAsync().Result.ToHex());
                    break;

                case "[object]":
                case "[dictionary]":
                    Assert.Equal("application/json", request.Content.Headers.ContentType + "");
                    Assert.Equal(args.ToJson(), content.ReadAsStringAsync().Result);
                    break;
                }
                break;

            default:
                Assert.Equal(action, request.RequestUri + "");
                Assert.Null(query);
                Assert.Null(request.Content);
                break;
            }
        }
 static void Postfix(Dictionary <IPEndPointProcessId, DistributedMatchUp.Match> ___m_remoteMatches, IPEndPointProcessId sender, DistributedMatchUp __instance)
 {
     Debug.Log(DateTime.Now.ToString() + " " + System.Diagnostics.Process.GetCurrentProcess().Id + " OnClientStateUpdate: sender " + sender + " all: " +
               ___m_remoteMatches.Join(x => x.Key + "[" + x.Value.uid + " " + x.Value.matchData.GetValueSafe("mm_ticketType") + " " + x.Value.matchData.GetValueSafe("mm_mmTickets") + "]"));
 }
Пример #34
0
        public void LinkAndLambda()
        {
            #region 1 普通筛选 lambda表达式更加优雅
            //构造数据
            List <CustomerModel> customerlist = new List <CustomerModel> {
            };
            int i = 0;
            while (i < 10)
            {
                customerlist.Add(new CustomerModel {
                    Id = i, Name = i + "哥", Age = i
                });
                i++;
            }
            //linq 查询表达式
            var linqcustomer = from customer in customerlist
                               where (customer.Age == 1 || customer.Age == 5)
                               select new { customer.Id, customer.Name, customer.Age }; // 此句不可省略否则报错

            //lambda 点表达式
            var lambdacustomer = customerlist.Where(customer => customer.Age == 1 || customer.Age == 5).ToList();

            var lambdacustomer1 = customerlist.Where(customer => customer.Age == 1 || customer.Age == 5)
                                  .Reverse()               // 逆序
                                  .Distinct()              //去重
                                  .Except(customerlist)    // 差集
                                  .Union(customerlist)     // 并集
                                  .Intersect(customerlist) // 交集
                                  .ToList();
            #endregion

            #region 2 查询两个列表中Id相等的值,多字段排序 linq表达式更加方便直接
            //var list1 = new List<CustomerModel> {
            //    new CustomerModel { Id=1,Name="张三"},
            //    new CustomerModel { Id=2,Name = "李四"},
            //    new CustomerModel { Id=3,Name="张三"},
            //    new CustomerModel { Id=4,Name = "小米"},
            //};
            //var list2 = new List<CustomerModel> {
            //    new CustomerModel { Id=1,Name="张三"},
            //    new CustomerModel { Id=2,Name = "李四"},
            //    new CustomerModel { Id=3,Name="张三"},
            //    new CustomerModel { Id=5,Name = "小米"},
            //};
            //// linq 查询表达式
            //var obj1 = from l1 in list1
            //           join l2 in list2
            //           on l1.Id equals l2.Id
            //           orderby l1.Id, l2.Id descending // 多字段不同方式排序
            //           select new { l1, l2 };
            //foreach (var item in obj1)
            //{
            //    System.Diagnostics.Debug.WriteLine(item.l1.Name.ToString() + item.l2.Name.ToString());
            //}

            //// lambda 点标记
            //var obj = list1.Join(list2, l1 => l1.Id, l2 => l2.Id, (l1, l2) => new { l1, l2 })
            //    .OrderBy(li => li.l1.Id) // 多字段不同方式排序 需要分开写
            //    .ThenByDescending(li => li.l2.Id).ToList(); // 多字段不同方式排序
            //foreach (var item in obj)
            //{
            //    System.Diagnostics.Debug.WriteLine(item.l1.Name.ToString() + item.l2.Name.ToString());
            //}
            #endregion

            #region 3.联接查询(内联、左联接、交叉联接)
            //内联查询
            var list1 = new Dictionary <int, string> {
                { 1, "小红" }, { 2, "小兰" }
            };
            var list2 = new Dictionary <int, string> {
                { 1, "小红" }, { 3, "小何" }
            };
            var linqnei = from l1 in list1
                          join l2 in list2
                          on l1.Key equals l2.Key
                          select new { l1, l2 };
            foreach (var item in linqnei)
            {
                System.Diagnostics.Debug.WriteLine(item);
            }
            var lambdanei = list1.Join(list2, l1 => l1.Key, l2 => l2.Key, (l1, l2) => new { l1, l2 }).ToList();
            foreach (var item in lambdanei)
            {
                System.Diagnostics.Debug.WriteLine(item);
            }
            // // 左联接
            //var linqleft = from l1 in list1
            //               join l2 in list2
            //               on l1.Key equals l2.Key into list
            //               from l2 in list.DefaultIfEmpty()
            //               select new { l1, l2 };
            // foreach (var item in linqleft)
            // {
            //     System.Diagnostics.Debug.WriteLine(item);
            // }
            // var lambdaleft = list1.GroupJoin(list2, l1 => l1.Key, l2 => l2.Key, (l1, l2) => new { l1, l2 = l2.FirstOrDefault() }).ToList();
            // foreach (var item in lambdaleft)
            // {
            //     System.Diagnostics.Debug.WriteLine(item);
            // }
            // // 交叉联接
            //var linq = from l1 in list1
            //           from l2 in list2
            //           select new { l1, l2 };
            // foreach (var item in linq)
            // {
            //     System.Diagnostics.Debug.WriteLine(item);
            // }
            // var lambda = list1.SelectMany(l1 => list2.Select(l2 => new { l1, l2 }));
            // foreach (var item in lambda)
            // {
            //     System.Diagnostics.Debug.WriteLine(item);
            // }
            #endregion
        }
Пример #35
0
        private void AssignValueToGrid(int size, IEnumerable <ICell> emptyCellList)
        {
            if (emptyCellList.Count() == 0)
            {
                return;
            }

            //Get All Possible Values for cell
            var allPossibleValuesForGrid = Enumerable.Range(1, size * size);

            //Generate possible values for empty cells
            var possibleCellValuesList = new Dictionary <ICell, IEnumerable <int> >();

            for (int i = 0; i < emptyCellList.Count(); i++)
            {
                var cell = emptyCellList.ElementAt(i);

                var globalY = (cell.ParentPoint.Y * size) + cell.Point.Y;
                var globalX = (cell.ParentPoint.X * size) + cell.Point.X;

                var rowList = Grid
                              .GetRowAtIndex(globalX)
                              .Where(x => x.Value.HasValue)
                              .Select(x => x.Value.Value);
                var columnList = Grid
                                 .GetColumnAtIndex(globalY)
                                 .Where(x => x.Value.HasValue)
                                 .Select(x => x.Value.Value);
                var gridList = Grid
                               .Grid[cell.ParentPoint.X, cell.ParentPoint.Y]
                               .Cells.Cast <ICell>()
                               .Where(x => x.Value.HasValue)
                               .Select(x => x.Value.Value);

                var possibleValueList = allPossibleValuesForGrid
                                        .Except(rowList)
                                        .Except(columnList)
                                        .Except(gridList);

                possibleCellValuesList.Add(cell, possibleValueList);
            }

            // Select cell which has only one entry available
            foreach (var grid in Grid.Grid)
            {
                var gridCells = grid.Cells.Cast <ICell>()
                                .Where(y => !y.Value.HasValue);
                var list = possibleCellValuesList.Join(gridCells,
                                                       s => s.Key,
                                                       q => q,
                                                       (s, q) => s);

                if (list.Any(x => x.Value.Count() == 1))
                {
                    var cellData = list
                                   .Where(x => x.Value.Count() == 1)
                                   .Select(x => x.Key)
                                   .FirstOrDefault();
                    cellData.Value = list
                                     .FirstOrDefault(x => x.Value.Count() == 1)
                                     .Value
                                     .FirstOrDefault();
                    break;
                }

                var uniqueKeyList = list
                                    .SelectMany(x => x.Value)
                                    .GroupBy(x => x)
                                    .Where(x => x.Count() == 1)
                                    .Select(x => x.Key);

                if (uniqueKeyList.Count() > 0)
                {
                    var cellData = list.Where(x => x.Value.Contains(uniqueKeyList.First())).FirstOrDefault();
                    cellData.Key.Value = uniqueKeyList.FirstOrDefault();
                    break;
                }
            }

            //if (possibleCellValuesList.Any(x => x.Value.Count() == 1))
            //{
            //    var cellValue = possibleCellValuesList.Where(x => x.Value.Count() == 1).First();
            //    cellValue.Key.Value = cellValue.Value.First();
            //}
            //else if (possibleCellValuesList.Any(x => x.Value.Count() == 2))
            //{
            //    var cellValue = possibleCellValuesList.Where(x => x.Value.Count() == 2).First();
            //    cellValue.Key.Value = cellValue.Value.First();
            //}

            var cellListRemaining = GetEmptyCellList();

            AssignValueToGrid(size, cellListRemaining);
        }
Пример #36
0
 public static void Apply()
 {
     if (oldSettings.Any())
     {
         Debug.Log("MPTweaks.Apply " + (Overload.NetworkManager.IsServer() ? "server" : "conn " + NetworkMatch.m_my_lobby_id) + " restoring to " + oldSettings.Join());
     }
     foreach (var x in oldSettings)
     {
         ApplySetting(x.Key, x.Value);
     }
     oldSettings.Clear();
     foreach (var x in settings)
     {
         oldSettings[x.Key] = ApplySetting(x.Key, x.Value);
     }
     Debug.Log("MPTweaks.Apply " + (Overload.NetworkManager.IsServer() ? "server" : "conn " + NetworkMatch.m_my_lobby_id) + " settings " + settings.Join() + " oldsettings " + oldSettings.Join());
 }
Пример #37
0
        public static IDictionary<string, int> StringValuesAndEnumInts( this Enum value )
        {
            IDictionary<string, int> ret = new Dictionary<string, int>();

            Type type = value.GetType();
            IDictionary<string, string> valuesText = new Dictionary<string, string>();
            //Look for our string value associated with fields in this enum
            foreach ( FieldInfo fi in type.GetFields() ) {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes( typeof( StringValueAttribute ), false ) as StringValueAttribute[];
                if ( attrs.Length > 0 ) {
                    valuesText.Add( attrs[0].StringValue, fi.Name );
                }

            }

            IDictionary<string, int> valuesInt = new Dictionary<string, int>();
            foreach ( var ttt in Enum.GetValues( type ) ) {
                valuesInt.Add( ttt.ToString(), ( (int)ttt ) );

            }

            var items = valuesText.Join( valuesInt,
                                    ( x ) => { return x.Value; },
                                    ( x ) => { return x.Key; },
                                    (outer, inner) =>{ return new KeyValuePair<string,int>(outer.Key,inner.Value);}

                );
            foreach(var item in items){
                ret.Add(item);
            }

            return ret;
        }