public static Dictionary<string, double> ProcessIntSequence(List<int> seq, int order, bool normalize) { var ans = new Dictionary<string, double>(); for (int i = 0; i < seq.Count - order; i++) { string nextkey = "v" + string.Join("_", seq.Skip(i).Take(order).Select(s => s.ToString()).ToArray()); if (ans.ContainsKey(nextkey)) { if (normalize) ans[nextkey] += (double)100 / (double)seq.Count; else ans[nextkey]++; } else { if (normalize) ans.Add(nextkey, (double)100 / (double)seq.Count); else ans.Add(nextkey, 1); } } if (normalize) ans = ans.Where(p => p.Value >= 200 / (double)seq.Count).ToDictionary(p => p.Key, p => p.Value); else ans = ans.Where(p => p.Value >= 2).ToDictionary(p => p.Key, p => p.Value); return ans; }
static void Main() { Console.SetIn(File.OpenText("TextFile1.txt")); int n = int.Parse(Console.ReadLine()); string move1 = Console.ReadLine(); string move2 = Console.ReadLine(); Dictionary<int, Turn> Turns = new Dictionary<int, Turn>(); for (int i = 1; i <= n; i++) { Turns.Add(i, new Turn() { Number = i} ); } int lastNumber = 0; int count = 0; int multiplayer = 1; while (Turns.Where(t => !t.Value.IsCaptured).ToList().Count > 0) { var newTurns = Turns.Where(t => !t.Value.IsCaptured).ToList(); count = newTurns.Count; for (int i = 0; i < count; i++) { lastNumber = newTurns[i].Value.Number; Turns[i].IsCaptured = true; i += multiplayer; } multiplayer++; } Console.WriteLine(lastNumber); Console.WriteLine(MakeMoves(move1)); Console.WriteLine(MakeMoves(move2)); //work :) //Console.WriteLine("bounded"); //Console.WriteLine("bounded"); }
public void ChangeMealeUnitAttack(Model M, Dictionary<int, Units> team) { int pos0 = 0; int pos1 = 0; int pos2 = 0; if (M.CurrentUnitAttack == 5) { string tostr = M.CanAttack[4].ToString(); char[] pos = tostr.ToCharArray(); try { int.TryParse(pos[0].ToString(), out pos0); int.TryParse(pos[1].ToString(), out pos1); int.TryParse(pos[2].ToString(), out pos2); } catch (Exception e) { } var Target = team.Where(z => z.Value.Live == true) .Where(y => y.Key == pos0 || y.Key == pos1 || y.Key == pos2) .OrderBy(x => x.Value.HP) .FirstOrDefault(); M.PositionUnitOfAttack = Target.Key; } else if (M.CurrentUnitAttack == 4) { string tostr = M.CanAttack[3].ToString(); char[] pos = tostr.ToCharArray(); try { int.TryParse(pos[0].ToString(), out pos0); int.TryParse(pos[1].ToString(), out pos1); } catch (Exception e) { } var Target = team.Where(z => z.Value.Live == true) .Where(y => y.Key == pos0 || y.Key == pos1) .OrderBy(x => x.Value.HP) .FirstOrDefault(); M.PositionUnitOfAttack = Target.Key; } else { string tostr = M.CanAttack[5].ToString(); char[] pos = tostr.ToCharArray(); try { int.TryParse(pos[0].ToString(), out pos0); int.TryParse(pos[1].ToString(), out pos1); } catch (Exception e) { } var Target = team.Where(z => z.Value.Live == true) .Where(y => y.Key == pos0 || y.Key == pos1) .OrderBy(x => x.Value.HP) .FirstOrDefault(); M.PositionUnitOfAttack = Target.Key; } }
public static IDictionary<Version, ChangeLogVersionDetails> GetChangeLog(Version fromVersion, Version toVersion, XDocument changeLogContent) { var changeLog = new Dictionary<Version, ChangeLogVersionDetails>(); foreach (var changeVersion in changeLogContent.Descendants("Version")) { var changeLogItem = BuildChangeLogItem(changeVersion); if (!changeLog.ContainsKey(changeLogItem.Key)) { changeLog.Add(changeLogItem.Key, changeLogItem.Value); } } if (fromVersion < toVersion && changeLog.Any(x => x.Key > fromVersion && x.Key <= toVersion)) { return changeLog.Where(x => x.Key > fromVersion && x.Key <= toVersion).OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value); } if (fromVersion < toVersion && changeLog.Any() && toVersion > changeLog.Keys.Max()) { return changeLog.Where(x => x.Key == changeLog.Keys.Max()).ToDictionary(detail => detail.Key, detail => detail.Value); } if (fromVersion < toVersion && toVersion.Revision > 0 && changeLog.Any() && toVersion < changeLog.Keys.Max()) { var versionWithoutRevision = new Version(toVersion.Major, toVersion.Minor, toVersion.Build); return changeLog.Where(x => x.Key > versionWithoutRevision).ToDictionary(detail => detail.Key, detail => detail.Value); } return changeLog.OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value); }
public static async Task <List <_ComponenteBase> > VerificarPreenchimentoCampos(this List <_ComponenteBase> listaCampos, bool mostrarMensagem = true, Dictionary <_ComponenteBase, Func <bool> > camposValores = null) { var camposAdicionais = camposValores?.Where(x => x.Value?.Invoke() ?? false).Select(x => x.Key).ToList() ?? new List <_ComponenteBase>(); var camposRemovidos = camposValores?.Where(x => !x.Value?.Invoke() ?? true).Select(x => x.Key).ToList() ?? new List <_ComponenteBase>(); var listaCamposTratado = listaCampos?.Where(x => !camposRemovidos.Contains(x)).Union(camposAdicionais).ToList() ?? new List <_ComponenteBase>(); var camposNaoPreenchidos = new List <_ComponenteBase>(); camposNaoPreenchidos.AddRange(listaCamposTratado.OfType <Entrada>().Where(x => string.IsNullOrEmpty(x.Texto)).ToList()); camposNaoPreenchidos.AddRange(listaCamposTratado.OfType <EntradaAdicional>().Where(x => string.IsNullOrEmpty(x.Texto)).ToList()); camposNaoPreenchidos.AddRange(listaCamposTratado.OfType <MostraValores>().Where(x => x.ListaItens == null || !x.ListaItens.Any() || x.ListaItens.Any(p => p.Objeto == Constantes.NaoSelecionar)).ToList()); if (mostrarMensagem) { if (camposNaoPreenchidos.Count == 1) { await Estrutura.Mensagem("Falta preencher um campo obrigatório!").ConfigureAwait(false); } else if (camposNaoPreenchidos.Count > 1) { await Estrutura.Mensagem($"Existem {camposNaoPreenchidos.Count} campos obrigatórios que não foram preenchidos!").ConfigureAwait(false); } } return(camposNaoPreenchidos); }
private List<string> GetLinksAsJs( List<MarriageSon> marriageSons, List<Marriage> marriages, Dictionary<long, Tuple<int, string>> personsJsNodes, Dictionary<long, Tuple<int, string>> marriageJsNodes) { var linksAsJs = new List<string>(); foreach(var marriageSon in marriageSons) { var marriage = marriages.Where(x => x.id.Equals(marriageSon.marriage_id)).FirstOrDefault(); var marriageJsId = marriageJsNodes.Where(x => x.Key.Equals(marriage.id)).Select(x => x.Value.Item1).FirstOrDefault(); var sonJsId = personsJsNodes.Where(x => x.Key.Equals(marriageSon.son_id)).Select(x => x.Value.Item1).FirstOrDefault(); var husbandJsId = personsJsNodes.Where(x => x.Key.Equals(marriage.husband_id)).Select(x => x.Value.Item1).FirstOrDefault(); var wifeJsId = personsJsNodes.Where(x => x.Key.Equals(marriage.wife_id)).Select(x => x.Value.Item1).FirstOrDefault(); var jsText2 = string.Format("{{\"source\": {0}, \"target\": {1}}}", husbandJsId, marriageJsId); var jsText3 = string.Format("{{\"source\": {0}, \"target\": {1}}}", wifeJsId, marriageJsId); var jsText1 = string.Format("{{\"source\": {0}, \"target\": {1}}}", marriageJsId, sonJsId); linksAsJs.AddRange(new string[] { jsText1, jsText2, jsText3 }); } return linksAsJs; }
public List<Coin> ReturnCache() { List<Coin> for_return = new List<Coin>(); //Получаем список всех доступных монет Dictionary<Coin, int> avail_coins = new Dictionary<Coin, int>(); foreach(var item in GetSorted()) { avail_coins.Add(new Coin(item.Key), item.Value); } //Массив всех доступных номиналов int[] values = avail_coins.Where(p => p.Value > 0).OrderByDescending(p => p.Key.Info.Price).Select(p => p.Key.Info.Price).ToArray(); int i = 0; while (_money_cache > 0 && i<values.Length) { //Сколько нам нужно монет данного номинала int need_coins = (int)Math.Floor((double)_money_cache / values[i]); //Сколько у нас их есть int have_coins=avail_coins.Where(p=>p.Key.Info.Price==values[i]).Select(p=>p.Value).First(); //Если у нас есть такое кол-во данных монет то возвращаем его, иначе отдаем что есть if(need_coins>have_coins) { need_coins = have_coins; } List<Coin> ret_coins=_GetCoins(values[i], need_coins); for_return.AddRange(ret_coins); _money_cache -= VMWallet.GetSum(ret_coins); i++; } return for_return; }
public Diff GetDiff(Dictionary<string, PriceItem> newProds, Dictionary<string, PriceItem> oldProds) { oldProds = oldProds ?? new Dictionary<string, PriceItem>(); var diff = new Diff { NewItems = newProds.Where(kvp => !oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value), DeletedItems = oldProds.Where(kvp => !newProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value), UpdatedItems = newProds.Where(kvp => oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value) }; var toRemove = new List<string>(); foreach (var item in diff.UpdatedItems.Values) { var oldItem = oldProds[item.Reference]; if (item.WholesalePrice == oldItem.WholesalePrice && item.Active == oldItem.Active && !SameBalance(item, oldItem)) { toRemove.Add(item.Reference); } } foreach (var reference in toRemove) { diff.UpdatedItems.Remove(reference); } return diff; }
public void SaveReport(DateTime sessionStart, DateTime sessionEnd, string path, Dictionary<MouseMessage, ulong> mouseUsage, Dictionary<string, ulong> keyboardUsage, Dictionary<string, ulong> windowUsage, ulong mouseMoveLength) { XDocument xDoc = new XDocument(new XDeclaration("1.0", "", ""), new XElement("StatistiksReport", new XAttribute("SessionStart", sessionStart.ToString("yyyyMMddHHmmss")), new XAttribute("SessionEnd", sessionEnd.ToString("yyyyMMddHHmmss")), new XElement("KeyboardEvents", from x in keyboardUsage.Where(x => ((int)x.Key[0]).IsValidXmlChar()) select new XElement("Event", new XAttribute("Key", x.Key), new XAttribute("Count", x.Value))), new XElement("MouseEvents", from x in mouseUsage.Where(x => x.Key == MouseMessage.WM_LBUTTONUP || x.Key == MouseMessage.WM_RBUTTONUP) // only left or right mouse button events select new XElement("Event", new XAttribute("Code", x.Key.ToString()), new XAttribute("Count", x.Value))), new XElement("MouseMetr", from x in mouseUsage.Where(x => x.Key == MouseMessage.WM_MOUSEMOVE) select new XElement("Event", new XAttribute("Code", "Length"), new XAttribute("Count", mouseMoveLength))), new XElement("WindowsEvents", from x in windowUsage select new XElement("Event", new XAttribute("ExeName", x.Key.Split('\\').Last()), new XAttribute("ExePath", x.Key), new XAttribute("Count", x.Value))))); xDoc.Save(path); }
public void Handle() { LogHelper.Info<RefreshGroupsHandler>("Refresh started"); // 1) get the groups from db var groups = _repo.GetAll(); // 2) get the users for each group from db var usersPerGroup = _repo.GetAllUsers(); // 3) query the users in ad for each group (step 1) var adGroupedUsers = new Dictionary<int, IEnumerable<EasyADUser>>(); foreach (var group in groups) { adGroupedUsers.Add(group.Id, _groupManager.GetUsersInGroup(group.Name)); } var adUsers = GetUniqueAdUsers(adGroupedUsers); var backofficeUsers = GetUniqueBackofficeUsers(usersPerGroup).ToList(); var deleteUsers = backofficeUsers.Select(u => u.Username).Except(adUsers.Select(u => u.Login)).ToList(); var newUsers = adUsers.Select(u => u.Login).Except(backofficeUsers.Select(u => u.Username)).ToList(); // Delete the users that aren't any group anymore foreach (var name in deleteUsers) { LogHelper.Info<RefreshGroupsHandler>(string.Format("Removing user '{0}' from backoffice", name)); var user = backofficeUsers.First(u => u.Username == name); _userService.Delete(user, deletePermanently: false); _repo.DeleteUser(user.Id); backofficeUsers.Remove(user); } // Create the users that aren't in the backoffice yet foreach (var name in newUsers) { LogHelper.Debug<RefreshGroupsHandler>(string.Format("Creating user '{0}' in backoffice", name)); var user = adUsers.First(u => u.Login == name); var firstGroup = groups.Single(g => g.Id == adGroupedUsers.First(a => a.Value.Contains(user)).Key); var backofficeUser = _userService.CreateUserWithIdentity(user.Login, user.Email, _userService.GetUserTypeById(firstGroup.UserType)); backofficeUser.Name = user.DisplayName; backofficeUsers.Add(backofficeUser); } // Update the current users foreach (var user in backofficeUsers) { var userGroupIds = adGroupedUsers.Where(g => g.Value.Any(u => u.Login == user.Username)).Select(g => g.Key).ToList(); _repo.SetGroupsForUser(user.Id, userGroupIds); var groupsUserIsIn = adGroupedUsers.Where(a => a.Value.Any(u => u.Login == user.Username)).Select(kvp => groups.First(g => g.Id == kvp.Key)); ConfigureUserRights(user, groupsUserIsIn); } LogHelper.Info<RefreshGroupsHandler>("Refresh completed"); }
static public IDnaDataReader CreateMockedIDnaDataReader(MockRepository mocks, List<TestDatabaseRow> testRowData) { IDnaDataReader reader = mocks.DynamicMock<IDnaDataReader>(); if (testRowData != null) { Dictionary<string, Queue<RowQueueItem>> queuedData = new Dictionary<string, Queue<RowQueueItem>>(); reader.Stub(x => x.HasRows).Return(true).WhenCalled(x => x.ReturnValue = queuedData.Where(y => y.Value.Count() > 0).Count() > 0); bool firstread = true; reader.Stub(x => x.Read()).Return(true).WhenCalled(x => { if (!firstread) { // Find the non-empty queues var nq = queuedData.Where(n => n.Value.Count() > 0); // Find the min value of Row in all the RowQueueItems var min = nq.Min(q => q.Value.Min(n => n.Row)); // Get all queues that contain a RowQueueItem with Row == min // These are the queues that contain column values for the current // row that need dequeuing var queues = nq.Where(q => q.Value.Min(n => n.Row) == min); foreach (var qd in queues) qd.Value.Dequeue(); } firstread = false; // If we still have at least 1 non-empty queue, return true x.ReturnValue = queuedData.Where(y => y.Value.Count() > 0).Count() >= 1; }); int row = 1; foreach (TestDatabaseRow o in testRowData) { foreach (KeyValuePair<string, object> kv in o.paramAndValues) { string keyName = kv.Key; object objectValue = kv.Value; if (!queuedData.ContainsKey(keyName)) { queuedData.Add(keyName, new Queue<RowQueueItem>()); } queuedData[keyName].Enqueue(new RowQueueItem { Row = row, ObjectValue = objectValue }); } row++; } QueueValuesToDataReaderCalls(reader, queuedData); } return reader; }
/// <summary> /// Sort the collection in the proper manner. /// </summary> internal static Dictionary<string, ListDictionary> SortCollection(Dictionary<string, ListDictionary> collection, string treeLevel, string sortLevel) { switch (sortLevel) { case "Alphabet": return collection .OrderBy(kvp => kvp.Key) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); case "Effort": return collection .OrderByDescending(kvp => kvp.Value["effort"]) .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie. .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); case "Priority": return collection .OrderByDescending(kvp => kvp.Value["priority"]) .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie. .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); case "Product": var missingTeamString = SimpleWorkItem.GetMissingString("Team"); var missingTeamCollection = collection.Where(kvp => kvp.Key == missingTeamString); // Reference the 'NO TEAM' grouping. return collection .Where(kvp => kvp.Key != missingTeamString) // Exclude 'NO TEAM' from sorting. .OrderBy(kvp => kvp.Key != "Atlas") .ThenBy(kvp => kvp.Key != "Anubis") .ThenBy(kvp => kvp.Key != "Proteus") .ThenBy(kvp => kvp.Key != "Shiva") .ThenBy(kvp => kvp.Key != "Janus") .ThenBy(kvp => kvp.Key != "Phoenix") .ThenBy(kvp => kvp.Key != "Brahma") .ThenBy(kvp => kvp.Key != "Loki") .ThenBy(kvp => kvp.Key != "Heimdall") .ThenBy(kvp => kvp.Key != "Vulcan") .ThenBy(kvp => kvp.Key != "Athena") .ThenBy(kvp => kvp.Key != "Ra") .ThenBy(kvp => kvp.Key) // Any unmentioned teams above will be sorted alphabetically. .Concat(missingTeamCollection) // Attach 'NO TEAM' back on. .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); case "Date": const string futureString = "Future"; var missingString = SimpleWorkItem.GetMissingString(treeLevel); var futureCollection = collection.Where(kvp => kvp.Key == futureString); // Reference the Future grouping. var missingCollection = collection.Where(kvp => kvp.Key == missingString); // Reference the missing grouping. return collection .Where(kvp => kvp.Key != futureString && kvp.Key != missingString) // Exclude Future and missing from sorting. .OrderBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(0, "Z")) // Sort by Year, using "Z" to place it last if it's missing. .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(1, "Z")) // Sort by Quarter, using "Z" to place it last if it's missing. .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(2, "Z")) // Sort by Sprint, using "Z" to place it last if it's missing. .Concat(futureCollection) // Attach Future back on. .Concat(missingCollection) // Attach missing back on. .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); default: throw new Exception("Sorting type: " + sortLevel + ", is not supported."); } }
public Contour GetSingleContour() { if (Contours.Count == 0){ throw new Exception("Контуры отсутствуют"); } if (!AllContoursAreCompleted){ throw new Exception("Все контуры должны быть замкнуты!"); } var boundingBoxes = new Dictionary<int, BoundingBox>(); for (int i=0; i<Contours.Count; i++){ boundingBoxes.Add(i, Contours[i].GetBoundingBox()); } var largestBox = boundingBoxes.FirstOrDefault(x => boundingBoxes.Where(y => y.Key != x.Key).All(y => x.Value.Contains(y.Value))); var restBoxes = boundingBoxes.Where(x => x.Key != largestBox.Key).ToArray(); if (largestBox.Value == null) { throw new Exception("Контуры не образуют единой области. Дальнейшие вычисления невозможны"); } if (restBoxes.Any(x => restBoxes.Where(y => y.Key != x.Key).Any(y => x.Value.Contains(y.Value)))){ throw new Exception("Вложенность дырок недопустима. Дальнейшие вычисления невозможны"); } var largestContour = Contours[largestBox.Key]; largestContour.OrientCounterclockwise(); for (int i = 0; i < Contours.Count; i++ ){ if (i != largestBox.Key){ var contour = Contours[i]; contour.OrientClockwise(); var nearestPoints = largestContour.ToDictionary(x => x, x => contour.ToDictionary(y => y, y => Math.Sqrt(Math.Pow(x.X - y.X, 2) + Math.Pow(x.Y - y.Y, 2))).OrderBy(r => r.Value).First()). OrderBy(r => r.Value.Value).First(); int largeContourPointIndex = nearestPoints.Key.Index; int contourPointIndex = nearestPoints.Value.Key.Index; for (int j = 0; j < contour.Count - contourPointIndex + 1; j++){ Point pt = contour[contourPointIndex - 1 + j].Clone(); pt.Index = largeContourPointIndex + 1 + j; largestContour.Insert(pt.Index - 1, pt); } for (int j = 0; j < contourPointIndex; j++){ Point pt = contour[j].Clone(); pt.Index = largeContourPointIndex + contour.Count - contourPointIndex + j + 2; largestContour.Insert(pt.Index - 1, pt); } Point self = largestContour[largeContourPointIndex - 1].Clone(); int offset = self.Index + contour.Count + 2; self.Index = offset; largestContour.Insert(self.Index - 1, self); for (int j = offset; j < largestContour.Count; j++){ largestContour[j].Index = j + 1; } } } largestContour.Index = 1; Contours.Clear(); Contours.Add(largestContour); return largestContour; }
static void Main(string[] args) { Dictionary<string, Car> cars = new Dictionary<string, Car>(); int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { var input = Console.ReadLine().Split(); var model = input[0]; var engineSpeed = long.Parse(input[1]); var enginePower = long.Parse(input[2]); var cargoWeight = long.Parse(input[3]); var cargoType = input[4]; var tier1P = double.Parse(input[5]); var tier1A = int.Parse(input[6]); var tier2P = double.Parse(input[7]); var tier2A = int.Parse(input[8]); var tier3P = double.Parse(input[9]); var tier3A = int.Parse(input[10]); var tier4P = double.Parse(input[11]); var tier4A = int.Parse(input[12]); var engine = new Engine(engineSpeed, enginePower); var cargo = new Cargo(cargoWeight, cargoType); var tierOne = new Tier(tier1P, tier1A); var tierTwo = new Tier(tier2P, tier2A); var tierThree = new Tier(tier3P, tier3A); var tierFour = new Tier(tier4P, tier4A); List<Tier> tiers = new List<Tier> { tierOne, tierTwo, tierThree, tierFour }; var car = new Car(model, engine, cargo, tiers); cars[car.Model] = car; } var type = Console.ReadLine(); if (type == "fragile") { var result = cars.Where(x => x.Value.Tiers.Exists(y => y.TirePressure < 1d)); foreach (var car in result) { Console.WriteLine(car.Key); } } else { var result = cars.Where(x => x.Value.Engine.EnginePower > 250); foreach (var car in result) { Console.WriteLine(car.Key); } } }
/// <summary> /// Inits the viewmodel with the specified sys info, and setups the default categories. /// </summary> /// <param name="sysInfo">The sys info.</param> /// <param name="attachedFiles">path to the attachment</param> /// <author>Jurie.smit</author> /// <datetime>2013/01/14-09:19 AM</datetime> private void Init(SystemInfoTO sysInfo, Dictionary<string, string> attachedFiles) { Comment = null; ServerLogAttachmentPath = attachedFiles.Where(f => f.Key.Equals("ServerLog", StringComparison.CurrentCulture)).Select(v => v.Value).SingleOrDefault(); StudioLogAttachmentPath = attachedFiles.Where(f => f.Key.Equals("StudioLog", StringComparison.CurrentCulture)).Select(v => v.Value).SingleOrDefault(); Comment = GenerateDefaultComment(sysInfo); SetCaretPosition(); Categories.AddRange(new List<string> { "General", "Compliment", "Feature request", "Bug", "Feedback" }); if(attachedFiles.Count > 0) SelectedCategory = "Feedback"; }
public Guid?GetModuleMeasureDbId(ModuleId module, Measure measure) { LazyLoad(); var dbId = _moduleDbIds?.Where(x => x.Key.Item1 == module && x.Key.Item2 == measure); if (dbId == null || !dbId.Any()) { return(null); } return(dbId.First().Value); }
public void CaptureReader_Can_Read_Back_A_Stream_That_Was_Written_By_A_CaptureWriter() { var writeOperations = 100; var ms = new ConcurrentStream(new MemoryStream()); var sat = new Dictionary<Guid, short>(); sat.Add(Guid.NewGuid(), 24); sat.Add(Guid.NewGuid(), 25); sat.Add(Guid.NewGuid(), 26); var stateResolver = new Mock<IStateResolver>(); stateResolver.SetupGet(s => s.AllocationTable).Returns(sat); stateResolver.Setup(s => s.IsAllocated(It.IsAny<Guid>())).Returns<Guid>(g => sat.ContainsKey(g)); stateResolver.Setup(s => s.GetAllocatedId(It.IsAny<Guid>())).Returns<Guid>(g => sat[g]); //write operations var captureWriter = new CaptureWriter(ms, stateResolver.Object); for (int i = 0; i < writeOperations; i++) { var timestamp = DateTime.UtcNow; var randomData = new byte[1024]; new Random().NextBytes(randomData); var randomSat = (short)new Random().Next(24, 26); var captureState = new Mock<ICaptureState>(); captureState.Setup(c => c.Data).Returns(randomData); captureState.Setup(c => c.Guid).Returns(sat.Where(f => f.Value == randomSat).First().Key); captureState.Setup(c => c.Timestamp).Returns(timestamp); captureWriter.Write(captureState.Object); } //rewind the stream to the beginning ms.Position = 0; //read operations var readStateResolver = new StateResolver(); readStateResolver.Add(new SimpleStateController { Guid = sat.Where(f => f.Value == 24).First().Key }); readStateResolver.Add(new SimpleStateController { Guid = sat.Where(f => f.Value == 25).First().Key }); readStateResolver.Add(new SimpleStateController { Guid = sat.Where(f => f.Value == 26).First().Key }); var captureReader = new CaptureReader(ms, readStateResolver); while (captureReader.Position < captureReader.Count) { captureReader.Read(); } }
public ActionResult Parts(int id = 0, int page = 1, int per_page = 10) { if (id > 0) { APICategory category = new APICategory(); category = CURTAPI.GetCategory(id); ViewBag.category = category; List<APIPart> parts = CURTAPI.GetCategoryParts(id, page, per_page); Dictionary<string, List<APIPart>> ordered_parts = new Dictionary<string, List<APIPart>>(); foreach (APIPart part in parts) { APIColorCode color_code = CURTAPI.GetColorCode(part.partID); part.colorCode = color_code.code; if (part.pClass.Length > 0) { if (ordered_parts.Keys.Contains(part.pClass)) { // Already added to dictionary List<APIPart> existing_parts = ordered_parts.Where(x => x.Key == part.pClass).Select(x => x.Value).FirstOrDefault<List<APIPart>>(); existing_parts.Add(part); ordered_parts[part.pClass] = existing_parts; } else { // New Color Code List<APIPart> new_parts = new List<APIPart>(); new_parts.Add(part); ordered_parts.Add(part.pClass, new_parts); } } else { if (ordered_parts.Keys.Contains(category.catTitle.Trim())) { // Already added to dictionary List<APIPart> existing_parts = ordered_parts.Where(x => x.Key == category.catTitle.Trim()).Select(x => x.Value).FirstOrDefault<List<APIPart>>(); existing_parts.Add(part); ordered_parts[category.catTitle.Trim()] = existing_parts; } else { // New Color Code List<APIPart> new_parts = new List<APIPart>(); new_parts.Add(part); ordered_parts.Add(category.catTitle.Trim(), new_parts); } } } ViewBag.parts = ordered_parts; // We need to figure out if there are going to be more parts to display int more_count = CURTAPI.GetCategoryParts(id, page + 1, per_page).Count; ViewBag.more_count = more_count; ViewBag.page = page; ViewBag.per_page = per_page; return View(); } else { return RedirectToAction("Index", "Index"); } }
private Dictionary<string, List<Session>> CondenseNumerics(Dictionary<string, List<Session>> dictionary) { var numerics = dictionary.Where(kv => kv.Key.AsInt() > 0); var sessionList = new List<Session>(); sessionList = numerics.Aggregate(sessionList, (current, kv) => current.Concat(kv.Value).ToList()); var finalDictionary = dictionary.Where(kv => kv.Key.AsInt() == int.MinValue) .ToDictionary(kv => kv.Key, kv => kv.Value); if (sessionList.Count > 0) finalDictionary.Add("#", sessionList); return finalDictionary; }
static void Main(string[] args) { Dictionary<char, int> FrequenciesChars = new Dictionary<char, int>(); FrequenciesChars.Add('a', 100); FrequenciesChars.Add('b', 50); FrequenciesChars.Add('c', 25); FrequenciesChars.Add('d', 15); FrequenciesChars.Add('e', 5); int Million = 10000000; int TwoMillions = Million * 2; Random Randomizer = new Random(); char[] Output = new char[TwoMillions]; int RandomFreq = 0; for (int i = 0; i < TwoMillions; i++) { RandomFreq = Randomizer.Next(1, 100); var From = FrequenciesChars.Where(g => g.Value <= RandomFreq).OrderByDescending(g => g.Value).FirstOrDefault(); var To = FrequenciesChars.Where(g => g.Value > RandomFreq).OrderBy(g => g.Value).FirstOrDefault(); int FromDiff = RandomFreq - From.Value; int ToDiff = To.Value - RandomFreq; char Selected = ' '; if (ToDiff < FromDiff) { Selected = To.Key; } else { Selected = From.Key; } Output[i] = Selected; } using (var OutputStream = System.IO.File.Open("output.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write)) { var StreamWriter = new StreamWriter(OutputStream); StreamWriter.Write(Output); StreamWriter.Flush(); } Console.WriteLine(Output); Console.ReadKey(); }
public string GetBestPool(Dictionary<string, PoolServer> pools, string currentPool, int advancedSeconds) { string best = null; if (currentPool != "") { if (_currentRouletteDelay++ < MaxRouletteDelay) { return currentPool; } else { _currentRouletteDelay = 0; } } var sharePropPools = pools .Where(pool => pool.Value.Type == PoolType.Prop && pool.Value.CurrentShare < _difficulty * Threshold) .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare); if (sharePropPools.Count == 0) { sharePropPools = pools .Where(pool => pool.Value.Type == PoolType.PropEarlyHop && pool.Value.CurrentShare * 4.0 < _difficulty * Threshold) .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare); } if (sharePropPools.Count == 0) { sharePropPools = pools .Where(pool => pool.Value.Type == PoolType.Score && pool.Value.CurrentShare * 4.0 < _difficulty * Threshold) .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare); } if (sharePropPools.Count == 0) { sharePropPools = pools .Where(pool => pool.Value.Type == PoolType.Pplns && pool.Value.CurrentShare * 4.0 < _difficulty * Threshold) .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare); } if (sharePropPools.Count > 0) { best = _rnd.Roulette(sharePropPools); } return best ?? (best = "smpps"); }
private string GetWebUrl(Dictionary <string, Link> links) { return(links? .Where(l => string.Equals(l.Key, "web", StringComparison.InvariantCultureIgnoreCase)) .Select(l => l.Value?.href) .FirstOrDefault()); }
/// <summary> /// 开始导出 /// </summary> /// <param name="uidoc"></param> /// <param name="view"></param> /// <param name="localConfig"></param> /// <param name="exportType"></param> /// <param name="outputStream"></param> /// <param name="features"></param> /// <param name="useShareTexture"></param> /// <param name="progressCallback"></param> /// <param name="viewIds"></param> /// <param name="cancellationToken"></param> private void StartExport(UIDocument uidoc, View3D view, AppConfigSvf localConfig, ExportType exportType, Stream outputStream, Dictionary <FeatureType, bool> features, bool useShareTexture, Action <int> progressCallback, List <int> viewIds, CancellationToken cancellationToken) { #if EXPRESS throw new NotImplementedException(); #else using (var log = new RuntimeLog()) { var featureList = features?.Where(x => x.Value).Select(x => x.Key).ToList() ?? new List <FeatureType>(); var elementIdList = _ElementIds?.Where(x => x.Value).Select(x => x.Key).ToList(); var exporter = new Bimangle.ForgeEngine.Revit.Pro.Svf.Exporter(InnerApp.GetHomePath()); if (uidoc != null && uidoc.ActiveView.Id == view.Id) { exporter.Export( uidoc, view, localConfig.LevelOfDetail, localConfig.LastTargetPath, exportType, outputStream, featureList, elementIdList, viewIds, log, progressCallback, cancellationToken ); } else { exporter.Export( view, localConfig.LevelOfDetail, localConfig.LastTargetPath, exportType, outputStream, featureList, elementIdList, viewIds, log, progressCallback, cancellationToken ); } } #endif }
public Response Speak() { Dictionary<Rule, int> acceptDict = new Dictionary<Rule, int>(); foreach (Rule rule in _ruleDb) { if (!rule.CanMatch()) continue; bool match = true; foreach (Criterion criterion in rule.Criteria) { if (!_factDict.ContainsKey(criterion.Lhs) || !criterion.Compare(_factDict[criterion.Lhs] as IComparable)) { match = false; break; } } if (match) acceptDict.Add(rule, rule.Criteria.Count); } if (acceptDict.Count == 0) return new Response("NullResponse", "NO RESPONSE"); // Of all the matched rules, find the one(s) that match the most criteria int maxScore = acceptDict.Max(kvp => kvp.Value); List<Rule> acceptList = acceptDict.Where(kvp => kvp.Value == maxScore).Select(kvp => kvp.Key).ToList(); // Of all the matched rules of maximum criteria, return a random one Rule matchedRule = acceptList.RandomItem(); matchedRule.Match(); Response response = matchedRule.Response; response.Match(); return response; }
public static Entity GetHeroEntity(bool forPlayer, Dictionary<int, Entity> entities, int id) { if(!forPlayer) id = (id % 2) + 1; var heros = entities.Where(x => IsHero(x.Value)).Select(x => x.Value).ToList(); return heros.FirstOrDefault(x => x.GetTag(CONTROLLER) == id); }
/// <summary> /// Initializes a new instance of the <see cref="StaticFilesModule" /> class. /// </summary> /// <param name="fileSystemPath">The file system path.</param> /// <param name="headers">The headers to set in every request.</param> /// <param name="additionalPaths">The additional paths.</param> /// <param name="useDirectoryBrowser">if set to <c>true</c> [use directory browser].</param> /// <exception cref="ArgumentException">Path ' + fileSystemPath + ' does not exist.</exception> public StaticFilesModule( string fileSystemPath, Dictionary <string, string> headers = null, Dictionary <string, string> additionalPaths = null, bool useDirectoryBrowser = false) { if (!Directory.Exists(fileSystemPath)) { throw new ArgumentException($"Path '{fileSystemPath}' does not exist."); } _virtualPaths = new VirtualPaths(Path.GetFullPath(fileSystemPath), useDirectoryBrowser); UseGzip = true; #if DEBUG // When debugging, disable RamCache UseRamCache = false; #else // Otherwise, enable it by default UseRamCache = true; #endif DefaultDocument = DefaultDocumentName; headers?.ForEach(DefaultHeaders.Add); additionalPaths?.Where(path => path.Key != "/") .ToDictionary(x => x.Key, x => x.Value) .ForEach(RegisterVirtualPath); AddHandler(ModuleMap.AnyPath, HttpVerbs.Head, (context, ct) => HandleGet(context, ct, false)); AddHandler(ModuleMap.AnyPath, HttpVerbs.Get, (context, ct) => HandleGet(context, ct)); }
/// <summary> /// TODO: input Namespace list instead; /// TODO: Save to ...yml.map /// </summary> /// <param name="allMembers"></param> /// <returns></returns> public static MetadataModel ResolveMetadata( Dictionary<string, MetadataItem> allMembers, Dictionary<string, ReferenceItem> allReferences, string apiFolder, bool preserveRawInlineComments, IEnumerable<string> externalReferencePackages) { MetadataModel viewModel = new MetadataModel(); viewModel.TocYamlViewModel = new MetadataItem() { Type = MemberType.Toc, Items = allMembers.Where(s => s.Value.Type == MemberType.Namespace).Select(s => s.Value).ToList(), }; viewModel.Members = new List<MetadataItem>(); ResolverContext context = new ResolverContext { ApiFolder = apiFolder, References = allReferences, PreserveRawInlineComments = preserveRawInlineComments, }; ExecutePipeline(viewModel, context); return viewModel; }
/// <summary> /// Turns all the properties into a semi-colon separated string. /// </summary> /// <returns> /// Returns semi-colon separated string of properties. /// </returns> public override string ToString() { var b = new Dictionary<string, object> { {"Server", Server}, {"Port", Port}, {"Userid", UserId}, {"Password", Password}, {"Protocol", Protocol}, {"SSL", Ssl}, {"Pooling", Pooling}, {"MinPoolSize", MinPoolSize}, {"MaxPoolSize", MaxPoolSize}, {"Timeout", Timeout}, {"SslMode", SslMode}, {"Database", Database} }; var buff = string.Join( ";", b.Where(kvp => kvp.Value != null) .Select( kvp => string.Format( "{0}={1}", kvp.Key, Convert(kvp.Value))) .ToArray()); return buff.ToString(); }
private void CaughtPokemonsCleanup() { var stamp = DateTime.UtcNow.ToUnixTime(); var toRemove = RecentlyCaughtPokemons?.Where(x => x.Value < stamp).ToList(); var removeQueue = new Queue <ulong>(); if (toRemove == null) { return; } try { for (var i = 0; i < toRemove.Count(); i++) { removeQueue.Enqueue(toRemove[i].Key); } } catch (Exception) { //ignore } while (removeQueue.Count > 0) { var r = removeQueue.Dequeue(); RecentlyCaughtPokemons.Remove(r); } }
public Dictionary<string, int> GetSortedWords(Dictionary<string, int> words, Dictionary<string, int> bannedWords) { return words .Where(x => !bannedWords.ContainsKey(x.Key)) .OrderByDescending(x => x.Value) .ToDictionary(pair => pair.Key, pair => pair.Value); }
public string GetFormattedLogMessage(Dictionary <LogMessageParameters, string>[] messageParameters, Dictionary <string, string> analysisParameters) { string formattedMessage = ""; var outputMessageParameters = messageParameters?.Where(mp => _fileOutputConfig.IncludedMessageParameters?.Any(imp => mp.Keys.Contains(imp)) ?? true).ToList(); var outputAnalysisParameters = analysisParameters?.Where(ap => _fileOutputConfig.IncludedAnalysisParameters?.Contains(ap.Key) ?? true).ToList(); outputMessageParameters?.ForEach(messageParams => { messageParams?.ToList().ForEach(param => formattedMessage += param.Key.ToString() + " : " + param.Value + Environment.NewLine); if (!string.IsNullOrEmpty(formattedMessage)) { formattedMessage += MSG_SEPARATOR_LINE + Environment.NewLine; } }); outputAnalysisParameters?.ForEach(param => formattedMessage += param.Key.ToString() + " : " + param.Value + Environment.NewLine); if (!string.IsNullOrEmpty(formattedMessage)) { formattedMessage += OUTPUT_SEPARATOR_LINE; } return(formattedMessage); }
public void Execute(CancellationToken cancellationToken) { foreach (string document in documents) { Logger.Debug($"Removing outdated records from the '{document}' document."); using (new FirebaseDistributedLock(distributedLockKey, defaultLockTimeout, connection.Client)) { FirebaseResponse respone = connection.Client.Get($"{document}"); if (respone.StatusCode == System.Net.HttpStatusCode.OK) { Dictionary <string, FireEntity> collection = respone.ResultAs <Dictionary <string, FireEntity> >(); string[] references = collection?.Where(c => c.Value.ExpireOn.HasValue && c.Value.ExpireOn < DateTime.UtcNow).Select(c => c.Key).ToArray(); if (references != null && references.Length > 0) { ParallelOptions options = new ParallelOptions { CancellationToken = cancellationToken }; Parallel.ForEach(references, options, (reference) => { options.CancellationToken.ThrowIfCancellationRequested(); connection.Client.Delete($"{document}/{reference}"); }); } } } Logger.Trace($"Outdated records removed from the '{document}' document."); cancellationToken.WaitHandle.WaitOne(checkInterval); } }
public void CreateModels(IEnumerable<OvhApi> apis) { Dictionary<string,ModelType> modelsByNamespace = new Dictionary<string, ModelType>(); foreach (var ovhApi in apis) { foreach (var model in ovhApi.Models) { string fullTypeName = Util.GetType(model.Key); if (modelsByNamespace.ContainsKey(fullTypeName)) continue; modelsByNamespace.Add(fullTypeName, new ModelType(model.Value)); } } foreach (var st in modelsByNamespace) { string modelNamespace = Util.GetNamespace(st.Value.Model); if (modelsByNamespace.ContainsKey(modelNamespace)) { modelsByNamespace[modelNamespace].AddChild(st.Value); } } foreach (var type in modelsByNamespace.Where(x => x.Value.Parent == null)) { CodeNamespace ns = new CodeNamespace(Util.GetNamespace(type.Value.Model)); ns.Types.Add(CreateType(type.Value)); _code.Namespaces.Add(ns); } }
public static HttpWebResponse _GetResponse(string url, Dictionary <string, string> data = null) { var keyValuePairs = data?.Where(item => item.Key != null && item.Value != null); if (NullableBooleanToBoolean(data?.Any())) { var stringBuilder = new StringBuilder("?"); stringBuilder.Append(string.Join("&", from KeyValuePair <string, string> item in keyValuePairs select $"{item.Key}={item.Value}")); url += stringBuilder.ToString(); } //Log.D(TAG, $"URL={url}"); HttpWebResponse response = null; try { var httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url)); response = (HttpWebResponse)httpWebRequest.GetResponse(); } catch (WebException e) { Log.E(TAG, e.Message); } return(response); }
public long Solve() { var result = new Dictionary<long, int> { { 1, 1 } }; for (var i = 2L; i <= Limit; i++) { var n = i; var row = new List<long>(); while (!result.ContainsKey(n)) { row.Add(n); n = GetNext(n); } var lenght = result[n]; var count = 0; foreach (var r in row) { result.Add(r, lenght + row.Count - count); count++; } } return result.Where(t => t.Key <= Limit).OrderByDescending(t => t.Value).First().Key; }
private string FromDictionaryToUrlEncoded(Dictionary<string, string> dictionary, string url) { var dic = dictionary.Where(x => !string.IsNullOrEmpty(x.Value)); var kvs = dic.Select(kvp => $"{kvp.Key}={string.Join("&", kvp.Value)}"); return string.Concat(url, "?", string.Join("&", kvs)); }
private void ExportToGltf(JobConfig config, RuntimeLog log, Action <int> progressCallback) { var features = new Dictionary <Common.Formats.Gltf.FeatureType, bool>(); var options = config.OutputOptions; if (options != null && options.Count > 0) { foreach (var option in options) { if (Enum.TryParse(option, true, out Common.Formats.Gltf.FeatureType result)) { features[result] = true; } } } var setting = new Bimangle.ForgeEngine.Common.Formats.Gltf.Navisworks.ExportSetting(); setting.OutputPath = config.OutputPath; setting.Features = features?.Where(x => x.Value).Select(x => x.Key).ToList(); #if EXPRESS var exporter = new Bimangle.ForgeEngine.Navisworks.Express.Gltf.Exporter(App.GetHomePath()); #else var exporter = new Bimangle.ForgeEngine.Navisworks.Pro.Gltf.Exporter(App.GetHomePath()); #endif exporter.Export(setting, log, progressCallback, CancellationToken.None); }
static void Main(string[] args) { var input = Console.ReadLine().ToLower().Split(); var elements = new Dictionary<string, int>(); for (int i = 0; i < input.Length; i++) { var currentElement = input[i]; if (!elements.ContainsKey(currentElement)) { elements[currentElement] = 0; } elements[currentElement]++; } var resultElements = elements.Where(x => x.Value % 2 != 0); var result = new List<string>(); foreach (var element in resultElements) { result.Add(element.Key); } Console.WriteLine(string.Join(", ", result)); }
private string FromDictionaryToJson(Dictionary<string, string> dictionary) { var dic = dictionary.Where(x => !string.IsNullOrEmpty(x.Value)); var kvs = dic.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Join(",", kvp.Value))); return string.Concat("{", string.Join(",", kvs), "}"); }
private static bool DoDepthFirstSearchingAux(Dictionary<string, int> existingRoutes, ref int runningWeight, string fromToKey, string requestedRoute) { // Concept: the minute you have entered this function, you have gone from...to. (See fromToKey.) So update recordkeeping now. runningWeight += existingRoutes[fromToKey]; if (YouHaveReachedYourDestination(requestedRoute)) return true; var nextLocation = requestedRoute.Substring(1); var possibleRoutes = existingRoutes.Where(r => r.Key == nextLocation.Substring(0, 2)); if (!possibleRoutes.Any()) return false; foreach (var route in possibleRoutes) { var savedWeight = runningWeight; if (DoDepthFirstSearchingAux(existingRoutes, ref runningWeight, route.Key, nextLocation)) { return true; } runningWeight = savedWeight; } return false; }
/// <summary> /// Converts DATATYPE of a shared parameter to <see cref="ParameterType"/> /// </summary> /// <param name="dataType">DATATYPE string to convert</param> /// <returns></returns> public static ParameterType FromSharedDataType(this string dataType) { var values = _parameterTypes2Shared?.Where(u => u.Value.Equals(dataType, StringComparison.OrdinalIgnoreCase)).Select(x => x.Key).ToArray(); return((values != null && values.Any()) ? values.FirstOrDefault() : ParameterType.Invalid); }
/// <summary> /// Gets the numeric value from the supplied dictionary /// where the key is 'number'. /// Returns the default Top N number if no key is found or if its null. /// </summary> public static int GetNumericEntity(Dictionary <string, object> paramters) { var theNumber = paramters?.Where(p => p.Key == BotConstants.ApiAiParametersConstants.Number) .Select(k => k.Value) .FirstOrDefault(); return((theNumber == null) || (string.IsNullOrEmpty(theNumber.ToString())) ? BotConstants.OtherConstants.DefaultTopN : Convert.ToInt32(theNumber)); }
public IList GetAllErrors(string[] propertyNames = null) { if (propertyNames?.Any() == true) { return(_errors?.Where(error => propertyNames.Contains(error.Key)).SelectMany(error => error.Value).ToList()); } return(_errors?.SelectMany(error => error.Value).ToList()); }
private static SiteSettings TargetSiteSettings( Dictionary <long, SiteSettings> links, long linkId) { return(links ?.Where(o => o.Key == linkId) .Select(o => o.Value) .FirstOrDefault()); }
/// <summary> /// 开始导出 /// </summary> /// <param name="localConfig"></param> /// <param name="features"></param> /// <param name="progressCallback"></param> /// <param name="cancellationToken"></param> private void StartExport(AppConfigCesium3DTiles localConfig, Dictionary <FeatureType, bool> features, Action <int> progressCallback, CancellationToken cancellationToken) { using (var log = new RuntimeLog()) { var featureList = features?.Where(x => x.Value).Select(x => x.Key).ToList() ?? new List <FeatureType>(); var exporter = new ExporterX(App.GetHomePath()); exporter.Export(localConfig.LastTargetPath, localConfig.Mode, featureList, log, progressCallback, cancellationToken); } }
private void CreateAssetValueForPendingDates(DomainObjects.Asset.Asset asset, DateTime lastUpdatedValue, Dictionary <DateTime, double> assetDateAndValues) { var pendingUpdate = assetDateAndValues?.Where(d => d.Key > lastUpdatedValue).OrderBy(v => v.Key); var previousDateAndValue = assetDateAndValues?.Where(d => d.Key == lastUpdatedValue).OrderByDescending(v => v.Key).FirstOrDefault(); if (pendingUpdate != null) { foreach (var pending in pendingUpdate) { previousDateAndValue = InsertAssetValueForPreviousDaysWithoutMarketValues(asset, previousDateAndValue, pending); var assetValue = new DomainObjects.Asset.AssetValue() { AssetId = asset.Id, Date = pending.Key, Value = pending.Value }; Data.Insert(assetValue); } } }
/// <summary> /// 使用指定的Clob内容键值对来执行Sql语句 /// </summary> /// <param name="sqlString">待执行的SQL语句</param> /// <param name="dict">包含CLOB内容的键值对</param> /// <returns></returns> public int ExecuteSqlWithClobContents(string sqlString, Dictionary <string, string> dict) { //将键值对转换为Clob类型的Oracle参数,参数名与内容分别由键、值决定 List <OracleParameter> _params = dict?.Where(pair => !string.IsNullOrWhiteSpace(pair.Key) && !string.IsNullOrWhiteSpace(pair.Value)).Select(pair => new OracleParameter(pair.Key, OracleDbType.Clob) { Value = pair.Value }).ToList(); return(ExecuteSql(sqlString, _params)); }
/// <summary> /// Tries the get the UnitType value for the given catalog string. /// </summary> /// <param name="catalogString">The catalog string to convert.</param> /// <param name="unitType">The resulting unit type.</param> /// <returns></returns> public static bool TryGetUnitTypeFromCatalogString(this string catalogString, out UnitType unitType) { var values = utToCatalog?.Where(u => u.Value.Equals(catalogString, System.StringComparison.OrdinalIgnoreCase)).Select(x => x.Key).ToList(); var valueExists = values != null && values.Any(); unitType = valueExists ? values.FirstOrDefault() : UnitType.UT_Undefined; return(valueExists); }
public override void AnnounceServer(string serverId, ServerContext context) { if (serverId == null) { throw new ArgumentNullException(nameof(serverId)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } QueryBuilder builder = QueryBuilder.New($@"equalTo=""{serverId}"""); builder.OrderBy("server_id"); FirebaseResponse response = Client.Get("servers", builder); if (response.StatusCode == HttpStatusCode.OK) { Dictionary <string, Entities.Server> servers = response.ResultAs <Dictionary <string, Entities.Server> >(); string reference = servers?.Where(s => s.Value.ServerId == serverId).Select(s => s.Key).FirstOrDefault(); Entities.Server server; if (!string.IsNullOrEmpty(reference) && servers.TryGetValue(reference, out server)) { server.LastHeartbeat = DateTime.UtcNow; server.Workers = context.WorkerCount; server.Queues = context.Queues; response = Client.Set($"servers/{reference}", server); if (response.StatusCode != HttpStatusCode.OK) { throw new HttpRequestException(response.Body); } } else { server = new Entities.Server { ServerId = serverId, Workers = context.WorkerCount, Queues = context.Queues, CreatedOn = DateTime.UtcNow, LastHeartbeat = DateTime.UtcNow }; response = Client.Push("servers", server); if (response.StatusCode != HttpStatusCode.OK) { throw new HttpRequestException(response.Body); } } } }
internal static Dictionary <BlockPos, TeleportData> GetAvailableTeleports(IPlayer forPlayer) { if (forPlayer.WorldData.CurrentGameMode == EnumGameMode.Creative) { return(Teleports); } if (Config.Current.SharedTeleports.Val) { return(Teleports ?.Where((dict) => dict.Value.Available) ?.ToDictionary(dict => dict.Key, dict => dict.Value) ); } return(Teleports ?.Where((dict) => dict.Value.Available && dict.Value.ActivatedBy.Contains(forPlayer.PlayerUID) )?.ToDictionary(dict => dict.Key, dict => dict.Value) ); }
protected override Task <string[]> FindAutoCompleteList(string value) { return(Task.Run(() => { value = value.ToLower(); return dictionary? .Where(x => x.Key.ToLower().StartsWith(value)) .OrderByDescending(b => b.Value) .Take(10) .Select(a => a.Key) .ToArray(); })); }
// COPIED FROM TwwStatsControllerBase.cs private string ConvertDataToString(DataTable dt, Dictionary <string, string> texts, String realTableName) { var tableTexts = texts?.Where(p => p.Key.StartsWith(realTableName)).ToList(); List <Dictionary <string, object> > rows = new List <Dictionary <string, object> >(); foreach (DataRow dr in dt.Rows) { var row = new Dictionary <string, object>(); foreach (DataColumn col in dt.Columns) { var colName = col.ColumnName.Replace('-', '_'); // Convert String to Boolean if (dr[col].ToString().ToLower() == "false") { row.Add(colName, false); } else if (dr[col].ToString().ToLower() == "true") { row.Add(colName, true); } else { row.Add(colName, dr[col]); } } if (tableTexts != null && tableTexts.Any()) { var rowKeys = computePotentialKeys(dt.PrimaryKey.Select(pk => dr[pk.ColumnName].ToString()).ToList()); foreach (var rowKey in rowKeys) { tableTexts.Where(p => p.Key.EndsWith(rowKey)).ToList().ForEach(p => { var key = p.Key.Replace($"_{rowKey}", "").Replace($"{realTableName}_", ""); if (row.ContainsKey(key)) { row[key] = p.Value; } else { row.Add(key, p.Value); } }); } } rows.Add(row); } return(JsonConvert.SerializeObject(rows)); }
/// <summary> /// 檢查是否有通路尚未填寫核銷規則 /// </summary> /// <returns></returns> private static void CheckChannelVerifyPeriod(SysMessageLog message, CollectionTypeSet set) { Dictionary <string, string> detail = set.CollectionTypeDetail.Select(p => p.Channel).Distinct().ToDictionary(p => p.ChannelId, q => q.ChannelName); Dictionary <string, CollectionTypeVerifyPeriodModel> period = set.CollectionTypeVerifyPeriod.ToDictionary(p => p.ChannelId, q => q); List <string> detailExpectChannels = detail.Keys.Except(period.Keys).ToList(); string[] notWriteChannels = detail?.Where(p => p.Key.In(detailExpectChannels.ToArray())).Select(p => p.Value).Distinct().ToArray(); string channelName = LibData.Merge(",", false, notWriteChannels); if (!channelName.IsNullOrEmpty()) { message.AddCustErrorMessage(MessageCode.Code1014, channelName); } }
/// <summary> /// 开始导出 /// </summary> /// <param name="uidoc"></param> /// <param name="view"></param> /// <param name="localConfig"></param> /// <param name="features"></param> /// <param name="progressCallback"></param> /// <param name="cancellationToken"></param> private void StartExport(UIDocument uidoc, View3D view, AppConfigCesium3DTiles localConfig, Dictionary <FeatureType, bool> features, Action <int> progressCallback, CancellationToken cancellationToken) { using (var log = new RuntimeLog()) { var featureList = features?.Where(x => x.Value).Select(x => x.Key).ToList() ?? new List <FeatureType>(); var elementIdList = _ElementIds?.Where(x => x.Value).Select(x => x.Key).ToList(); var exporter = new ExporterX(InnerApp.GetHomePath()); exporter.Export( uidoc, view, localConfig.LevelOfDetail, localConfig.LastTargetPath, localConfig.Mode, featureList, elementIdList, log, progressCallback, cancellationToken ); } }
/// <summary> /// 开始导出 /// </summary> /// <param name="targetPath"></param> /// <param name="exportType"></param> /// <param name="outputStream"></param> /// <param name="features"></param> /// <param name="progressCallback"></param> /// <param name="cancellationToken"></param> private void StartExport(string targetPath, ExportType exportType, Stream outputStream, Dictionary <FeatureType, bool> features, Action <int> progressCallback, CancellationToken cancellationToken) { #if EXPRESS throw new NotImplementedException(); #else using (var log = new RuntimeLog()) { var featureList = features?.Where(x => x.Value).Select(x => x.Key).ToList() ?? new List <FeatureType>(); var exporter = new Bimangle.ForgeEngine.Navisworks.Pro.Svf.Exporter(App.GetHomePath()); exporter.Export( targetPath, exportType, outputStream, featureList, log, progressCallback, cancellationToken ); } #endif }
public void AddToSet(string key, string value, double score) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(value)); } QueueCommand(() => { Set data = new Set { Key = key, Value = value, Score = score }; QueryBuilder builder = QueryBuilder.New($@"equalTo=""{key}"""); builder.OrderBy("key"); FirebaseResponse response = connection.Client.Get("sets", builder); if (response.StatusCode == HttpStatusCode.OK) { Dictionary <string, Set> sets = response.ResultAs <Dictionary <string, Set> >(); string reference = sets?.Where(s => s.Value.Value == value).Select(s => s.Key).FirstOrDefault(); if (!string.IsNullOrEmpty(reference)) { response = connection.Client.Set($"sets/{reference}", data); } else { response = connection.Client.Push("sets", data); } if (response.StatusCode != HttpStatusCode.OK) { throw new HttpRequestException(response.Body); } } }); }
public static OverridableFrameSettingsArea GetGroupContent(int groupIndex, FrameSettings defaultFrameSettings, SerializedFrameSettings serializedFrameSettings) { if (!attributesGroup.ContainsKey(groupIndex) || attributesGroup[groupIndex] == null) { attributesGroup[groupIndex] = attributes?.Where(pair => pair.Value?.group == groupIndex)?.OrderBy(pair => pair.Value.orderInGroup); } if (!attributesGroup.ContainsKey(groupIndex)) { throw new ArgumentException("Unknown groupIndex"); } var area = new OverridableFrameSettingsArea(attributesGroup[groupIndex].Count(), defaultFrameSettings, serializedFrameSettings); foreach (var field in attributesGroup[groupIndex]) { area.Add(field.Key); } return(area); }
private void ExportToCesium3DTiles(JobConfig config, RuntimeLog log, Action <int> progressCallback) { var features = new Dictionary <Common.Formats.Cesium3DTiles.FeatureType, bool>(); var options = config.OutputOptions; if (options != null && options.Count > 0) { foreach (var option in options) { if (Enum.TryParse(option, true, out Common.Formats.Cesium3DTiles.FeatureType result)) { features[result] = true; } } features[Common.Formats.Cesium3DTiles.FeatureType.EnableEmbedGeoreferencing] = true; } else { var defaultConfig = new AppConfigCesium3DTiles(); foreach (var feature in defaultConfig.Features) { features[feature] = true; } } var setting = new Bimangle.ForgeEngine.Common.Formats.Cesium3DTiles.Navisworks.ExportSetting(); setting.OutputPath = config.OutputPath; setting.Mode = config.Mode; setting.Features = features?.Where(x => x.Value).Select(x => x.Key).ToList(); setting.Site = SiteInfo.CreateDefault(); setting.Oem = LicenseConfig.GetOemInfo(App.GetHomePath()); #if EXPRESS var exporter = new Bimangle.ForgeEngine.Navisworks.Express.Cesium3DTiles.Exporter(App.GetHomePath()); #else var exporter = new Bimangle.ForgeEngine.Navisworks.Pro.Cesium3DTiles.Exporter(App.GetHomePath()); #endif exporter.Export(setting, log, progressCallback, CancellationToken.None); }
private void Acquire(string resource, TimeSpan timeout) { System.Diagnostics.Stopwatch acquireStart = new System.Diagnostics.Stopwatch(); acquireStart.Start(); while (true) { FirebaseResponse response = client.Get("locks"); if (response.StatusCode == System.Net.HttpStatusCode.OK) { Dictionary <string, Lock> locks = response.ResultAs <Dictionary <string, Lock> >(); string reference = locks?.Where(l => l.Value.Resource == resource).Select(l => l.Key).FirstOrDefault(); if (string.IsNullOrEmpty(reference)) { response = client.Push("locks", new Lock { Resource = resource, ExpireOn = DateTime.UtcNow.Add(timeout) }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { reference = ((PushResponse)response).Result.name; if (!string.IsNullOrEmpty(reference)) { lockReference = reference; break; } } } } // check the timeout if (acquireStart.ElapsedMilliseconds > timeout.TotalMilliseconds) { throw new FirebaseDistributedLockException($"Could not place a lock on the resource '{resource}': Lock timeout."); } // sleep for 500 millisecond System.Threading.Thread.Sleep(500); } }
private async Task <bool> CheckIfPropertiesInsideTheAnimesListAreNull() { bool listOfAnimesForTheDayIsNull = false; Dictionary <string, List <Anime> > dictionaryOfDaysInAWeek = Animes.GetDictionaryOfAllObjectProperties <List <Anime> >(); List <Anime> listForTheRequestedDay = dictionaryOfDaysInAWeek? .Where(w => w.Key.ToLower() == _dayOfTheWeek.ToLower())? .Select(s => s.Value).FirstOrDefault(); if (listForTheRequestedDay == null) { throw new ArgumentException("Couldn't find a day for the week with the day you provided me."); } if (listForTheRequestedDay.Count == 0) { await ReplyAsync($"I didn't find any animes scheduled for {_dayOfTheWeek}. Is there a day where animes just don't come out? :thinking:"); listOfAnimesForTheDayIsNull = true; } return(listOfAnimesForTheDayIsNull); }