Example #1
0
    public EBIDatasetParser()
    {
      var keymap = new Dictionary<string, ColumnName>();
      keymap["Array Data File"] = ColumnName.Sample;

      //E-MTAB-365
      keymap["Characteristics[Age]"] = ColumnName.Age;
      keymap["Characteristics[Grade::Scarff Bloom Richardson]"] = ColumnName.Grade;
      keymap["Characteristics[ESR1::Protein expression]"] = ColumnName.ER;
      keymap["Characteristics[PGR::Protein expression]"] = ColumnName.PR;
      keymap["Characteristics[ERBB2::Protein expression]"] = ColumnName.HER2;

      //E-TABM-158
      keymap["Characteristics [EstrogenReceptorStatus]"] = ColumnName.ER;
      keymap["Characteristics [Progesterone Receptor status]"] = ColumnName.PR;
      keymap["Characteristics [ErbB2 positive (IHC)]"] = ColumnName.HER2;
      keymap["Characteristics [dead of disease]"] = ColumnName.DeadOfDisease;
      keymap["Characteristics [node positive]"] = ColumnName.NodalStatus;
      keymap["Characteristics [TumorStaging]"] = ColumnName.TumorStage;
      keymap["Characteristics [alive at endpoint]"] = ColumnName.OverallServive;
      keymap["Characteristics [TumorGrading]"] = ColumnName.Grade;


      nameKeyMap = keymap.GroupBy(m => m.Value).ToDictionary(m => m.Key, m => new HashSet<string>(from n in m select n.Key));
    }
Example #2
0
        public AggregateResult(IEnumerable<GameResult> results)
        {
            _playerToScoreMap = new Dictionary<BotPlayer, int>();
              results.SelectMany(x => x.Players).Each(x => _playerToScoreMap[x] = 0);

              results.Each(result =>
              {
            if (result.IsTie)
            {
              result.Players.Each(player =>
              {
            _playerToScoreMap[player]++;
              });
            }
            else
            {
              _playerToScoreMap[result.Winner] += 3;
            }
              });

              var winners = _playerToScoreMap.GroupBy(x => x.Value).OrderByDescending(x => x.Key).First();

              if (winners.Count() == _playerToScoreMap.Count)
              {
            IsTie = true;
              }
              else
              {
            Winner = winners.First().Key;
              }
        }
Example #3
0
        /// <summary>
        /// if needed, will merge the images base on page in the image names
        /// </summary>
        /// <param name="imageBytes"></param>
        /// <param name="imageNames"></param>
        /// <returns></returns>
        public Dictionary<PageImageIndex, System.Drawing.Image> Merge(Dictionary<PageImageIndex, System.Drawing.Image> imagesList, string outputPath)
        {
            var imageListByPage = imagesList.GroupBy(i => i.Key.PageIndex);
            var newImageList = new Dictionary<PageImageIndex, System.Drawing.Image>();

            foreach (var imagesInfo in imageListByPage)
            {
                var imagesPage = new Dictionary<PageImageIndex, System.Drawing.Image>();

                foreach (var item in imagesInfo)
                {
                    var image = item.Value;
                    if (item.Value == null)
                    {
                        var imagePath = string.Format(@"{0}\{1}", outputPath, item.Key.ImageName);
                        image = new System.Drawing.Bitmap(imagePath);
                    }

                    imagesPage.Add(item.Key, image);

                }

                //var imagesPage = imagesInfo.Select(i => i).ToDictionary(x => x.Key, x => x.Value);
                var keyValue = MergeGroup(imagesPage, outputPath);
                newImageList.Add(keyValue.Key, keyValue.Value);
            }

            return newImageList;
        }
Example #4
0
 public void InitCaches()
 {
     var db = new FacesDBDataContext(_connectionString);
     _faceUKeyLookup = db.Faces.ToDictionary(x => x.FaceUKey, x => (api.Face) new FaceImpl(x, _m, null));
     var query =  (from f in db.Faces join p in db.Persons on f.PersonID equals p.PersonID select new { f, p });
     _Faces = new Dictionary<api.Face,api.Person>();
     Dictionary<int, api.Person> persons = new Dictionary<int,api.Person>();
     foreach (var x in query) {
         // todo; build pers dic at same time...
         api.Person person = null;
         if (!persons.TryGetValue(x.p.PersonID, out person))
         {
             person = (api.Person)new PersonImpl(x.p.FirstName, x.p.LastName, x.p.PersonID);
             persons.Add(person.Id, person);
         }
         api.Face thisFace = _faceUKeyLookup[x.f.FaceUKey];
         thisFace.Person = person;
         _Faces.Add(thisFace, person);
     }
     _Persons = _Faces.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(y=>y.Key).ToList());
     _allPersonsLookup = persons;
     foreach (var pers in db.Persons) // add in other persons that don't have faces.
     {
         if (!_allPersonsLookup.ContainsKey(pers.PersonID))
             _allPersonsLookup.Add(pers.PersonID, (api.Person)new PersonImpl(pers.FirstName, pers.LastName, pers.PersonID));
     }
     _PicturesToFaces = db.Faces
         .ToLookup(x => x.PictureID, x => _faceUKeyLookup[x.FaceUKey]);
 }
        public Contracts.ExpensesReportDto GenerateReport()
        {
            // from user Id to user Id
            var expenseMap = new Dictionary<Tuple<int, int>, decimal>();
            Action<int, int, decimal> addToMap = (fromUser, toUser, amount) =>
            {
                var key = new Tuple<int, int>(fromUser, toUser);
                if (expenseMap.ContainsKey(key))
                    amount += expenseMap[key];

                if (amount != 0)
                    expenseMap[key] = amount;
                else
                    expenseMap.Remove(key);
            };

            // add expenses
            var allExpenses = DataContext.ExpenseItemsAsLightDto.ToArray();
            var calculator = new CostCalculatorStrategy();
            foreach (var expense in DataContext.Expenses.Where(e => e.Pricing != null).ToArray())
            {
                var expenseItems = allExpenses.Where(ei => ei.ExpenseId == expense.Id);
                foreach (var costData in calculator.CalculateCosts(expense, expenseItems))
                {
                    addToMap(costData.UserId, expense.Creator.Id, costData.Cost);
                }
            }

            // remove bi-directional items
            NormalizeMap(expenseMap);

            // build result
            var resultItems = new List<ExpensesUserReportDto>();
            var allUsers = DataContext.UsersAsLightDto.ToDictionary(u=>u.Id);
            foreach (var emi in expenseMap.GroupBy(em => em.Key.Item1))
            {
                var user = allUsers[emi.Key];
                resultItems.Add(new ExpensesUserReportDto()
                {
                    UserId = user.Id,
                    FullName = user.FullName,
                    TotalCost = emi.Sum(ei => ei.Value),
                    CostDetails = emi.Select(ei =>
                    new ExpensesCostDetailDto() {
                        Cost = ei.Value,
                        UserId = ei.Key.Item2,
                        FullName = allUsers[ei.Key.Item2].FullName
                    }).ToArray()
                });
            }

            var result = new ExpensesReportDto();
            result.Users = resultItems.ToArray();
            return result;
        }
        public static void GenerateSalesReportXMLMontly(List<XMLReportInfo> salesReports)
        {
            var doc = new XDocument();
            var sales = new XElement("sales");

            foreach (var report in salesReports)
            {
                var sale = new XElement("sale", new XAttribute("vendor", report.Key));
                var dates = report.Dates.Distinct().ToList();
                Dictionary<DateTime, decimal> pair = new Dictionary<DateTime, decimal>();
                for (int i = 0; i < dates.Count; i++)
                {
                    pair[dates[i]] = 0;
                }

                for (int i = 0; i < report.Dates.Count; i++)
                {
                    for (int j = 0; j < dates.Count; j++)
                    {
                        if (report.Dates[i] == dates[j])
                        {
                            pair[dates[j]] += report.Sums[i];
                        }
                    }
                }

                var monthExpens = pair.GroupBy(x => x.Key.Month).ToList();
                for (int i = 0; i < monthExpens.Count(); i++)
                {
                    var expense = new XElement("expenses", new XAttribute("month", CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(monthExpens[i].Key).Substring(0,3) + "-2013"));
                    decimal sum = 0;
                    foreach (var item in monthExpens)
                    {

                        foreach (var dailySum in item)
                        {
                            sum += dailySum.Value;
                        }
                    }
                    expense.Value = sum.ToString();
                    sale.Add(expense);
                }

                sales.Add(sale);
            }

            doc.Add(sales);
               // Console.WriteLine(doc);
            doc.Save(@"..\..\SalesReportByMonth.xml");
        }
        /// <summary>
        /// Parse and Import to DTOs
        /// </summary>
        /// <param name="spreadsheet"></param>
        /// <param name="parseErrors"></param>
        /// <returns></returns>
        public List<DocumentImportDTO> ValidateAndImportDocuments(ExcelPackage spreadsheet, ref Dictionary<string, List<string>> parseErrors)
        {
            var items = new List<DocumentImportDTO>();

            if (spreadsheet != null && spreadsheet.Workbook != null)
            {
                var worksheet = spreadsheet.Workbook.Worksheets.SingleOrDefault(x => x.Name == "Items");
                if (worksheet == null)
                {
                    return items;
                }
                var totalRows = worksheet.Dimension.End.Row;
                for (var rowId = 2; rowId <= totalRows; rowId++)
                {
                    //Prepare handle name for storing and grouping errors
                    var urlSegment = worksheet.GetValue<string>(rowId, 1);
                    var name = worksheet.GetValue<string>(rowId, 4);
                    var handle = urlSegment.HasValue() ? urlSegment : name;

                    if (string.IsNullOrWhiteSpace(handle) || items.Any(x => x.UrlSegment == urlSegment))
                        continue;

                    List<string> errors = parseErrors.ContainsKey(handle)
                        ? parseErrors[handle]
                        : new List<string>();

                    var item = GetDocumentImportDataTransferObject(worksheet, rowId, name, ref errors);
                    parseErrors[handle] = errors;

                    items.Add(item);
                }

                //Remove duplicate errors
                parseErrors = parseErrors.GroupBy(x => x.Value)
                    .Select(x => x.First())
                    .ToDictionary(pair => pair.Key, pair => pair.Value);
            }

            //Remove handles with no errors
            parseErrors = parseErrors.Where(x => x.Value.Any()).ToDictionary(pair => pair.Key, pair => pair.Value);

            return items;
        }
        public void ThreadNamesTest()
        {
            var rnd = new Random();
            var range = Enumerable.Range(0, 50);

            var rangeBack = new Dictionary<int, int>();
            var rangeBackLocker = new object();

            range.AsParallel().AsOrdered()
                .WithDegreeOfParallelism(4).ForAll(x =>
            {
                lock (rangeBackLocker)
                {
                    rangeBack.Add(x, Thread.CurrentThread.ManagedThreadId);
                }
                Thread.Sleep(100 * rnd.Next(10));         
            });

            Assert.AreEqual(rangeBack.GroupBy(x=>x.Value).Count(), 4);
        }
        public void DictionaryExample()
        {
            // Mime Types
            Dictionary<string, string> lookupTable = new Dictionary<string, string>();
            lookupTable.Add("html", "text/html");
            lookupTable.Add("htm", "text/html");
            lookupTable.Add("png", "image/png");
            lookupTable.Add("pdf", "application/pdf");

            // Are there any type with more than one extension associated?
            var t = lookupTable.GroupBy(x => x.Key).Select(x => new { MimeType = x.Key, Count = x.Count() }).Where(x => x.Count > 1);

            // for each of the types with more than one extension...
            foreach (var item in t)
            {
                // get the extensions:
                var extensionArray = lookupTable.Where(x => x.Value == item.MimeType).Select(x => x.Key).ToArray<string>();
                var extensions = string.Join(",", extensionArray);
                Console.WriteLine("{0} has the following extensions: {1}", item, extensions);
            }
        }
        private void WriteETWActor(StringBuilder sb, XElement provider, Dictionary<Tuple<int, int, string>, XElement> events)
        {
            sb.AppendFormat("public autostart actor actor_{0}", provider.Attribute("guid").Value.Replace("-", "").TrimStart('{').TrimEnd('}'));
            sb.AppendLine();
            sb.AppendLine("\t(EtwEvent.Node node)");
            sb.AppendLine("{");
            sb.AppendLine("\tprocess node accepts m:EtwProviderMsgEx");
            sb.AppendFormat("\t\twhere (m.EventRecord.Header.ProviderId == {0} )", provider.Attribute("guid").Value);
            sb.AppendLine();
            sb.AppendLine("\t{");

            sb.AppendLine("\t\tswitch(m.EventRecord.Header.Descriptor.Version)");
            sb.AppendLine("\t\t{");
            foreach (var etwEventGroup in events.GroupBy(p => p.Key.Item2))
            {
                sb.AppendFormat("\t\t\t//EventVersion {0}", etwEventGroup.Key);
                sb.AppendLine();
                sb.AppendFormat("\t\t\tcase $ {0} =>", etwEventGroup.Key);
                sb.AppendLine();
                sb.AppendLine("\t\t\t\tswitch(m.EventRecord.Header.Descriptor.Id)");
                sb.AppendLine("\t\t\t\t{");
                foreach (var etwEvent in etwEventGroup)
                {
                    sb.AppendFormat("\t\t\t\t\t//{0} =>", GetEventName(etwEvent.Key.Item3, etwEvent.Key.Item2));
                    sb.AppendLine();
                    sb.AppendFormat("\t\t\t\t\tcase $ {0} =>", etwEvent.Key.Item1);
                    sb.AppendLine();
                    sb.AppendLine("\t\t\t\t\t\tswitch(m.Payload)");
                    sb.AppendLine("\t\t\t\t\t\t{");
                    sb.AppendFormat("\t\t\t\t\t\t\tcase decodedMsg: {0} from BinaryDecoder <{0}> =>", GetEventName(etwEvent.Key.Item3, etwEvent.Key.Item2));
                    sb.AppendLine();
                    sb.AppendLine("\t\t\t\t\t\t\t{");
                    sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.EtwKeywords = Keywords.Decode(m.EventRecord.Header.Descriptor.Keywords);");
                    sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.EventId = m.EventRecord.Header.Descriptor.Id;");
                    sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.ActivityId = m.EventRecord.Header.ActivityId;");
                    sb.AppendLine();

                    if (string.Equals(etwEvent.Value?.Attribute("opcode")?.Value, "win:Start"))
                    {
                        sb.AppendLine("\t\t\t\t\t\t\t\tint count = m.ExtendedData.Count;");
                        sb.AppendLine("\t\t\t\t\t\t\t\tif (count > 0)");
                        sb.AppendLine("\t\t\t\t\t\t\t\t{");
                        sb.AppendLine("\t\t\t\t\t\t\t\t\tarray <EventHeaderExtendedDataItem> items = m.ExtendedData;");
                        sb.AppendLine("\t\t\t\t\t\t\t\t\tEVENT_HEADER_EXT_TYPE_RELATED_ACTIVITYID dataItem = items[0].DataItem as EVENT_HEADER_EXT_TYPE_RELATED_ACTIVITYID;");
                        sb.AppendLine();
                        sb.AppendLine("\t\t\t\t\t\t\t\t\tif (dataItem != null)");
                        sb.AppendLine("\t\t\t\t\t\t\t\t\t\tdecodedMsg.RelatedActivityId = dataItem.RelatedActivityId;");
                        sb.AppendLine();
                        sb.AppendLine("\t\t\t\t\t\t\t\t\tdecodedMsg.ActivityTree = Facton_ActivityTree_Utils.GetActivityTree(decodedMsg.ActivityId, decodedMsg.RelatedActivityId, m.EventRecord.Header.ProcessId, m.EventRecord.Header.ThreadId);");
                        sb.AppendLine("\t\t\t\t\t\t\t\t}");
                        sb.AppendLine();
                    }
                    else
                    {
                        if (etwEvent.Key.Item1 != 0 && etwEvent.Key.Item1 != 65534)
                        {
                            sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.ActivityTree = Facton_ActivityTree_Utils.GetActivityTree(decodedMsg.ActivityId, m.EventRecord.Header.ProcessId, m.EventRecord.Header.ThreadId);");
                        }
                    }
                    sb.AppendFormat("\t\t\t\t\t\t\t\tep_{0} ep = endpoint ep_{0};", provider.Attribute("name").Value.Replace('-', '_'));
                    sb.AppendLine();
                    sb.AppendLine("\t\t\t\t\t\t\t\tdispatch ep accepts decodedMsg;");
                    sb.AppendLine("\t\t\t\t\t\t\t}");
                    sb.AppendLine("\t\t\t\t\t\t\tdefault =>");
                    sb.AppendFormat("\t\t\t\t\t\t\t\tThrowDecodingException(\"{0}\", \"{1}\");", provider.Attribute("name").Value, GetEventName(etwEvent.Key.Item3, etwEvent.Key.Item2));
                    sb.AppendLine();
                    sb.AppendLine("\t\t\t\t\t\t}");
                    sb.AppendLine();
                }
                sb.AppendLine("\t\t\t\t}");
                sb.AppendLine();
            }
            sb.AppendLine("\t\t}");
            sb.AppendLine("\t}");
            sb.AppendLine("}");
            sb.AppendLine();
        }
		void BuildCachedVersionsList(List<FileRevision> versions)
		{
			using (var sw = File.CreateText(DataFileName))
			{
				foreach (var fileGroup in versions.GroupBy(v => v.FileSpec))
				{
					// get in ascending order
					var fileVersions = fileGroup.OrderBy(f => f.VssVersion).ToList();

					var brokenVersions = new List<int>();
					var notRetainedVersions = new List<int>();
					var otherErrors = new Dictionary<int, string>();

					if (IsShouldBePinned(fileGroup.Key))
					{
						// reduce file versions to latest only
						fileVersions = fileVersions.Skip(fileVersions.Count - 1).ToList();
					}

					foreach (var file in fileVersions)
					{
						var inf = _cache.GetFileInfo(file.FileSpec, file.VssVersion);

						if (inf == null)
							throw new ApplicationException(string.Format("No in cache, but should be: {0}@{1}", file.FileSpec, file.VssVersion));

						if (inf.ContentPath != null)
						{
							if (brokenVersions.Count > 0 || notRetainedVersions.Count > 0 || otherErrors.Count > 0)
							{
								var commentPlus = string.Format("\nBalme for '{0}' can be incorrect, because:", file.FileSpec);
								if (brokenVersions.Count > 0)
								{
									commentPlus += "\n\tbroken vss versions: " +
													string.Join(", ", brokenVersions.Select(v => v.ToString(CultureInfo.InvariantCulture)).ToArray());
								}
								if (notRetainedVersions.Count > 0)
								{
									commentPlus += "\n\tnot retained versions: " +
													string.Join(", ", notRetainedVersions.Select(v => v.ToString(CultureInfo.InvariantCulture)).ToArray());
								}
								if (otherErrors.Count > 0)
								{
									foreach (var otherErrorsGroup in otherErrors.GroupBy(kvp => kvp.Value))
									{
										var revs = otherErrorsGroup.Select(kvp => kvp.Key.ToString(CultureInfo.InvariantCulture)).ToArray();
										commentPlus += string.Format("\n\tError in VSS versions {0}: '{1}'", string.Join(", ", revs),
											otherErrorsGroup.Key);
									}
								}

								file.Comment += commentPlus;
							}

							sw.WriteLine("Ver:{0}	Spec:{1}	Phys:{2}	User:{3}	At:{4}	DT:{5}	Comment:{6}",
								file.VssVersion,
								file.FileSpec,
								file.Physical,
								file.User,
								file.At.Ticks,
								file.At,
								file.Comment.Replace('\n', '\u0001')
							);

							notRetainedVersions.Clear();
							brokenVersions.Clear();
							otherErrors.Clear();
						}
						else if (inf.Notes == "not-retained")
							notRetainedVersions.Add(file.VssVersion);
						else if (inf.Notes == "broken-revision")
							brokenVersions.Add(file.VssVersion);
						else if (!string.IsNullOrWhiteSpace(inf.Notes))
							otherErrors[file.VssVersion] = inf.Notes;
					}

					if (brokenVersions.Count > 0 || notRetainedVersions.Count > 0 || otherErrors.Count > 0)
						throw new ApplicationException(string.Format("Absent content for latest file version: {0}", fileGroup.Key));
				}
			}
		}
Example #12
0
        static TypeMapper()
        {
            typeMapping = new Dictionary<string, Type>();
            typeMapping.Add("bigint", typeof(long));
            typeMapping.Add("int", typeof(int));
            typeMapping.Add("smallint", typeof(short));
            typeMapping.Add("tinyint", typeof(byte));
            typeMapping.Add("decimal", typeof(decimal));
            typeMapping.Add("numeric", typeof(decimal));
            typeMapping.Add("money", typeof(decimal));
            typeMapping.Add("smallmoney", typeof(decimal));
            typeMapping.Add("bit", typeof(bool));
            typeMapping.Add("float", typeof(float));
            typeMapping.Add("real", typeof(double));
            typeMapping.Add("datetime2", typeof(DateTime));
            typeMapping.Add("datetime", typeof(DateTime));
            typeMapping.Add("smalldatetime", typeof(DateTime));
            typeMapping.Add("date", typeof(DateTime));
            typeMapping.Add("datetimeoffset", typeof(DateTime));
            typeMapping.Add("time", typeof(DateTime));
            typeMapping.Add("timestamp", typeof(DateTime));
            typeMapping.Add("nvarchar", typeof(string));
            typeMapping.Add("char", typeof(string));
            typeMapping.Add("varchar", typeof(string));
            typeMapping.Add("text", typeof(string));
            typeMapping.Add("nchar", typeof(string));
            typeMapping.Add("ntext", typeof(string));
            typeMapping.Add("varbinary", typeof(byte[]));
            typeMapping.Add("binary", typeof(byte[]));
            typeMapping.Add("image", typeof(byte[]));
            typeMapping.Add("uniqueidentifier", typeof(Guid));

            reverseTypeMapping = typeMapping
                .GroupBy(kv => kv.Value, kv => kv.Key)
                .ToDictionary(g => g.Key, g => g.First());

            reverseTypeMapping.Add(typeof(char[]), "nchar");

            reverseTypeMapping.Add(typeof(int?), "int");
            reverseTypeMapping.Add(typeof(uint), "int");
            reverseTypeMapping.Add(typeof(uint?), "int");

            reverseTypeMapping.Add(typeof(long?), "bigint");
            reverseTypeMapping.Add(typeof(ulong), "bigint");
            reverseTypeMapping.Add(typeof(ulong?), "bigint");

            reverseTypeMapping.Add(typeof(short?), "smallint");
            reverseTypeMapping.Add(typeof(ushort), "smallint");
            reverseTypeMapping.Add(typeof(ushort?), "smallint");

            reverseTypeMapping.Add(typeof(byte?), "tinyint");
            reverseTypeMapping.Add(typeof(sbyte), "tinyint");
            reverseTypeMapping.Add(typeof(sbyte?), "tinyint");
            reverseTypeMapping.Add(typeof(char), "tinyint");
            reverseTypeMapping.Add(typeof(char?), "tinyint");

            reverseTypeMapping.Add(typeof(decimal?), "decimal");
            reverseTypeMapping.Add(typeof(bool?), "bit");
            reverseTypeMapping.Add(typeof(float?), "float");
            reverseTypeMapping.Add(typeof(double?), "real");
            reverseTypeMapping.Add(typeof(DateTime?), "datetime2");
            reverseTypeMapping.Add(typeof(Guid?), "uniqueidentifier");
        }
Example #13
0
        IEnumerable<IGrouping<string, string>> OverrideWithInputs(IEnumerable<IGrouping<string,string>> parameters)
        {
            var overrides = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            if (Configuration != null)
                overrides.Add("Configuration", Configuration);
            if (Incremental)
                overrides.Add("Incremental", "True");

            return overrides.GroupBy(x => x.Key, x => x.Value).Concat(parameters.Where(param => !overrides.ContainsKey(param.Key)));
        }
Example #14
0
 private void AverageHitsPerSecondPerHourSectionOutput(Dictionary<DateTime, int> hitsPerSecond)
 {
     Console.WriteLine();
     OutputHeading("Average hits per second, by hour");
     var groupedHourlyList = hitsPerSecond.GroupBy(u => u.Key.Hour)
                               .Select(grp => new { GroupID = grp.Key, subList = grp.ToList() })
                               .ToList();
     foreach (var hourlyHits in groupedHourlyList)
     {
         Console.WriteLine("{0,2:D2}-{1,2:D2} : {2:0}", hourlyHits.GroupID, hourlyHits.GroupID + 1, hourlyHits.subList.Average(c => c.Value));
     }
 }
Example #15
0
        private DfmTagNameResolveResult ResolveTagNamesFromPath(string fencesPath, string[] fencesCodeLines, string tagName, Regex regexToExtractCode)
        {
            var lazyResolveResults =
                _dfmTagNameLineRangeCache.GetOrAdd(fencesPath,
                    path => new Lazy<ConcurrentDictionary<string, DfmTagNameResolveResult>>(
                            () =>
                            {
                                var linesOfSnippetComment = new Dictionary<long, string>();
                                for (long i = 0; i < fencesCodeLines.Length; i++)
                                {
                                    var match = regexToExtractCode.Match(fencesCodeLines[i]);
                                    if (match.Success)
                                    {
                                        linesOfSnippetComment.Add(i + 1, match.Groups[1].Value);
                                    }
                                }

                                var excludedLines = new HashSet<long>(linesOfSnippetComment.Keys);

                                var dictionary = new ConcurrentDictionary<string, DfmTagNameResolveResult>(StringComparer.OrdinalIgnoreCase);

                                foreach (var snippetCommentsInPair in linesOfSnippetComment.GroupBy(kvp => kvp.Value))
                                {
                                    DfmTagNameResolveResult tagResolveResult;
                                    var lineNumbers = snippetCommentsInPair.Select(line => line.Key).OrderBy(line => line).ToList();
                                    if (lineNumbers.Count == 2)
                                    {
                                        tagResolveResult = new DfmTagNameResolveResult
                                        {
                                            IsSuccessful = true,
                                            StartLine = lineNumbers[0] + 1,
                                            EndLine = lineNumbers[1] - 1,
                                            ExcludesLines = excludedLines
                                        };
                                    }
                                    else
                                    {
                                        tagResolveResult = new DfmTagNameResolveResult
                                        {
                                            IsSuccessful = false,
                                            ErrorMessage = lineNumbers.Count == 1
                                                ? $"Tag name {snippetCommentsInPair.Key} is not closed"
                                                : $"Tag name {snippetCommentsInPair.Key} occurs {lineNumbers.Count} times"
                                        };
                                    }

                                    dictionary.TryAdd(snippetCommentsInPair.Key, tagResolveResult);
                                }

                                return dictionary;
                            }));

            DfmTagNameResolveResult resolveResult;
            var tagNamesDictionary = lazyResolveResults.Value;
            return (tagNamesDictionary.TryGetValue(tagName, out resolveResult) || tagNamesDictionary.TryGetValue($"snippet{tagName}", out resolveResult))
                    ? resolveResult
                    : new DfmTagNameResolveResult { IsSuccessful = false, ErrorMessage = $"Tag name {tagName} is not found" };
        }
Example #16
0
        private IEnumerable<NuGetFramework> GetNearestPCLtoPCL(NuGetFramework framework, IEnumerable<NuGetFramework> reduced)
        {
            // Compare each framework in the target framework individually
            // against the list of possible PCLs. This effectively lets
            // each sub-framework vote on which PCL is nearest.
            var subFrameworks = ExplodePortableFramework(framework);

            // reduce the sub frameworks - this would only have an effect if the PCL is 
            // poorly formed and contains duplicates such as portable-win8+win81
            subFrameworks = Reduce(subFrameworks);

            // Find all frameworks in all PCLs
            var pclToFrameworks = ExplodePortableFrameworks(reduced);
            var allPclFrameworks = pclToFrameworks.Values.SelectMany(f => f).Distinct(_fullComparer);

            var scores = new Dictionary<NuGetFramework, int>(NuGetFramework.Comparer);

            // find the nearest PCL for each framework
            foreach (var sub in subFrameworks)
            {
                Debug.Assert(!sub.IsPCL, "a PCL returned a PCL as its profile framework");

                // from all possible frameworks, find the best match
                var nearestForSub = GetNearest(sub, allPclFrameworks);

                // +1 each framework containing the best match
                foreach (var pair in pclToFrameworks)
                {
                    if (pair.Value.Contains(nearestForSub, _fullComparer))
                    {
                        if (!scores.ContainsKey(pair.Key))
                        {
                            scores.Add(pair.Key, 1);
                        }
                        else
                        {
                            scores[pair.Key]++;
                        }
                    }
                }
            }

            // take the highest vote count, this will be at least one
            reduced = scores.GroupBy(pair => pair.Value).OrderByDescending(g => g.Key).First().Select(e => e.Key);

            return reduced;
        }
        static void Main(string[] args)
        {
            try
            {                
                NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings;

                Dictionary<string, List<string>> uprnDictionaryResidual = new Dictionary<string, List<string>>();
                Boolean overwriteResidual = true;

                // Open the geodatabase for residual.
                Geodatabase geodatabaseResidual = Geodatabase.Open(appSettings["residualGeoDB"]);
                StringBuilder residualCsv = new StringBuilder();
                string sqlStatementResidual = "SELECT * FROM " + appSettings["residualTableName"];

                foreach (Row attrQueryRow in geodatabaseResidual.ExecuteSQL(sqlStatementResidual))
                {
                    string uprn = "";
                    string day = "";
                    string route = "";
                    if (!attrQueryRow.IsNull("LLPG_UPRN_DOUBLE"))
                    {
                        uprn = attrQueryRow.GetDouble("LLPG_UPRN_DOUBLE").ToString();
                    }
                    else
                    {
                        overwriteResidual = false;
                    }
                    if (!attrQueryRow.IsNull("REFUSE_DAY"))
                    {
                        day = attrQueryRow.GetString("REFUSE_DAY");
                    }
                    else
                    {
                        //overwriteResidual = false;
                    }
                    if (!attrQueryRow.IsNull("Route"))
                    {
                        route = attrQueryRow.GetString("Route");
                    }
                    else
                    {
                        //overwriteResidual = false;
                    }

                    //Matthew Steer added this on: 29.9.16
                    string gullBag = "";
                    if (!attrQueryRow.IsNull("Gull_Bag")) gullBag = attrQueryRow.GetString("Gull_Bag");

                    string newLine = string.Format("{0},{1},{2},{3}{4}", uprn, day, route, gullBag, Environment.NewLine);
                    residualCsv.Append(newLine);

                    // Additional fields for assisted
                    string address = "";
                    string postcode = "";
                    string refuseRound = "";
                    string refuseSequence = "";
                    string llpgName = "";
                    string llpgNo = "";
                    string llpgStreet = "";
                    string llpgTown = "";
                    string llpgPostTown = "";
                    string llpgPostcode = "";

                    if (!attrQueryRow.IsNull("Address")) address = attrQueryRow.GetString("Address");
                    if (!attrQueryRow.IsNull("Postal_Code")) postcode = attrQueryRow.GetString("Postal_Code");
                    if (!attrQueryRow.IsNull("Region")) refuseRound = attrQueryRow.GetString("Region");
                    if (!attrQueryRow.IsNull("Sequence")) refuseSequence = attrQueryRow.GetInteger("Sequence").ToString();
                    if (!attrQueryRow.IsNull("LLPG_NAME")) llpgName = attrQueryRow.GetString("LLPG_NAME");
                    if (!attrQueryRow.IsNull("LLPG_NO")) llpgNo = attrQueryRow.GetString("LLPG_NO");
                    if (!attrQueryRow.IsNull("LLPG_STREET")) llpgStreet = attrQueryRow.GetString("LLPG_STREET");
                    if (!attrQueryRow.IsNull("LLPG_TOWN")) llpgTown = attrQueryRow.GetString("LLPG_TOWN");
                    if (!attrQueryRow.IsNull("LLPG_POSTTOWN")) llpgPostTown = attrQueryRow.GetString("LLPG_POSTTOWN");
                    if (!attrQueryRow.IsNull("LLPG_POSTCODE")) llpgPostcode = attrQueryRow.GetString("LLPG_POSTCODE");
                   
                    //And add the relevant data to our dictionary
                    if (!uprnDictionaryResidual.ContainsKey(uprn))
                    {
                        uprnDictionaryResidual.Add(uprn, new List<string> { route, day, address, postcode, refuseRound,
                            refuseSequence, llpgName, llpgNo, llpgStreet, llpgTown, llpgPostTown, llpgPostcode, gullBag });
                    }
                }
                geodatabaseResidual.Close();
                if (overwriteResidual) File.WriteAllText(appSettings["residualCsv"], residualCsv.ToString());

                Dictionary<string, List<string>> uprnDictionaryOrganic = new Dictionary<string, List<string>>();
                Boolean overwriteOrganic = true;

                // Open the geodatabase for organic.
                Geodatabase geodatabaseOrganic = Geodatabase.Open(appSettings["organicGeoDB"]);
                StringBuilder organicCsv = new StringBuilder();
                string sqlStatementOrganic = "SELECT LLPG_UPRN_DOUBLE, Organic_Collection, Route FROM " + appSettings["organicTableName"];

                foreach (Row attrQueryRow in geodatabaseOrganic.ExecuteSQL(sqlStatementOrganic))
                {
                    string uprn = "";
                    string route = "";
                    string day = "";
                    if (!attrQueryRow.IsNull("LLPG_UPRN_DOUBLE"))
                    {
                        uprn = attrQueryRow.GetDouble("LLPG_UPRN_DOUBLE").ToString();
                    }
                    else
                    {
                        //overwriteOrganic = false;
                    }
                    if (!attrQueryRow.IsNull("Organic_Collection"))
                    {
                        day = attrQueryRow.GetString("Organic_Collection");
                    }
                    else
                    {
                        //overwriteOrganic = false;
                    }
                    if (!attrQueryRow.IsNull("Route"))
                    {
                        route = attrQueryRow.GetString("Route");
                    }
                    else
                    {
                        //overwriteOrganic = false;
                    }
                    string newLine = string.Format("{0},{1},{2}{3}", uprn, day, route, Environment.NewLine);
                    organicCsv.Append(newLine);

                    // Additional fields for assisted
                    string address = "";
                    string postcode = "";
                    string organicRound = "";
                    string organicSequence = "";
                    string llpgName = "";
                    string llpgNo = "";
                    string llpgStreet = "";
                    string llpgTown = "";
                    string llpgPostTown = "";
                    string llpgPostcode = "";
                    string week = "";

                    if (!attrQueryRow.IsNull("Address")) address = attrQueryRow.GetString("Address");
                    if (!attrQueryRow.IsNull("Postal_Code")) postcode = attrQueryRow.GetString("Postal_Code");
                    if (!attrQueryRow.IsNull("Region")) organicRound = attrQueryRow.GetString("Region");
                    if (!attrQueryRow.IsNull("Sequence")) organicSequence = attrQueryRow.GetInteger("Sequence").ToString();
                    if (!attrQueryRow.IsNull("LLPG_NAME")) llpgName = attrQueryRow.GetString("LLPG_NAME");
                    if (!attrQueryRow.IsNull("LLPG_NO")) llpgNo = attrQueryRow.GetString("LLPG_NO");
                    if (!attrQueryRow.IsNull("LLPG_STREET")) llpgStreet = attrQueryRow.GetString("LLPG_STREET");
                    if (!attrQueryRow.IsNull("LLPG_TOWN")) llpgTown = attrQueryRow.GetString("LLPG_TOWN");
                    if (!attrQueryRow.IsNull("LLPG_POSTTOWN")) llpgPostTown = attrQueryRow.GetString("LLPG_POSTTOWN");
                    if (!attrQueryRow.IsNull("LLPG_POSTCODE")) llpgPostcode = attrQueryRow.GetString("LLPG_POSTCODE");
                    if (!attrQueryRow.IsNull("Collection")) week = attrQueryRow.GetString("Collection");

                    // And add the relevant data to our dictionary
                    if (!uprnDictionaryOrganic.ContainsKey(uprn))
                    {
                        uprnDictionaryOrganic.Add(uprn, new List<string> { route, day, address, postcode, organicRound,
                        organicSequence, week, llpgName, llpgNo, llpgStreet, llpgTown, llpgPostTown, llpgPostcode });
                    }
                }
                geodatabaseOrganic.Close();
                if (overwriteOrganic) File.WriteAllText(appSettings["organicCsv"], organicCsv.ToString());

                Dictionary<string, List<string>> uprnDictionaryRecycling = new Dictionary<string, List<string>>();
                Boolean overwriteRecycling = true;

                // Open the geodatabase for recyling.
                Geodatabase geodatabaseRecycling = Geodatabase.Open(appSettings["recyclingGeoDB"]);
                StringBuilder recylingCsv = new StringBuilder();
                string sqlStatementRecyling = "SELECT LLPG_UPRN_DOUBLE, Recycle_Collection, Route , Green_Sack FROM " + appSettings["recyclingTableName"];

                foreach (Row attrQueryRow in geodatabaseRecycling.ExecuteSQL(sqlStatementRecyling))
                {
                    string uprn = "";
                    string day = "";
                    string route = "";
                    string greensack = "";

                    if (!attrQueryRow.IsNull("LLPG_UPRN_DOUBLE"))
                    {
                        uprn = attrQueryRow.GetDouble("LLPG_UPRN_DOUBLE").ToString();
                    }
                    else
                    {
                        //overwriteRecycling = false;
                    }
                    if (!attrQueryRow.IsNull("Recycle_Collection"))
                    {
                        day = attrQueryRow.GetString("Recycle_Collection");
                    }
                    else
                    {
                        //overwriteRecycling = false;
                    }
                    if (!attrQueryRow.IsNull("Route"))
                    {
                        route = attrQueryRow.GetString("Route");
                    }
                    else
                    {
                        //overwriteRecycling = false;
                    }
                    if (!attrQueryRow.IsNull("Green_Sack"))
                    {
                        greensack = attrQueryRow.GetString("Green_Sack");
                    }
                    else
                    {
                        //overwriteRecycling = false;
                    }

                    string newLine = string.Format("{0},{1},{2},{3}{4}", uprn, day, route, greensack, Environment.NewLine);
                    recylingCsv.Append(newLine);

                    // Additional fields for assisted
                    string address = "";
                    string postcode = "";
                    string recyclingRound = "";
                    string recyclingSequence = "";
                    string llpgName = "";
                    string llpgNo = "";
                    string llpgStreet = "";
                    string llpgTown = "";
                    string llpgPostTown = "";
                    string llpgPostcode = "";
                    string llpgLocality = "";

                    if (!attrQueryRow.IsNull("Address")) address = attrQueryRow.GetString("Address");
                    if (!attrQueryRow.IsNull("Postal_Code")) postcode = attrQueryRow.GetString("Postal_Code");
                    if (!attrQueryRow.IsNull("Region")) recyclingRound = attrQueryRow.GetString("Region");
                    if (!attrQueryRow.IsNull("Sequence")) recyclingSequence = attrQueryRow.GetInteger("Sequence").ToString();
                    if (!attrQueryRow.IsNull("LLPG_NAME")) llpgName = attrQueryRow.GetString("LLPG_NAME");
                    if (!attrQueryRow.IsNull("LLPG_NO")) llpgNo = attrQueryRow.GetString("LLPG_NO");
                    if (!attrQueryRow.IsNull("LLPG_STREET")) llpgStreet = attrQueryRow.GetString("LLPG_STREET");
                    if (!attrQueryRow.IsNull("LLPG_TOWN")) llpgTown = attrQueryRow.GetString("LLPG_TOWN");
                    if (!attrQueryRow.IsNull("LLPG_POSTTOWN")) llpgPostTown = attrQueryRow.GetString("LLPG_POSTTOWN");
                    if (!attrQueryRow.IsNull("LLPG_POSTCODE")) llpgPostcode = attrQueryRow.GetString("LLPG_POSTCODE");
                    //if (!attrQueryRow.IsNull("LLPG_LOCALITY")) llpgLocality = attrQueryRow.GetString("LLPG_LOCALITY");

                    // And add the relevant data to our dictionary
                    if (!uprnDictionaryRecycling.ContainsKey(uprn))
                    {
                        uprnDictionaryRecycling.Add(uprn, new List<string> { route, day, address, postcode, recyclingRound,
                        recyclingSequence, llpgName, llpgNo, llpgStreet, llpgTown, llpgPostTown, llpgPostcode, llpgLocality });
                    }
                }
                geodatabaseRecycling.Close();
                if (overwriteRecycling) File.WriteAllText(appSettings["recyclingCsv"], recylingCsv.ToString());

                // For recycling we also generate a set of route participation monitor sheets for importing
                // firstly create a set of dictionaries grouped by route
                var recyclingDictionaries = uprnDictionaryRecycling.GroupBy(pair => pair.Value[4])
                                                 .ToDictionary(gr => gr.Key,
                                                     gr => gr.ToDictionary(item => item.Key,
                                                                           item => item.Value));

                string recyclingRoutesHeaderLine = string.Format("{0}{1}", "LLPG_NAME, LLPG_NO, LLPG_STREET, LLPG_LOCALITY, LLPG_TOWN, LLPG_POSTTOWN, LLPG_POSTCODE, Recycle_collection, Recycling_Round, Service_Location_RECYCLING_Sequence", Environment.NewLine);
                foreach (var route in recyclingDictionaries)
                {
                    StringBuilder mondayCsv = new StringBuilder();
                    mondayCsv.Append(recyclingRoutesHeaderLine);
                    StringBuilder tuesdayCsv = new StringBuilder();
                    tuesdayCsv.Append(recyclingRoutesHeaderLine);
                    StringBuilder wednesdayCsv = new StringBuilder();
                    wednesdayCsv.Append(recyclingRoutesHeaderLine);
                    StringBuilder thursdayCsv = new StringBuilder();
                    thursdayCsv.Append(recyclingRoutesHeaderLine);
                    StringBuilder fridayCsv = new StringBuilder();
                    fridayCsv.Append(recyclingRoutesHeaderLine);

                    Boolean mondayRoute = false;
                    Boolean tuesdayRoute = false;
                    Boolean wednesdayRoute = false;
                    Boolean thursdayRoute = false;
                    Boolean fridayRoute = false;

                    // Each route is a set of dictionaries
                    foreach (var item in route.Value)
                    {
                        string llpgName = "\"" + item.Value[6] + "\"";
                        string llpgNo = item.Value[7];
                        string llpgStreet = item.Value[8];
                        string llpgLocality = item.Value[12];
                        string llpgTown = item.Value[9];
                        string llpgPostTown = item.Value[10];
                        string llpgPostCode = item.Value[11];
                        string recycycleCollection = item.Value[1];
                        string recycleRound = item.Value[4];
                        string recycleSequence = item.Value[5];
                        string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}{10}",
                                            llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown,
                                            llpgPostTown, llpgPostCode, recycycleCollection,
                                            recycleRound, recycleSequence, Environment.NewLine);

                        switch (item.Value[1])
                        {
                            case "Monday":
                                mondayCsv.Append(newLine);
                                mondayRoute = true;
                                break;
                            case "Tuesday":
                                tuesdayCsv.Append(newLine);
                                tuesdayRoute = true;
                                break;
                            case "Wednesday":
                                wednesdayCsv.Append(newLine);
                                wednesdayRoute = true;
                                break;
                            case "Thursday":
                                thursdayCsv.Append(newLine);
                                thursdayRoute = true;
                                break;
                            case "Friday":
                                fridayCsv.Append(newLine);
                                fridayRoute = true;
                                break;
                        }
                    }
                    if (mondayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Monday.csv", mondayCsv.ToString());
                    if (tuesdayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Tuesday.csv", tuesdayCsv.ToString());
                    if (wednesdayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Wednesday.csv", wednesdayCsv.ToString());
                    if (thursdayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Thursday.csv", thursdayCsv.ToString());
                    if (fridayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Friday.csv", fridayCsv.ToString());
                }

                // Also need to do an output for the assisted collections db
                // this will be from each of the databases, into a single file,taken from the dictionaries we've built up.

                // The table holds the data for each UPRN.
                // The fields are: UPRN as number, Address, Postal_Code, Organic_Day, Organic_Route, Oroutea, Organics_Round, Organic_Week, Service_Location_ORGANIC_Sequence, Recycle_collection, Recycle_route, Recycling_Round, Service_Location_RECYCLING_Sequence, Residual_Collection, Residual_Route, Refuse_Round, Service_Location_REFUSE_Sequence, LLPG_NAME, LLPG_NO, LLPG_STREET, LLPG_LOCALITY, LLPG_TOWN, LLPG_POSTTOWN, LLPG_POSTCODE
                StringBuilder uprnCsv = new StringBuilder();
                char[] charsToTrim = { 'a', 'b', 'A', 'B' };
                string headerLine = string.Format("{0}{1}", "UPRN as number, Address, Postal_Code, Organic_Day, Organic_Route, Oroutea, Organics_Round, Organic_Week, Service_Location_ORGANIC_Sequence, Recycle_collection, Recycle_route, Recycling_Round, Service_Location_RECYCLING_Sequence, Residual_Collection, Residual_Route, Refuse_Round, Service_Location_REFUSE_Sequence, LLPG_NAME, LLPG_NO, LLPG_STREET, LLPG_LOCALITY, LLPG_TOWN, LLPG_POSTTOWN, LLPG_POSTCODE, Gull_Bag", Environment.NewLine);
                uprnCsv.Append(headerLine);
                foreach (var val in uprnDictionaryResidual)
                {
                    string uprn = val.Key;
                    string address = "\"" + val.Value[2] + "\"";
                    string postcode = val.Value[3];
                    string organicDay = "";
                    string organicRoute = "";
                    string oRoutea = "";
                    string organicsRoute = "";
                    string organicWeek = "";
                    string serviceLocationOrganicSequence = "";
                    if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][1].Split(' ') != null) organicDay = uprnDictionaryOrganic[val.Key][1].Split(' ')[0];
                    if (uprnDictionaryOrganic.ContainsKey(val.Key)) organicRoute = uprnDictionaryOrganic[val.Key][0];
                    if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][0].Length > 2) oRoutea = uprnDictionaryOrganic[val.Key][0].Substring(0, 1) + (uprnDictionaryOrganic[val.Key][0].Length > 3 ? uprnDictionaryOrganic[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryOrganic[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim));
                    if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][0].Length > 2) organicsRoute = uprnDictionaryOrganic[val.Key][0].Substring(0, 1) + (uprnDictionaryOrganic[val.Key][0].Length > 3 ? uprnDictionaryOrganic[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryOrganic[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim));
                    if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][6] != null && uprnDictionaryOrganic[val.Key][6].Split(' ').Length > 2) organicWeek = uprnDictionaryOrganic[val.Key][6].Split(' ')[1] + " " + uprnDictionaryOrganic[val.Key][6].Split(' ')[2];
                    if (uprnDictionaryOrganic.ContainsKey(val.Key)) serviceLocationOrganicSequence = uprnDictionaryOrganic[val.Key][5];

                    string recycleCollection = "";
                    string recycleRoute = "";
                    string recyclingRound = "";
                    string serviceLocationRecyclingSequence = "";
                    if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleCollection = uprnDictionaryRecycling[val.Key][1];
                    if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleRoute = uprnDictionaryRecycling[val.Key][0];
                    if (uprnDictionaryRecycling.ContainsKey(val.Key) && uprnDictionaryRecycling[val.Key][0].Length > 2) recyclingRound = uprnDictionaryRecycling[val.Key][0].Substring(0, 1) + (uprnDictionaryRecycling[val.Key][0].Length > 3 ? uprnDictionaryRecycling[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryRecycling[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim));
                    if (uprnDictionaryRecycling.ContainsKey(val.Key)) serviceLocationRecyclingSequence = uprnDictionaryRecycling[val.Key][5];

                    string residualCollection = val.Value[1];
                    string residualRoute = val.Value[0];
                    string refuseRound = "";
                    if (val.Value[0].Length > 2) refuseRound = val.Value[0].Substring(0, 1) + (val.Value[0].Length > 3 ? val.Value[0].Substring(2, 2).TrimEnd(charsToTrim) : val.Value[0].Substring(2, 1).TrimEnd(charsToTrim));
                    string serviceLocationRefuseSequence = val.Value[5];
                    string llpgName = "\"" + val.Value[6] + "\"";
                    string llpgNo = val.Value[7];
                    string llpgStreet = val.Value[8];
                    string llpgLocality = "";
                    string llpgTown = val.Value[9];
                    string llpgPosttown = val.Value[10];
                    string llpgPostcode = val.Value[11];
                  
                    string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23}{24}",
                        uprn, address, postcode, organicDay, organicRoute, oRoutea, organicsRoute, organicWeek,
                        serviceLocationOrganicSequence, recycleCollection, recycleRoute, recyclingRound,
                        serviceLocationRecyclingSequence, residualCollection, residualRoute, refuseRound,
                        serviceLocationRefuseSequence, llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown,
                        llpgPosttown, llpgPostcode, Environment.NewLine);
                    uprnCsv.Append(newLine);
                }
                // Then add all the ones from organic where they don't exist in residual
                foreach (var val in uprnDictionaryOrganic.Where(x => !uprnDictionaryResidual.ContainsKey(x.Key)))
                {
                    string uprn = val.Key;
                    string address = "\"" + val.Value[2] + "\"";
                    string postcode = val.Value[3];
                    string organicDay = "";
                    string organicRoute = "";
                    string oRoutea = "";
                    string organicsRoute = "";
                    string organicWeek = "";
                    string serviceLocationOrganicSequence = "";
                    organicDay = val.Value[1].Split(' ')[0];
                    organicRoute = val.Value[0];
                    // Round is the Letter and Third and Fourth Digit
                    oRoutea = val.Value[0].Substring(0, 1) + val.Value[0].Substring(2, 2).TrimEnd(charsToTrim);
                    organicsRoute = val.Value[0].Substring(0, 1) + val.Value[0].Substring(2, 2).TrimEnd(charsToTrim);
                    if (val.Value[6] != null && val.Value[6].Split(' ') != null && val.Value[6].Split(' ').Length > 2) organicWeek = val.Value[6].Split(' ')[1] + " " + val.Value[6].Split(' ')[2];
                    serviceLocationOrganicSequence = val.Value[5];

                    string recycleCollection = "";
                    string recycleRoute = "";
                    string recyclingRound = "";
                    string serviceLocationRecyclingSequence = "";
                    if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleCollection = uprnDictionaryRecycling[val.Key][1];
                    if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleRoute = uprnDictionaryRecycling[val.Key][0];
                    if (uprnDictionaryRecycling.ContainsKey(val.Key) && uprnDictionaryRecycling[val.Key][0].Length > 2) recyclingRound = uprnDictionaryRecycling[val.Key][0].Substring(0, 1) + (uprnDictionaryRecycling[val.Key][0].Length > 3 ? uprnDictionaryRecycling[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryRecycling[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim));
                    if (uprnDictionaryRecycling.ContainsKey(val.Key)) serviceLocationRecyclingSequence = uprnDictionaryRecycling[val.Key][5];

                    string residualCollection = "";
                    string residualRoute = "";
                    string refuseRound = "";
                    string serviceLocationRefuseSequence = "";
                    string llpgName = "\"" + val.Value[7] + "\"";
                    string llpgNo = val.Value[8];
                    string llpgStreet = val.Value[9];
                    string llpgLocality = "";
                    string llpgTown = val.Value[10];
                    string llpgPosttown = val.Value[11];
                    string llpgPostcode = val.Value[12];
                    string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23}{24}",
                        uprn, address, postcode, organicDay, organicRoute, oRoutea, organicsRoute, organicWeek,
                        serviceLocationOrganicSequence, recycleCollection, recycleRoute, recyclingRound,
                        serviceLocationRecyclingSequence, residualCollection, residualRoute, refuseRound,
                        serviceLocationRefuseSequence, llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown,
                        llpgPosttown, llpgPostcode, Environment.NewLine);
                    uprnCsv.Append(newLine);
                }
                // Then add all the ones from organic where they don't exist in residual
                foreach (var val in uprnDictionaryOrganic.Where(x => !uprnDictionaryResidual.ContainsKey(x.Key) && !uprnDictionaryOrganic.ContainsKey(x.Key)))
                {
                    string uprn = val.Key;
                    string address = "\"" + val.Value[2] + "\"";
                    string postcode = val.Value[3];
                    string organicDay = "";
                    string organicRoute = "";
                    string oRoutea = "";
                    string organicsRoute = "";
                    string organicWeek = "";
                    string serviceLocationOrganicSequence = "";

                    string recycleCollection = "";
                    string recycleRoute = "";
                    string recyclingRound = "";
                    string serviceLocationRecyclingSequence = "";
                    recycleCollection = val.Value[1];
                    recycleRoute = val.Value[0];
                    if (uprnDictionaryRecycling.ContainsKey(val.Key) && uprnDictionaryRecycling[val.Key][0].Length > 2) recyclingRound = uprnDictionaryRecycling[val.Key][0].Substring(0, 1) + (uprnDictionaryRecycling[val.Key][0].Length > 3 ? uprnDictionaryRecycling[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryRecycling[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim));
                    serviceLocationRecyclingSequence = val.Value[5];

                    string residualCollection = "";
                    string residualRoute = "";
                    string refuseRound = "";
                    string serviceLocationRefuseSequence = "";
                    string llpgName = "\"" + val.Value[6] + "\"";
                    string llpgNo = val.Value[7];
                    string llpgStreet = val.Value[8];
                    string llpgLocality = "";
                    string llpgTown = val.Value[9];
                    string llpgPosttown = val.Value[10];
                    string llpgPostcode = val.Value[11];
                    string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23}{24}",
                        uprn, address, postcode, organicDay, organicRoute, oRoutea, organicsRoute, organicWeek,
                        serviceLocationOrganicSequence, recycleCollection, recycleRoute, recyclingRound,
                        serviceLocationRecyclingSequence, residualCollection, residualRoute, refuseRound,
                        serviceLocationRefuseSequence, llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown,
                        llpgPosttown, llpgPostcode, Environment.NewLine);
                    uprnCsv.Append(newLine);
                }
                File.WriteAllText(appSettings["uprnCsv"], uprnCsv.ToString());
            }
            catch (FileGDBException ex)
            {
                Console.WriteLine("{0} - {1}", ex.Message, ex.ErrorCode);
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception.  " + ex.Message);
            }
            //}
        }
Example #18
0
        public void displayWinner()
        {
            Dictionary<PairParticipant, double> dict = new Dictionary<PairParticipant, double>();
            foreach (Сompetition competition in competitions)
            {
                var CompetitionProtocols = this.protocols.FindAll(protocol => protocol.competition == competition);
                var pairsInCompetition = CompetitionProtocols.GroupBy(protocol => protocol.pair);
                var data = pairsInCompetition.Select(
                    g => new
                    {      
                        Pair = g.Key,
                        Score = g.Sum(pair => pair.score) * competition.coefficient
                    }
                 );

                foreach (var datum in data)
                {
                    if (dict.ContainsKey(datum.Pair))
                    {
                        dict[datum.Pair] += datum.Score;
                    }
                    else
                    {
                        dict.Add(datum.Pair, datum.Score);
                    }
                }
            }

            var result = dict.GroupBy(x => x.Key).Select(
                g => new
                {
                    Pair = g.Key,
                    Score = g.Sum(x => x.Value)
                }
            ).OrderBy(x => x.Score);

            System.Console.Write("Number of pairs is: ");
            System.Console.WriteLine(result.Count());
            System.Console.WriteLine("Winner is: ");
            result.First().Pair.display();
            System.Console.WriteLine();
            System.Console.Write("Score is: ");
            System.Console.WriteLine(result.First().Score);

        }
        public async Task<List<string>> IssueInventoryAsync(Dictionary<string, IEnumerable<ImportInvetoryIssueToSalesman>> stockLines)
        {
            return await Task.Run(() =>
                                      {
                                          var errors = new List<string>();
                                          Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Starting inventory issue to salesmen..."));
                                          var applicationId = _configService.Load().CostCentreApplicationId;
                                         
                                          foreach (var stockLine in stockLines.GroupBy(n => n.Key)) //key=>salesmancode
                                          {
                                             
                                              
                                              InventoryTransferNote inventoryTransferDoc = null;
                                              InventoryAdjustmentNote inventoryAdjustmentNote = null;
                                              var salsmancode = stockLine.Key;

                                              var distributor =
                                                  _repositoryHelpers.MapDistributor(
                                                      _ctx.tblCostCentre.FirstOrDefault(
                                                          n => n.CostCentreType == (int) CostCentreType.Distributor));
                                              Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Loading Salesman...."));
                                              var transferTo = _costCentreRepository.GetByCode(salsmancode,CostCentreType.DistributorSalesman, true);

                                              var salesmanUser = _userRepository.GetByCostCentre(distributor.Id).FirstOrDefault();
                                              if (distributor != null && transferTo != null && salesmanUser != null)
                                              {

                                                  #region create inventory adjustment note

                                                  inventoryAdjustmentNote =
                                                      _inventoryAdjustmentNoteFactory.Create(distributor, applicationId,
                                                                                             distributor,
                                                                                             salesmanUser, "",
                                                                                             InventoryAdjustmentNoteType
                                                                                                 .Available, Guid.Empty);
                                                  Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("AInventory adjustment note created for distribuor=>{0}",distributor.CostCentreCode));

                                                  #endregion

                                                  #region create inventory transfer note

                                                  inventoryTransferDoc =
                                                      _inventoryTransferNoteFactory.Create(distributor, applicationId,
                                                                                           salesmanUser, transferTo,
                                                                                           distributor, "");
                                                  Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("AInventory transfer note created to salesman=>{0}", transferTo.CostCentreCode));

                                                  #endregion

                                                  foreach (var stockitem in stockLine.SelectMany(n => n.Value.ToList()))
                                                  {
                                                      string msg = string.Empty;
                                                      try
                                                      {
                                                          var product =
                                                              _ctx.tblProduct.FirstOrDefault(
                                                                  p =>
                                                                  p.ProductCode != null &&
                                                                  p.ProductCode == stockitem.ProductCode);

                                                          if (product != null)
                                                          {
                                                              var lineitem =
                                                                  _inventoryAdjustmentNoteFactory.CreateLineItem(
                                                                      stockitem.
                                                                          ApprovedQuantity, product.id,
                                                                      0,
                                                                      0,
                                                                      "Inventory Adjustment");

                                                              inventoryAdjustmentNote.AddLineItem(lineitem);

                                                              InventoryTransferNoteLineItem itnLineitem =
                                                                  _inventoryTransferNoteFactory.CreateLineItem(
                                                                      product.id,
                                                                      stockitem.
                                                                          ApprovedQuantity,
                                                                      0, 0,
                                                                      "");
                                                              if (itnLineitem != null)
                                                                  inventoryTransferDoc.AddLineItem(itnLineitem);



                                                              if (msg != "")
                                                              {
                                                                  FileUtility.LogError(msg);
                                                                  errors.Add(msg);
                                                              }
                                                          }
                                                          else
                                                          {
                                                              var error = string.Format("{0} doest exist=>",
                                                                                        stockitem.ProductCode);
                                                              if (!errors.Any(p => p.Contains(error)))
                                                                  errors.Add(error);
                                                          }

                                                      }
                                                      catch (Exception ex)
                                                      {
                                                          Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Error occured while adjusting inventory..See error logs"));
                                                          FileUtility.LogError(ex.Message);
                                                      }
                                                  }
                                                  Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Confirming inventory adjustment note for distributr=>{0}", distributor.CostCentreCode));
                                                  inventoryAdjustmentNote.Confirm();
                                                  _inventoryAdjustmentNoteWfManager.SubmitChanges(inventoryAdjustmentNote);
                                                  Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Inventory adjustment note CONFIRMED for distributr=>{0}", distributor.CostCentreCode));
                                                  
                                                  Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Confirming inventory transfer to salesman=>{0}", transferTo.CostCentreCode));
                                                  inventoryTransferDoc.Confirm();
                                                  _inventoryTransferNoteWfManager.SubmitChanges(inventoryTransferDoc);
                                                  Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Inventory  transfer CONFIRMED to salesman=>{0}", transferTo.CostCentreCode));

                                                 

                                              }
                                              else
                                              {
                                                  FileUtility.LogError(
                                                      string.Format("Inventory issue failed for salesman=>{0}",
                                                                    salsmancode));
                                                  if (distributor == null)
                                                  {
                                                      FileUtility.LogError(
                                                          string.Format("Distributor is null=> doest exist"));
                                                      Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Distributor is null=> doest exist"));
                                                  }
                                                  
                                                  if (transferTo == null)
                                                  {
                                                      FileUtility.LogError(
                                                          string.Format("salesman is with code=>{0} doest exist",
                                                                        salsmancode));
                                                      Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("salesman is with code=>{0} doest exist",
                                                                        salsmancode));

                                                  }
                                                  
                                                  if (salesmanUser == null)
                                                  {
                                                      Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("user is null=> doest exist"));
                                                      FileUtility.LogError(string.Format("user is null=> doest exist"));
                                                  }
                                                  

                                                  FileUtility.LogError("----------------------------------------------");

                                              }
                                          }
                                          
                                          return errors;
                                      });
        }
Example #20
0
        //                      entry, <minlevel, maxlevel>
        public static Dictionary<uint, Tuple<uint, uint>> GetLevels(Dictionary<WowGuid, Unit> units)
        {
            if (units.Count == 0)
                return null;

            var entries = units.GroupBy(unit => unit.Key.GetEntry());
            var list = new Dictionary<uint, List<uint>>();

            foreach (var pair in entries.SelectMany(entry => entry))
            {
                if (list.ContainsKey(pair.Key.GetEntry()))
                    list[pair.Key.GetEntry()].Add(pair.Value.Level.GetValueOrDefault(1));
                else
                    list.Add(pair.Key.GetEntry(), new List<uint> { pair.Value.Level.GetValueOrDefault(1) });
            }

            var result = list.ToDictionary(pair => pair.Key, pair => Tuple.Create(pair.Value.Min(), pair.Value.Max()));

            return result.Count == 0 ? null : result;
        }
Example #21
0
		private void btnMoveHoldemTable_Click(object sender, EventArgs e)
		{
			var gameTableWindowList = new Dictionary<string, IntPtr>();

			var childs = NativeMethodsHelper.GetAllWindows();
			foreach (var handle in childs)
			{
				var sb = new StringBuilder(500);

				var length = NativeMethodsHelper.GetWindowText((IntPtr)handle, sb, 500);
				if (length <= 0)
					continue;

				var title = sb.ToString();

				var pattern = @"\[(?<NickName>.*)\]\[(?<TableId>.*)\]\[(?<JumpEntryId>.*)\]";
				foreach (Match m in Regex.Matches(title, pattern))
				{
					if (m.Success == false)
						continue; ;

					var nickName = m.Groups["NickName"];
					var tableId = m.Groups["TableId"];
					var jumpEntryId = m.Groups["JumpEntryId"];

					// JumpEntryId -> NickName 순으로 정렬
					gameTableWindowList.Add(string.Format("{0}.{1}", tableId, nickName), (IntPtr)handle);
				}
			}

			// 정렬
			if (gameTableWindowList.Count == 0)
				return;

			// 위치 정렬
			var tableIdList = gameTableWindowList.GroupBy(g => g.Key.Split('.')[0]).ToList().OrderBy(list => list.Key).ToList();
			if (tableIdList.Count > 0)
			{
				int yLocation = 0;
				foreach (var tableIdKV in tableIdList)
				{
					var tableId = tableIdKV.Key;
					var lists = gameTableWindowList.Where(g => g.Key.Split('.')[0] == tableId).OrderBy(g => g.Key).Select(g => g.Value).ToList();

					this.MoveGameTable(tableId, lists, yLocation++);
				}
			}
		}
        private static async Task PermuteSingleDiagonal(Dictionary<FaceType, RelativePosition> relations, CubeConfiguration<FaceColour> configuration, ICollection<IRotation> solution)
        {
            var groups = relations.GroupBy(kvp => kvp.Value).ToList();
            var oppositeRelation = groups.FirstOrDefault(group => group.Key == RelativePosition.Opposite);
            if (oppositeRelation != null)
            {
                switch (oppositeRelation.Count())
                {
                    case 2:
                    case 4:
                        await CommonActions.ApplyAndAddRotation(Rotations.UpperClockwise, solution, configuration).ConfigureAwait(false);

                        relations = CrossRelativePositions(configuration);
                        await PermuteSingleDiagonal(relations, configuration, solution).ConfigureAwait(false);

                        return;
                }
            }

            // TODO: TIDY
            var sameRelation = groups.FirstOrDefault(group => group.Key == RelativePosition.Same);
            if (sameRelation == null) return;
            if (sameRelation.Count() > 1)
            {
                await CommonActions.ApplyAndAddRotation(Rotations.UpperClockwise, solution, configuration).ConfigureAwait(false);

                relations = CrossRelativePositions(configuration);
                await PermuteSingleDiagonal(relations, configuration, solution).ConfigureAwait(false);

                return;
            }

            var faceType = sameRelation.First().Key;

            var faceColour = configuration.Faces[faceType].TopCentre();
            var cubeRotation = await CommonActions.PositionOnFront(configuration, faceColour).ConfigureAwait(false);

            if (cubeRotation != null)
                solution.Add(cubeRotation);

            if (oppositeRelation.First().Key == FaceRules.FaceAtRelativePositionTo(faceType, RelativePosition.Right))
            {
                await PermuteClockwise(configuration, solution).ConfigureAwait(false);

            }
            else
            {
                await PermuteAntiClockwise(configuration, solution).ConfigureAwait(false);

            }
        }
 public virtual Dictionary<string, string> DowncaseDictionary(Dictionary<string, string> dict) {
     Contract.Requires<ArgumentNullException>(dict != null);
     return dict.GroupBy(x => x.Key.ToLower()).Select(x => x.First())
         .ToDictionary(x => x.Key.ToLower(), x => x.Value);
 }
        void CheckSchema() {
            using( MySqlTransaction transaction = connection.BeginTransaction() ) {
                // Create metadata table. Does noting if table already exists.
                transaction.ExecuteNonQuery( MetadataTableSchema );

                // load metadata
                using( MySqlCommand loadMetadataCmd = new MySqlCommand( LoadMetadataQuery, connection, transaction ) ) {
                    using( MySqlDataReader reader = loadMetadataCmd.ExecuteReader() ) {
                        if( reader.Read() ) {
                            // read existing metadata
                            int workingFormatVersion = reader.GetInt32( 0 );
                            string workingServerVersionString = reader.GetString( 1 );
                            DateTime workingLastModified = reader.GetInt64( 2 ).ToDateTime();
                            Logger.Log( LogType.SystemActivity,
                                        "Loading PlayerDB (format {0}, generated by {1}, last modified {2})",
                                        workingFormatVersion,
                                        workingServerVersionString,
                                        workingLastModified.ToCompactString() );
                        } else {
                            // no metadata found - insert a row
                            Logger.Log( LogType.Warning,
                                        "No existing metadata record found in the specified database." );
                            GenerateSchema( transaction );
                        }
                    }
                }

                // load the rank mapping
                var databaseRankMapping = new Dictionary<int, Rank>();
                using( MySqlCommand loadRankMappingCmd = new MySqlCommand( LoadRankMappingQuery, connection, transaction ) ) {
                    using( MySqlDataReader reader = loadRankMappingCmd.ExecuteReader() ) {
                        while( reader.Read() ) {
                            int index = reader.GetInt32( 0 );
                            string rankName = reader.GetString( 1 );
                            Rank rank = Rank.Parse( rankName );
                            if( rank == null ) {
                                rank = RankManager.DefaultRank;
                                Logger.Log( LogType.Warning,
                                            "MySqlPlayerDBProvider: Unrecognized rank \"{0}\". Any reference to this rank will be replaced with \"{1}\".",
                                            rankName, rank.Name );
                            }
                            databaseRankMapping.Add( index, rank );
                        }
                    }
                }

                // check if multiple indices refer to the same rank
                var indicesGroupedByRank = databaseRankMapping.GroupBy( pair => pair.Value );
                foreach( var indexGroup in indicesGroupedByRank.Where( group => group.Count() > 1 ) ) {
                    Logger.Log( LogType.Warning,
                                "MySqlPlayerDBProvider: Multiple incides ({0}) refer to the same rank ({1}) and will be merged.",
                                indexGroup.Select( pair => pair.Key ).JoinToString(),
                                indexGroup.Key.Name );
                }

                // enumerate all rank IDs in the database
                var allRankIDs = new HashSet<int>();
                using( MySqlCommand listRanksCmd = new MySqlCommand( ListRanksQuery, connection, transaction ) ) {
                    using( MySqlDataReader reader = listRanksCmd.ExecuteReader() ) {
                        while( reader.Read() ) {
                            allRankIDs.Add( reader.GetInt32( 0 ) );
                        }
                    }
                }
                using( MySqlCommand listPreviousRanksCmd = new MySqlCommand( ListPreviousRanksQuery, connection, transaction ) ) {
                    using( MySqlDataReader reader = listPreviousRanksCmd.ExecuteReader() ) {
                        while( reader.Read() ) {
                            allRankIDs.Add( reader.GetInt32( 0 ) );
                        }
                    }
                }

                // Replace any unknown rank indices with the default rank.
                var unknownRanks = allRankIDs.Except( databaseRankMapping.Keys );
                if( unknownRanks.Count() > 0 ) {
                    Logger.Log( LogType.Warning,
                                "MySqlPlayerDBProvider: Following unrecognized rank indices will be replaced with the default rank ({0}): {1}",
                                RankManager.DefaultRank.Name,
                                unknownRanks.JoinToString() );
                    foreach( int unknownIndex in unknownRanks ) {
                        databaseRankMapping.Add( unknownIndex, RankManager.DefaultRank );
                    }
                }

                // check if rank mappings are in sync
                rankMapping = RankManager.Ranks
                                         .OrderBy( rank => rank.Index )
                                         .ToDictionary( rank => rank.Index );

                if( !rankMapping.SequenceEqual( databaseRankMapping.OrderBy( pair => pair.Key ) ) ) {
                    Logger.Log( LogType.Warning,
                                "MySqlPlayerDBProvider: Updating database rank mapping..." );
                    RebuildRankMapping( databaseRankMapping, transaction );
                }

                // done loading (phew)
                transaction.Commit();
            }
        }
Example #25
0
        IEnumerable<IGrouping<string, string>> OverrideWithInputs(IEnumerable<IGrouping<string, string>> parameters)
        {
            var overrides = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            if (Configuration != null)
                overrides.Add("Configuration", Configuration);
            if (Incremental)
                overrides.Add("Incremental", "True");
            overrides.Add("OpenWrap-CurrentBuildVersion", _generatedVersion.ToString());
            if (_sharedAssemblyInfoFile != null)
                overrides.Add("OpenWrap-SharedAssemblyInfoFile", _sharedAssemblyInfoFile.Path.FullPath);

            return overrides.GroupBy(x => x.Key, x => x.Value).Concat(_wildcards.Concat(parameters).Where(param => !overrides.ContainsKey(param.Key)));
        }
        public override HashSet<string[]> ReduceNames(Dictionary<string, int> nodeNames)
        {
            var hash = new HashFunction8();
            var groups = nodeNames.GroupBy(n => hash.HashName(n.Key)).Select(g => new Group
            {
                Hash = g.Key,
                Instances = g.ToList(),
                Words = hash.HashName(g.First().Key).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray()
            }).OrderBy(g => g.Instances.Count).ToArray();

            var numbers = groups.Where(g => g.Hash.All(c => '0' <= c && c <= '9')).Select(g => Convert.ToInt32(g.Hash));
            groups = groups.Where(g => !g.Hash.All(c => '0' <= c && c <= '9')).ToArray();

            {
                var wordFrequency = new Dictionary<string, int>();
                var wordCount = 0;
                foreach (var group in groups)
                {
                    foreach (var word in group.Words)
                    {
                        if (!wordFrequency.ContainsKey(word))
                        {
                            wordFrequency[word] = 0;
                        }
                        wordFrequency[word] += group.Instances.Count;
                        wordCount += group.Instances.Count;
                    }
                }
                WordScore = wordFrequency.ToDictionary(k => k.Key, k => wordCount/(1.0*k.Value));
            }

            Logger.Log(string.Format("The {0} groups have an average size {1}",
                groups.Length, groups.Average(g => g.Instances.Count)));
            bool reduced;
            int pass = 0;
            do
            {
            #if DEBUG
                Filename = "Reductions_3_" + pass + ".txt";
                lock (Filename)
                {
                    File.Delete(Filename);
                }
            #endif

                var reductions = Logger.Batch(groups.Length - 1, i => ReduceName(groups, i, 25), "reduced this pass")
                    .Where(p => p != null).OrderBy(p => p.Item1).ToList();

                reduced = reductions.Count > 0;

                foreach (var reduction in reductions)
                {
                    groups[reduction.Item2].Instances.AddRange(groups[reduction.Item1].Instances);
                    groups[reduction.Item1] = null;
                }

                groups = groups.Where(g => g != null).OrderBy(g => g.Instances.Count()).ToArray();

            #if DEBUG
                lock (Filename)
                {
                    File.AppendAllText(Filename, ("~~~ " + reductions.Count + " ~~~ reductions were made in this pass" + "\n"));
                }
            #endif

                Logger.Log(reductions.Count + " reductions were made");
                Logger.Log(string.Format("The {0} groups have an average size {1}",
                    groups.Length, groups.Average(g => g.Instances.Count())));
                pass++;
            } while (reduced);

            var numberNameGroups = numbers.OrderBy(n => n).Select(n => new[] {n.ToString()});
            var textNameGroups = groups.Select(g => g.Instances.Select(inst => inst.Key).Distinct().ToArray());

            return new HashSet<string[]>(numberNameGroups.Concat(textNameGroups));
        }