private void DrawAvailability(Graphics g)
        {
            var avail = new Dictionary<int, float> ();
            foreach (var pair in _NodeManager.GlobalAvailability ().PieceAvailability) {
                avail[pair.Key] = (float) pair.Value / _NodeManager.Nodes.Count ();
            }

            var rw = ClientRectangle.Width * 0.25f;
            var rh = rw / 5 * (float) Math.Sqrt (_NodeManager.Nodes.Count ());
            var rectPieces = new RectangleF (ClientRectangle.Width - rw, 0, rw, rh);
            Node.DrawPieceRect (g, rectPieces, avail, 100f * avail.Average (x => x.Value), true);
        }
Example #2
0
        /// <summary>
        /// Run Calculations for cost analyzer chart
        /// </summary>
        public List<Price_Data> PriceCalculator(int numberOfTrains, List<Tuple<int, double>> numberRegensNormOps, List<Tuple<int, double>> numberRegensClean, Dictionary<DateTime, Tuple<int, double, string>> throughputClean, Dictionary<DateTime, Tuple<int, double, string>> throughputNormOps, System.Data.DataTable trainList)
        {
            try
            {
                // Load calculation parameters
                double causticPrice = calculationParameters.CausticPrice;
                double acidPrice = calculationParameters.AcidPrice;
                double percentCaustic = calculationParameters.CausticConcentration * 0.01;
                double percentAcid = calculationParameters.AcidConcentration * 0.01;
                double causticUsed = calculationParameters.AmountOfCaustic;
                double acidUsed = calculationParameters.AmountOfAcid;
                double acidPriceFactor = calculationParameters.AcidPriceConversion;
                double causticPriceFactor = calculationParameters.CausticPriceConversion;
                double amountAnion = calculationParameters.AnionAmount;
                double amountCation = calculationParameters.CationAmount;

                // Account for dividing by zero for chemical concentration by making value arbitrarily small
                if (percentCaustic == 0)
                {
                    percentCaustic = 0.0001;
                }
                if (percentAcid == 0)
                {
                    percentAcid = 0.0001;
                }
                // Variable to hold entire price timeseries data
                List<Price_Data> price = new List<Price_Data>();

                // Holds the cost to regenerate data
                List<double> regenerationCostBefore = new List<double>();
                List<double> regenerationCostAfter = new List<double>();
                List<double> weeklyRegenerationsNormOps = new List<double>();
                List<double> weeklyRegenerationsClean = new List<double>();
                List<double> cleaningCostBefore = new List<double>();
                List<double> replacementCostBefore = new List<double>();
                List<double> cleaningCostAfter = new List<double>();
                List<double> replacementCostAfter = new List<double>();
                List<double> opsCostBefore = new List<double>();
                List<double> opsCostAfter = new List<double>();

                // Calculate the per regeneration before price
                int wk = 0;
                foreach (var week in numberRegensNormOps)
                {
                    Price_Data eachPrice_before = new Price_Data();
                    double costToRegenerate = (((((causticPrice * causticPriceFactor) / percentCaustic) * (causticUsed)) * amountAnion) + ((((acidPrice * acidPriceFactor) / percentAcid) * (acidUsed)) * amountCation)) * week.Item2;
                    regenerationCostBefore.Add(costToRegenerate);
                    // Check if the resin was either cleaned or replaced
                    string cleanOrReplace;
                    if (wk <= throughputNormOps.Count - 1)
                    {
                        cleanOrReplace = throughputNormOps.ElementAt(wk).Value.Item3;
                        if (cleanOrReplace == "Replace")
                        {
                            double replacmentCost = (calculationParameters.ReplacementPriceAnion + calculationParameters.ReplacemtntPriceCation) * (calculationParameters.AnionAmount + calculationParameters.CationAmount);
                            costToRegenerate = costToRegenerate + replacmentCost;
                            replacementCostBefore.Add(replacmentCost);
                        }
                        else if (cleanOrReplace == "Clean")
                        {
                            double cleaningCost = ((calculationParameters.CationCleaningPrice - (calculationParameters.CationCleaningPrice * calculationParameters.CationDiscount)) + (calculationParameters.AnionCleaningPrice - (calculationParameters.AnionCleaningPrice * calculationParameters.AnionDiscount))) * (calculationParameters.AnionAmount + calculationParameters.CationAmount);
                            costToRegenerate = costToRegenerate + cleaningCost;
                            cleaningCostBefore.Add(cleaningCost);
                        }
                        else
                        {
                            replacementCostBefore.Add(0);
                            cleaningCostBefore.Add(0);
                        }
                    }
                    opsCostBefore.Add(costToRegenerate);
                    eachPrice_before.BeforePrice = costToRegenerate;
                    eachPrice_before.WeekNumber = week.Item1;
                    price.Add(eachPrice_before);
                    weeklyRegenerationsNormOps.Add(week.Item2);

                    wk++;
                }

                int count = 0;
                wk = 0;
                // Calculate the per regeneration for the after price
                foreach (var week in numberRegensClean)
                {
                    Price_Data eachPrice_after = new Price_Data();
                    double costToRegenerate = (((((causticPrice * causticPriceFactor) / percentCaustic) * (causticUsed)) * amountAnion) + ((((acidPrice * acidPriceFactor) / percentAcid) * (acidUsed)) * amountCation)) * week.Item2;
                    regenerationCostAfter.Add(costToRegenerate);
                    // Check if the resin was either cleaned or replaced
                    if (wk <= throughputClean.Count - 1)
                    {
                        string cleanOrReplace = throughputClean.ElementAt(wk).Value.Item3;
                        if (cleanOrReplace == "Replace")
                        {
                            double replacmentCost = (calculationParameters.ReplacementPriceAnion + calculationParameters.ReplacemtntPriceCation) * (calculationParameters.AnionAmount + calculationParameters.CationAmount);
                            costToRegenerate = costToRegenerate + replacmentCost;
                            replacementCostAfter.Add(replacmentCost);
                        }
                        else if (cleanOrReplace == "Clean")
                        {
                            double cleaningCost = ((calculationParameters.CationCleaningPrice - (calculationParameters.CationCleaningPrice * calculationParameters.CationDiscount)) + (calculationParameters.AnionCleaningPrice - (calculationParameters.AnionCleaningPrice * calculationParameters.AnionDiscount))) * (calculationParameters.AnionAmount + calculationParameters.CationAmount);
                            costToRegenerate = costToRegenerate + cleaningCost;
                            cleaningCostAfter.Add(cleaningCost);
                        }
                        else
                        {
                            replacementCostAfter.Add(0);
                            cleaningCostAfter.Add(0);
                        }

                        wk++;
                    }
                    opsCostAfter.Add(costToRegenerate);
                    eachPrice_after.AfterPrice = costToRegenerate;
                    eachPrice_after.WeekNumber = week.Item1;
                    price.ElementAt(count).AfterPrice = eachPrice_after.AfterPrice;
                    count++;
                }

                // Average the cost to regenerate and update the display
                double regenCostBefore = regenerationCostBefore.Average();
                double regenCostAfter = regenerationCostAfter.Average();

                costAnalyzerResultData.RegenWeeklyCostAfter = "$" + string.Format("{0:n}", Math.Round(regenCostAfter, 2));

                // Average the cost to clean or the cost to replace and update display
                double cleanCostBefore = cleaningCostBefore.Sum();
                double cleanCostAfter = cleaningCostAfter.Sum();
                double replaceCostBefore = replacementCostBefore.Sum();
                double replaceCostAfter = replacementCostAfter.Sum();
                costAnalyzerResultData.CleaningCostBefore = "$" + string.Format("{0:n}", Math.Round(cleanCostBefore));
                costAnalyzerResultData.CleaningCostAfter = "$" + string.Format("{0:n}", Math.Round(cleanCostAfter));
                costAnalyzerResultData.ReplacementCostBefore = "$" + string.Format("{0:n}", Math.Round(replaceCostBefore));
                costAnalyzerResultData.ReplacementCostAfter = "$" + string.Format("{0:n}", Math.Round(replaceCostAfter));

                // Sum the operations cost to calculate total cost for given duration
                double absoluteTotalCostBefore = opsCostBefore.Sum();
                double absoluteTotalCostAfter = opsCostAfter.Sum();
                double averageOpsBefore = opsCostBefore.Average();
                double averageOpsAfter = opsCostAfter.Average();
                double regenSavings = (averageOpsBefore - averageOpsAfter) * throughputClean.Count;
                double cumSavings = (absoluteTotalCostBefore - absoluteTotalCostAfter) + regenSavings;
                double cumInvestment = cleanCostAfter;
                costAnalyzerResultData.TotalOpsCostBefore = "$" + string.Format("{0:n0}", Math.Round(absoluteTotalCostBefore, 0));
                costAnalyzerResultData.TotalOpsCostAfter = "$" + string.Format("{0:n0}", Math.Round(absoluteTotalCostAfter, 0));
                costAnalyzerResultData.TotalWeeklyCostBefore = "$" + string.Format("{0:n}", Math.Round(averageOpsBefore, 2));
                costAnalyzerResultData.TotalWeeklyCostAfter = "$" + string.Format("{0:n}", Math.Round(averageOpsAfter, 2));
                cumulativeSavings = "$" + string.Format("{0:n}", Math.Round(cumSavings, 2));

                // Calculate the average cost per gallon of water produced
                double totalOpsAverageBefore = opsCostBefore.Average();
                double totalOpsAverageAfter = opsCostAfter.Average();
                double beforeTPAverage = throughputNormOps.Average(x => x.Value.Item2);
                double afterTPAverage = throughputClean.Average(x => x.Value.Item2);
                double costPerGAL_Before = totalOpsAverageBefore / (beforeTPAverage / 1000);
                double costPerGAL_After = totalOpsAverageAfter / (afterTPAverage / 1000);
                costAnalyzerResultData.AvgCostPerGalBefore = "$" + string.Format("{0:n}", Math.Round(costPerGAL_Before, 2));
                costAnalyzerResultData.AvgCostPerGalAfter = "$" + string.Format("{0:n}", Math.Round(costPerGAL_After, 2));

                // Calculate the average amount of time before the customer breaks even from cleanings
                double averageCleaningCost;
                if (cleaningCostAfter != null && cleaningCostAfter.Count > 0 && cleaningCostAfter.Max() != 0)
                {
                    averageCleaningCost = cleaningCostAfter.Where(x => x != 0).Average();
                }
                else
                {
                    averageCleaningCost = 0;
                }

                double? weeksToRecoupe = WeeksUntillBreakEven(averageOpsBefore, averageOpsAfter, averageCleaningCost);

                double averageReplacingCost;
                if (replacementCostBefore.Max() != 0)
                {
                    averageReplacingCost = replacementCostBefore.Where(x => x != 0).Average();
                }
                else
                {
                    averageReplacingCost = 0;
                }
                weeksToRecoupe = WeeksUntillBreakEven(averageOpsBefore, averageOpsAfter, averageReplacingCost);
                double ROI = Math.Round((((cumSavings) - cleanCostAfter) / cleanCostAfter) * 100);
                roiGlobal = string.Format("{0:n0}", ROI) + "%";
                return price;
            }
            catch
            {
                throw;
            }
        }
Example #3
0
        public string GetReadyForNumerical(bool saveLoadedData = true)
        {
            if (ReadyForNumerical) { return "Is ready."; }

            StringBuilder log = new StringBuilder();
            Utils.StartTimer();

            log.AppendLine(Utils.PrintHeading("Create R_train/R_test sets from " + DataSetFile));
            Utils.LoadMovieLensSplitByCount(DataSetFile, out R_train,
                out R_test, MinCountOfRatings, MaxCountOfRatings, CountOfRatingsForTrain, ShuffleData, Seed);

            Console.WriteLine(R_train.DatasetBrief("Train set"));
            Console.WriteLine(R_test.DatasetBrief("Test set"));
            log.AppendLine(R_train.DatasetBrief("Train set"));
            log.AppendLine(R_test.DatasetBrief("Test set"));

            R_unknown = R_test.IndexesOfNonZeroElements();

            log.AppendLine(Utils.PrintValue("Relevant item criteria", RelevantItemCriteria.ToString("0.0")));
            RelevantItemsByUser = ItemRecommendationCore.GetRelevantItemsByUser(R_test, RelevantItemCriteria);
            log.AppendLine(Utils.PrintValue("Mean # of relevant items per user",
                RelevantItemsByUser.Average(k => k.Value.Count).ToString("0")));
            log.AppendLine(Utils.StopTimer());

            #region Prepare similarity data
            if (File.Exists(GetDataFileName("USR"))
                && File.Exists(GetDataFileName("ISR"))
                && File.Exists(GetDataFileName("SSIIR")))
            {
                Utils.StartTimer();
                Utils.PrintHeading("Load user-user similarities (rating based)");
                UserSimilaritiesOfRating = Utils.IO<SimilarityData>.LoadObject(GetDataFileName("USR"));
                Utils.StopTimer();

                Utils.StartTimer();
                Utils.PrintHeading("Load item-item similarities (rating based)");
                ItemSimilaritiesOfRating = Utils.IO<SimilarityData>.LoadObject(GetDataFileName("ISR"));
                Utils.StopTimer();

                Utils.StartTimer();
                Utils.PrintHeading("Load item-item strong similarity indicators (rating based)");
                StrongSimilarityIndicatorsByItemRating = Utils.IO<HashSet<Tuple<int, int>>>.LoadObject(GetDataFileName("SSIIR"));
                Utils.StopTimer();
            }
            else
            {
                Utils.StartTimer();
                Utils.PrintHeading("Compute user-user similarities (rating based)");
                Metric.GetPearsonOfRows(R_train, MaxCountOfNeighbors,StrongSimilarityThreshold,
                    out UserSimilaritiesOfRating);
                if (saveLoadedData) 
                {
                    Utils.IO<SimilarityData>.SaveObject(UserSimilaritiesOfRating, GetDataFileName("USR"));
                }
                Utils.StopTimer();

                Utils.StartTimer();
                Utils.PrintHeading("Compute item-item similarities (rating based)");
                Metric.GetPearsonOfColumns(R_train, MaxCountOfNeighbors, StrongSimilarityThreshold, 
                    out ItemSimilaritiesOfRating, out StrongSimilarityIndicatorsByItemRating);
                if (saveLoadedData)
                {
                    Utils.IO<SimilarityData>.SaveObject(ItemSimilaritiesOfRating, GetDataFileName("ISR"));
                    Utils.IO<HashSet<Tuple<int,int>>>
                        .SaveObject(StrongSimilarityIndicatorsByItemRating, GetDataFileName("SSIIR"));
                }
                Utils.StopTimer();
            }
            #endregion

            ReadyForNumerical = true;

            return log.ToString();
        }
Example #4
0
        private static void PrintStatistics()
        {
            var remappedDictionary = new Dictionary<long, long>();

            if (!StartTimes.Any()) return;

            foreach (var k in StartTimes)
            {
                long endTime;
                if (EndTimes.TryGetValue(k.Key, out endTime))
                {
                    remappedDictionary[k.Value] = endTime;
                }
            }

            var averageTime = remappedDictionary.Average(kv =>
            {
                return kv.Value - kv.Key;
            });

            Console.WriteLine(string.Format("\n==Average time per Fansub File parse: {0} milliseconds==", averageTime));
        }
Example #5
0
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args)
        {
            var fbEmailFile = @"../../facebook.email.dontcommit";
            var fbPasswordFile = @"../../facebook.pw.dontcommit";
            var fbAuthInfoFile = @"../../facebook.auth.dontcommit";
            var tndrAuthInfoFile = @"../../tinder.auth.dontcommit";
            var fbEmailAddress = File.ReadAllText (fbEmailFile);
            var fbPassword = File.ReadAllText (fbPasswordFile);
            var recommendationsFolderPath = "nyc_recommendations";
            var nopeFolderPath = "nope";
            var yesFolderPath = "yes";
            var startTime = DateTime.Now;
            var runForTimeSpan = new TimeSpan (4, 0, 0);
            var hitCountDictionaryFile = DateTime.Now.ToString ("MM.dd.yyyy.hh.mm.ss") + "_hitcountdict.dontcommit.txt";

            var recsIntervalRandomizer = new Random ();
            var recsIntervalTimeSpanMininum = new TimeSpan (0, 0, 1, 0);
            var recsIntervalTimeSpanMaximum = new TimeSpan (0, 0, 2, 0);

            var totalRecommendations = 0.0;
            var hitCountDictionary = new Dictionary<string, int> ();
            var disposables = new List<IDisposable> ();

            var jsonSerializer = new NewtonsoftJsonSerializer ();

            var webDriverFactory = new PhantomJSWebDriverFactory ();
            var webDriverForFacebookAuthenticator = webDriverFactory.CreateWebDriver ();
            disposables.Add (webDriverForFacebookAuthenticator);

            Console.Clear ();

            try
            {
                FacebookSession fbSession = null;

                if(File.Exists (fbAuthInfoFile))
                {
                    var fbAuthInfo = File.ReadAllLines (fbAuthInfoFile);
                    if(fbAuthInfo.Any ())
                    {
                        var fbAccessToken = fbAuthInfo[0];
                        var fbId = fbAuthInfo[1];
                        fbSession = new FacebookSession (fbAccessToken, fbId);
                    }
                }
                if(fbSession != null)
                {
                    Console.WriteLine ("Using previous Facebook session authentication.");
                }
                else
                {
                    Console.WriteLine ("Reauthenticating with Facebook...");
                    var fbAuthenticator = new SeleniumFacebookAuthenticator (webDriverForFacebookAuthenticator, fbEmailAddress, fbPassword);
                    fbSession = fbAuthenticator.Authenticate ();
                }
                if(fbSession != null)
                {
                    Console.WriteLine ("Authenticated with Facebook: '{0}'.", fbSession);
                    File.WriteAllLines (fbAuthInfoFile, new string[] { fbSession.AccessToken, fbSession.Id });
                }
                else
                {
                    Console.WriteLine ("Authentication with Facebook failed.");
                    if(File.Exists (fbAuthInfoFile))
                    {
                        File.Delete (fbAuthInfoFile);
                    }
                    goto end;
                }

                string tndrAccessToken = null;
                TndrClient tndrClient = null;

                if(File.Exists (tndrAuthInfoFile))
                {
                    var tndrAuthInfo = File.ReadAllLines (tndrAuthInfoFile);
                    if(tndrAuthInfoFile.Any ())
                    {
                        tndrAccessToken = tndrAuthInfo[0];
                    }
                }
                if(tndrAccessToken != null)
                {
                    Console.WriteLine ("Using previous Tinder session authentication.");
                    tndrClient = new TndrClient (tndrAccessToken);
                    try
                    {
                        var tndrUpdatesResponse = tndrClient.GetUpdates ();
                        if(tndrUpdatesResponse == null || tndrUpdatesResponse.LastActiveDate == null)
                        {
                            tndrAccessToken = null;
                        }
                    }
                    catch
                    {
                        tndrAccessToken = null;
                    }
                }
                if(tndrAccessToken == null)
                {
                    Console.WriteLine ("Reauthenticating with Tinder using current FacebookSession...");
                    var tndrAuthenticationResponse = TndrClient.Authenticate (fbSession);
                    if(tndrAuthenticationResponse != null)
                    {
                        tndrAccessToken = tndrAuthenticationResponse.AccessToken;
                    }
                }
                if(tndrAccessToken != null)
                {
                    Console.WriteLine ("Authenticated with Tinder: '{0}'.", tndrAccessToken);
                    File.WriteAllLines (tndrAuthInfoFile, new string[] { tndrAccessToken });
                    tndrClient = new TndrClient (tndrAccessToken);
                }
                else
                {
                    Console.WriteLine ("Authentication with Tinder failed.");
                    if(File.Exists (tndrAuthInfoFile))
                    {
                        File.Delete (tndrAuthInfoFile);
                    }
                    if(File.Exists (fbAuthInfoFile))
                    {
                        File.Delete (fbAuthInfoFile);
                    }
                    goto end;
                }

                var webClient = new WebClient ();
                disposables.Add (webClient);
                //IWebDriver photoWebDriver = null;
                while((DateTime.Now - startTime) < runForTimeSpan)
                {
                    var tndrUpdatesResponse = tndrClient.GetUpdates ();
                    if(tndrUpdatesResponse.Matches != null)
                    {
                        Console.WriteLine ("Tinder matches: {0}.", tndrUpdatesResponse.Matches.Count ());
                    }

                    var tndrReccomendationsResponse = tndrClient.GetRecommendations ();
                    if(tndrReccomendationsResponse.StatusCode != 200)
                    {
                        Console.WriteLine ("No Tinder recommendations available or requesting too fast.");
                    }
                    else
                    {
                        if(tndrReccomendationsResponse.Recommendations.Any (r => r.TinderId.StartsWith ("tinder_rate_limited_id")))
                        {
                            Console.WriteLine ("Tinder Rate Limit Reached");
                            goto end;
                        }

                        totalRecommendations += tndrReccomendationsResponse.Recommendations.Count ();
                        Console.WriteLine ("Tinder recommendations: {0}.", tndrReccomendationsResponse.Recommendations.Count ());

                        if(tndrReccomendationsResponse.Recommendations.Any ())
                        {
                            //try
                            //{
                            //	var urlTest = photoWebDriver.Url;
                            //}
                            //catch
                            //{
                            //	photoWebDriver = new FirefoxDriver ();
                            //	webDrivers.Add (photoWebDriver);
                            //}

                            foreach(var tndrRecommendation in tndrReccomendationsResponse.Recommendations)
                            {
                                if(hitCountDictionary.ContainsKey (tndrRecommendation.TinderId))
                                {
                                    hitCountDictionary[tndrRecommendation.TinderId]++;
                                }
                                else
                                {
                                    hitCountDictionary[tndrRecommendation.TinderId] = 1;
                                }

                                //photoWebDriver.Url = tndrRecommendation.Photos.First ().Url;
                                //photoWebDriver.Navigate ();
                                //photoWebDriver.FindElement (By.TagName ("body")).SendKeys (Keys.Command + "t");

                                var recommendationFolderPath = Path.Combine (recommendationsFolderPath, tndrRecommendation.TinderId);
                                var nopeRecommendationFolderPath = Path.Combine (nopeFolderPath, tndrRecommendation.TinderId);
                                var yesRecommendationFolderPath = Path.Combine (yesFolderPath, tndrRecommendation.TinderId);

                                if(!Directory.Exists (recommendationFolderPath) && !Directory.Exists (nopeRecommendationFolderPath) && !Directory.Exists (yesRecommendationFolderPath))
                                {
                                    Console.WriteLine ("\tNEW=> Name: {0, -20} Age: {1, -10} Recommended {2} time(s).", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, hitCountDictionary[tndrRecommendation.TinderId]);

                                    Directory.CreateDirectory (recommendationFolderPath);
                                    Directory.CreateDirectory (Path.Combine (recommendationFolderPath, "photos"));
                                    var recommendationFile = Path.Combine (recommendationFolderPath, string.Format ("{0}_{1}_{2}.txt", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, tndrRecommendation.TinderId));
                                    File.WriteAllText (recommendationFile, jsonSerializer.Serialize (tndrRecommendation, indented: true));

                                    foreach(var photo in tndrRecommendation.Photos)
                                    {
                                        //Console.WriteLine ("\t\tPhoto: {0}", photo.Url);

                                        var photoUri = new Uri (photo.Url);
                                        var photoFileName = Path.GetFileName (photoUri.AbsoluteUri);
                                        var photoLocalFilePath = Path.Combine (recommendationFolderPath, "photos", photoFileName);
                                        {
                                            try
                                            {
                                                webClient.DownloadFile (photoUri.ToString (), photoLocalFilePath);
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Console.WriteLine ("\tOLD=> Name: {0, -20} Age: {1, -10} Recommended {2} time(s).", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, hitCountDictionary[tndrRecommendation.TinderId]);
                                }
                            }

                            try
                            {
                                var jsonHitCountDictionary = jsonSerializer.Serialize (hitCountDictionary.OrderByDescending (h => h.Value), true);
                                File.WriteAllText (Path.Combine (recommendationsFolderPath, hitCountDictionaryFile), jsonHitCountDictionary);
                            }
                            catch
                            {
                            }
                        }
                        else
                        {
                            Console.WriteLine ("No recommendations provided.");
                        }
                    }

                    var average = hitCountDictionary.Average (x => x.Value);
                    Console.WriteLine ("Top 20 Hits:");
                    foreach(var hitCountEntry in hitCountDictionary.OrderByDescending (h => h.Value).Take (20))
                    {
                        Console.WriteLine ("\tId: {0}\tTotal Hits: {1} ({2:P2})\tLiked You: {3:P2}", hitCountEntry.Key, hitCountEntry.Value, (hitCountEntry.Value / totalRecommendations), (1 - (average / hitCountEntry.Value)));
                    }

                    Console.WriteLine ("Time left {0}...", runForTimeSpan - (DateTime.Now - startTime));
                    TimeSpan timeLapsed;
                    var sleepForMs = recsIntervalRandomizer.Next (Convert.ToInt32 (recsIntervalTimeSpanMininum.TotalMilliseconds), Convert.ToInt32 (recsIntervalTimeSpanMaximum.TotalMilliseconds));
                    var sleepForTimeSpan = TimeSpan.FromMilliseconds (sleepForMs);
                    var sleepStart = DateTime.Now;
                    while((timeLapsed = DateTime.Now - sleepStart) < sleepForTimeSpan)
                    {
                        Console.WriteLine ("Sleeping for {0} {1}", (sleepForTimeSpan - timeLapsed), GenerateProgressBar (timeLapsed.TotalMilliseconds, sleepForTimeSpan.TotalMilliseconds));

                        if(Console.KeyAvailable)
                        {
                            if(Console.ReadKey (true).Key == ConsoleKey.Escape)
                            {
                                Console.WriteLine ("\nExiting Tndr tester...");
                                goto end;
                            }
                        }

                        Console.CursorTop = Console.CursorTop - 1;
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine (ex);
            }
            finally
            {
                foreach(var webDriver in disposables)
                {
                    webDriver.Dispose ();
                }
            }
            end:
            Console.WriteLine ("Ran for {0}.", (DateTime.Now - startTime));
            Console.WriteLine ("Press enter to quit.");
            Console.ReadLine ();
        }
Example #6
0
    protected void SetReviews(string UPC)
    {
        var reviews = DBHelper.GetTable("ItemReviews").Table.AsEnumerable().Where(r => r.Field<string>("UPC") == UPC);

        this.ReviewNum.Text = reviews.Count().ToString();

        if (reviews.Count() != 0)
        {
            var rating = new Dictionary<string, double>();
            foreach(var type in new[]{ "Quality", "Features", "Performance", "Appearance", "Durability" })
            {
                rating[type] = Math.Round(reviews.Average(r => r.Field<int>(type + "Rating")));
            };

            this.ItemRating.DataSource = new ArrayList {
                new {
                    Overall = Math.Round(rating.Average(p => p.Value)),
                    Quality = rating["Quality"],
                    Features = rating["Features"],
                    Performance = rating["Performance"],
                    Appearance = rating["Appearance"],
                    Durability = rating["Durability"]
                }
            };
            this.ItemRating.DataBind();
        }

        this.ItemReviews.DataSource = reviews.AsDataView();
        this.ItemReviews.DataBind();
    }