public static DominatorState CumulativeState(this IEnumerable<DominatorState?> states) { var allDominated = states.All(state_ => state_ != null && state_.Value.Kind == DominatorStateKind.Dominated); if (allDominated) return DominatorState.Dominated(); var allSubmissive = states.All(state_ => state_ != null && state_.Value.Kind == DominatorStateKind.Submissive); if (allSubmissive) return DominatorState.Submissive(); return DominatorState.Indetermined(""); }
public static string RemoveExtraSpacesLeavingIndentation(this string line) { var newString = new StringBuilder(); var lastWasWhiteSpace = false; if (line.All(char.IsWhiteSpace)) { return line; } var firstNonwhitespaceIndex = line.IndexOf(line.FirstOrDefault(c => !char.IsWhiteSpace(c))); for (var i = 0; i < line.Length; i++) { if (i < firstNonwhitespaceIndex) { newString.Append(line[i]); continue; } if (char.IsWhiteSpace(line[i]) && lastWasWhiteSpace) { continue; } newString.Append(line[i]); lastWasWhiteSpace = char.IsWhiteSpace(line[i]); } return newString.ToString().Replace('\r', ' '); }
/// <summary> /// Takes a list of stringy integers and collapses any ranges found within /// Example: [1, 2, 3, 5, 8, 9, 10] => [1-3, 5, 8-10] /// </summary> /// <param name="self">The list to collapse</param> /// <returns>A collapsed list</returns> public static IEnumerable<string> CollapseRanges(this IEnumerable<string> self) { if (!self.All(IsNumericValidator.IsNumeric)){ return self; } var returnList = new List<string>(); var selfStack = new Stack<int>(self.Select(int.Parse)); while (selfStack.Count > 0){ var maxElement = selfStack.Pop(); var minElement = maxElement; while (selfStack.Count > 0 && selfStack.Peek() == minElement - 1){ minElement = selfStack.Pop(); } returnList.Add(maxElement != minElement ? string.Format("{0}-{1}", minElement, maxElement) : maxElement.ToString()); } returnList.Reverse(); return returnList; }
public static int? CheckStatus(this int[] self) { int sumVertical = 0; int sumHorizontal = 0; int sumDiagonal1 = 0; int sumDiagonal2 = 0; for (int j = 0; j < 3; j++) { for (int i = 0; i < 3; i++) { sumVertical += self[i * 3 + j]; sumHorizontal += self[j * 3 + i]; } if (Math.Abs(sumVertical) == 3) { return sumVertical; } if (Math.Abs(sumHorizontal) == 3) { return sumHorizontal; } sumDiagonal1 += self[j * 4]; sumDiagonal2 += self[2*(j+1)]; sumVertical = 0; sumHorizontal = 0; } if (Math.Abs(sumDiagonal1) == 3) { return sumDiagonal1; } if (Math.Abs(sumDiagonal2) == 3) { return sumDiagonal2; } if (self.All(element => Math.Abs(element) == 1)) { return 0; } return null; }
/// <summary> /// Transliterate Unicode string to ASCII string. /// </summary> /// <param name="input">String you want to transliterate into ASCII</param> /// <param name="tempStringBuilderCapacity"> /// If you know the length of the result, /// pass the value for StringBuilder capacity. /// InputString.Length*2 is used by default. /// </param> /// <returns> /// ASCII string. There are [?] (3 characters) in places of some unknown(?) unicode characters. /// It is this way in Python code as well. /// </returns> public static string Unidecode(this string input, int? tempStringBuilderCapacity = null) { if (string.IsNullOrEmpty(input)) { return ""; } if (input.All(x => x < 0x80)) { return input; } // Unidecode result often can be at least two times longer than input string. var sb = new StringBuilder(tempStringBuilderCapacity ?? input.Length*2); foreach (char c in input) { // Copypaste is bad, but sb.Append(c.Unidecode()); would be a bit slower. if (c < 0x80) { sb.Append(c); } else { int high = c >> 8; int low = c & 0xff; string[] transliterations; if (characters.TryGetValue(high, out transliterations)) { sb.Append(transliterations[low]); } } } return sb.ToString(); }
public static string ToFriendlyString(this string text) { if (text.All(char.IsUpper)) return text; var capitalLetterMatch = new Regex("\\B[A-Z]", RegexOptions.Compiled); return capitalLetterMatch.Replace(text, " $&"); }
public static bool IsNullOrWhiteSpace(this String value) { #if NET35 return value == null || value.All(Char.IsWhiteSpace); #else return string.IsNullOrWhiteSpace(value); #endif }
/// <summary> /// Determines whether the input string is alpha numeric. /// </summary> /// <param name="input">The input.</param> /// <returns> /// <c>true</c> if the input string is alpha numeric; otherwise, <c>false</c>. /// </returns> public static bool IsAlphaNumeric(this string input) { if (input == null) throw new ArgumentNullException("input"); return input.All(char.IsLetterOrDigit); // return Regex.IsMatch(input, @"^[a-zA-Z0-9]*$"); }
/// <summary> /// Determines whether the string is all white space. Empty string will return false. /// </summary> /// <param name="input">The string to test whether it is all white space.</param> /// <returns> /// <c>true</c> if the string is all white space; otherwise, <c>false</c>. /// </returns> public static bool HasWhiteSpace(this string input) { if (string.IsNullOrEmpty(input)) { return false; } return input.All(char.IsWhiteSpace); }
public static string ToShortSha(this string sha) { if (sha == null) return null; return sha.Length > 7 && sha.All(c => '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F') ? sha.Substring(0, 7) : sha; }
public static Course GetCourseByID(this IRepository<Course> repo, int id) { // 0: operations on courses must use valid course IDs var course = repo.All().SingleOrDefault(c => c.ID == id); if (course == null) { throw new ArgumentException("No course with this ID exists"); } return course; }
public static string Unidecode(this string self) { if (string.IsNullOrEmpty(self)) return ""; if (self.All(x => x < 128)) return self; return String.Join("", self.Select(c => c.Unidecode()).ToArray()); }
/// <summary> /// Humanizes the input string; e.g. Underscored_input_String_is_turned_INTO_sentence -> 'Underscored input String is turned INTO sentence' /// </summary> /// <param name="input">The string to be humanized</param> /// <returns></returns> public static string Humanize(this string input) { // if input is all capitals (e.g. an acronym) then return it without change if (input.All(Char.IsUpper)) return input; if (input.Contains('_') || input.Contains('-')) return FromUnderscoreDashSeparatedWords(input); return FromPascalCase(input); }
public static ValidationResult CheckForUnallowedSymbols(this string[] tags) { const string allowedSymbols = "_"; if (tags == null || tags.All(tag => tag.All(symbol => char.IsLetterOrDigit(symbol) || allowedSymbols.Contains(symbol)))) { return ValidationResult.Success; } throw new ArgumentException("Tags contains unallowed symbols."); }
public static void RemoveAllExcept(this IList<ServerConfig> servers, string serverName) { if (servers.All(x => x.Name.ToLower() != serverName)) { throw new ConDepNoServersFoundException(string.Format("Server [{0}] where not one of the servers defined for environment.", serverName)); } var server = servers.Single(x => x.Name.ToLower() == serverName.ToLower()); servers.Clear(); servers.Add(server); }
public static bool ValidarPosicao(this string posicao) { if (posicao.Length == 2 && posicao.All(char.IsDigit)) { return true; } else { return false; } }
public static void DeleteChilds(this IRepository<Student> sc, int studentId) { Student student = sc.All().Where(x => x.StudentId == studentId).FirstOrDefault(); var marksRepository = new EfRepository<Mark>(new SchoolContext()); if (student != null) { foreach (Mark mark in student.Marks) { marksRepository.Delete(mark.MarkId); } } }
/// <summary> /// Adds routing testing services. /// </summary> /// <param name="serviceCollection">Instance of <see cref="IServiceCollection"/> type.</param> /// <returns>The same <see cref="IServiceCollection"/>.</returns> public static IServiceCollection AddRoutingTesting(this IServiceCollection serviceCollection) { CommonValidator.CheckForNullReference(serviceCollection, nameof(serviceCollection)); var modelBindingActionInvokerFactoryServiceType = typeof(IModelBindingActionInvokerFactory); if (serviceCollection.All(s => s.ServiceType != modelBindingActionInvokerFactoryServiceType)) { serviceCollection.TryAddEnumerable( ServiceDescriptor.Transient<IActionInvokerProvider, ModelBindingActionInvokerProvider>()); serviceCollection.TryAddSingleton(modelBindingActionInvokerFactoryServiceType, typeof(ModelBindingActionInvokerFactory)); } return serviceCollection; }
public static bool TryAddItem(this IEnumerable<DataRow> inputCollection, DataRow itemToAdd, out ICollection<DataRow> outputCollection) { bool result = false; outputCollection = null; if (inputCollection.All(item => !item.ContentEquals(itemToAdd))) { inputCollection = inputCollection.Concat(new[] { itemToAdd }); outputCollection = inputCollection.ToArray(); result = true; } return result; }
public static async Task<Node> WaitForLeader(this IEnumerable<Node> nodes, TestScheduler testScheduler = null) { while (nodes.All(n => n.State != State.Leader)) { if (testScheduler != null) { testScheduler.AdvanceBy(TestNode.MaxElectionTimeout.Ticks); } else { await Task.Delay(TestNode.MaxElectionTimeout); } } return nodes.Single(n => n.State == State.Leader); }
/// <summary> /// Checks if a string is either null, empty or contains one or more whitespace characters. /// </summary> /// <param name="value">The string to test.</param> /// <param name="name">The name of the string.</param> /// <exception cref="ArgumentNullException">If the string is null.</exception> /// <exception cref="ArgumentException">If the string is empty or contains one or more whitespace characters.</exception> public static void ThrowIfNullOrWhiteSpace(this string value, string name) { if (value == null) { throw new ArgumentNullException(name); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Argument must not be the empty string.", name); } if (value.All(char.IsWhiteSpace)) { throw new ArgumentException("Argument must not be only composed of whitespace characters.", name); } }
public async static void AddItem(this GroupInfoList<ExplorerItem> itemList, IStorageItem retrievedItem) { ExplorerItem item = new ExplorerItem { Name = retrievedItem.Name, Path = retrievedItem.Path }; if (retrievedItem is StorageFolder) { item.StorageFolder = retrievedItem as StorageFolder; item.Type = ExplorerItemType.Folder; } else if (retrievedItem is StorageFile) { item.StorageFile = retrievedItem as StorageFile; item.Type = ExplorerItemType.File; item.Size = (await item.StorageFile.GetBasicPropertiesAsync()).Size; item.ModifiedDateTime = (await item.StorageFile.GetBasicPropertiesAsync()).DateModified.DateTime; } if (itemList.All(p => p.Name != item.Name)) itemList.Add(item); }
public static bool HasNoUserCreatedModel3DObjects(this IEnumerable<Model3D> dictionary) { return dictionary.All(g => keyList.Contains(g.Name)); }
/// <summary> /// Determines whether a string of text contains only question marks and /// whitespace characters. This is useful in determining whether a conversion /// from unicode to ASCII failed completely, as often happens with languages /// like Arabic. /// </summary> /// <returns> /// <code>True</code> if this string of text contains only question marks and whitespace /// characters, otherwise <code>false</code>. /// </returns> internal static bool ContainsOnlyQuestionMarksAndWhiteSpace(this string text) { return text.All(character => character == '?' || character == ' ' || character == '\'' || character == '-' || character == '_' || character == '(' || character == ')' || character == ',' || character == '/' || character == '.' || character == '&' || character == '"'); }
/// <summary>验证是否是空白字符串</summary> /// <param name="str">要验证的字符</param> /// <returns>指示是否为空白字符串</returns> public static bool IsWhiteSpace_(this string str) { return str.All(c => c.IsWhiteSpace_()); }
/// <summary>验证是否是拉丁(0-255)字符串</summary> /// <param name="str">要验证的字符</param> /// <returns>指示是否为拉丁(0-255)字符串</returns> public static bool IsLatin_(this string str) { if(str.IsNullOrEmpty_()) return false; return str.All(c => c.IsLatin_()); }
/// <summary>验证是否是十六进制字符串</summary> /// <param name="str">要验证的字符</param> /// <returns>指示是否为十六进制字符串</returns> public static bool IsHex_(this string str) { return str.All(c => c.IsHex_()); }
/// <summary> /// Replcace russian characters by latin equivalent according to GOST(2002) transliteration table /// http://en.wikipedia.org/wiki/Romanization_of_Russian /// </summary> /// <param name="input">String to process</param> /// <returns></returns> public static string TransliterateRussianToLatin(this string input) { if (string.IsNullOrEmpty(input)) { return ""; } if (input.All(x => x < 0x80)) { return input; } var sb = new StringBuilder(input.Length * 2); foreach (char c in input) { if (c < 0x80) { sb.Append(c); } else { string latinEquivalent; if (RussianCharacters.TryGetValue(c, out latinEquivalent)) { sb.Append(latinEquivalent); } else { sb.Append(c); } } } return sb.ToString(); }
private static bool IsEmpty(this Dictionary<string, List<object>> dictionary) { return dictionary.All(pair => pair.Value.Count == 0); }
/// <summary> /// Gets true if all the levels are known /// </summary> /// <param name="src"></param> public static bool AreTrained(this IEnumerable<SkillLevel> src) { return src.All(x => x.IsKnown); }