public string CalculateMode(List<decimal> numbers) { decimal max = 0; string result = ""; var numDictionary = new Dictionary<decimal, int>(); AddToDictionary(numbers, numDictionary); if(numDictionary.Count == 0) throw new ArgumentException("No numbers given!", "numbers"); if (numDictionary.All(d => d.Value == 1)) return "none"; foreach (KeyValuePair<decimal, int> pair in numDictionary) { if (pair.Value > max) { result = ""; max = pair.Value; result += string.Format("{0},", pair.Key); } else if (pair.Value == max) result += string.Format("{0},", pair.Key); } return result.Trim(','); }
/// <summary> /// Apply business logic here /// </summary> /// <param name="productsToImport"></param> /// <returns></returns> public Dictionary<string, List<string>> ValidateBusinessLogic(IEnumerable<ProductImportDataTransferObject> productsToImport) { var errors = new Dictionary<string, List<string>>(); var productRules = MrCMSApplication.GetAll<IProductImportValidationRule>(); var productVariantRules = MrCMSApplication.GetAll<IProductVariantImportValidationRule>(); foreach (var product in productsToImport) { var productErrors = productRules.SelectMany(rule => rule.GetErrors(product)).ToList(); if (productErrors.Any()) errors.Add(product.UrlSegment, productErrors); foreach (var variant in product.ProductVariants) { var productVariantErrors = productVariantRules.SelectMany(rule => rule.GetErrors(variant)).ToList(); if (productVariantErrors.Any()) { if (errors.All(x => x.Key != product.UrlSegment)) errors.Add(product.UrlSegment, productVariantErrors); else errors[product.UrlSegment].AddRange(productVariantErrors); } } } return errors; }
public static List<IRequiredService> DetermineMissingServices(this IEnumerable<XmlModuleConfig> modules, List<string> bootStrappedServices) { var providedServices = new List<IProvidedService>(); var requiredServices = new Dictionary<IRequiredService, XmlModuleConfig>(); foreach (var module in modules) { foreach (IRequiredService requiredService in module.RequiredServices) { if (requiredServices.All(r => r.Key.ServiceName != requiredService.ServiceName)) { requiredServices.Add(requiredService, module); } } foreach (IProvidedService providedService in module.ProvidedServices) { if (providedServices.All(r => r.ServiceName != providedService.ServiceName)) { providedServices.Add(providedService); } } } var query = requiredServices.Where( requiredService => providedServices.All(s => s.ServiceName != requiredService.Key.ServiceName) && bootStrappedServices.All(s => s != requiredService.Key.ServiceName)); return query.Select(s => s.Key).ToList(); }
public bool DetermineIfAnagram(string s1, string s2) { if (s1.Length != s2.Length) { return false; } var dict = new Dictionary<char,int>(); foreach (var item in s1) { if (dict.ContainsKey(item)) { dict[item]++; } else { dict.Add(item, 1); } } foreach (var item in s2) { if (!dict.ContainsKey(item)) { return false; } else { dict[item]--; } } return dict.All(x => x.Value == 0); }
public void Test_Gamma_Of_Valid_Values() { Dictionary<double, double> expected = new Dictionary<double, double> { {1,1}, {Math.PI, 2.288037796}, {Math.E, 1.567468255}, {-1.5,2.363271801} }; //foreach (var item in expected) //{ // double actual = GammaRelated.Gamma(item.Key); // Assert.IsTrue(AreApproximatelyEqual(item.Value, actual)); //} Assert.IsTrue( expected.All(x => AreApproximatelyEqual(x.Value, GammaRelated.Gamma(x.Key)) ) ); Assert.IsTrue( AreApproximatelyEqual( GammaRelated.Gamma(Math.PI + 1), Math.PI * GammaRelated.Gamma(Math.PI) ) ); }
public void WebConfigStateAllowsEnumeratingOverConfigItems() { // Arrange var dictionary = new Dictionary<string, string> { { "a", "b" }, { "c", "d" }, { "x12", "y34" } }; var stateStorage = GetWebConfigScopeStorage(dictionary); // Act and Assert Assert.IsTrue(dictionary.All(item => item.Value == stateStorage[item.Key] as string)); }
public void DictionaryExtensions_All_ReturnsTrueIfDictionaryIsEmpty() { var dictionary = new Dictionary<Int32, String>(); var result = dictionary.All(x => x.Key % 2 == 0); TheResultingValue(result).ShouldBe(true); }
internal static int DispatchCommand(Dictionary<CommandMetadata, object> commands, string[] args) { if (args == null || !args.Any()) throw new ShellHelpException(); var commandName = args.First().ToLower(); if (commands.All(meta => meta.Key.Name != commandName)) throw new ShellHelpException(); var command = commands.Single(meta => meta.Key.Name == commandName).Value; var metadata = commands.Single(meta => meta.Key.Name == commandName).Key; return RunCommand(command, metadata, args.Skip(1).ToArray()); }
public void CountWords_EmptySentences_CountsWordCorrectly() { var wordsCounter = new ClassicCounterLogic(); var properDict = new Dictionary<string, int>(); var result = wordsCounter.CountWordsInSentence(string.Empty); Assert.IsTrue(properDict.All(e => result.Contains(e))); }
public bool AddStream(string sStreamName) { var results = new Dictionary<IStreamProvider, bool>(); foreach (var streamProvider in _streamProviders) { results.Add(streamProvider, streamProvider.AddStream(sStreamName)); } return results.All(result => !result.Value); }
public SearchEngine(Dictionary<string, List<string>> lookups) { if (lookups == null) throw new ArgumentNullException("lookups"); if (lookups.Count == 0) throw new ArgumentException("The lookups must not be empty.", "lookups"); if (lookups.All(x => x.Value.Count == 0)) throw new ArgumentException("None of the lookups (keys) have results (values). This is invalid as a lookup table."); _lookupTable = lookups; }
public void GetAllKeysAsListTestCase() { var dictionary = new Dictionary<String, String> { { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() }, { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() } }; var allKeys = dictionary.GetAllKeysAsList(); Assert.IsTrue( dictionary.All( x => allKeys.Contains( x.Key ) ) ); }
public async Task TestPostRequestWithCustomeHeadersAndBody() { using (var server = new HttpHost(TestPort)) { const string path = "/test/path?query=value"; var headers = new Dictionary<string, string> { { "custom-header-1", "custom-value-1" }, { "content-custom", "content-value" } }; const string contentType = "suave/test"; const string content = "string content"; var responseContent = new byte[] { 1, 2, 3 }; await server.OpenAsync(async request => { Assert.Equal(path, request.RequestUri.PathAndQuery); Assert.Equal(HttpMethod.Post, request.Method); Assert.True(headers.All(pair => request.Headers.First(s => s.Key == pair.Key).Value.First() == pair.Value)); Assert.Equal(contentType, request.Content.Headers.ContentType.ToString()); Assert.Equal(content, await request.Content.ReadAsStringAsync()); var response = new HttpResponseMessage { StatusCode = HttpStatusCode.Accepted, Content = new ByteArrayContent(responseContent) }; response.Headers.Add("server-custom", "server-value"); return response; }); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, LocalHost + path); headers.Aggregate(request.Headers, (a, b) => { a.Add(b.Key, b.Value); return a; }); request.Content = new StringContent(content); request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); var response = await client.SendAsync(request); Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); Assert.Equal(responseContent, await response.Content.ReadAsByteArrayAsync()); Assert.Equal("server-value", response.Headers.First(s => s.Key == "server-custom").Value.First()); } } }
/// <summary> /// Adds authorization token to POST body /// </summary> /// <param name="body">Dictionary containing the body parameters</param> /// <param name="token">The token to add to the post body</param> /// <returns></returns> public virtual Dictionary<string, object> Authorize(Dictionary<string, object> body, string token) { if (body == null) throw new ArgumentNullException("body"); var d = new Dictionary<string, object>(body); if (d.All(b => !String.Equals(b.Key, this.FieldName, StringComparison.CurrentCultureIgnoreCase))) d.Add(this.FieldName, token); return d; }
public void DictionaryExtensions_All_ReturnsTrueIfAllItemsMatchPredicate() { var dictionary = new Dictionary<Int32, String>() { { 2, "A" }, { 4, "B" }, { 6, "C" }, }; var result = dictionary.All(x => x.Key % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public void DictionaryExtensions_All_ReturnsFalseIfOneItemDoesNotMatchPredicate() { var dictionary = new Dictionary<Int32, String>() { { 1, "A" }, { 2, "B" }, { 4, "C" }, { 6, "D" }, }; var result = dictionary.All(x => x.Key % 2 == 0); TheResultingValue(result).ShouldBe(false); }
public ActionResult CompleteReservation(Dictionary<string, string> roomsToBook) { if (roomsToBook.All(r => r.Value == "0" || string.IsNullOrEmpty(r.Value))) { this.TempData["Notification"] = "No room selected.Choose new dates"; return this.RedirectToAction("Index", "Home"); } var dates = this.Session["SearchDates"] as SearchInputModel; var newRoomsToBook = new Dictionary<string, int>(); var roomToBookTypes = new List<string>(); foreach (var roomType in roomsToBook) { if (roomType.Value != "0" && !string.IsNullOrEmpty(roomType.Value)) { newRoomsToBook.Add(roomType.Key, int.Parse(roomType.Value)); roomToBookTypes.Add(roomType.Key); } } var reservation = new ReservationViewModel { CreatorId = this.User.Identity.GetUserId(), StartDate = dates.Start, EndDate = dates.End, Rooms = new List<BookedRoomView>() }; var availableRoomsTypes = this.rooms .AvailableForPeriod(dates.Start, dates.End).ToList() .Where(r => roomToBookTypes.Contains(r.RoomType.Type)) .GroupBy(r => r.RoomType.Type); foreach (var roomType in availableRoomsTypes) { roomType .Take(newRoomsToBook[roomType.Key]) .ForEach(x => reservation.Rooms.Add(new BookedRoomView { Guests = new List<PersonInputModel>(), Room = x, Status = ReservationStatus.Pending })); } this.Session["reservation"] = reservation; return new HttpStatusCodeResult(HttpStatusCode.OK); }
public GraphPetriNet(string id, Dictionary<int, string> placeNames, Dictionary<int, string> transitionNames, Dictionary<int, List<InArc>> inArcs, Dictionary<int, List<OutArc>> outArcs ) { Contract.Requires(!string.IsNullOrEmpty(id)); Contract.Requires(placeNames != null); Contract.Requires(placeNames.Count > 0); Contract.Requires(placeNames.All(pn => !string.IsNullOrEmpty(pn.Value))); Contract.Requires(transitionNames != null); Contract.Requires(transitionNames.Count > 0); Contract.Requires(transitionNames.All(tn => !string.IsNullOrEmpty(tn.Value))); Contract.Requires(inArcs != null); Contract.Requires(inArcs.Count > 0); Contract.Requires(outArcs != null); // disabled because the petri net may be built in stages using other APIs // Contract.Requires(outArcs.Count > 0); Contract.Ensures(Places.Count == placeNames.Count); Contract.Ensures(Places == placeNames); Id = id; Places = placeNames; Transitions = transitionNames; InArcs = inArcs; // each arc into a transition can be seen as an arc out of a place // (which may be convenient for conflict resolution) if (InArcs != null) { foreach (var transitionInArcs in InArcs) { foreach (var inArc in transitionInArcs.Value) { if (!PlaceOutArcs.ContainsKey(inArc.Source)) { PlaceOutArcs[inArc.Source] = new List<OutArc>(); } PlaceOutArcs[inArc.Source].Add(new OutArc(transitionInArcs.Key)); } } } OutArcs = outArcs; PlaceCapacities = new Dictionary<int, int>(); }
protected virtual IEnumerable<IDictionary<string, object>> ReadFileContents() { while (Reader.Read()) { var rowData = new Dictionary<string, object>(); for (var fieldIndex = 0; fieldIndex < Reader.FieldCount; fieldIndex++) { var name = FieldNames[fieldIndex]; var value = Reader.GetValue(fieldIndex); rowData[name] = value; } if (rowData.All(pair => string.IsNullOrEmpty(string.Format("{0}", pair.Value)))) continue; yield return rowData; } }
public void CountWords_IncorrectSentencePassed_CountsWordCorrectly() { var wordsCounter = new ClassicCounterLogic(); var properDict = new Dictionary<string, int> { { "this", 2 }, { "is", 2 }, { "a", 1 }, { "sentence", 1 }, { "so", 1 } }; var result = wordsCounter.CountWordsInSentence("This a different sentence, so is this."); Assert.IsFalse(properDict.All(e => result.Contains(e))); }
public List<BulkShippingUpdateDataTransferObject> ValidateAndBulkShippingUpdateOrders(Stream rawFile, ref Dictionary<string, List<string>> parseErrors) { var bulkShippingUpdateDataTransferObjects = new List<BulkShippingUpdateDataTransferObject>(); if (rawFile != null) { using (var file = new CsvReader(new StreamReader(rawFile), new CsvConfiguration{HasHeaderRecord = true})) { while (file.Read()) { var orderId = file.GetField<int?>(0); //skip blank rows if (!orderId.HasValue) continue; //check for duplicates if (bulkShippingUpdateDataTransferObjects.SingleOrDefault(x=>x.OrderId == orderId) != null) continue; if (orderId.HasValue && parseErrors.All(x => x.Key != orderId.ToString())) parseErrors.Add(orderId.ToString(), new List<string>()); else parseErrors.Add("no-supplied-id", new List<string>()); var pv = new BulkShippingUpdateDataTransferObject(); if (file.GetField<string>(0).HasValue()) pv.OrderId = file.GetField<int>(0); else parseErrors["no-supplied-id"].Add("Order Id is required."); if (file.GetField<string>(1).HasValue()) pv.ShippingMethod = file.GetField<string>(1); if (file.GetField<string>(2).HasValue()) pv.TrackingNumber = file.GetField<string>(2).Trim(); bulkShippingUpdateDataTransferObjects.Add(pv); } } } parseErrors = parseErrors.Where(x => x.Value.Any()).ToDictionary(pair => pair.Key, pair => pair.Value); return bulkShippingUpdateDataTransferObjects; }
/// <summary> /// Execution of the Action. /// </summary> /// <returns>True: Execution of the Action was successful</returns> public bool Execute(ActionCallingContext ctx) { using (UndoStep undo = new UndoManager().CreateUndoStep()) { SelectionSet sel = new SelectionSet(); //Make sure that terminals are ordered by designation var terminals = sel.Selection.OfType<Terminal>().OrderBy(t => t.Properties.FUNC_PINORTERMINALNUMBER.ToInt()); if (terminals.Count() < 2) throw new Exception("Must select at least 2 Terminals"); //Create a list of terminals for each level. Those lists get added to a dictionnary //with the level as the key. Dictionary<int, List<Terminal>> levels = new Dictionary<int, List<Terminal>>(); //Fill the dictionnary foreach (Terminal t in terminals) { int level = t.Properties.FUNC_TERMINALLEVEL; if (!levels.ContainsKey(level)) levels.Add(level, new List<Terminal>()); levels[level].Add(t); } var keys = levels.Keys.OrderBy(k => k); //Make sure that all levels have the same number of terminals int qty = levels.First().Value.Count; if (!levels.All(l => l.Value.Count == qty)) throw new Exception("There must be the same number of Terminals on each level"); //Assign sort code by taking a terminal from each level in sequence int sortCode = 1; for (int i = 0; i < qty; i++) { foreach (int j in keys) { levels[j][i].Properties.FUNC_TERMINALSORTCODE = sortCode++; } } } return true; }
protected virtual IEnumerable<IDictionary<string, object>> ReadData() { for (var rowIndex = RowStart; rowIndex <= EndAddress.Row; rowIndex++) { var rowData = new Dictionary<string, object>(); for (var colIndex = 1; colIndex <= EndAddress.Column; colIndex++) { var currentCell = Worksheet.Cells[rowIndex, colIndex]; var currentValue = currentCell.Value; var currentKey = FieldNames[(colIndex - 1)]; rowData[currentKey] = currentValue; } if (rowData.All(pair => string.IsNullOrEmpty(string.Format("{0}", pair.Value)))) continue; yield return rowData; } }
public void Test_Log_Of_Factorial() { Dictionary<int, long> factorials = new Dictionary<int, long>(); for (int i = 0; i < 20; i++) { factorials.Add(i, Get.Factorial(i)); } Assert.IsTrue( factorials.All(x => AreApproximatelyEqual( Math.Log(x.Value), GammaRelated.LogOfFactorial(x.Key)) ) ); }
public void CreateParts_should_add_metadata_from_part_convention_to_part_definition() { var partDefinitions = GetPartDefinitionsFromNonEmptyRegistry(); var expectedMetadata = new Dictionary<string, object> { { CompositionConstants.PartCreationPolicyMetadataName, CreationPolicy.Shared }, { "Foo", "Bar" } }; var inspectedPartDefinition = partDefinitions.First(); expectedMetadata.All(x => inspectedPartDefinition.Metadata.ContainsKey(x.Key)).ShouldBeTrue(); }
// http://leetcode.com/2010/11/finding-minimum-window-in-s-which.html public string MinWindow(string src, string target) { if (src.Length < target.Length) return ""; Dictionary<char, int> mapping = new Dictionary<char, int>(); foreach (char c in target) mapping[c] = mapping.ContainsKey(c) ? mapping[c] + 1 : 1; int left = 0, right = 0; int answerLeft = 0, answerLength = int.MaxValue; while (right < src.Length) { if (mapping.ContainsKey(src[right])) { mapping[src[right]]--; if (mapping.All(s => s.Value <= 0)) { while (left <= right) { if (mapping.ContainsKey(src[left])) { mapping[src[left]]++; if (mapping[src[left]] == 1) // left <-> right can be a candidate answer { if (right - left + 1 < answerLength) { answerLeft = left; answerLength = right - left + 1; } left++; // make it invalid again break; } } left++; } } } right++; } if (answerLength == int.MaxValue) return ""; return src.Substring(answerLeft, answerLength); }
public List<BulkStockUpdateDataTransferObject> ValidateAndBulkStockUpdateProductVariants(Stream rawFile, ref Dictionary<string, List<string>> parseErrors) { var items = new List<BulkStockUpdateDataTransferObject>(); if (rawFile != null) { using (var file = new CsvReader(new StreamReader(rawFile))) { while (file.Read()) { string sku = file.GetField<string>(1), name = file.GetField<string>(0); string handle = sku.HasValue() ? sku : SeoHelper.TidyUrl(name); if (parseErrors.All(x => x.Key != handle)) parseErrors.Add(handle, new List<string>()); var pv = new BulkStockUpdateDataTransferObject { Name = file.GetField<string>(0), SKU = file.GetField<string>(1) }; if (file.GetField<string>(1).HasValue()) pv.SKU = file.GetField<string>(1); else parseErrors[handle].Add("SKU is required."); if (!GeneralHelper.IsValidInput<int>(file.GetField<string>(2))) parseErrors[handle].Add("Stock value is not a valid number."); else pv.StockRemaining = file.GetField<string>(2).HasValue() ? Int32.Parse(file.GetField<string>(2)) : 0; items.Add(pv); } } } parseErrors = parseErrors.Where(x => x.Value.Any()).ToDictionary(pair => pair.Key, pair => pair.Value); return items; }
public static bool accidentsEqual(BindingList<tblPatientAccident> left, BindingList<tblPatientAccident> right) { if (left.Count != right.Count) return false; foreach (tblPatientAccident A in left) { if ((A == null) || (A.ClaimNo == null)) return false; } foreach (tblPatientAccident B in right) { if ((B == null) || (B.ClaimNo == null)) return false; } var dict = new Dictionary<string, int>(); foreach (tblPatientAccident member in left) { if (dict.ContainsKey(member.ClaimNo) == false) dict[member.ClaimNo] = 1; else dict[member.ClaimNo]++; } foreach (tblPatientAccident member in right) { switch (dict.ContainsKey(member.ClaimNo)) { case false: return false; default: dict[member.ClaimNo]--; break; } } return dict.All(kvp => kvp.Value == 0); }
public Dictionary<int, string> FindMarkdownTags(string text) { var tagPositions = new Dictionary<int, string>(); foreach (var tag in tagForSymbol.Keys.OrderByDescending(x => x.Length)) { var count = 0; while (text.IndexOf(tag, count, StringComparison.Ordinal) != -1) { var tagIndex = text.IndexOf(tag, count, StringComparison.Ordinal); if (!IsEscaped(tagIndex, text) && (tagForSymbol[tag].IsFormattableInNumbers || !IsInNumbers(tagIndex, text)) && tagPositions.All(item => !IsInAnotherTag(item, tagIndex) && !IsInAnotherTag(item, tagIndex + tag.Length - 1))) { tagPositions.Add(tagIndex, tag); } count = tagIndex + tag.Length; } } return tagPositions; }
public IDictionary<int, RoundResult> GetResults() { var results = new Dictionary<int, RoundResult>(); foreach (var selection in Selections) { RoundResult result; var comparisions = from s in Selections where s.Key != selection.Key select selection.Value.Compare(s.Value); if (comparisions.All(x => x == RoundResult.Draw)) { result = RoundResult.Draw; } else if (comparisions.All(x => x == RoundResult.Win)) { result = RoundResult.Win; } else if (comparisions.Any(x => x == RoundResult.Lose)) { result = RoundResult.Lose; } else { result = RoundResult.Lose; } results[selection.Key] = result; } if (results.All(x => x.Value == RoundResult.Lose)) { results = (from s in Selections select new { Key = s.Key, Value = RoundResult.Draw }) .ToDictionary(x => x.Key, y => y.Value); } return results; }
private static int VerifyForwardedTypes( Dictionary <INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies, Compilation compilation, HashSet <INamedTypeSymbol> verifiedKeys, bool isSearchSymbolCompilation) { Contract.ThrowIfNull(compilation); Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies); Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any()); // Must contain equivalents named types residing in different assemblies. Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly))); // Must contain non-nested named types. Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null)); Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null)); var referencedAssemblies = new MultiDictionary <string, IAssemblySymbol>(); foreach (var assembly in compilation.GetReferencedAssemblySymbols()) { referencedAssemblies.Add(assembly.Name, assembly); } int verifiedCount = 0; foreach (var kvp in equivalentTypesWithDifferingAssemblies) { if (!verifiedKeys.Contains(kvp.Key)) { INamedTypeSymbol originalType, expectedForwardedType; if (isSearchSymbolCompilation) { originalType = kvp.Value.OriginalDefinition; expectedForwardedType = kvp.Key.OriginalDefinition; } else { originalType = kvp.Key.OriginalDefinition; expectedForwardedType = kvp.Value.OriginalDefinition; } foreach (var referencedAssembly in referencedAssemblies[originalType.ContainingAssembly.Name]) { var fullyQualifiedTypeName = originalType.MetadataName; if (originalType.ContainingNamespace != null) { fullyQualifiedTypeName = originalType.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat) + "." + fullyQualifiedTypeName; } // Resolve forwarded type and verify that the types from different assembly are indeed equivalent. var forwardedType = referencedAssembly.ResolveForwardedType(fullyQualifiedTypeName); if (forwardedType == expectedForwardedType) { verifiedKeys.Add(kvp.Key); verifiedCount++; } } } } return(verifiedCount); }
public virtual List <Expression> GeneratePropertyAssignExpression(ParameterExpression sourcePar, ParameterExpression targetPar, ParameterExpression checkerPar, bool isCopy = false, Dictionary <MemberInfo, Expression> excludeProperties = null) { Type sType = typeof(TSource); Type tType = typeof(TTarget); List <PropertyInfo> spis = sType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).ToList(); List <PropertyInfo> tpis = tType.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList(); // target property --> source property // Dictionary<PropertyInfo, PropertyInfo> propertyMap = new Dictionary<PropertyInfo, PropertyInfo>(tpis.Select(p => new KeyValuePair<PropertyInfo, PropertyInfo>(p, null))); Dictionary <PropertyInfo, List <string> > sourceNamesMap = new Dictionary <PropertyInfo, List <string> >(spis.Select(x => new KeyValuePair <PropertyInfo, List <string> >(x, new List <string>() { x.Name }))); sourceNamesMap.All(x => { // [MapperPropertyName(Name="",SourceType=xxx)] var sAttrs = x.Key.GetCustomAttributes <MapperPropertyNameAttribute>(); if (sAttrs != null) { foreach (var attr in sAttrs) { if ((attr.TargetType == null || (attr.TargetType != null && attr.TargetType.IsAssignableFrom(tType))) && !x.Value.Contains(attr.Name)) { x.Value.Add(attr.Name); } } } return(true); }); // [MapperPropertyName(Name="",SourceType=xxx)] tpis.All(x => { var tAttrs = x.GetCustomAttributes <MapperPropertyNameAttribute>(); if (tAttrs != null) { foreach (var attr in tAttrs) { if (attr.SourceType == null || (attr.SourceType != null && attr.SourceType.IsAssignableFrom(sType))) { var sp = sourceNamesMap.FirstOrDefault(x => x.Key.Name == attr.Name); if (sp.Value != null && !sp.Value.Contains(x.Name)) { sp.Value.Add(x.Name); } } } } return(true); }); List <Expression> expList = new List <Expression>() { }; foreach (var pi in spis) { Expression excludeExpression = excludeProperties?.FirstOrDefault(p => p.Key == pi || (p.Key.DeclaringType == pi.DeclaringType && p.Key.Name == pi.Name)).Value; if (excludeExpression == null && excludeProperties != null && excludeProperties.Count > 0) { excludeExpression = excludeProperties.FirstOrDefault(x => x.Value is MemberExpression me && me.Member == pi).Value; } if (excludeExpression?.NodeType == ExpressionType.MemberAccess || excludeExpression?.NodeType == ExpressionType.Constant) { continue; } MemberInitExpression _dic = null; if (excludeExpression is MemberInitExpression mie) { _dic = mie; } var names = sourceNamesMap[pi]; // 获取targetProperty var targetList = tpis.Where(x => names.Any(y => y == x.Name)).ToList(); if (targetList == null || targetList.Count == 0) { targetList = tpis.Where(x => names.Any(y => y.Equals(x.Name, StringComparison.OrdinalIgnoreCase))).ToList(); } if (targetList == null || targetList.Count == 0) { continue; } foreach (var property in targetList) { if (!property.CanWrite) { continue; } var exp = ConvertProperty(sourcePar, checkerPar, pi, targetPar, property, isCopy, _dic); if (exp != null) { expList.Add(exp); } } } return(expList); }
private void GetTextures(McResourcePack resourcePack, Dictionary <ResourceLocation, Image <Rgba32>[]> seperateFrames, Dictionary <ResourceLocation, Image <Rgba32> > regularTextures, IProgressReceiver progressReceiver) { progressReceiver.UpdateProgress(0, "Processing blockstate textures..."); int blockstatesProcessed = 0; int totalStates = resourcePack.BlockStates.Count; foreach (var state in resourcePack.BlockStates) { progressReceiver.UpdateProgress((int)(100D * ((double)blockstatesProcessed / (double)totalStates)), null, state.Key); var blockState = BlockFactory.GetBlockState(state.Key); if (blockState.Name == "Unknown") { Log.Warn($"Missing blockstate: {state.Key}"); blockstatesProcessed++; continue; } foreach (var variant in state.Value.Variants) { foreach (var entry in BlockState.ParseData(variant.Key)) { blockState = blockState.WithProperty(entry.Key, entry.Value); } foreach (var va in variant.Value) { var model = va.Model; foreach (var texture in model.Textures) //foreach(var element in model.Elements) //foreach(var face in element.Faces) { // var text = face.Value.Texture; //ResourcePackBlockModel.ResolveTexture(model, texture.Value); var text = texture.Value; if (text[0] == '#') { var substr = text.Substring(1); if (model.Textures.TryGetValue(substr, out var p)) { text = p; } else { var parent = model.Parent; while (parent != null) { if (parent == null) { break; } if (parent.Textures.TryGetValue(substr, out string parentName)) { text = parentName; break; } parent = parent.Parent; } } } if (resourcePack.TryGetBitmap(text, out var bmp)) { if (blockState.Block.Animated && !seperateFrames.ContainsKey(text)) { var frameSize = GetTextureDimensions(resourcePack, text); seperateFrames.Add(text, GetFrames(bmp, (int)frameSize.X, (int)frameSize.Y)); } else if (!blockState.Block.Animated && regularTextures.All(x => x.Key != text)) { regularTextures.Add(text, bmp); } } else { /// if (!texture.Value) // Log.Warn($"Could not get bitmap {texture.Value} or {text} (Key: {texture.Key} Model: {model.Name})"); } } } } blockstatesProcessed++; // state. } if (resourcePack.TryGetBitmap("block/water_flow", out var flow)) { var frameSize = GetTextureDimensions(resourcePack, "block/water_flow"); seperateFrames.TryAdd("block/water_flow", GetFrames(flow, (int)frameSize.X, (int)frameSize.Y)); } if (resourcePack.TryGetBitmap("block/water_still", out var still)) { var frameSize = GetTextureDimensions(resourcePack, "block/water_still"); seperateFrames.TryAdd("block/water_still", GetFrames(still, (int)frameSize.X, (int)frameSize.Y)); } }
//byr(Birth Year) - four digits; at least 1920 and at most 2002. //iyr(Issue Year) - four digits; at least 2010 and at most 2020. //eyr(Expiration Year) - four digits; at least 2020 and at most 2030. //hgt(Height) - a number followed by either cm or in: //If cm, the number must be at least 150 and at most 193. //If in, the number must be at least 59 and at most 76. //hcl(Hair Color) - a # followed by exactly six characters 0-9 or a-f. //ecl(Eye Color) - exactly one of: amb blu brn gry grn hzl oth. //pid(Passport ID) - a nine-digit number, including leading zeroes. //cid(Country ID) - ignored, missing or not. public bool IsValidPassport(Dictionary <string, string> passport) { return(Rules.Keys.All(passport.ContainsKey) && Rules.All(r => ApplyValidityAndPredicateFor(passport, r.Key, r.Value))); }
private static void ImportDiffFilesToTable(string[] args) { string location = args[0], extension = args[1], server = args[2], database = args[3], masterTableName = args[4]; var cnn = new SqlConnection("Data Source=" + server + ";Database=" + database + ";integrated security=true"); cnn.Open(); var filesHeaders = new Dictionary <string, string>(); var files = Directory.GetFiles(location, extension, SearchOption.AllDirectories); Console.WriteLine("Found Files: " + files.Length); foreach (var file in files) { var sr = new StreamReader(File.OpenRead(file)); var fileHeader = sr.ReadLine(); fileHeader = fileHeader.Replace(" ", "").Replace(",,", ",_,"); if (fileHeader.EndsWith(",")) { fileHeader += "_"; } fileHeader = fileHeader.Replace(",", "], ["); fileHeader = "[" + fileHeader + "]"; sr.Close(); filesHeaders.Add(file, fileHeader); var fileName = file.Substring(file.LastIndexOf("\\") + 1, file.LastIndexOf(".") - file.LastIndexOf("\\") - 1); Console.WriteLine("Processing File: " + fileName); fileHeader = fileHeader.Replace(",", " VARCHAR(1024),"); var dropTableScript = "IF OBJECT_ID('dbo." + fileName + "', 'U') IS NOT NULL DROP TABLE dbo." + fileName; var createTableScript = "CREATE TABLE " + fileName + "(" + fileHeader + " VARCHAR(1024))"; var insertDataScript = "EXECUTE stp_CommaBulkInsert @filePath,@tableName"; new SqlCommand(dropTableScript, cnn).ExecuteNonQuery(); new SqlCommand(createTableScript, cnn).ExecuteNonQuery(); var insertCmd = new SqlCommand(insertDataScript, cnn); insertCmd.Parameters.AddWithValue("filePath", file); insertCmd.Parameters.AddWithValue("tableName", fileName); insertCmd.CommandTimeout = 0; //wait indefinitely for the procedure to finish import insertCmd.ExecuteNonQuery(); } Console.WriteLine("Done Processing files!"); var masterTableHeader = ""; if (filesHeaders.All(x => x.Value == filesHeaders.ElementAt(0).Value)) { masterTableHeader = filesHeaders.ElementAt(0).Value; } else { var columns = new List <string>(); foreach (var filesHeader in filesHeaders) { columns.AddRange(filesHeader.Value.Split(',')); } masterTableHeader = string.Join(",", columns.Distinct()); } CreateTableFromHeader(server, database, masterTableName, masterTableHeader); Console.WriteLine("Done Creating Master Table!"); Console.WriteLine("Transferring Data to Master Table!"); foreach (var file in files) { var fileHeader = filesHeaders[file]; var fileName = file.Substring(file.LastIndexOf("\\") + 1, file.LastIndexOf(".") - file.LastIndexOf("\\") - 1); Console.WriteLine("Transferring File: " + fileName); var insertDataScript = $"insert into {masterTableName} ({fileHeader}) select {fileHeader} from {fileName}"; var insertCmd = new SqlCommand(insertDataScript, cnn); insertCmd.CommandTimeout = 0; //wait indefinitely for the procedure to finish import insertCmd.ExecuteNonQuery(); } Console.WriteLine("Done transferring files!"); Console.WriteLine("Cleaning tables!"); foreach (var file in files) { var fileName = file.Substring(file.LastIndexOf("\\") + 1, file.LastIndexOf(".") - file.LastIndexOf("\\") - 1); Console.WriteLine("Dropping table: " + fileName); var dropTableScript = "IF OBJECT_ID('dbo." + fileName + "', 'U') IS NOT NULL DROP TABLE dbo." + fileName; new SqlCommand(dropTableScript, cnn) { CommandTimeout = 0 }.ExecuteNonQuery(); } Console.WriteLine("Done!"); cnn.Close(); cnn.Dispose(); }
public static void Main(string[] args) { Console.SetIn(Console.In); Console.SetOut(Console.Out); var map = Networking.getInit(out _MyID); DarrekLog.LogFileName = String.Format("log{0}.txt", _MyID); const ushort MAX_STRENGTH = 255; const ushort HALF_STRENGTH = 128; /* ------ * Do more prep work, see rules for time limit * ------ */ Networking.SendInit(MyBotName); // Acknoweldge the init and begin the game var random = new Random(); DarrekLog.AppendLog("Starting battle!"); int frameNumber = 0; var movesTowardHighProductionByDirection = new Dictionary <Direction, ushort>(); movesTowardHighProductionByDirection.Add(Direction.North, 0); movesTowardHighProductionByDirection.Add(Direction.South, 0); movesTowardHighProductionByDirection.Add(Direction.East, 0); movesTowardHighProductionByDirection.Add(Direction.West, 0); while (true) { //try //{ Networking.getFrame(ref map); // Update the map to reflect the moves before this turn //} //catch (Exception) //{ // return; //} #region Check Production if (frameNumber == 0) { var sb = new StringBuilder(); sb.Append("production values:"); //TODO: find nearest high production zone and head there. for (ushort y = 0; y < map.Height; y++) { sb.Append("\r\n"); for (ushort x = 0; x < map.Width; x++) { var prodVal = map[x, y].Production; sb.Append(prodVal + " "); if (_MaxProductionValue < prodVal) { _MaxProductionValue = prodVal; } } } DarrekLog.AppendLog(sb.ToString()); _TopProductionValuesGreaterThan = (ushort)(_MaxProductionValue * .70); DarrekLog.AppendLog(string.Format("Max Production Value Found = {0}", _MaxProductionValue)); DarrekLog.AppendLog(string.Format("Top Production Values >= {0}", _TopProductionValuesGreaterThan)); } #endregion frameNumber++; DarrekLog.AppendLog(string.Format("Frame {0}", frameNumber)); movesTowardHighProductionByDirection[Direction.North] = 0; movesTowardHighProductionByDirection[Direction.South] = 0; movesTowardHighProductionByDirection[Direction.East] = 0; movesTowardHighProductionByDirection[Direction.West] = 0; var moves = new List <Move>(); for (ushort x = 0; x < map.Width; x++) { for (ushort y = 0; y < map.Height; y++) { if (map[x, y].Owner == _MyID) { var activeSite = new SiteEx(map, x, y); if (activeSite.Strength < MAX_STRENGTH / 10) { continue; } var neighbors = new List <SiteEx>() { GetNeighbor(map, activeSite, Direction.West), GetNeighbor(map, activeSite, Direction.East), GetNeighbor(map, activeSite, Direction.North), GetNeighbor(map, activeSite, Direction.South) }; var friendlySites = neighbors.Where(c => c.Owner == _MyID); var neutralNeighbors = neighbors.Where(c => c.Owner == 0); var potentialLunchSites = neighbors.Where(c => c.Strength < activeSite.Strength && c.Owner == 0); //1. Try to grow if (potentialLunchSites.Any()) { if (neutralNeighbors.Count() >= 3 || potentialLunchSites.Count() > 1) { var directionToMove = GetNearestFreeHighProductionDirection(map, activeSite); movesTowardHighProductionByDirection[directionToMove]++; if (GetNeighbor(map, activeSite, directionToMove).Strength < activeSite.Strength) { moves.Add(new Move { Location = activeSite.Location, Direction = directionToMove }); } } else { var lunchSite = potentialLunchSites.OrderByDescending(s => s.Production).First(); var directionToMove = GetMoveDirection(map, activeSite, lunchSite); moves.Add(new Move { Location = activeSite.Location, Direction = directionToMove }); continue; } } //2. If all neighbors are friendly, move where most of the blob is moving (toward high production) if (friendlySites.Count() == neighbors.Count && ((activeSite.Strength >= (activeSite.Production * 5)) || activeSite.Strength > HALF_STRENGTH)) { ushort distanceFromEdge; var nearestNonPlayerDirection = GetNearestNonPlayerDirection(map, activeSite, _MyID, out distanceFromEdge); if (movesTowardHighProductionByDirection.All(m => m.Value == 0) || distanceFromEdge > 3) { if (nearestNonPlayerDirection != Direction.Still) { moves.Add(new Move { Location = activeSite.Location, Direction = nearestNonPlayerDirection }); } else //All orthagonal directions are occupied. { //TODO: could have logic here to find enemies or something, or go diagonally. } } else { var blobMoveDirection = movesTowardHighProductionByDirection.First(m => m.Value == movesTowardHighProductionByDirection.Max(n => n.Value)).Key; DarrekLog.AppendLog(string.Format("Moving with blob to the {0}", blobMoveDirection)); moves.Add(new Move { Location = activeSite.Location, Direction = blobMoveDirection }); } } } } } Networking.SendMoves(moves); // Send moves } }
public SaveResponse Update(IUnitOfWork uow, UserPermissionUpdateRequest request) { Check.NotNull(request, "request"); Check.NotNull(request.UserID, "userID"); Check.NotNull(request.Permissions, "permissions"); var userID = request.UserID.Value; var oldList = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase); foreach (var p in GetExisting(uow.Connection, userID, request.Module, request.Submodule)) { oldList[p.PermissionKey] = p.Granted.Value; } var newList = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase); foreach (var p in request.Permissions) { newList[p.PermissionKey] = p.Granted ?? false; } if (oldList.Count == newList.Count && oldList.All(x => newList.ContainsKey(x.Key) && newList[x.Key] == x.Value)) { return(new SaveResponse()); } foreach (var k in oldList.Keys) { if (newList.ContainsKey(k)) { continue; } new SqlDelete(fld.TableName) .Where( new Criteria(fld.UserId) == userID & new Criteria(fld.PermissionKey) == k) .Execute(uow.Connection); } foreach (var k in newList.Keys) { if (!oldList.ContainsKey(k)) { uow.Connection.Insert(new MyRow { UserId = userID, PermissionKey = k, Granted = newList[k] }); } else if (oldList[k] != newList[k]) { new SqlUpdate(fld.TableName) .Where( fld.UserId == userID & fld.PermissionKey == k) .Set(fld.Granted, newList[k]) .Execute(uow.Connection); } } BatchGenerationUpdater.OnCommit(uow, fld.GenerationKey); return(new SaveResponse()); }
private Dictionary <string, object> ProcessDynamicParams(SqlParams sqlParams, ref string reportsql, ref string prepareSql, ref string totalSql) { var parameters = new Dictionary <string, object>(); var elements = XmlConfig.Elements("Dynamic"); if (XmlConfig.Attribute("BaseType") != null) { var baseConfig = AllReportConfig.Elements("Rep").FirstOrDefault(q => q.Attribute("key").Value == XmlConfig.Attribute("BaseType").Value); if (baseConfig != null) { foreach (var item in baseConfig.Elements("Dynamic")) { var property = elements.FirstOrDefault(p => p.Attribute("property").Value == item.Attribute("property").Value); if (property != null) { property.Add(item.Elements()); } } } } foreach (var itemEle in elements) { Dictionary <string, object> dataRes; List <ReportWhereEntity> list = FillReportWhereEntity(itemEle); string dynamicStr = GetDynamicStr(list, sqlParams.Where, out dataRes); string dyProperty = itemEle.Attribute("property").Value; if (!string.IsNullOrEmpty(reportsql)) { reportsql = reportsql.Replace(dyProperty, dynamicStr); } //if (!string.IsNullOrEmpty(footerSql)) // footerSql = footerSql.Replace(dyProperty, dynamicStr); if (!string.IsNullOrEmpty(prepareSql)) { prepareSql = prepareSql.Replace(dyProperty, dynamicStr); } if (!string.IsNullOrEmpty(totalSql)) { totalSql = totalSql.Replace(dyProperty, dynamicStr); } if (dataRes != null) { foreach (var item in dataRes) { if (parameters.All(p => p.Key != item.Key.ToLower())) { parameters.Add(item.Key.ToLower(), item.Value); } } } } foreach (var item in sqlParams.Where) { if (parameters.All(p => p.Key != item.Key.ToLower())) { parameters.Add(item.Key.ToLower(), item.Value); } } return(parameters); }
//checks to see if any pills are still on the map public bool AreAllPillsEaten() { return(map.All(i => i.Value != BoardStates.PILL)); }
public ValidationRule <TMember> Complete() { _isValidObject = _rules.All(x => x.Value.IsValid); return(this); }
bool AreAllChunksRendered() { return(renderedChunks.All(pair => pair.Value.GetComponent <ChunkRenderer>().IsRendered())); }
public bool ConstraintsAreFree() { return(propertyDocuments.All(x => x.Value == null)); }
public bool AllPatternLinesProcessed() { return(patternLines.All(x => x.Value.Count() < (int)x.Key)); }
/// <summary> /// checks if the sdk is installed or has been synced /// </summary> /// <returns></returns> private bool HasAnySDK() { string NDKPath = Environment.GetEnvironmentVariable("NDKROOT"); /* Don't check for existence of env vars, always set them from the .ini values if they exist * // bool bNeedsNDKPath = string.IsNullOrEmpty(NDKPath); * // bool bNeedsAndroidHome = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ANDROID_HOME")); * // bool bNeedsAntHome = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ANT_HOME")); * // if((bNeedsNDKPath || bNeedsAndroidHome || bNeedsAntHome)) */ { var configCacheIni = new ConfigCacheIni("Engine", null); var AndroidEnv = new Dictionary <string, string>(); Dictionary <string, string> EnvVarNames = new Dictionary <string, string> { { "ANDROID_HOME", "SDKPath" }, { "NDKROOT", "NDKPath" }, { "ANT_HOME", "ANTPath" }, { "JAVA_HOME", "JavaPath" } }; string path; foreach (var kvp in EnvVarNames) { if (configCacheIni.GetPath("/Script/AndroidPlatformEditor.AndroidSDKSettings", kvp.Value, out path) && !string.IsNullOrEmpty(path)) { // Log.TraceWarning("Adding {0} from ini as {1} to {2}", kvp.Value, path, kvp.Key); AndroidEnv.Add(kvp.Key, path); } else { var envValue = Environment.GetEnvironmentVariable(kvp.Key); if (!String.IsNullOrEmpty(envValue)) { // Log.TraceWarning("Adding {0} from env as {1}", kvp.Key, envValue); AndroidEnv.Add(kvp.Key, envValue); } } } // If we are on Mono and we are still missing a key then go and find it from the .bash_profile if (Utils.IsRunningOnMono && !EnvVarNames.All(s => AndroidEnv.ContainsKey(s.Key))) { string BashProfilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".bash_profile"); if (File.Exists(BashProfilePath)) { string[] BashProfileContents = File.ReadAllLines(BashProfilePath); foreach (string Line in BashProfileContents) { foreach (var kvp in EnvVarNames) { if (AndroidEnv.ContainsKey(kvp.Key)) { continue; } if (Line.StartsWith("export " + kvp.Key + "=")) { string PathVar = Line.Split('=')[1].Replace("\"", ""); AndroidEnv.Add(kvp.Key, PathVar); } } } } } // Set for the process foreach (var kvp in AndroidEnv) { Environment.SetEnvironmentVariable(kvp.Key, kvp.Value); } // See if we have an NDK path now... AndroidEnv.TryGetValue("NDKROOT", out NDKPath); } // we don't have an NDKROOT specified if (String.IsNullOrEmpty(NDKPath)) { return(false); } NDKPath = NDKPath.Replace("\"", ""); // need a supported llvm if (!Directory.Exists(Path.Combine(NDKPath, @"toolchains/llvm-3.5")) && !Directory.Exists(Path.Combine(NDKPath, @"toolchains/llvm-3.3")) && !Directory.Exists(Path.Combine(NDKPath, @"toolchains/llvm-3.1"))) { return(false); } return(true); }
public int IdentificarBiometriaComCarga(byte[] template) { var relogio = new Stopwatch(); relogio.Start(); Console.WriteLine($"Localizando digital ..."); var tasks = new Dictionary <Guid, Task <int> >(); foreach (var buscaNitgen in _mecanismosBusca) { var task = buscaNitgen.CriarTaskParaIdentificacaoBiometrica(template); tasks.Add(buscaNitgen.Id, task); if (!task.IsCanceled) { task.Start(); } } //while (tasks.Count() > 0) //{ // var indice = Task.WaitAny(tasks.Select(t => t.Value).ToArray()); // var resultado = tasks.ElementAt(indice); // Console.WriteLine($"{resultado.Key} - Terminou com {resultado.Value.Result}"); // if (resultado.Value.Result > 0) // { // relogio.Stop(); // Console.WriteLine($"Localizada digital em > {relogio.Elapsed.TotalSeconds} segundos"); // return resultado.Value.Result; // } // tasks.Remove(resultado.Key); //} var possoSair = false; while (!possoSair) { if (tasks.Any(t => t.Value.IsCompleted)) { var completadas = tasks.Where(t => t.Value.IsCompleted && !t.Value.IsCanceled); var resultado = completadas.FirstOrDefault(c => c.Value.Result > 0); if (resultado.Key != Guid.Empty) { foreach (var task in tasks.Where(t => t.Key != resultado.Key)) { _mecanismosBusca.FirstOrDefault(m => m.Id.Equals(task.Key)).CancellationSource.Cancel(); } relogio.Stop(); Console.WriteLine($"Digital localizada em {relogio.Elapsed.TotalSeconds} segundos"); return(resultado.Value.Result); } } if (tasks.All(t => t.Value.IsCompleted)) { possoSair = true; } Thread.Sleep(10); } relogio.Stop(); Console.WriteLine($"Nenhuma digital localizada em {relogio.Elapsed.TotalSeconds} segundos"); return(0); }
private void btnStart_Click(object sender, EventArgs e) { if (lstMedia.Items.Count == 0) { return; } if (Properties.Settings.Default.ShutdownType == 1 || Properties.Settings.Default.ShutdownType == 2) { var msg = MessageBox.Show(Language.Lang.MsgBoxShutdown.Message, Language.Lang.MsgBoxShutdown.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (msg == DialogResult.No) { return; } } if (bgThread.IsBusy) { if (!btnPause.Enabled) { btnStart.Enabled = false; btnPause.Enabled = true; ProcessManager.Resume(); return; } } else { // thread safe, make a copy // int = ListView Index // MediaQueue = ListView Tag var dict = new Dictionary <int, MediaQueue>(); foreach (ListViewItem item in lstMedia.Items) { dict.Add(item.Index, item.Tag as MediaQueue); item.SubItems[4].Text = "Waiting..."; } // check if all queue has enable hardsub if (!dict.All(x => !x.Value.HardSub)) { if (!Elevated.IsAdmin) { var msg = MessageBox.Show(Language.Lang.MsgHardSub.Message, Language.Lang.MsgHardSub.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (msg == DialogResult.Yes) { var tempFile = Path.Combine(Path.GetTempPath(), $"ifme_elevated_{DateTime.Now:yyyy-MM-dd_hh-mm-ss}.pis"); ProjectSave(tempFile); Elevated.RunAsAdmin(tempFile); return; } } } bgThread.RunWorkerAsync(dict); btnStart.Enabled = false; btnPause.Enabled = true; btnStop.Enabled = true; } }
public static string FindRoot(Dictionary <string, List <string> > tree) { return(tree.FirstOrDefault(pair => tree.All(p => !p.Value.Contains(pair.Key))).Key); }
/// <summary> /// Checks the request and query strings to see if it matches the definition of having a Surface controller /// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information. /// </summary> /// <param name="requestContext"></param> /// <returns></returns> private static PostedDataProxyInfo GetFormInfo(RequestContext requestContext) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } //if it is a POST/GET then a value must be in the request if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace() && requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace()) { return(null); } string encodedVal; switch (requestContext.HttpContext.Request.RequestType) { case "POST": //get the value from the request. //this field will contain an encrypted version of the surface route vals. encodedVal = requestContext.HttpContext.Request.Form["ufprt"]; break; case "GET": //this field will contain an encrypted version of the surface route vals. encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"]; break; default: return(null); } string decryptedString; try { decryptedString = encodedVal.DecryptWithMachineKey(); } catch (FormatException) { LogHelper.Warn <RenderRouteHandler>("A value was detected in the ufprt parameter but Umbraco could not decrypt the string"); return(null); } var parsedQueryString = HttpUtility.ParseQueryString(decryptedString); var decodedParts = new Dictionary <string, string>(); foreach (var key in parsedQueryString.AllKeys) { decodedParts[key] = parsedQueryString[key]; } //validate all required keys exist //the controller if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Controller)) { return(null); } //the action if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Action)) { return(null); } //the area if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Area)) { return(null); } foreach (var item in decodedParts.Where(x => new[] { ReservedAdditionalKeys.Controller, ReservedAdditionalKeys.Action, ReservedAdditionalKeys.Area }.Contains(x.Key) == false)) { // Populate route with additional values which aren't reserved values so they eventually to action parameters requestContext.RouteData.Values[item.Key] = item.Value; } //return the proxy info without the surface id... could be a local controller. return(new PostedDataProxyInfo { ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value), ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value), Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value), }); }
// 10-100 Rule Exception - Algorithm public static bool UnorderedEquals <T>(this IEnumerable <T> left, IEnumerable <T> right, IEqualityComparer <T> comparer = null) { if (left == null && right == null) // Scenario 1 - both null { return(true); } if (left == null || right == null) // Scenario 2 - one null one not null { return(false); } if (!left.Any() && !right.Any()) // Scenario 3 - Both are instantiated but empty lists { return(true); } if (!left.Any() || !right.Any()) // Scenario 4 - Both are instantiated but only one is an empty list { return(false); } var leftList = left.ToList(); var rightList = right.ToList(); if (leftList.Count != rightList.Count) // Scenario 5 - Both are instantiated but have different number of items. { return(false); } var countDictionary = new Dictionary <T, int>(comparer); // Scenario 6 - We have to compare the actual elements foreach (var item in leftList) { if (item == null) { continue; // No action needed } if (!countDictionary.TryGetValue(item, out int _)) { countDictionary.Add(item, 1); } else { ++countDictionary[item]; } } foreach (var item in rightList) { if (item == null) { continue; // No action needed } if (!countDictionary.TryGetValue(item, out int _)) { return(false); } --countDictionary[item]; } return(countDictionary.All(i => i.Value == 0)); // Why no action is needed for nulls? // - If there are different number of items, the comparison is false. // - If there are the same number of items, but different number of nulls, // countDictionary.All(i => i.Value == 0) will always be false. }
static void Main(string[] args) { Console.WriteLine("Hello World!"); Dictionary <string, IValidationRule> requirements = new Dictionary <string, IValidationRule> { { "byr", new MinMaxValidator { Min = 1920, Max = 2002 } }, { "iyr", new MinMaxValidator { Min = 2010, Max = 2020 } }, { "eyr", new MinMaxValidator { Min = 2020, Max = 2030 } }, { "hgt", new HeightValidator { MinCm = 150, MaxCm = 193, MinIn = 59, MaxIn = 76 } }, { "hcl", new RegexValidator { FieldRegex = new Regex(@"^#[0-9a-f]{6}$") } }, { "ecl", new ListValidator { ValidItems = "amb blu brn gry grn hzl oth".Split(' ').ToList() } }, { "pid", new RegexValidator { FieldRegex = new Regex(@"^[0-9]{9}$") } } //"cid" }; int validCount = 0; int invalidCount = 0; using (StreamReader sr = new StreamReader("puzzleinput.txt")) { string line; Dictionary <string, bool> elementsNeeded = GenerateValidationDictionary(requirements.Keys); while ((line = sr.ReadLine()) != null) { if (string.IsNullOrEmpty(line)) { //validate passport if (elementsNeeded.All(t => t.Value)) { validCount++; } else { invalidCount++; } elementsNeeded = GenerateValidationDictionary(requirements.Keys); } else { var elements = line.Split(' '); foreach (var element in elements) { var t = element.IndexOf(':'); var field = element.Substring(0, t); var value = element.Substring(t + 1); if (elementsNeeded.ContainsKey(field)) { #if PART2 if (requirements[field].Validate(value)) #endif elementsNeeded[field] = true; } } } } if (elementsNeeded.All(t => t.Value)) { validCount++; } else { invalidCount++; } Console.WriteLine($"Valid {validCount} Invalid {invalidCount}"); Console.ReadLine(); } }
public bool Shrunk() { return(shrunk.All(kv => kv.Value)); }
private bool IsIntraPoolMigration() { return(m_vmMappings.All(IsIntraPoolMigration)); }
internal void ParseInventorySettings() { foreach (PropertyInfo configSetting in GetType().GetProperties()) { Log.Debug($"Name: {configSetting.Name}"); if (!configSetting.Name.Contains("Inventory")) { continue; } string configName = configSetting.Name; Dictionary <string, List <string> > dict = (Dictionary <string, List <string> >)configSetting.GetValue(this); RoleType role = RoleType.None; switch (configName) { case nameof(ClassDInventory): role = RoleType.ClassD; break; case nameof(ChaosInventory): role = RoleType.ChaosInsurgency; break; case nameof(ScientistInventory): role = RoleType.Scientist; break; case nameof(GuardInventory): role = RoleType.FacilityGuard; break; case nameof(CadetInventory): role = RoleType.NtfCadet; break; case nameof(LieutenantInventory): role = RoleType.NtfLieutenant; break; case nameof(CommanderInventory): role = RoleType.NtfCommander; break; case nameof(NtfSciInventory): role = RoleType.NtfScientist; break; } if (role == RoleType.None) { Log.Error("Role is none - This should never happen."); continue; } if (dict == null || dict.All(l => l.Value == null)) { Log.Warn($"The dictionary for {configName} is empty, they will have default inventory."); if (Inventories.ContainsKey(role)) { Inventories.Remove(role); } continue; } foreach (KeyValuePair <string, List <string> > unparsedDict in dict) { string slotName = unparsedDict.Key; List <string> list = unparsedDict.Value; if (list == null) { Log.Debug($"The list for {configName}:{slotName} is empty."); continue; } foreach (string unparsedRaw in list) { ItemType item; if (unparsedRaw == "empty") { if (!Inventories.ContainsKey(role)) { Inventories.Add(role, new Dictionary <string, List <Tuple <ItemType, int> > > { { slotName, new List <Tuple <ItemType, int> >() } }); } continue; } string[] rawChance = unparsedRaw.Split(':'); try { item = (ItemType)Enum.Parse(typeof(ItemType), rawChance[0], true); } catch (Exception) { Log.Error($"Unable to parse item: {rawChance[0]} in {configName} inventory settings."); continue; } if (!int.TryParse(rawChance[1], out int chance)) { Log.Error( $"Unable to parse item chance {rawChance[0]} for {rawChance[0]} in {configName} inventory settings."); continue; } Log.Debug($"{item} was added to {configName} inventory with {chance} chance.", Debug); if (!Inventories.ContainsKey(role)) { Inventories.Add(role, new Dictionary <string, List <Tuple <ItemType, int> > > { { "slot1", new List <Tuple <ItemType, int> >() }, { "slot2", new List <Tuple <ItemType, int> >() }, { "slot3", new List <Tuple <ItemType, int> >() }, { "slot4", new List <Tuple <ItemType, int> >() }, { "slot5", new List <Tuple <ItemType, int> >() }, { "slot6", new List <Tuple <ItemType, int> >() }, { "slot7", new List <Tuple <ItemType, int> >() }, { "slot8", new List <Tuple <ItemType, int> >() } }); } Inventories[role][slotName].Add(new Tuple <ItemType, int>(item, chance)); } } } }
public int Prompt(string message = "", ConsoleColor?color = null, bool allowEmpty = false, bool clearConsole = true) { if (Contents?.Any() == false) { return(-1); } var prevRenderOptionChoice = RenderOptions.IncludeChoices; RenderOptions.IncludeChoices = true; int selection = -1; do { Write(clearConsole); if (!string.IsNullOrEmpty(message)) { Consoul.Write("HELP ME!", Console.BackgroundColor); Consoul.Write(message, color ?? ConsoulLibrary.RenderOptions.PromptColor); } if (allowEmpty) { Consoul.Write("Press Enter to continue", ConsoulLibrary.RenderOptions.SubnoteColor); } string input = Consoul.Read(); if (string.IsNullOrEmpty(input) && allowEmpty) { selection = Contents.Count + 1; break; } if (input.Contains("=")) { Dictionary <int, List <int> > matches = new Dictionary <int, List <int> >(); string[] queries = input.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); foreach (string queryInput in queries) { string[] queryParts = queryInput.Split('='); if (queryParts.Length == 2) { int columnIndex = Headers.IndexOf(queryParts[0]); if (columnIndex >= 0) { if (!matches.ContainsKey(columnIndex)) { matches.Add(columnIndex, new List <int>()); } for (int i = 0; i < Contents.Count; i++) { if (Contents[i][columnIndex] == queryParts[1]) { matches[columnIndex].Add(i); } } } else { raiseQueryYieldsNoResults($"Invalid Header reference! Could not find Header '{queryParts[0]}'.", input); } } else { raiseQueryYieldsNoResults("Query-based selection not formatted correctly. Must be in {Header Name}={Value} format", input); } } List <int> results = new List <int>(); for (int i = 0; i < Contents.Count; i++) { if (matches.All(o => o.Value.Contains(i))) { results.Add(i); } } if (results.Count == 1) { selection = results.First() + 1; // selection is expected as one-based } else if (results.Count > 1) { raiseQueryYieldsNoResults("Invalid Query! Query yielded multiple results. Try a more refined search.", input); } else if (results.Count == 0) { raiseQueryYieldsNoResults("Invalid Query! Query yielded no results.", input); } } else if (!int.TryParse(input, out selection) || selection <= 0 || selection > Contents.Count) { Consoul.Write("Invalid selection!", ConsoleColor.Red); Consoul.Wait(); selection = -1; } } while (selection < 0); if (selection > Contents.Count) { selection = 0; } RenderOptions.IncludeChoices = prevRenderOptionChoice; return(selection - 1); }
/// <summary> /// Yield values in a dictionary as key/value pairs. (one pair for each value in each key) /// </summary> /// <param name="dictionary"></param> /// <returns></returns> public bool Yield(Dictionary <string, string[]> dictionary) { return(dictionary.All(Yield)); }
/// <summary> /// /// </summary> /// <param name="templateIds"></param> /// <param name="quantity"></param> /// <returns></returns> public bool Match(Dictionary <int, long> templates, long kamas) { return(RequiredKamas == kamas && RequiredItems.All(required => templates.Any(template => required.TemplateId == template.Key && required.Quantity == template.Value)) && templates.All(template => RequiredItems.Any(required => required.TemplateId == template.Key && required.Quantity == template.Value))); }
private void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { // TODO: Insert monitoring activities here. //await semaphoreSlim.WaitAsync().ConfigureAwait(false); semaphoreSlim.Wait(); MayFlower dbContext = new MayFlower(); try { PaymentQueueHandler.Components.BookingList bookPaidList = new PaymentQueueHandler.Components.BookingList(dbContext, null); IEnumerable <SuperPNR> bookingProcessed = null; List <string> successProcessed = new List <string>(); Dictionary <string, ProductReserve.BookResultType> reserveStatus = new Dictionary <string, ProductReserve.BookResultType>(); if (sender.GetType().Name == "String" && !string.IsNullOrWhiteSpace(sender.ToString())) { string[] splitAttr = sender.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); bool includeEXP = splitAttr.Length == 2; bookingProcessed = bookPaidList.GetBookingPaid(splitAttr[0], true, true, false); } else { bookPaidList.CheckUpdatePendingPayment(true, true, false).ConfigureAwait(false).GetAwaiter().GetResult(); bookingProcessed = bookPaidList.GetAllBookingPaid(true, true, false); } foreach (var item in bookingProcessed) { // Process Add On Here foreach (var record in item.BookingInsurances) { try { if (record.BookingStatusCode == "PPA") { var insService = new InsuranceService(logger); var bookRespond = insService.ConfirmInsuranceQuotation(record, record.SuperPNRNo); bool res = bookRespond?.BatchBookResult == ProductReserve.BookResultType.AllSuccess || bookRespond?.BatchBookResult == ProductReserve.BookResultType.PartialSuccess; reserveStatus.Add(string.Format("Insurance ({0} - {1})", record.SuperPNRID, record.SuperPNRNo), bookRespond?.BatchBookResult ?? ProductReserve.BookResultType.AllFail); if (!res) { break; //any failed exit loop } else { successProcessed.Add(string.Format("Insurance ({0} - {1}): Update from [{2}] --> [{3}]" , item.SuperPNRID, item.SuperPNRNo, record.BookingStatusCode, "CON")); record.BookingStatusCode = res ? "CON" : "EXP"; } } } catch (Exception ex) { logger.Error(ex.GetBaseException(), "Reserve Fail in Insurance Booking - " + DateTime.Now.ToLoggerDateTime()); reserveStatus.Add(string.Format("Insurance ({0} - {1})", record.SuperPNRID, record.SuperPNRNo), ProductReserve.BookResultType.AllFail); break; // exit looping prevent continue book } finally { dbContext.SaveChanges(); } } bool allSuccess = reserveStatus.All(x => x.Value == ProductReserve.BookResultType.AllSuccess); // Check is main last book item success if (allSuccess && item.EventBookings.Count > 0 && item.EventBookings.Any(x => x.BookingStatusCode == "PPA" || x.BookingStatusCode == "RHI")) { // check if status CON then doesn't execute Components.EventBookings eventBookings = new Components.EventBookings(item, "CON", allSuccess); string bookStatus = string.Join(",", item.EventBookings.Select(x => x.BookingStatusCode)); if (eventBookings.InformationCaution == null) { reserveStatus.Add(string.Format("Event ({0} - {1})", item.SuperPNRID, item.SuperPNRNo) , ProductReserve.BookResultType.AllSuccess); successProcessed.Add(string.Format("Event ({0} - {1}): Update from [{2}] --> [{3}]" , item.SuperPNRID, item.SuperPNRNo, bookStatus, "CON")); } else if (eventBookings.InformationCaution != null && eventBookings.InformationCaution.Count > 0) { reserveStatus.Add(string.Format("Event ({0} - {1})", item.SuperPNRID, item.SuperPNRNo) + Environment.NewLine + Environment.NewLine + JsonConvert.SerializeObject(eventBookings.InformationCaution, Formatting.Indented), ProductReserve.BookResultType.AllFail); } } else if (!allSuccess) { string _msg = "Deduct event booking inventory failed." + Environment.NewLine + Environment.NewLine + JsonConvert.SerializeObject(reserveStatus, Formatting.Indented); // throw error and end looping logger.Error(_msg); eventLog1.WriteEntry(_msg, EventLogEntryType.FailureAudit, 401); break; } } if (successProcessed != null && successProcessed.Count > 0) { string msg = "AddOn Scheduler Information" + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, successProcessed); logger.Info(msg); eventLog1.WriteEntry(msg, EventLogEntryType.SuccessAudit, 200); } if (bookPaidList.InformationCaution != null && bookPaidList.InformationCaution.Count > 0) { string msg = "AddOn Scheduler Information" + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, bookPaidList.InformationCaution); logger.Warn(msg); eventLog1.WriteEntry(msg, EventLogEntryType.Warning); } } catch (Exception ex) { string msg = "Error Occured when running async action. " + Environment.NewLine + Environment.NewLine + ex.ToString(); eventLog1.WriteEntry(msg, EventLogEntryType.Warning); logger.Warn(ex, msg); } finally { try { dbContext.SaveChanges(); } catch (Exception ex) { var changedInfo = dbContext.ChangeTracker.Entries() .Where(t => t.State == System.Data.Entity.EntityState.Modified) .Select(t => new { Original = t.OriginalValues.PropertyNames.ToDictionary(pn => pn, pn => t.OriginalValues[pn]), Current = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn]), }); logger.Error(ex, "Error while attemp to save db change on finally action." + Environment.NewLine + Environment.NewLine + JsonConvert.SerializeObject(changedInfo, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); } semaphoreSlim.Release(); } }
/// <summary>Raised by the bootstrapper when the it is notified that the detection stage is complete.</summary> /// <param name="args">The arguments of the event.</param> public override void OnDetectComplete(WPFBootstrapperEventArgs <Wix.DetectCompleteEventArgs> args) { InstallData.IsBusy = false; InstallData.IsInstalled = _packageStates.All(x => Wix.PackageState.Present.Equals(x.Value)); }
private static bool FindJsonPaths(object obj, Dictionary <object, string> searchedObjects, string basePath, HashSet <object> checkedObjects, IContractResolver contractResolver) { if (obj == null) { return(false); } var type = obj.GetType(); if (type == typeof(string) #if !NETSTANDARD1_0 || type.IsPrimitive || type.IsEnum #endif || type == typeof(JValue) || checkedObjects.Contains(obj) ) { // no need to inspect return(false); } if (searchedObjects.ContainsKey(obj)) { searchedObjects[obj] = basePath; if (searchedObjects.All(p => p.Value != null)) { return(true); } } checkedObjects.Add(obj); var pathAndSeparator = basePath + "/"; if (obj is IDictionary dictionary) { foreach (DictionaryEntry pair in dictionary) { if (FindJsonPaths(pair.Value, searchedObjects, pathAndSeparator + pair.Key, checkedObjects, contractResolver)) { return(true); } } } else if (obj is IList list) { for (var i = 0; i < list.Count; ++i) { var item = list[i]; if (FindJsonPaths(item, searchedObjects, pathAndSeparator + i, checkedObjects, contractResolver)) { return(true); } } } else if (obj is IEnumerable enumerable) { var i = 0; foreach (var item in enumerable) { if (FindJsonPaths(item, searchedObjects, pathAndSeparator + i, checkedObjects, contractResolver)) { return(true); } i++; } } else { if (contractResolver.ResolveContract(type) is JsonObjectContract contract) { foreach (var jsonProperty in contract.Properties) { if (jsonProperty.Ignored) { continue; } var value = jsonProperty.ValueProvider.GetValue(obj); if (value != null) { if (FindJsonPaths(value, searchedObjects, pathAndSeparator + jsonProperty.PropertyName, checkedObjects, contractResolver)) { return(true); } } } if (obj is IJsonExtensionObject) { var extensionDataProperty = type.GetRuntimeProperty(nameof(IJsonExtensionObject.ExtensionData)); if (extensionDataProperty != null) { var value = extensionDataProperty.GetValue(obj); if (FindJsonPaths(value, searchedObjects, basePath, checkedObjects, contractResolver)) { return(true); } } } } } return(false); }
void IDanmakuWindow.AddDanmaku(DanmakuType type, string comment, uint color) { if ((this as Window).CheckAccess()) { //<Storyboard x:Key="Storyboard1"> // <ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="fullScreenDanmaku"> // <EasingThicknessKeyFrame KeyTime="0" Value="3,0,0,0"/> // <EasingThicknessKeyFrame KeyTime="0:0:1.9" Value="220,0,0,0"/> // </ThicknessAnimationUsingKeyFrames> // </Storyboard> lock (LayoutRoot.Children) { var v = new FullScreenDanmaku(); v.Text.Text = comment; v.ChangeHeight(); var wd = v.Text.DesiredSize.Width; Dictionary <double, bool> dd = new Dictionary <double, bool>(); dd.Add(0, true); foreach (var child in LayoutRoot.Children) { if (child is FullScreenDanmaku) { var c = child as FullScreenDanmaku; if (!dd.ContainsKey(Convert.ToInt32(c.Margin.Top))) { dd.Add(Convert.ToInt32(c.Margin.Top), true); } if (c.Margin.Left > (SystemParameters.PrimaryScreenWidth - wd - 50)) { dd[Convert.ToInt32(c.Margin.Top)] = false; } } } double top; if (dd.All(p => p.Value == false)) { top = dd.Max(p => p.Key) + v.Text.DesiredSize.Height; } else { top = dd.Where(p => p.Value).Min(p => p.Key); } // v.Height = v.Text.DesiredSize.Height; // v.Width = v.Text.DesiredSize.Width; Storyboard s = new Storyboard(); Duration duration = new Duration( TimeSpan.FromTicks(Convert.ToInt64((SystemParameters.PrimaryScreenWidth + wd) / Store.FullOverlayEffect1 * TimeSpan.TicksPerSecond))); ThicknessAnimation f = new ThicknessAnimation(new Thickness(SystemParameters.PrimaryScreenWidth, top, 0, 0), new Thickness(-wd, top, 0, 0), duration); s.Children.Add(f); s.Duration = duration; Storyboard.SetTarget(f, v); Storyboard.SetTargetProperty(f, new PropertyPath("(FrameworkElement.Margin)")); LayoutRoot.Children.Add(v); s.Completed += s_Completed; s.Begin(); } } else { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action( () => (this as IDanmakuWindow).AddDanmaku(type, comment, color)) ); } }