public void Except() { var dict = new Dictionary<int, string>(); dict.Add(1, "one"); dict.Add(2, "two"); dict.Add(3, "three"); Assert.AreEqual("([1,one],[2,two])", dict.Except(3).Print()); Assert.AreEqual("([2,two])", dict.Except(1, 3).Print()); Assert.AreEqual("([1,one],[2,two],[3,three])", dict.Except(57).Print()); }
public string evaluate() { Console.WriteLine("Your best option(s) are: "); while (myenumfact.MoveNext()) { var res = result.Except(myenumfact.Current.GetIDList()); if (res.Count() == 0) { return(myenumfact.Current.GetDescription()); } } return("error"); }
/// <summary> /// Check word 1 and 2 contains same letters only /// </summary> /// <param name="str1"></param> /// <param name="str2"></param> /// <returns></returns> public static bool ValidAnagram(string str1, string str2) { if (str1.Length != str2.Length) { return(false); } Dictionary <string, int> dictionary1 = GetCharacterCount(str1); Dictionary <string, int> dictionary2 = GetCharacterCount(str2); dictionary1.Except(dictionary2); return(dictionary1.Count == dictionary2.Count && !dictionary1.Except(dictionary2).Any()); }
public void CollectionExcept() { List <int> list1 = new List <int> { 1, 2, 3, 4, 5 }; List <int> list2 = new List <int> { 4, 5, 6 }; IEnumerable <int> deltaList = list1.Except(list2).ToList(); foreach (int delta in deltaList) { TestContext.WriteLine(delta); } Dictionary <string, object> dict1 = new Dictionary <string, object> { { "a", 1 }, { "b", 2 } }; Dictionary <string, object> dict2 = new Dictionary <string, object> { { "b", 2 }, { "c", 3 } }; IEnumerable <KeyValuePair <string, object> > deltaDict = dict1.Except(dict2); foreach (KeyValuePair <string, object> delta in deltaDict) { TestContext.WriteLine($"{delta.Key} : {delta.Value}"); } }
public void CheckStateForStrucutredLogWithGeneralType() { var food = new Dictionary <string, object> { ["Name"] = "truffle", ["Price"] = 299.99, }; this.logger.LogInformation("{food}", food); var state = this.exportedItems[0].State as IReadOnlyList <KeyValuePair <string, object> >; // state only has food and {OriginalFormat} Assert.Equal(2, state.Count); // Check if state has food Assert.Contains(state, item => item.Key == "food"); var foodParameter = state.First(item => item.Key == "food").Value as Dictionary <string, object>; Assert.True(food.Count == foodParameter.Count && !food.Except(foodParameter).Any()); // Check if state has OriginalFormat Assert.Contains(state, item => item.Key == "{OriginalFormat}"); Assert.Equal("{food}", state.First(item => item.Key == "{OriginalFormat}").Value); Assert.Equal("[Name, truffle], [Price, 299.99]", state.ToString()); }
public static bool DictsAreEqual(Dictionary <State, int> dict1, Dictionary <State, int> dict2) { // Dicts are 'equal' if same length, and there is no set difference between the kv-pair sequences bool areEqual = (dict1.Count == dict2.Count) && (dict1.Except(dict2).Any() == false); return(areEqual); }
public bool IsAnagram_Dictionary(string s, string t) { Dictionary <char, int> sDict = new Dictionary <char, int>(); Dictionary <char, int> tDict = new Dictionary <char, int>(); foreach (var s1 in s) { if (sDict.ContainsKey(s1)) { sDict[s1]++; } else { sDict[s1] = 1; } } foreach (var t1 in t) { if (tDict.ContainsKey(t1)) { tDict[t1]++; } else { tDict[t1] = 1; } } return(!(sDict.Count != tDict.Count || sDict.Except(tDict).Any())); }
/// <summary> /// Creates a URI /// </summary> /// <param name="endpoint">The endpoint to request</param> /// <param name="parameters">The parameters to add</param> /// <returns></returns> public async Task <Uri> BuildUrl(Endpoint endpoint, Dictionary <string, string> parameters) { // Creates a list of parameters in the url path Dictionary <string, string> pathParameters = parameters .Where(x => Regex.IsMatch(endpoint.Path, $@":{x.Key}(?!\w)")) .ToDictionary(x => x.Key, x => x.Value); // Creates url string string url = _fqdn + pathParameters .Aggregate(endpoint.Path, (acc, next) => Regex.Replace(acc, $@":{next.Key}(?!\w)", next.Value)); // Returns url if not get request if (endpoint.Method != HttpMethod.Get) { return(new Uri(url)); } // Creates a list of remaining parameters Dictionary <string, string> remainingParams = parameters .Except(pathParameters) .ToDictionary(x => x.Key, x => x.Value); // Adds parameters to url and returns UriBuilder address = new UriBuilder(url); address.Query = await new FormUrlEncodedContent(remainingParams).ReadAsStringAsync().ConfigureAwait(false); return(new Uri(address.ToString())); }
public bool PegouColetaveisTodos() { /// Funçao que detecta se o player pegou todos os coletaveis da cena return(dicionarioColetaveis.Count == itensColetados.Count && !dicionarioColetaveis.Except(itensColetados).Any() && dicionarioColetaveis.Count > 0 && itensColetados.Count > 0); // compara os dicionarios de itens coletados e itens na cena }
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPaths) { string[] created = importedAssets.Except(QuickAssetWatcher.allAssets).ToArray(); string[] modified = importedAssets.Except(created).ToArray(); Dictionary <string, string> allMoved = new Dictionary <string, string>(); for (int i = 0; i < movedAssets.Length; i++) { allMoved.Add(movedAssets[i], movedFromPaths[i]); } // Renamed to, renamed from Dictionary <string, string> renamed = (from m in allMoved where (Path.GetDirectoryName(m.Key)) == (Path.GetDirectoryName(m.Value)) select m).ToDictionary(p => p.Key, p => p.Value); Dictionary <string, string> moved = allMoved.Except(renamed).ToDictionary(p => p.Key, p => p.Value); // Dispatch asset events to available watchers foreach (QuickAssetWatcher w in QuickAssetWatcher.allWatchers) { w.InvokeEventForPaths(created, w.OnAssetCreated); w.InvokeEventForPaths(deletedAssets, w.OnAssetDeleted); w.InvokeEventForPaths(modified, w.OnAssetModified); w.InvokeMovedEventForPaths(renamed, w.OnAssetRenamed); w.InvokeMovedEventForPaths(moved, w.OnAssetMoved); } // Update asset paths cache QuickAssetWatcher.allAssets = AssetDatabase.GetAllAssetPaths(); }
/// <summary> /// Finds all possible algorithms for this pattern /// </summary> /// <param name="p">Current rubik pattern</param> /// <param name="rotationLayer">Transformation rotation</param> /// <returns>Returns all possible solutions for this pattern</returns> public Dictionary <Pattern, Algorithm> FindMatches(Pattern p, CubeFlag rotationLayer, PatternFilter filter) { Dictionary <Pattern, Algorithm> transformedPatterns = Patterns.ToDictionary(kvp => kvp.Key.DeepClone(), a => a.Value); // clone Dictionary <Pattern, Algorithm> filteredPatterns = transformedPatterns.Where(kvp => filter.Filter(p, kvp.Key)).ToDictionary(pa => pa.Key, a => a.Value); // filter filteredPatterns = filteredPatterns.OrderByDescending(k => k.Key.Probability).ToDictionary(pa => pa.Key.DeepClone(), a => a.Value); // order by probability Dictionary <Pattern, Algorithm> matches = new Dictionary <Pattern, Algorithm>(); // 4 possible standard transformations for (int i = 0; i < 4; i++) { // Get matches foreach (KeyValuePair <Pattern, Algorithm> kvp in filteredPatterns.Where(pa => p.IncludesAllPatternElements(pa.Key))) { matches.Add(kvp.Key, kvp.Value); // Add to matches } if (rotationLayer == CubeFlag.None) { return(matches); } if (filter.OnlyAtBeginning) { transformedPatterns = filteredPatterns.Except(matches).ToDictionary(pa => pa.Key.Transform(rotationLayer), a => a.Value.Transform(rotationLayer)); filteredPatterns = transformedPatterns; } else { transformedPatterns = transformedPatterns.ToDictionary(pa => pa.Key.Transform(rotationLayer), a => a.Value.Transform(rotationLayer)); filteredPatterns = transformedPatterns.Where(kvp => filter.Filter(p, kvp.Key)).ToDictionary(pa => pa.Key, a => a.Value); } } return(matches); }
internal static TechLevel RuleA() { var notResearched = researchProjectStoreTotal.Except(researchProjectStoreFinished); int min = notResearched.Where(x => x.Value > 0).Select(x => (int)x.Key).DefaultIfEmpty(0).Min(); return((TechLevel)Util.Clamp(0, min - 1 + TechAdvancing_Config_Tab.Conditionvalue_A, (int)TechLevel.Archotech)); }
private static Dictionary <Fact, float> getNewlyDiscoveredAvsMap(Dictionary <Fact, float> knownAvMap, List <MMTTerm> variables, Vector <double> glsSolution) { Dictionary <Fact, float> discoveredAvsMap = new Dictionary <Fact, float>(); //Find KeyValuePairs<Fact,float> ... if (glsSolution.Count.Equals(variables.Count)) { foreach (Fact fact in GameState.Facts) { if (fact.GetType().Equals(typeof(CogwheelFact))) { MMTTerm knownAvVariable = variables.Find(variable => variable.isSimplifiedCogwheelAvTerm() && ((OMF)((RECARG)((OMA)((OMA)variable).arguments.ElementAt(0)).arguments.ElementAt(0)).value).f.Equals(((CogwheelFact)fact).Radius) && ((OMF)((OMA)((RECARG)((OMA)((OMA)variable).arguments.ElementAt(0)).arguments.ElementAt(3)).value).arguments.ElementAt(0)).f.Equals(((CogwheelFact)fact).Point.x) && ((OMF)((OMA)((RECARG)((OMA)((OMA)variable).arguments.ElementAt(0)).arguments.ElementAt(3)).value).arguments.ElementAt(1)).f.Equals(((CogwheelFact)fact).Point.y) && ((OMF)((OMA)((RECARG)((OMA)((OMA)variable).arguments.ElementAt(0)).arguments.ElementAt(3)).value).arguments.ElementAt(2)).f.Equals(((CogwheelFact)fact).Point.z)); //If an element was found if (knownAvVariable != null) { double newlyDiscoveredAv = glsSolution.ElementAt(variables.IndexOf(knownAvVariable)); //Now we know that the Fact = fact should rotate with angularVelocity = newlyDiscoveredAv discoveredAvsMap.Add(fact, (float)newlyDiscoveredAv); } } } } else { Debug.Log("KnowledgeBasedSimulation.getNewlyDiscoveredAvsMap: Variables and GLS-Solution don't have the same number of elements."); return(null); } //Build relative complement A \ B => discoveredAvsMap \ knownAvMap return(discoveredAvsMap.Except(knownAvMap).ToDictionary(x => x.Key, x => x.Value)); }
public static bool HaveSameKeys(Dictionary <string, object> source, Dictionary <string, object> destination, TBSeed.HaveSameKeys checkKeyOption = TBSeed.HaveSameKeys.Equal) { bool ret = true; IEnumerable <KeyValuePair <string, object> > v = source.Except(destination); if (checkKeyOption == TBSeed.HaveSameKeys.Equal || checkKeyOption == TBSeed.HaveSameKeys.DestCanBeMore) { source.ToList().ForEach(x => { if (!destination.ContainsKey(x.Key)) { ret = false; return; } }); } if (checkKeyOption == TBSeed.HaveSameKeys.Equal || checkKeyOption == TBSeed.HaveSameKeys.SourceCanBeMore) { if (ret) { destination.ToList().ForEach(x => { if (!source.ContainsKey(x.Key)) { ret = false; return; } }); } } return(ret); }
public IEnumerable <FileSnapshot> GetDeletedSnapshots(string[] filters = null) { return(_previousSnapshot .Except(_currentSnapshot, _comparer) .Where(x => MatchPattern(x.Key, filters)) .Select(x => x.Value)); }
public void ServerUrlWithTrailingSlash() { ws = new SonarWebService(downloader, "http://localhost:9000/", "cs", "fxcop"); downloader.Pages["http://localhost:9000/api/profiles/list?language=cs&project=foo%20bar"] = "[{\"name\":\"profile1\",\"language\":\"cs\",\"default\":true}]"; Assert.AreEqual("profile1", ws.GetQualityProfile("foo bar")); downloader.Pages["http://localhost:9000/api/profiles/index?language=cs&name=Sonar%20way"] = "[{\"name\":\"Sonar way\",\"language\":\"cs\",\"default\":true}]"; var expected1 = new List <string>(); var actual1 = new List <string>(ws.GetActiveRuleKeys("Sonar way")); Assert.AreEqual(true, expected1.SequenceEqual(actual1)); downloader.Pages["http://localhost:9000/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}"; var expected2 = new Dictionary <string, string>(); expected2["fxcop:My_Own_FxCop_Rule"] = null; expected2["fxcop:UriParametersShouldNotBeStrings"] = "CA1054"; var actual2 = ws.GetInternalKeys(); Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any()); downloader.Pages["http://localhost:9000/api/properties?resource=foo%20bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]"; var expected3 = new Dictionary <string, string>(); expected3["sonar.property1"] = "value1"; expected3["sonar.property2"] = "value2"; expected3["sonar.cs.msbuild.testProjectPattern"] = ".*test.*"; var actual3 = ws.GetProperties("foo bar"); Assert.AreEqual(true, expected3.Count == actual3.Count && !expected3.Except(actual3).Any()); }
private static Dictionary <string, List <string> > CrossMatch(Dictionary <string, List <string> > potentialIngredients) { var SinglePotential = potentialIngredients.Where(x => x.Value.Count() == 1).ToList(); if (SinglePotential.Count() == potentialIngredients.Count()) { return(potentialIngredients); } else if (SinglePotential.Count() == 0) { throw new Exception("well thats not good"); } foreach (var DeterminedPotential in SinglePotential) { potentialIngredients = potentialIngredients.Except(SinglePotential) .Select(x => { var NewList = x.Value.Where(y => y != DeterminedPotential.Value.First()) .ToList(); return(new { x.Key, NewList }); }) .ToDictionary(x => x.Key, x => x.NewList); } return(CrossMatch(potentialIngredients.Union(SinglePotential).ToDictionary(x => x.Key, x => x.Value))); }
public bool Equals(JsonObject other) { if (ReferenceEquals(null, other)) { return(false); } switch (Type) { case JsonObjectType.Null: case JsonObjectType.Boolean: return(other.Type == Type); case JsonObjectType.Number: return(other.Type == Type && Math.Abs(other.Double - Double) < double.Epsilon); case JsonObjectType.String: return(other.Type == Type && String == other.String); case JsonObjectType.Object: return(other.Type == Type && Object.Count == other.Object.Count && !Object.Except(other.Object).Any()); case JsonObjectType.Array: return(other.Type == Type && Array.SequenceEqual(other.Array)); default: throw new ArgumentOutOfRangeException(); } }
private static bool HashedUpdate() { DestroyDownloadDirectory(); Directory.CreateDirectory(ExecutableDirectory + @"\tmp\release\"); var fileList = _latest.Except(_hashes).ToList(); if (!fileList.Any()) { return(false); } File.WriteAllLines(ExecutableDirectory + @"\tmp\ShinraMeterV.sha1", _latest.Select(x => x.Value + " *" + x.Key)); fileList.Where(x => x.Key.Contains('\\')).Select(x => Path.GetDirectoryName(ExecutableDirectory + @"\tmp\release\" + x.Key)).Distinct().ToList().ForEach(x => Directory.CreateDirectory(x)); bool badhash = false; fileList.ForEach(x => badhash = badhash || GetDiff(x)); if (badhash) { MessageBox.Show("Invalid checksum, abording upgrade"); return(false); } if (File.Exists(ExecutableDirectory + @"\tmp\release\Autoupdate.exe")) { File.Copy(ExecutableDirectory + @"\tmp\release\Autoupdate.exe", ExecutableDirectory + @"\tmp\Autoupdate.exe"); } else { File.Copy(ExecutableDirectory + @"\Autoupdate.exe", ExecutableDirectory + @"\tmp\Autoupdate.exe"); } Process.Start(ExecutableDirectory + @"\tmp\Autoupdate.exe", "pass"); return(true); }
public void GetProperties() { // This test includes a regression scenario for SONARMSBRU-187: // Requesting properties for project:branch should return branch-specific data // Check that properties are correctly defaulted as well as branch-specific downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"},{\"key\": \"sonar.cs.msbuild.testProjectPattern\",\"value\": \"pattern\"}]"; downloader.Pages["http://myhost:222/api/properties?resource=foo+bar%3AaBranch"] = "[{\"key\": \"sonar.property1\",\"value\": \"anotherValue1\"},{\"key\": \"sonar.property2\",\"value\": \"anotherValue2\"}]"; // default var expected1 = new Dictionary <string, string>(); expected1["sonar.property1"] = "value1"; expected1["sonar.property2"] = "value2"; expected1["sonar.msbuild.testProjectPattern"] = "pattern"; var actual1 = ws.GetProperties("foo bar"); Assert.AreEqual(true, expected1.Count == actual1.Count && !expected1.Except(actual1).Any()); // branch specific var expected2 = new Dictionary <string, string>(); expected2["sonar.property1"] = "anotherValue1"; expected2["sonar.property2"] = "anotherValue2"; var actual2 = ws.GetProperties("foo bar", "aBranch"); Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any()); }
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPaths) { string[] created = importedAssets.Except (Watcher.allAssets).ToArray (); string[] modified = importedAssets.Except (created).ToArray (); Dictionary<string, string> allMoved = new Dictionary<string, string> (); for (int i = 0; i < movedAssets.Length; i++) { allMoved.Add (movedAssets [i], movedFromPaths [i]); } // Renamed to, renamed from Dictionary<string, string> renamed = (from m in allMoved where (Path.GetDirectoryName (m.Key)) == (Path.GetDirectoryName (m.Value)) select m).ToDictionary (p => p.Key, p => p.Value); Dictionary<string, string> moved = allMoved.Except (renamed).ToDictionary (p => p.Key, p => p.Value); // Dispatch asset events to available watchers foreach (Watcher w in Watcher.allWatchers) { w.InvokeEventForPaths (created, w.onAssetCreated); w.InvokeEventForPaths (deletedAssets, w.onAssetDeleted); w.InvokeEventForPaths (modified, w.onAssetModified); w.InvokeMovedEventForPaths (renamed, w.onAssetRenamed); w.InvokeMovedEventForPaths (moved, w.onAssetMoved); } // Update asset paths cache Watcher.allAssets = AssetDatabase.GetAllAssetPaths (); }
public void TestMethod2() { var dictionary = new Dictionary<string, int>(); WordCounter text = new WordCounter(string.Empty); text.Count(); Assert.IsTrue(!dictionary.Except(text.GetDictionary()).Any(), "Error"); }
public bool Equals( Dictionary<TKey , TValue> x , Dictionary<TKey , TValue> y ) { bool unequal = x.Count != y.Count || x.Except( y ).Any() // this is probably redundant || y.Except( x ).Any() // but my caffiene titration is off this AM ; return !unequal ; }
public bool IsEqual(PsConfiguration configuration) { bool rolesEqual = Roles.SetEquals(configuration.Roles); bool variablesEqual = (Variables.Count == configuration.Variables.Count && !Variables.Except(configuration.Variables).Any()); return(rolesEqual && variablesEqual); }
public void ExceptNoEqualityComparer_SameKeyInSecondDict_RemovesDuplicateKeyValuePair() { var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 } }; var second = new SortedList<int, int> { { 3, 2 }, { 4, 7 } }; var expected = 1; var actual = first.Except(second).Count; Assert.AreEqual(expected, actual); }
public override bool Equals(object obj) { if (obj is Object ob) { return(dict.Count == ob.dict.Count && !dict.Except(ob.dict).Any()); } return(false); }
/// <summary> /// Return true if the given dictionaries, <paramref name="dic1" /> and /// <paramref /// name="dic2" /> /// , have identical key-pair entries. /// </summary> /// <typeparam name="T1">The type of the key in the dictionary.</typeparam> /// <typeparam name="T2">The type of the value in the dictionary.</typeparam> /// <param name="dic1">The first dictionary to compare.</param> /// <param name="dic2">The second dictionary to compare.</param> /// <returns>true iff the items in both dictionaries are identical.</returns> public static bool DictionaryEquals <T1, T2>(this Dictionary <T1, T2> dic1, Dictionary <T1, T2> dic2) { // Return true if either (1) both dictionaries point to the same object, OR return(dic1 == dic2 || // (2) the dictionaries have the same number of elements, and the difference of // dic1 - dic2 is empty. dic1.Count == dic2.Count && !dic1.Except(dic2).Any()); }
public void ExceptDefaultEqualityComparer_SameKeyDifferentValues_KeepsKeyValuePairWithMatchingKey() { var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 } }; var second = new SortedList<int, int> { { 3, 2 }, { 4, 7 } }; var expected = 2; var actual = first.Except(second, EqualityComparer<KeyValuePair<int, int>>.Default).Count; Assert.AreEqual(expected, actual); }
public bool Craftable(Dictionary <int, int> ingredientsAvailable) { if (!ingredientsAvailable.CollectionIsNotNullOrEmpty() || !ingredients.ValidList()) { return(false); } return(!ingredientsAvailable.Except(IngredientMap).Any()); }
public static bool same <TKey, TValue>( Dictionary <TKey, TValue> first, Dictionary <TKey, TValue> second) { List <KeyValuePair <TKey, TValue> > firstNotSecond = first.Except(second).ToList(); List <KeyValuePair <TKey, TValue> > secondNotFirst = second.Except(first).ToList(); return(!firstNotSecond.Any() && !secondNotFirst.Any()); }
public override bool Equals(object obj) { //((DataTranslator)obj).attributeInfo if (attributeInfo.Count == ((DataTranslator)obj).attributeInfo.Count && !attributeInfo.Except(((DataTranslator)obj).attributeInfo).Any()) { return(true); } return(false); }
private bool DictionaryEquals <TKey, TValue>(Dictionary <TKey, TValue> dic1, Dictionary <TKey, TValue> dic2) where TKey : notnull { if (dic1 == dic2) { throw new ArgumentException("Compared dictionaries cannot be the same reference."); } return(dic1.Count == dic2.Count && !dic1.Except(dic2).Any()); }
public void TestDictionarySerialize() { var dic1 = new Dictionary <string, int> { ["hi mom"] = 2 }; var json = JsonConvert.SerializeObject(dic1); var dic2 = JsonConvert.DeserializeObject <Dictionary <string, int> >(json); Assert.IsTrue(dic1.Count == dic2.Count && !dic1.Except(dic2).Any()); }
private void RemoveCoins(List <Coin> coinsToKeep) { var keyValuesToKeep = coinsToKeep.Select(a => new KeyValuePair <int, PictureBox>(a.Id, coins[a.Id])); var removedCoins = coins.Except(keyValuesToKeep).ToList(); removedCoins.ForEach(keyValue => { coins.Remove(keyValue.Key); form.Invoke((MethodInvoker)(() => form.Controls.Remove(keyValue.Value))); }); }
public void GetInternalKeys() { downloader.Pages["http://myhost:222/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}"; var expected = new Dictionary <string, string>(); expected["fxcop:UriParametersShouldNotBeStrings"] = "CA1054"; var actual = ws.GetInternalKeys("fxcop"); Assert.AreEqual(true, expected.Count == actual.Count && !expected.Except(actual).Any()); }
public Dictionary<string, SqlColumnType> GetFieldTypes(string tablename, Dictionary<string, object> example) { if (!TableExists(tablename)) return null; var types = _items.First(i => i.Name == tablename).Types; var extras = example.Except(types.Keys).SelectVals(v => SqlTypeConversion.GetSqlType(v)); var res = extras.Union(types); return res; }
public void TestMethod3() { var dictionary = new Dictionary<string, int> { { "123", 2 }, { "21312", 1 }, { "2452", 1 } }; WordCounter text = new WordCounter("21312 2452 123 123!!$$%#$^&$%"); text.Count(); Assert.IsTrue(!dictionary.Except(text.GetDictionary()).Any(), "Error"); }
public static void CreateTable(this IDBModifier meta, string tablename, Dictionary<string, object> instance) { var taxonomyTypes = meta.Taxonomy == null ? new Dictionary<string, SqlColumnType>() : meta.Taxonomy.GetFieldTypes(tablename, instance); taxonomyTypes = taxonomyTypes ?? new Dictionary<string, SqlColumnType>(); var missingTypes = instance.Except(taxonomyTypes.Keys) .SelectVals(v => SqlTypeConversion.GetSqlType(v)); var fieldTypes = missingTypes.Union(taxonomyTypes); meta.CreateTable(tablename, fieldTypes); }
public override string _getCreateTableSql(string schema, string table, Dictionary<string, SqlColumnType> fieldTypes) { // Strip off the primary key if it was supplied in fields - we'll make it ourselves var datafields = fieldTypes.Except(table + "Id"); var fieldList = _fieldDefinitions(datafields); var sql = String.Format(@"CREATE TABLE `{1}` ( {1}Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, {2} )", schema, table, fieldList); return sql; }
public void TestMethod1() { var dictionary = new Dictionary<string, int> { { "is", 2 }, { "this", 2 }, { "a", 1 }, { "and", 1 }, { "so", 1 }, { "statement", 1 } }; WordCounter text = new WordCounter("This is a statement, and so is this."); text.Count(); Assert.IsTrue(!dictionary.Except(text.GetDictionary()).Any(), "Error"); }
private void SplitByRack(Dictionary<int, int> smpPlasmaSlices) { int totalSliceCnt = smpPlasmaSlices.Count; while (smpPlasmaSlices.Any()) { int remaining = smpPlasmaSlices.Count; int splitted = totalSliceCnt - remaining; var tmpPlasmaSlices = smpPlasmaSlices.Take(Math.Min(remaining, 16)).ToDictionary(x => x.Key, x => x.Value); allRackSmpPlasmaSlices.Add(tmpPlasmaSlices); var tmpPackageInfos = CreatePackInfo(tmpPlasmaSlices); allPackageExpectedInfos.Add(new Dictionary<Point, string>(tmpPackageInfos)); allPackageScannedInfos.Add(new Dictionary<Point, string>()); smpPlasmaSlices = smpPlasmaSlices.Except(tmpPlasmaSlices).ToDictionary(x => x.Key, x => x.Value); } ChangeRackIndex(0); }
public void GetProperties() { // This test includes a regression scenario for SONARMSBRU-187: // Requesting properties for project:branch should return branch-specific data // Check that properties are correctly defaulted as well as branch-specific downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]"; downloader.Pages["http://myhost:222/api/properties?resource=foo+bar%3AaBranch"] = "[{\"key\": \"sonar.property1\",\"value\": \"anotherValue1\"},{\"key\": \"sonar.property2\",\"value\": \"anotherValue2\"}]"; // default var expected1 = new Dictionary<string, string>(); expected1["sonar.property1"] = "value1"; expected1["sonar.property2"] = "value2"; expected1["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern; var actual1 = ws.GetProperties("foo bar"); Assert.AreEqual(true, expected1.Count == actual1.Count && !expected1.Except(actual1).Any()); // branch specific var expected2 = new Dictionary<string, string>(); expected2["sonar.property1"] = "anotherValue1"; expected2["sonar.property2"] = "anotherValue2"; expected2["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern; var actual2 = ws.GetProperties("foo bar", "aBranch"); Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any()); }
public void ServerUrlWithTrailingSlash() { ws = new SonarWebService(downloader, "http://myhost:222/", new TestLogger()); // Check that profiles are correctly defaulted as well as branch-specific // This test includes a regression scenario for SONARMSBRU-187: // Requesting properties for project:branch should return branch-specific data downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar"] = "[{\"name\":\"profile1\",\"language\":\"cs\",\"default\":true}]"; downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar%3AaBranch"] = "[{\"name\":\"profile2\",\"language\":\"cs\",\"default\":false}]"; downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar%3AanotherBranch"] = "[{\"name\":\"profile3\",\"language\":\"cs\",\"default\":false}]"; string qualityProfile1; string qualityProfile2; string qualityProfile3; bool result1 = ws.TryGetQualityProfile("foo bar", null, "cs", out qualityProfile1); bool result2 = ws.TryGetQualityProfile("foo bar", "aBranch", "cs", out qualityProfile2); bool result3 = ws.TryGetQualityProfile("foo bar", "anotherBranch", "cs", out qualityProfile3); Assert.IsTrue(result1); Assert.IsTrue(result2); Assert.IsTrue(result3); Assert.AreEqual("profile1", qualityProfile1); Assert.AreEqual("profile2", qualityProfile2); Assert.AreEqual("profile3", qualityProfile3); Assert.IsTrue(result1); Assert.IsTrue(result2); Assert.IsTrue(result3); Assert.AreEqual("profile1", qualityProfile1); Assert.AreEqual("profile2", qualityProfile2); Assert.AreEqual("profile3", qualityProfile3); downloader.Pages["http://myhost:222/api/profiles/index?language=cs&name=Sonar+way"] = "[{\"name\":\"Sonar way\",\"language\":\"cs\",\"default\":true}]"; var expected1 = new List<string>(); var actual1 = new List<string>(ws.GetActiveRuleKeys("Sonar way", "cs", "foo")); Assert.AreEqual(true, expected1.SequenceEqual(actual1)); downloader.Pages["http://myhost:222/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}"; var expected2 = new Dictionary<string, string>(); expected2["fxcop:UriParametersShouldNotBeStrings"] = "CA1054"; var actual2 = ws.GetInternalKeys("fxcop"); Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any()); downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]"; downloader.Pages["http://myhost:222/api/properties?resource=foo+bar%3AaBranch"] = "[{\"key\": \"sonar.property1\",\"value\": \"anotherValue1\"},{\"key\": \"sonar.property2\",\"value\": \"anotherValue2\"}]"; var expected3_1 = new Dictionary<string, string>(); expected3_1["sonar.property1"] = "value1"; expected3_1["sonar.property2"] = "value2"; expected3_1["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern; var actual3_1 = ws.GetProperties("foo bar"); var expected3_2 = new Dictionary<string, string>(); expected3_2["sonar.property1"] = "anotherValue1"; expected3_2["sonar.property2"] = "anotherValue2"; expected3_2["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern; var actual3_2 = ws.GetProperties("foo bar", "aBranch"); Assert.AreEqual(true, expected3_1.Count == actual3_1.Count && !expected3_1.Except(actual3_1).Any()); Assert.AreEqual(true, expected3_2.Count == actual3_2.Count && !expected3_2.Except(actual3_2).Any()); downloader.Pages["http://myhost:222/api/updatecenter/installed_plugins"] = "[{\"key\":\"visualstudio\",\"name\":\"...\",\"version\":\"1.2\"},{\"key\":\"csharp\",\"name\":\"C#\",\"version\":\"4.0\"}]"; var expected4 = new List<string>(); expected4.Add("visualstudio"); expected4.Add("csharp"); var actual4 = new List<string>(ws.GetInstalledPlugins()); Assert.AreEqual(true, expected4.SequenceEqual(actual4)); }
public void ServerUrlWithTrailingSlash() { ws = new SonarWebService(downloader, "http://myhost:222/", new TestLogger()); downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar"] = "[{\"name\":\"profile1\",\"language\":\"cs\",\"default\":true}]"; string qualityProfile; bool result = ws.TryGetQualityProfile("foo bar", "cs", out qualityProfile); Assert.IsTrue(result); Assert.AreEqual("profile1", qualityProfile); downloader.Pages["http://myhost:222/api/profiles/index?language=cs&name=Sonar+way"] = "[{\"name\":\"Sonar way\",\"language\":\"cs\",\"default\":true}]"; var expected1 = new List<string>(); var actual1 = new List<string>(ws.GetActiveRuleKeys("Sonar way", "cs", "foo")); Assert.AreEqual(true, expected1.SequenceEqual(actual1)); downloader.Pages["http://myhost:222/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}"; var expected2 = new Dictionary<string, string>(); expected2["fxcop:UriParametersShouldNotBeStrings"] = "CA1054"; var actual2 = ws.GetInternalKeys("fxcop"); Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any()); downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]"; var expected3 = new Dictionary<string, string>(); expected3["sonar.property1"] = "value1"; expected3["sonar.property2"] = "value2"; expected3["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern; var actual3 = ws.GetProperties("foo bar"); Assert.AreEqual(true, expected3.Count == actual3.Count && !expected3.Except(actual3).Any()); downloader.Pages["http://myhost:222/api/updatecenter/installed_plugins"] = "[{\"key\":\"visualstudio\",\"name\":\"...\",\"version\":\"1.2\"},{\"key\":\"csharp\",\"name\":\"C#\",\"version\":\"4.0\"}]"; var expected4 = new List<string>(); expected4.Add("visualstudio"); expected4.Add("csharp"); var actual4 = new List<string>(ws.GetInstalledPlugins()); Assert.AreEqual(true, expected4.SequenceEqual(actual4)); }
private void LinkRooms(ICollection<ConnectionPoint> _connectionPoints) { var connectors = new Dictionary<Point, Connector>(); var rooms = m_mazeBlocks.Values.SelectMany(_mapBlock => _mapBlock.Rooms).ToArray(); if (rooms.Length == 0) return; var forbid = new Dictionary<Point, EDirections>(); { foreach (var room in rooms) { foreach (var pair in room.WorldRoomRectangle.ForbidBorders) { EDirections dir; if (!forbid.TryGetValue(pair.Key, out dir)) { dir = EDirections.DOWN | EDirections.UP | EDirections.LEFT | EDirections.RIGHT; } dir &= pair.Value; forbid[pair.Key] = dir; } } } Action<IEnumerable<ConnectionPoint>> actRemove = delegate(IEnumerable<ConnectionPoint> _points) { foreach (var connectionPoint in _points) { _connectionPoints.Remove(connectionPoint); } }; if (true) { #region конечные точки совпадают var sameEndPoints = _connectionPoints.GroupBy(_point => _point.End).Where(_points => _points.Count() > 1).ToArray(); foreach (var grouping in sameEndPoints) { var points = grouping.ToArray(); if (points.Length > 2) { throw new NotImplementedException("Как может сойтись в одной точке более двух комнат????"); } ConnectTwoRooms(points[0].Room, points[1].Room, forbid, connectors, points[0].Begin, points[0].End, points[1].Begin); foreach (var point in grouping) { _connectionPoints.Remove(point); } } #endregion } if (true) { #region концевая точка касается другой комнаты { var toRemove = new List<ConnectionPoint>(); foreach (var cp in _connectionPoints) { if (toRemove.Contains(cp)) continue; var oppositeDelta = cp.Dir.Opposite().GetDelta(); foreach (var room in rooms) { if (room == cp.Room) continue; var rrect = room.WorldRoomRectangle; var frect = rrect.Inflate(1, 1); var end = cp.End; if (frect.Contains(end)) { while (rrect.Contains(end)) { end += oppositeDelta; } if (!frect.AllPointsExceptCorners().Contains(end)) { end += cp.Dir.GetDelta(); } { ConnectTwoRooms(room, cp.Room, forbid, connectors, end, cp.Begin); toRemove.Add(cp); var revert = _connectionPoints.Where(_point => _point.Dir == cp.Dir.Opposite() && _point.Room == room).ToArray(); toRemove.AddRange(revert); } //else { //концевая точка примыкает к углу комнаты //toRemove.Add(connectionPoint); } } } } actRemove(toRemove); } #endregion } if (true) { #region Конечные точки в одном столбце { var toRemove = new List<ConnectionPoint>(); var sameCol = _connectionPoints.GroupBy(_point => _point.End.X).Where(_points => _points.Count() > 1).ToArray(); foreach (var grouping in sameCol) { var points = grouping.OrderBy(_point => _point.End.Y).ToArray(); for (var i = 0; i < points.Length - 1; ++i) { if ((points[i].End - points[i + 1].End).QLenght > MAX_PATH_LEN) continue; if (!points[i].End.GetLineToPoints(points[i + 1].End).Any(forbid.ContainsKey)) { ConnectTwoRooms(points[i].Room, points[i + 1].Room, forbid, connectors, points[i].Begin, points[i].End, points[i + 1].End, points[i + 1].Begin); toRemove.Add(points[i]); toRemove.Add(points[i + 1]); } } } actRemove(toRemove.Distinct()); } #endregion } if (true) { #region Конечные точки на одной строке { var toRemove = new List<ConnectionPoint>(); var sameRow = _connectionPoints.GroupBy(_point => _point.End.Y).Where(_points => _points.Count() > 1).ToArray(); foreach (var grouping in sameRow) { var points = grouping.OrderBy(_point => _point.End.X).ToArray(); for (var i = 0; i < points.Length - 1; ++i) { if ((points[i].End - points[i + 1].End).QLenght > MAX_PATH_LEN) continue; if (!points[i].End.GetLineToPoints(points[i + 1].End).Any(forbid.ContainsKey)) { ConnectTwoRooms(points[i].Room, points[i + 1].Room, forbid, connectors, points[i].Begin, points[i].End, points[i + 1].End, points[i + 1].Begin); toRemove.Add(points[i]); toRemove.Add(points[i + 1]); } } } actRemove(toRemove.Distinct()); } #endregion } if (true) { #region можно проложить путь между двумя концами не затрагивая forbid var toRemove = new List<ConnectionPoint>(); foreach (var cp in _connectionPoints) { if (toRemove.Contains(cp) || forbid.ContainsKey(cp.End)) continue; var candidates = _connectionPoints.Where(_point => _point.Room != cp.Room && cp.Dir <= _point.Dir && !_point.Room.ConnectedTo.Contains(cp.Room) && !forbid.ContainsKey(_point.End) && (_point.End - cp.End).QLenght < MAX_PATH_LEN).ToArray(); foreach (var candidate in candidates) { if (toRemove.Contains(cp) || toRemove.Contains(candidate)) continue; var points = new[] {cp, candidate}; //.OrderBy(_point => _point.Dir).ToArray(); var minx = cp.End.X < candidate.End.X ? cp : candidate; var miny = cp.End.Y < candidate.End.Y ? cp : candidate; var maxx = cp.End.X > candidate.End.X ? cp : candidate; var maxy = cp.End.Y > candidate.End.Y ? cp : candidate; var dx = maxx.End.X - minx.End.X; var dy = maxy.End.Y - miny.End.Y; var way1 = new List<Point>(); var way2 = new List<Point>(); for (var i = 0; i < 20; ++i) { way1.Clear(); way2.Clear(); switch (points[0].Dir) { case EDirections.UP: switch (points[1].Dir) { case EDirections.UP: if (dx >= dy) { way1.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X, miny.End.Y - i), new Point(maxx.End.X, miny.End.Y - i), maxx.End, maxx.Begin }); } else { way1.AddRange(new[] { miny.Begin, miny.End, new Point(miny.End.X - i, miny.End.Y), new Point(miny.End.X - i, maxy.End.Y), maxx.End, maxx.Begin }); way2.AddRange(new[] { minx.Begin, minx.End, new Point(miny.End.X + i, miny.End.Y), new Point(miny.End.X + i, maxy.End.Y), maxx.End, maxx.Begin }); } break; case EDirections.DOWN: if (maxx.End.X - minx.End.X < 2) continue; way1.AddRange(new[] { miny.Begin, miny.End, new Point(miny.End.X + i, miny.End.Y), new Point(miny.End.X + i, maxy.End.Y), maxy.End, maxy.Begin }); way2.AddRange(new[] { miny.Begin, miny.End, new Point(miny.End.X - i, miny.End.Y), new Point(miny.End.X - i, maxy.End.Y), maxy.End, maxy.Begin }); break; case EDirections.LEFT: way1.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X - i, minx.End.Y), new Point(minx.End.X - i, maxx.End.Y), maxx.End, maxx.Begin }); way2.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X, minx.End.Y - i), new Point(minx.End.X, maxx.End.Y - i), maxx.End, maxx.Begin }); break; case EDirections.RIGHT: way1.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X + i, minx.End.Y), new Point(minx.End.X + i, maxx.End.Y), maxx.End, maxx.Begin }); way2.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X, minx.End.Y + i), new Point(minx.End.X, maxx.End.Y + i), maxx.End, maxx.Begin }); break; default: throw new ArgumentOutOfRangeException(); } break; case EDirections.DOWN: switch (points[1].Dir) { case EDirections.DOWN: if (dx >= dy) { way1.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X, miny.End.Y + i), new Point(maxx.End.X, miny.End.Y + i), maxx.End, maxx.Begin }); } else { way1.AddRange(new[] { miny.Begin, miny.End, new Point(miny.End.X - i, miny.End.Y), new Point(miny.End.X - i, maxy.End.Y), maxx.End, maxx.Begin }); way2.AddRange(new[] { minx.Begin, minx.End, new Point(miny.End.X + i, miny.End.Y), new Point(miny.End.X + i, maxy.End.Y), maxx.End, maxx.Begin }); } break; case EDirections.LEFT: way1.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X, minx.End.Y + i), new Point(maxx.End.X, minx.End.Y + i), maxx.End, maxx.Begin }); way2.AddRange(new[] { minx.Begin, minx.End, new Point(maxx.End.X - i, minx.End.Y), new Point(maxx.End.X - i, maxx.End.Y), maxx.End, maxx.Begin }); break; case EDirections.RIGHT: way1.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X + i, minx.End.Y), new Point(minx.End.X + i, maxx.End.Y), maxx.End, maxx.Begin }); way2.AddRange(new[] { minx.Begin, minx.End, new Point(minx.End.X, minx.End.Y + i), new Point(minx.End.X, maxx.End.Y + i), maxx.End, maxx.Begin }); break; default: throw new ArgumentOutOfRangeException(); } break; case EDirections.LEFT: switch (points[1].Dir) { case EDirections.LEFT: if (maxy.End.Y - miny.End.Y < 2) continue; way1.AddRange(new[] { miny.Begin, miny.End, new Point(miny.End.X - i, miny.End.Y), new Point(miny.End.X - i, maxy.End.Y), maxy.End, maxy.Begin }); break; case EDirections.RIGHT: if (i > 0) continue; way1.AddRange(new[] { miny.Begin, miny.End, new Point(maxy.End.X, miny.End.Y), maxy.End, maxy.Begin }); way2.AddRange(new[] { miny.Begin, miny.End, new Point(miny.End.X, maxy.End.Y), maxy.End, maxy.Begin }); break; default: throw new ArgumentOutOfRangeException(); } break; case EDirections.RIGHT: switch (points[1].Dir) { case EDirections.RIGHT: if (maxy.End.Y - miny.End.Y < 2) continue; way1.AddRange(new[] { miny.Begin, miny.End, new Point(maxx.End.X + i, miny.End.Y), new Point(maxx.End.X + i, maxy.End.Y), maxy.End, maxy.Begin }); break; default: throw new ArgumentOutOfRangeException(); } break; default: throw new ArgumentOutOfRangeException(); } var flag = false; foreach (var way in new[] {way1, way2}) { flag = true; if (way.Count == 0) continue; var pnt = way[1]; for (var index = 2; index < way.Count - 1 && flag; ++index) { flag = !pnt.GetLineToPoints(way[index]).Any(forbid.ContainsKey); pnt = way[index]; } if (!flag) continue; if (way[0] != cp.Begin) way.Reverse(); ConnectTwoRooms(cp.Room, candidate.Room, forbid, connectors, way1.ToArray()); toRemove.Add(candidate); break; } if (flag) { break; } } } if (cp.Room.IsConnected) { toRemove.Add(cp); } } actRemove(toRemove.Distinct()); #endregion } if (true) { #region остатки ConnectionPoints var notConnectedToAny = rooms.Where(_room => !_room.IsConnected).ToList(); foreach (var room in notConnectedToAny) { var cps = _connectionPoints.Where(_point => _point.Room == room).ToList(); if (cps.Count == 0) { continue; } foreach (var cp in cps) { var delta = cp.Dir.GetDelta(); var point = cp.End; var i = 0; var flag = false; for (; i < 10; ++i) { point += delta; EDirections dir; if (forbid.TryGetValue(point, out dir)) { if (!dir.HasFlag(cp.Dir)) break; } Connector connector; if (connectors.TryGetValue(point, out connector)) { ConnectTwoRooms(room, null, forbid, connectors, cp.Begin, cp.End, point); flag = true; break; } else { var rm = rooms.FirstOrDefault(_room => _room.WorldRoomRectangle.Contains(point)); if (rm != null) { ConnectTwoRooms(room, rm, forbid, connectors, cp.Begin, cp.End, point - delta); flag = true; break; } } } _connectionPoints.Remove(cp); if (flag) break; } } #endregion } if (true) { #region финальный этап while (true) { var nConnectors = connectors.Where(_pair => _pair.Value.Rooms.Any(_room => !_room.IsConnected)).ToArray(); var nKeys = nConnectors.Select(_pair => _pair.Key).ToArray(); var pConnectors = connectors.Except(nConnectors).ToArray(); if (nConnectors.Length == 0) { break; } var flag = false; foreach (var nPair in nConnectors) { var nPnt = nPair.Key; var possible = pConnectors.Where(_pair => (_pair.Key.X == nPnt.X || _pair.Key.Y == nPnt.Y)).OrderBy( _pair => (_pair.Key - nPnt).QLenght).ToList(); foreach (var pPair in possible) { var pPnt = pPair.Key; var npDir = Util.GetDirection(nPnt, pPnt); flag = true; foreach (var point in nPnt.GetLineToPoints(pPnt)) { if (point != nPnt && nKeys.Contains(point)) { flag = false; break; } EDirections dir; if (forbid.TryGetValue(point, out dir)) { if (!dir.HasFlag(npDir)) { flag = false; break; } } } if (flag) { var nRooms = nPair.Value.Rooms.ToArray(); foreach (var room in nRooms) { ConnectTwoRooms(room, null, forbid, connectors, nPnt + npDir.GetDelta(), pPnt); } break; } } if (flag) { break; } } if (!flag) { break; } } #endregion } }
/// <summary> /// /// </summary> /// <param name="schema"></param> /// <param name="table"></param> /// <param name="fieldTypes">A mapping of the fieldname to .NET type of the fields</param> /// <returns></returns> public virtual string _getCreateTableSql(string schema, string table, Dictionary<string, SqlColumnType> fieldTypes) { // Strip off the primary key if it was supplied in fields - we'll make it ourselves var datafields = fieldTypes.Except(table + "Id"); var fieldList = _fieldDefinitions(datafields); var sql = String.Format(@"CREATE TABLE [{0}].[{1}] ( {1}Id int NOT NULL IDENTITY (1,1) PRIMARY KEY, {2} ) ON [PRIMARY]", schema, table, fieldList); return sql; }
public virtual string MakeWhereClause(Dictionary<string, object> keyFields, string paramPrefix = "", bool useParameters = true) { keyFields = keyFields ?? new Dictionary<string, object>(); // TODO: Figure out how to pass null values as parameters // instead of hardcoding them in here var nullFields = keyFields.WhereValues(v => v == DBNull.Value || v == null).Keys; var nullFieldParts = nullFields.Select(x => x + " is null"); var nonNullFields = keyFields.Except(nullFields).Keys; var nonNullFieldParts = useParameters ? nonNullFields.Select(x => x + " = @" + paramPrefix + x) : nonNullFields.Select(x => x + " = " + SqlLiteral(keyFields[x])); var whereClause = ""; if (keyFields.Any()) whereClause = " WHERE " + nullFieldParts.And(nonNullFieldParts).Join(" AND "); return whereClause; }
public void GetInternalKeys() { downloader.Pages["http://myhost:222/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}"; var expected = new Dictionary<string, string>(); expected["fxcop:UriParametersShouldNotBeStrings"] = "CA1054"; var actual = ws.GetInternalKeys("fxcop"); Assert.AreEqual(true, expected.Count == actual.Count && !expected.Except(actual).Any()); }
public Result BuildModel(Grevit.Types.ComponentCollection components) { bool delete = false; if (components == null) { // Create new Grevit Client sending existing Families Grevit.Client.ClientWindow grevitClientDialog = new Grevit.Client.ClientWindow(document.GetFamilies()); //Grevit.Serialization.Client grevitClientDialog = new Grevit.Serialization.Client(document.GetFamilies()); // Show Client Dialog grevitClientDialog.ShowWindow(); //if (grevitClientDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return Result.Cancelled; // Set the received component collection components = grevitClientDialog.componentCollection; delete = grevitClientDialog.componentCollection.delete; Scale = grevitClientDialog.componentCollection.scale; } // Set up a List for stalled components (with References) List<Component> componentsWithReferences = new List<Component>(); // Get all existing Grevit Elements from the Document // If Update is false this will just be an empty List existing_Elements = document.GetExistingGrevitElements(components.update); // Set up an empty List for created Elements created_Elements = new Dictionary<string, ElementId>(); #region createComponents Transaction trans = new Transaction(GrevitBuildModel.document, "GrevitCreate"); trans.Start(); // Walk thru all received components foreach (Component component in components.Items) { // If they are not reference dependent, create them directly // Otherwise add the component to a List of stalled elements if (!component.stalledForReference) component.Build(false); else componentsWithReferences.Add(component); } // Walk thru all elements which are stalled because they are depending on // an Element which needed to be created first foreach (Component component in componentsWithReferences) component.Build(true); trans.Commit(); trans.Dispose(); #endregion // If Delete Setting is activated if (delete) { // Create a new transaction Transaction transaction = new Transaction(document, "GrevitDelete"); transaction.Start(); // get the Difference between existing and new elements to erase them IEnumerable<KeyValuePair<string, ElementId>> unused = existing_Elements.Except(created_Elements).Concat(created_Elements.Except(existing_Elements)); // Delete those elements from the document foreach (KeyValuePair<string, ElementId> element in unused) document.Delete(element.Value); // commit and dispose the transaction transaction.Commit(); transaction.Dispose(); } return Result.Succeeded; }
public void FindFrontContractFindsCorrectContractNMonthsBack() { List<Instrument> contracts = ContinuousFuturesBrokerTestData.GetVIXFutures().Where(x => x.ID < 6).ToList(); //return the contracts requested _instrumentMgrMock.Setup(x => x .FindInstruments(It.IsAny<Expression<Func<Instrument, bool>>>(), It.IsAny<MyDBContext>())) .Returns( (Expression<Func<Instrument, bool>> y, MyDBContext a) => contracts.AsQueryable().Where(y).ToList() ); _cfInst.ContinuousFuture.RolloverDays = 1; var expectedExpirationMonths = new Dictionary<DateTime, int?> { { new DateTime(2012, 11,20), 1 }, { new DateTime(2012, 11,21), 1 }, { new DateTime(2012, 11,23), 1 }, { new DateTime(2012, 11,26), 1 }, { new DateTime(2012, 11,27), 1 }, { new DateTime(2012, 11,28), 1 }, { new DateTime(2012, 11,29), 1 }, { new DateTime(2012, 11,30), 1 }, { new DateTime(2012, 12,3), 1 }, { new DateTime(2012, 12,4), 1 }, { new DateTime(2012, 12,5), 1 }, { new DateTime(2012, 12,6), 1 }, { new DateTime(2012, 12,7), 1 }, { new DateTime(2012, 12,10), 1 }, { new DateTime(2012, 12,11), 1 }, { new DateTime(2012, 12,12), 1 }, { new DateTime(2012, 12,13), 1 }, { new DateTime(2012, 12,14), 1 }, { new DateTime(2012, 12,17), 1 }, { new DateTime(2012, 12,18), 2 }, { new DateTime(2012, 12,19), 2 }, { new DateTime(2012, 12,20), 2 }, { new DateTime(2012, 12,21), 2 }, { new DateTime(2012, 12,24), 2 }, { new DateTime(2012, 12,26), 2 }, { new DateTime(2012, 12,27), 2 }, { new DateTime(2012, 12,28), 2 }, { new DateTime(2012, 12,31), 2 }, { new DateTime(2013, 1,2), 2 }, { new DateTime(2013, 1,3), 2 }, { new DateTime(2013, 1,4), 2 }, { new DateTime(2013, 1,7), 2 }, { new DateTime(2013, 1,8), 2 }, { new DateTime(2013, 1,9), 2 }, { new DateTime(2013, 1,10), 2 }, { new DateTime(2013, 1,11), 2 }, { new DateTime(2013, 1,14), 2 }, { new DateTime(2013, 1,15), 3 }, { new DateTime(2013, 1,16), 3 }, { new DateTime(2013, 1,17), 3 }, { new DateTime(2013, 1,18), 3 }, { new DateTime(2013, 1,22), 3 }, { new DateTime(2013, 1,23), 3 }, { new DateTime(2013, 1,24), 3 }, { new DateTime(2013, 1,25), 3 }, { new DateTime(2013, 1,28), 3 }, { new DateTime(2013, 1,29), 3 }, { new DateTime(2013, 1,30), 3 }, { new DateTime(2013, 1,31), 3 }, { new DateTime(2013, 2,1), 3 }, { new DateTime(2013, 2,4), 3 }, { new DateTime(2013, 2,5), 3 }, { new DateTime(2013, 2,6), 3 }, { new DateTime(2013, 2,7), 3 }, { new DateTime(2013, 2,8), 3 }, { new DateTime(2013, 2,11), 3 }, { new DateTime(2013, 2,12), null }, { new DateTime(2013, 2,13), null }, { new DateTime(2013, 2,14), null }, { new DateTime(2013, 2,15), null }, { new DateTime(2013, 2,19), null }, { new DateTime(2013, 2,20), null }, { new DateTime(2013, 2,21), null }, { new DateTime(2013, 2,22), null }, { new DateTime(2013, 2,25), null }, { new DateTime(2013, 2,26), null }, { new DateTime(2013, 2,27), null }, { new DateTime(2013, 2,28), null }, { new DateTime(2013, 3,1), null }, { new DateTime(2013, 3,4), null }, { new DateTime(2013, 3,5), null }, { new DateTime(2013, 3,6), null }, { new DateTime(2013, 3,7), null }, { new DateTime(2013, 3,8), null }, { new DateTime(2013, 3,11), null }, { new DateTime(2013, 3,12), null }, { new DateTime(2013, 3,13), null } }; Dictionary<DateTime, int?> returnedExpirationMonths = new Dictionary<DateTime, int?>(); //hook up the event to add the expiration month _broker.FoundFrontContract += (sender, e) => { returnedExpirationMonths.Add(e.Date, e.Instrument == null ? null : (int?)e.Instrument.Expiration.Value.Month); }; _cfInst.ContinuousFuture.Month = 2; //make the request foreach (DateTime dt in expectedExpirationMonths.Keys) { _broker.RequestFrontContract(_cfInst, dt); } int i = 0; while (expectedExpirationMonths.Count != returnedExpirationMonths.Count) { i++; if (i >= 50) { string missing = string.Join(", ", expectedExpirationMonths.Except(returnedExpirationMonths).Select(x => x.Key)); Assert.IsTrue(false, "Took too long. Missing: " + missing); } Thread.Sleep(50); } string missing2 = string.Join(", ", expectedExpirationMonths.Except(returnedExpirationMonths).Select(x => x.Key)); Assert.AreEqual(0, expectedExpirationMonths.Except(returnedExpirationMonths).Count(), missing2); foreach (var kvp in expectedExpirationMonths) { var month = kvp.Value; Assert.IsTrue(returnedExpirationMonths.ContainsKey(kvp.Key), "Contains: " + kvp.Key.ToString()); Assert.AreEqual(month, returnedExpirationMonths[kvp.Key], "Are equal: " + kvp.Key.ToString()); } }
public void TC13_VerifyDrainWashStepFunctionality() { Thread.Sleep(2000); if (Page.WasherGroupPage.WasherGroupTableGrid.Rows.Count > 1) { Thread.Sleep(1000); Page.WasherGroupPage.WasherGroupTableGrid.SelectedRows(setWasherType)[0].GetButtonControls()[4].DeskTopMouseClick(); Page.WasherGroupPage.TabFormula.DeskTopMouseClick(); Thread.Sleep(1000); Page.WasherGroupPage.WasherGroupFormulaTabelGrid.Rows[1].GetButtonControls()[4].DeskTopMouseClick(); Thread.Sleep(1000); if (Page.WasherGroupPage.WashStepsTableGrid.Rows.Count > 1) { //Verifying the conditions. Thread.Sleep(1000); for (int k = 1; k <= Page.WasherGroupPage.WashStepsTableGrid.Rows.Count; k++) { Thread.Sleep(1000); if (Page.WasherGroupPage.WashStepsTableGrid.Rows[k].GetColumnValues()[2].ToString() == "Drain") { Dictionary<string, string> ActualDrainWashStep = new Dictionary<string, string>(); Dictionary<string, string> ExpectedDrainWashStep = new Dictionary<string, string>(); ExpectedDrainWashStep.Add("Operations", "Drain"); ExpectedDrainWashStep.Add("Run Time (mm:ss)", "02:00"); ExpectedDrainWashStep.Add("Temperature (oF)", "1"); ExpectedDrainWashStep.Add("Water Level (inches)", "0"); //Need to find the list of row values to compare and fail or pass the test case....with this finish... ReadOnlyCollection<string> getValues = Page.WasherGroupPage.WashStepsTableGrid.Rows[k].GetColumnValues(); ActualDrainWashStep.Add("Operations", getValues[2]); ActualDrainWashStep.Add("Run Time (mm:ss)", getValues[3]); ActualDrainWashStep.Add("Temperature (oF)", getValues[4]); ActualDrainWashStep.Add("Water Level (inches)", getValues[5]); List<KeyValuePair<string,string>> diffCount = ExpectedDrainWashStep.Except(ActualDrainWashStep).ToList(); if(diffCount.Count > 0) { Assert.Fail("Drain Wash Steps are not matching with Expected.Actual - " + diffCount[0]); } break; } } } else { Assert.Fail("Drain WashStep not found in the gridview: Expected- Drain WashStep to be display while adding new WashStep"); } } else { Assert.Fail("Washer Group data not found in grid page"); } }
public void GetProperties() { downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]"; var expected = new Dictionary<string, string>(); expected["sonar.property1"] = "value1"; expected["sonar.property2"] = "value2"; expected["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern; var actual = ws.GetProperties("foo bar"); Assert.AreEqual(true, expected.Count == actual.Count && !expected.Except(actual).Any()); }
/// <summary> /// Given a vector, it will attempt to trim any superfluous /// axes e.g. conjunctives, times (but not dates). /// </summary> /// <param name="vec"></param> /// <returns></returns> public static Dictionary<string, int> TrimVector(Dictionary<string, int> vec) { var removalList = new Dictionary<string, int>(); foreach (var kvp in vec) { var timePattern = @"^\d{2}:\d{2}:\d{2}$"; var timeRgx = new Regex(timePattern); if (kvp.Key.Length <= 3) { removalList.Add(kvp.Key, kvp.Value); } else if ((timeRgx.Match(kvp.Key)).Success) { removalList.Add(kvp.Key, kvp.Value); } } return vec.Except(removalList).ToDictionary(x => x.Key, x => x.Value); }