public void AddTest() { var tree = new ShieldedTree<int, object>(); Assert.Throws<InvalidOperationException>(() => tree.Add(1, new object())); Assert.Throws<InvalidOperationException>(() => ((ICollection<KeyValuePair<int, object>>)tree).Add( new KeyValuePair<int, object>(1, new object()))); var objectA = new object(); var objectB = new object(); Shield.InTransaction(() => { tree.Add(1, objectA); ((ICollection<KeyValuePair<int, object>>)tree).Add( new KeyValuePair<int, object>(2, objectB)); Assert.AreEqual(2, tree.Count); Assert.AreEqual(objectA, tree[1]); Assert.AreEqual(objectB, tree[2]); }); Assert.AreEqual(2, tree.Count); Assert.AreEqual(objectA, tree[1]); Assert.AreEqual(objectB, tree[2]); var objectA2 = new object(); var expectedValues = new HashSet<object>(new object[] { objectA, objectA2 }); Shield.InTransaction(() => { tree.Add(1, objectA2); Assert.AreEqual(3, tree.Count); Assert.IsTrue(expectedValues.SetEquals(tree.Range(1, 1).Select(kvp => kvp.Value))); }); Assert.AreEqual(3, tree.Count); Shield.InTransaction( () => Assert.IsTrue(expectedValues.SetEquals(tree.Range(1, 1).Select(kvp => kvp.Value)))); }
public void SingletonEqualitySane() { var a = SmallSet<string>.Create("A"); var b = SmallSet<string>.Create(new HashSet<string> {"A"}); var c = SmallSet<string>.Create(new[] { "A" }); var d = new HashSet<string> {"A"}; Assert.IsType(typeof(SmallSet<string>), a); Assert.IsType(typeof(SmallSet<string>), b); Assert.IsType(typeof(SmallSet<string>), c); Assert.IsNotType(typeof(SmallSet<string>), d); var diff = SmallSet<string>.Create("B"); Assert.Equal(a, b); Assert.True(a.SetEquals(b)); Assert.Equal(a, c); Assert.Equal(b, c); Assert.True(a.SetEquals(d)); Assert.True(d.SetEquals(a)); Assert.True(d.SetEquals(b)); Assert.True(d.SetEquals(c)); Assert.NotEqual(a, diff); Assert.NotEqual(b, diff); Assert.NotEqual(c, diff); Assert.False(diff.SetEquals(a)); Assert.False(a.SetEquals(diff)); Assert.False(diff.SetEquals(b)); Assert.False(diff.SetEquals(c)); Assert.False(diff.SetEquals(d)); }
public void BigSetSane() { var values = new[] { "A", "B" }; var a = SmallSet<string>.Create(values); var b = new HashSet<string>(values); var c = SmallSet<string>.Create(b); Assert.IsNotType(typeof(SmallSet<string>), a); Assert.IsNotType(typeof(SmallSet<string>), c); Assert.True(a.SetEquals(b)); Assert.True(b.SetEquals(a)); Assert.True(b.SetEquals(c)); }
public static ApiDescription GetApiDescription(HttpConfiguration config, string controllerName, string actionName, params string[] parameterNames) { if (config == null) { config = new HttpConfiguration(); config.Formatters.Clear(); config.Formatters.Add(new XmlMediaTypeFormatter()); config.Formatters.Add(new JsonMediaTypeFormatter()); config.Routes.MapHttpRoute("Default", "{controller}"); } HashSet<string> parameterSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var apiDescription in config.Services.GetApiExplorer().ApiDescriptions) { HttpActionDescriptor actionDescriptor = apiDescription.ActionDescriptor; if (String.Equals(actionDescriptor.ControllerDescriptor.ControllerName, controllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionDescriptor.ActionName, actionName, StringComparison.OrdinalIgnoreCase)) { HashSet<string> actionParameterSet = new HashSet<string>(actionDescriptor.GetParameters().Select(p => p.ParameterName), StringComparer.OrdinalIgnoreCase); if (parameterSet.SetEquals(actionParameterSet)) { return apiDescription; } } } return null; }
public bool Add(Vertex[] Edge1, Vertex[] Edge2) { PointF[] edge1 = new PointF[2]; PointF[] edge2 = new PointF[2]; edge1 = VertToPoint(Edge1); edge2 = VertToPoint(Edge2); HashSet<PointF> crossing = new HashSet<PointF>(); crossing.Add(edge1[0]); crossing.Add(edge1[1]); crossing.Add(edge2[0]); crossing.Add(edge2[1]); foreach (HashSet<PointF> storedCrossing in set) { if (crossing.SetEquals(storedCrossing)) // Crossing already exists in set, so return false and don't add { return false; } } set.Add(crossing); return true; }
public void ScanForTestClasses() { Assembly assembly = Assembly.GetAssembly(typeof(AssemblyTestMock1)); HashSet<Type> expectedTestClasses = new HashSet<Type> {typeof(AssemblyTestMock1), typeof(AssemblyTestMock2)}; AssertEx.That(expectedTestClasses.SetEquals(AssemblyScanner.GetTestClassesIn(assembly)), Is.True()); }
public object Get(IMetadata metadata) { // The metadata value could get resolved concurrently so we need to lock it while caching lock (Lock) { // Check if we're excluded from evaluation if (metadata.TryGetValue(Keys.ExcludeFromEvaluation, out object excludeObject) && ((excludeObject is bool excludeBool && excludeBool) || metadata.GetList <string>(Keys.ExcludeFromEvaluation).Contains(_key, StringComparer.OrdinalIgnoreCase))) { return(_originalPrefix + _script); } // Check if we've already cached a compilation for the current set of metadata keys KeyValuePair <string, string>[] metadataProperties = _executionState.ScriptHelper.GetMetadataProperties(metadata).ToArray(); if (_cachedMetadataProperties?.SetEquals(metadataProperties) != true) { // Compilation cache miss, not cached or the metadata keys are different _cachedMetadataProperties = new HashSet <KeyValuePair <string, string> >(metadataProperties); byte[] rawAssembly = _executionState.ScriptHelper.Compile(_script, metadataProperties); _cachedScriptType = _executionState.ScriptHelper.Load(rawAssembly); } } return(_executionState.ScriptHelper.EvaluateAsync(_cachedScriptType, metadata).GetAwaiter().GetResult()); }
static void Main(string[] args) { var bigCities = new HashSet<string> { "New York", "Manchester", "Sheffield", "Paris" }; var citiesInUK = new HashSet<string> { "Sheffield", "Ripon", "Truro", "Manchester" }; var bigCitiesArray = new string[] { "New York", "Manchester", "Sheffield", "Paris" }; // The order in the array or the set does not matter since a set does not know the position of the values. bool areEqual = bigCities.SetEquals(bigCitiesArray); Console.WriteLine("bigcities = bigCitiesArray ? {0}", areEqual); bool areEqualUK = citiesInUK.SetEquals(bigCitiesArray); Console.WriteLine("citiesInUK = BigCitiesArray? {0}", areEqualUK); }
public int GetPrefixSuffixSetCount(int[] set) { int output = 0; var prefixesNumbersUsed = new HashSet<int>(); var suffixNumbersUsed = new HashSet<int>(); foreach (var rangePair in GetPrefixSuffixIndexRanges(set)) { var prefixRange = rangePair.Prefix; var suffixRange = rangePair.Suffix; prefixesNumbersUsed.Add(prefixRange.Number); suffixNumbersUsed.Add(suffixRange.Number); if (prefixesNumbersUsed.SetEquals(suffixNumbersUsed)) { //No need to keep comparing values that worked already prefixesNumbersUsed.Clear(); suffixNumbersUsed.Clear(); output += (prefixRange.Range * suffixRange.Range); } if (output > TOO_LARGE) return TOO_LARGE; } return output; }
static void Main(string[] args) { var one = new HashSet<MailAddress> { new MailAddress("*****@*****.**"), new MailAddress("*****@*****.**") }; var two = new HashSet<MailAddress> { new MailAddress("*****@*****.**"), new MailAddress("*****@*****.**"), }; var equal = one.SetEquals(two); var sink = Observable .FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(x => oc.CollectionChanged += x, y => oc.CollectionChanged -= y) .Where(e => e.EventArgs.Action == NotifyCollectionChangedAction.Add); var window = sink.Window(10).Subscribe(x => { if(oc.Count >= 10) Send("window"); }); var throttle = sink.Throttle(TimeSpan.FromSeconds(2)).Subscribe(x => Send("throttle")); unchecked { for(int i = 1; i <= 3; i++) Seed(i * 1000, i.ToString()); } Console.WriteLine("Press any key to exit.."); Console.ReadKey(true); window.Dispose(); throttle.Dispose(); }
public async Task LookupService() { Exception lastFailure = new Exception("No reference source URLs defined"); foreach (var url in urls) { string assemblyList; try { using (var http = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true })) assemblyList = await http.GetStringAsync(url + "/assemblies.txt"); // Format: // AssemblyName; ProjectIndex; DependentAssemblies var assemblies = new HashSet<string>( assemblyList.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Remove(s.IndexOf(';'))) ); // If nothing changed, don't spam the log if (assemblies.SetEquals(this.AvailableAssemblies) && url == this.baseUrl) return; AvailableAssemblies = assemblies; baseUrl = url; logger.Log("Using reference source from " + url + " with " + AvailableAssemblies.Count + " assemblies"); return; } catch (Exception ex) { lastFailure = ex; continue; } } logger.Log("Errors occurred while trying all reference URLs; Ref12 will not work", lastFailure); AvailableAssemblies = new HashSet<string>(); }
public ShortTestResultEntity GetShortTestResult(TestCompletedEntity testCompletedEntity) { ShortTestResultEntity shortTestResult = new ShortTestResultEntity() { TestName = testCompletedEntity.Test.Name, DateTimeStart = testCompletedEntity.DateTimeStart, DateTimeFinish = testCompletedEntity.DateTimeFinish, User = testCompletedEntity.User }; foreach (var questionEntity in testCompletedEntity.Test.Questions) { QuestionResultEntity questionResult = new QuestionResultEntity() { Text = questionEntity.Text }; var answersSet = new HashSet<int>(questionEntity.Options.Where(m => m.IsAnswer).Select(m => m.Id)); var pickedSet = new HashSet<int>(testCompletedEntity.Answers.Where(m => m.QuestionId == questionEntity.Id).Select(m => m.Id)); questionResult.IsAnsweredCorrectly = answersSet.SetEquals(pickedSet); shortTestResult.QuestionResults.Add(questionResult); } shortTestResult.Questions = testCompletedEntity.Test.Questions.Count; shortTestResult.RightAnsweredQuestions = shortTestResult.QuestionResults.Count(m => m.IsAnsweredCorrectly); return shortTestResult; }
public void ShuffleRange() { var set = new HashSet<int>(Enumerable.Range(0, 100)); var result = RandomHelper.ShuffleRange(100).ToArray(); Assert.IsTrue(set.SetEquals(result)); }
public void Permissions_ReturnsExpectedValues() { string[] permissions = new[] { "email", "user_likes", "friends_likes" }; FacebookAuthorizeAttribute authorizeAttribute = new FacebookAuthorizeAttribute(permissions); HashSet<string> permissionSet = new HashSet<string>(permissions); Assert.True(permissionSet.SetEquals(authorizeAttribute.Permissions)); }
public void Test_DynamicProperty_NewDP_Pass(string expression, string[] expectedResult) { var kb = TestFactory.PopulatedTestMemory(); kb.RegistDynamicProperty((Name)"Concat", Test_Concat_Dynamic_Property); var results = new HashSet<Name>(kb.AskPossibleProperties((Name)expression, Name.SELF_SYMBOL, null).Select(r => r.Item1)); var expected = new HashSet<Name>(expectedResult.Select(s => (Name) s)); Assert.True(results.SetEquals(expected)); }
public void PairsValues() { var left = new[] { 0, 2, 4, 1, 3, 5 }.ToObservable(); var right = new[] { 0, 3, 5, 4, 2, 1 }.ToObservable(); var expected = new HashSet<Pair<int>>(Enumerable.Range(0, 6).Select(x => new Pair<int>(x, x))); var results = left.MatchPair(right, x => x).ToEnumerable(); Assert.True(expected.SetEquals(results)); }
public void IgnoresSingleValuesAfterCompletion() { var left = new[] { 1, 2, 1 }; var right = new[] { 2, 1, 2 }; var expected = new HashSet<Pair<int>>(Enumerable.Range(1, 2).Select(x => new Pair<int>(x, x))); var results = left.ToObservable().MatchPair(right.ToObservable(), x => x).ToEnumerable().ToList(); Assert.True(expected.SetEquals(results)); }
/// <summary> /// Gets the product which contains exactly the given set of modules. /// </summary> /// <param name="modules">A set of modules</param> /// <returns>Name of the matching product, or <c>null</c></returns> public string GetProductName(IEnumerable<Module> modules) { var set1 = new HashSet<Module>(modules); return ( from product in suite.Products let set2 = new HashSet<Module>(product.Modules) where set1.SetEquals(set2) select product.Name).FirstOrDefault(); }
public void Should_shuffle_array() { var randomIntegers = Fake.Create<int>().Generate(100); var shuffled = randomIntegers.Shuffle().ToList(); Assert.AreEqual(randomIntegers.Count, shuffled.Count); Assert.False(randomIntegers.SequenceEqual(shuffled)); var hashset1 = new HashSet<int>(randomIntegers); var hashset2 = new HashSet<int>(shuffled); Assert.True(hashset1.SetEquals(hashset2)); }
public void GivenBundlesAdded_WhenEnumerated_ThenBundlesReturned() { var bundle1 = new TestableBundle("~/test1"); var bundle2 = new TestableBundle("~/test2"); bundles.Add(bundle1); bundles.Add(bundle2); var set = new HashSet<Bundle>(bundles); set.SetEquals(new[] { bundle1, bundle2 }).ShouldBeTrue(); }
public async Task TestSetDataWithMultipleInstanceIds() { ICloudBlob blob = await CreateEmptyBlob(); string leaseId = blob.AcquireLease(null, null); UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob); var instanceIds = new HashSet<string>(new[] {"instanceId1"}); await updateBlobWrapper.SetData(leaseId, "1", instanceIds); Assert.AreEqual("1", updateBlobWrapper.GetUpdateDomain()); Assert.IsTrue(instanceIds.SetEquals(updateBlobWrapper.GetInstanceIds())); }
private bool IsRoyalFlush(Hand hand) { bool isFlush = HandEvaluatorHelper.IsFlush(hand); if (!isFlush) { return false; } var cardsValues = new HashSet<CardValue>(hand.Cards.Select(card => card.Value)); return cardsValues.SetEquals(this.NeededCardValues); }
public void MethodManagement() { TestClassSession classSession = new TestClassSession(typeof(TestClassMock)); classSession.Add(typeof(TestClassMock).GetMethod("FirstTestMethod")); HashSet<MethodInfo> expectedMethods = new HashSet<MethodInfo> { typeof(TestClassMock).GetMethod("FirstTestMethod") }; Assert.IsTrue(expectedMethods.SetEquals(classSession.TestsToRun)); classSession.AddAll(); expectedMethods.Add(typeof(TestClassMock).GetMethod("SecondTestMethod")); Assert.IsTrue(expectedMethods.SetEquals(classSession.TestsToRun)); }
public StandardDeck(IShuffler shuffler, string gameId) : base() { _gameid = gameId; Shuffler = shuffler; Cards = new HashSet<Card>(); PokerCalculator.PokerLib.init_deck(deck); var ed = new HashSet<int>(expectedDeck); var actDeck = new HashSet<int>(deck); if (!actDeck.SetEquals(ed)) throw new ApplicationException("The deck returned from the PokerLib is corrupt"); }
public void GivenMinAndNonMinScripts_WhenFindFiles_ThenOnlyIncludeNonMinScripts() { CreateFile("jquery.js"); CreateFile("jquery.min.js"); CreateFile("jquery-ui.js"); CreateFile("jquery-ui.min.js"); var search = new FileSearch { Pattern = "*.js" }; var files = search.FindFiles(directory).ToArray(); var names = new HashSet<string>(files.Select(f => f.FullPath)); names.SetEquals(new[] { "~/jquery.js", "~/jquery-ui.js" }); }
private void CheckSheetConsistence(DataSheet sheet) { var columnNames = new HashSet<string>(sheet.Rows[0].Keys); foreach (var row in sheet.Rows) { if (!columnNames.SetEquals(row.Keys)) { throw new Exception( string.Format("{0} columns mismatch: ({1}),({2})", sheet.Name, JsonOperation.Serialize(columnNames), JsonOperation.Serialize(row))); } } }
public SaveResponse Update(IUnitOfWork uow, RolePermissionUpdateRequest request) { Check.NotNull(request, "request"); Check.NotNull(request.RoleID, "roleID"); Check.NotNull(request.Permissions, "permissions"); var roleID = request.RoleID.Value; var oldList = new HashSet<string>( GetExisting(uow.Connection, roleID, request.Module, request.Submodule) .Select(x => x.PermissionKey), StringComparer.OrdinalIgnoreCase); var newList = new HashSet<string>(request.Permissions.ToList(), StringComparer.OrdinalIgnoreCase); var allowedKeys = new UserPermissionRepository().ListPermissionKeys() .Entities.ToDictionary(x => x); if (newList.Any(x => !allowedKeys.ContainsKey(x))) throw new AccessViolationException(); if (oldList.SetEquals(newList)) return new SaveResponse(); foreach (var k in oldList) { if (newList.Contains(k)) continue; new SqlDelete(fld.TableName) .Where( new Criteria(fld.RoleId) == roleID & new Criteria(fld.PermissionKey) == k) .Execute(uow.Connection); } foreach (var k in newList) { if (oldList.Contains(k)) continue; uow.Connection.Insert(new MyRow { RoleId = roleID, PermissionKey = k }); } BatchGenerationUpdater.OnCommit(uow, fld.GenerationKey); BatchGenerationUpdater.OnCommit(uow, Entities.UserPermissionRow.Fields.GenerationKey); return new SaveResponse(); }
public bool BoxesChanged(ImportedCloud orig) { // FIXME this is too sensitive #if false HashSet<Matrix4x4> oldBoxes = new HashSet<Matrix4x4>( boxes ); HashSet<Matrix4x4> newBoxes = new HashSet<Matrix4x4>(); Matrix4x4 cloud2world = orig.transform.localToWorldMatrix; foreach(Transform box in orig.transform.FindChild("CutBoxes")) newBoxes.Add(box.worldToLocalMatrix * cloud2world); return ! oldBoxes.SetEquals( newBoxes ); #endif return false; }
public void AddTest1Test() { DependencyGraph t = new DependencyGraph(); t.AddDependency("A1", "A2"); t.AddDependency("A1", "A3"); t.RemoveDependency("A1", "A2"); Assert.AreEqual(1, t.Size); t.AddDependency("A1", "A4"); Assert.AreEqual(2, t.Size); HashSet<string> test = new HashSet<string>(); test.Add("A3"); test.Add("A4"); Assert.AreEqual(true, test.SetEquals(t.GetDependents("A1"))); }
public void CreateSessionForAssembly() { Assembly assembly = Assembly.GetAssembly(typeof(AssemblyTestMock1)); HashSet<TestClassSession> expectedClassSessions = new HashSet<TestClassSession>(); TestClassSession classSession = new TestClassSession(typeof(AssemblyTestMock1)); classSession.AddAll(); expectedClassSessions.Add(classSession); classSession = new TestClassSession(typeof(AssemblyTestMock2)); classSession.AddAll(); expectedClassSessions.Add(classSession); AssertEx.That(expectedClassSessions.SetEquals(AssemblyScanner.CreateSessionFor(assembly).TestClassSessions), Is.True()); }
private static async Task TestRemindersHashInterval(IReminderTable reminderTable, uint beginHash, uint endHash, uint[] remindersHashes) { var rowsTask = reminderTable.ReadRows(beginHash, endHash); var expectedHashes = beginHash < endHash ? remindersHashes.Where(r => r > beginHash && r <= endHash) : remindersHashes.Where(r => r > beginHash || r <= endHash); HashSet<uint> expectedSet = new HashSet<uint>(expectedHashes); var returnedHashes = (await rowsTask).Reminders.Select(r => r.GrainRef.GetUniformHashCode()); var returnedSet = new HashSet<uint>(returnedHashes); Assert.IsTrue(returnedSet.SetEquals(expectedSet)); }
private IEnumerable <KeyValuePair <HelpPageSampleKey, object> > GetAllActionSamples(string controllerName, string actionName, IEnumerable <string> parameterNames, SampleDirection sampleDirection) { HashSet <string> parameterNamesSet = new HashSet <string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return(sample); } } }
/// <summary> /// Tries to load a valid VRTK_SDKSetup from setups. /// </summary> public void TryLoadSDKSetupFromList(bool tryUseLastLoadedSetup = true) { int index = 0; if (tryUseLastLoadedSetup && _previouslyUsedSetupInfos.Count > 0) { index = Array.FindIndex( setups, setup => _previouslyUsedSetupInfos.SetEquals( new[] { setup.systemSDKInfo, setup.boundariesSDKInfo, setup.headsetSDKInfo, setup.controllerSDKInfo }) ); } else if (XRSettings.enabled) { // Use the SDK Setup for the current VR Device if it's working already // (may be due to command line argument '-vrmode') index = Array.FindIndex( setups, setup => setup.usedVRDeviceNames.Contains(XRSettings.loadedDeviceName) ); } else { // If '-vrmode none' was used try to load the respective SDK Setup string[] commandLineArgs = Environment.GetCommandLineArgs(); int commandLineArgIndex = Array.IndexOf(commandLineArgs, "-vrmode", 1); if (XRSettings.loadedDeviceName == "None" || (commandLineArgIndex != -1 && commandLineArgIndex + 1 < commandLineArgs.Length && commandLineArgs[commandLineArgIndex + 1].ToLowerInvariant() == "none")) { index = Array.FindIndex( setups, setup => setup.usedVRDeviceNames.All(vrDeviceName => vrDeviceName == "None") ); } } index = index == -1 ? 0 : index; TryLoadSDKSetup(index, false, setups.ToArray()); }
public void checkPixelsStegoImage1(string pixel) { Bitmap bmp = new Bitmap("randomImage2.png"); HashSet <int> pixelValues = new HashSet <int>(); int comma = pixel.IndexOf(','); Console.WriteLine("INDEXOF " + comma); string subX = pixel.Split(',')[0]; string subY = pixel.Substring(comma + 1); Console.WriteLine("X {0} Y {1} ", subX, subY); //string[] xy = pixel.Split(',').Select(sValue => sValue.Trim()).ToArray(); int x; int y; if (int.TryParse(subX, out x) && int.TryParse(subY, out y)) { for (int i = 0; i < 32; i += 4) { Color pVals = bmp.GetPixel(x, y); pixelValues.Add(pVals.A); pixelValues.Add(pVals.R); pixelValues.Add(pVals.G); pixelValues.Add(pVals.B); x++; } string hashSet1 = ""; string hashSet2 = ""; foreach (int i in pixelValues) { hashSet1 += Convert.ToString(i) + " "; } bmp.Dispose(); foreach (int i in userPin) { hashSet2 += Convert.ToString(i) + " "; } Console.WriteLine("\nHashset1 of pixels in StegoImage1 is: {0}\nHashset 2 is {1}\n", hashSet1, hashSet2); bool yesNo = pixelValues.SetEquals(userPin); Console.WriteLine(yesNo); } }
public void TestEnvironmentOfChildProcess() { const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff"; Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output try { // Schedule a process to see what env vars it gets. Have it write out those variables // to its output stream so we can read them. Process p = CreateProcess(() => { Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast <DictionaryEntry>().Select(e => Convert.ToBase64String(Encoding.UTF8.GetBytes(e.Key + "=" + e.Value))))); return(SuccessExitCode); }); p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); // Parse the env vars from the child process var actualEnv = new HashSet <string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None).Select(s => Encoding.UTF8.GetString(Convert.FromBase64String(s)))); // Validate against StartInfo.Environment. var startInfoEnv = new HashSet <string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value)); Assert.True(startInfoEnv.SetEquals(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", startInfoEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(startInfoEnv)))); // Validate against current process. (Profilers / code coverage tools can add own environment variables // but we start child process without them. Thus the set of variables from the child process could // be a subset of variables from current process.) var envEnv = new HashSet <string>(Environment.GetEnvironmentVariables().Cast <DictionaryEntry>().Select(e => e.Key + "=" + e.Value)); Assert.True(envEnv.IsSupersetOf(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", envEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(envEnv)))); } finally { Environment.SetEnvironmentVariable(ExtraEnvVar, null); } }
private void OnEnable() { string path = StandardPaths.saveDataDirectory; DirectoryInfo dir = new DirectoryInfo(path); FileInfo[] infos = dir.GetFiles(SearchFilter, SearchOption.AllDirectories); if (infos.Length == 0) { loadButton.interactable = false; selectionErrorText.text = "No save files found, please start a new game from the main menu."; } if (infos.Length == loadedFiles.Count) { return; } HashSet <FileInfo> hashSet = new HashSet <FileInfo>(infos); if (hashSet.SetEquals(loadedFiles)) { return; } for (int i = 0; i < instances.Count; i++) { FileData data = instances[i]; toggleGroup.UnregisterToggle(data.toggle); Destroy(data.gameObject); } instances.Clear(); for (int i = 0; i < infos.Length; i++) { FileData data = Instantiate(textPrefab, parent); toggleGroup.RegisterToggle(data.toggle); data.toggle.group = toggleGroup; instances.Add(data); data.SetInfo(infos[i]); } loadedFiles = hashSet; }
public bool Equals(Collection <SpatialPath> additionalSpatialSpeces1, Collection <SpatialPath> additionalSpatialSpeces2) { if (object.ReferenceEquals(additionalSpatialSpeces1, additionalSpatialSpeces2)) { return(true); } if (additionalSpatialSpeces1 == null || additionalSpatialSpeces2 == null) { return(false); } HashSet <SpatialPath> hashedAdditionalSpatialSpeces1 = new HashSet <SpatialPath>(additionalSpatialSpeces1, spatialSpecEqualityComparer); HashSet <SpatialPath> hashedAdditionalSpatialSpeces2 = new HashSet <SpatialPath>(additionalSpatialSpeces2, spatialSpecEqualityComparer); return(hashedAdditionalSpatialSpeces1.SetEquals(additionalSpatialSpeces2)); }
void IterativeDataFlowAnalysis(IList <CfgNode> nodes, RegType regType = RegType.Data) { bool changes; do { changes = false; for (int i = nodes.Count - 1; i >= 0; i--) { var n = nodes[i]; if (n == null) { // label? continue; } var newout = new HashSet <string>(n.Out); foreach (var s in n.Succ) { foreach (var sn in s.In) { newout.Add(sn); } } var use = n.Instruction.Use(regType).ToList(); var def = n.Def; var newin = new HashSet <string>(use.Union(newout.Where(o => !def.Contains(o)))); if (!newin.SetEquals(n.In)) { changes = true; n.In = newin; } if (!newout.SetEquals(n.Out)) { changes = true; n.Out = newout; } } } while (changes); }
public void ResolveAllWithChildDoesNotRepeatOverriddenRegistrations() { var expected = new HashSet <string>(new[] { "string1", "string20", "string30" }); Container .RegisterInstance("str1", "string1") .RegisterInstance("str2", "string2"); var child = Container.CreateChildContainer() .RegisterInstance("str2", "string20") .RegisterInstance("str3", "string30"); var array = child.ResolveAll <string>(); var actual = new HashSet <string>(array); Assert.IsTrue(actual.SetEquals(expected)); }
private void UpdateSelectableSongs() { this.filteredSongs = this.Library.Songs.FilterSongs(this.SearchText) .ToLookup(x => x.Artist, StringComparer.InvariantCultureIgnoreCase); var newArtists = new HashSet <string>(this.filteredSongs.Select(x => x.Key)); var oldArtists = this.Artists.Where(x => !x.IsAllArtists).Select(x => x.Name); if (!newArtists.SetEquals(oldArtists)) { this.artistUpdateSignal.OnNext(Unit.Default); } List <LocalSongViewModel> selectableSongs = this.filteredSongs .Where(group => this.SelectedArtist.IsAllArtists || @group.Key.Equals(this.SelectedArtist.Name, StringComparison.OrdinalIgnoreCase)) .SelectMany(x => x) .Select(song => new LocalSongViewModel(song)) .OrderBy(this.SongOrderFunc) .ToList(); // Ignore redundant song updates. if (!selectableSongs.SequenceEqual(this.SelectableSongs)) { // Scratch the old viewmodels foreach (var viewModel in this.SelectableSongs) { viewModel.Dispose(); } this.SelectableSongs = selectableSongs; } else { // We don't have to update the selectable songs, get rid of the redundant ones we've created foreach (LocalSongViewModel viewModel in selectableSongs) { viewModel.Dispose(); } } if (this.SelectedSongs == null) { this.SelectedSongs = this.SelectableSongs.Take(1).ToList(); } }
public void ForeachTest() { var list = new FixedIndexList <int>(); var elem = Enumerable.Range(0, 10); var indices = elem.Select(i => list.Add(i)).ToList(); list.RemoveAt(indices[8]); var set = new HashSet <int>(); foreach (var i in list) { set.Add(i); } Assert.IsTrue(set.SetEquals(elem.Except(new[] { 8 }))); }
public static void SetEqual <T>(IEnumerable <T> expected, IEnumerable <T> actual, IEqualityComparer <T> comparer = null, string message = null, string itemSeparator = "\r\n") { var expectedSet = new HashSet <T>(expected, comparer); var result = expected.Count() == actual.Count() && expectedSet.SetEquals(actual); if (!result) { if (string.IsNullOrEmpty(message)) { message = GetAssertMessage( ToString(expected, itemSeparator), ToString(actual, itemSeparator)); } Assert.True(result, message); } }
/** * @param me * @param stayWithMe */ private void checkEquals(UnicodeMap <Integer> me, SortedDictionary <String, Integer> stayWithMe) { temp.Clear(); foreach (var e in me.EntrySet()) { temp.Add(e); } ISet <KeyValuePair <String, Integer> > entrySet = new HashSet <KeyValuePair <string, Integer> >(stayWithMe); if (!entrySet.SetEquals(temp)) { Logln(me.EntrySet().ToString()); Logln(me.ToString()); assertEquals("are in parallel", entrySet, temp); // we failed. Reset and start again entrySet.Clear(); temp.Clear(); return; } foreach (String key in stayWithMe.Keys) { assertEquals("containsKey", stayWithMe.ContainsKey(key), me.ContainsKey(key)); Integer value = stayWithMe.Get(key); assertEquals("get", value, me.Get(key)); assertEquals("containsValue", stayWithMe.ContainsValue(value), me.ContainsValue(value)); int cp = UnicodeSet.GetSingleCodePoint(key); if (cp != int.MaxValue) { assertEquals("get", value, me.Get(cp)); } } // ICU4N TODO: complete implementation //ISet<String> nonCodePointStrings = stayWithMe.tailMap("").keySet(); //if (nonCodePointStrings.Count == 0) nonCodePointStrings = null; // for parallel api //assertEquals("getNonRangeStrings", nonCodePointStrings, me.GetNonRangeStrings()); SortedSet <Integer> values = new SortedSet <Integer>(stayWithMe.Values); SortedSet <Integer> myValues = new SortedSet <Integer>(me.Values()); assertEquals("values", myValues, values); foreach (String key in stayWithMe.Keys) { assertEquals("containsKey", stayWithMe.ContainsKey(key), me.ContainsKey(key)); } }
public void SplitByNotes_ValidFiles() { foreach (var filePath in TestFilesProvider.GetValidFiles()) { var midiFile = MidiFile.Read(filePath); var fileIndex = 0; var allNoteEventsCount = 0; var allNotesIds = new HashSet <NoteId>(); foreach (var fileByNotes in midiFile.SplitByNotes()) { var noteEvents = fileByNotes.GetTrackChunks() .SelectMany(c => c.Events) .OfType <NoteEvent>() .ToList(); var notesIds = new HashSet <NoteId>(noteEvents.Select(n => n.GetNoteId())); allNoteEventsCount += noteEvents.Count; foreach (var noteId in notesIds) { allNotesIds.Add(noteId); } Assert.AreEqual(1, notesIds.Count, $"New file ({fileIndex}) contains different notes."); fileIndex++; } var originalNoteEvents = midiFile.GetTrackChunks() .SelectMany(c => c.Events) .OfType <NoteEvent>() .ToList(); var originalNoteEventsCount = originalNoteEvents.Count(); var originalNotesIds = new HashSet <NoteId>(originalNoteEvents.Select(e => e.GetNoteId())); Assert.AreEqual(originalNoteEventsCount, allNoteEventsCount, "Notes count of new files doesn't equal to count of notes of the original file."); Assert.IsTrue(originalNotesIds.SetEquals(allNotesIds), "Notes in new files differ from notes in the original file."); } }
internal void SetCompositeRolesMany2Many(IRoleType roleType, HashSet <Strategy> roles) { this.AssertNotDeleted(); var originalRoles = this.GetStrategies(roleType); if (!roles.SetEquals(originalRoles)) { this.RemoveCompositeRolesMany2Many(roleType); // TODO: Optimize this foreach (var strategy in roles) { this.AddCompositeRoleMany2Many(roleType, strategy); } } }
private Query BuildQuery(string query, SearchFilter? filter, SearchContext context) { if (queryParser == null || currentLanguages == null || !currentLanguages.SetEquals(context.Languages)) { var fields = context.Languages.Union(Invariant).ToArray(); queryParser = new MultiFieldQueryParser(Version, fields, index.Analyzer); currentLanguages = context.Languages; } try { var byQuery = queryParser.Parse(query); if (filter?.SchemaIds.Count > 0) { var bySchemas = new BooleanQuery { Boost = 2f }; foreach (var schemaId in filter.SchemaIds) { var term = new Term(MetaSchemaId, schemaId.ToString()); bySchemas.Add(new TermQuery(term), Occur.SHOULD); } var occur = filter.Must ? Occur.MUST : Occur.SHOULD; return new BooleanQuery { { byQuery, Occur.MUST }, { bySchemas, occur } }; } return byQuery; } catch (ParseException ex) { throw new ValidationException(ex.Message); } }
public void TestBandStopSinusoid() { const int order = 16; const int fs = 44100; const int targetFrequency = 3; const double br = 5; const int cycles = 10; double[] frequencies = { 65.406, 130.81, 261.63, 523.25, 1046.5, 2093.0, 4186.0, 8372.0 }; var signal = new double[cycles * fs]; foreach (var frequency in frequencies) { Helpers.GenerateSinusoid(frequency, fs, signal); } var im = new double[signal.Length]; var coeff = new BandStopButterworthCoefficients(order, fs, frequencies[targetFrequency] - br, frequencies[targetFrequency] + br); var chain = coeff.Calculate(); chain.Filter(signal, 0, signal, 0, signal.Length); var count = signal.Length / 2; FourierTransform2.FFT(signal, im, FourierTransform.Direction.Forward); Helpers.CalculateEnergy(signal, im, count); var maxEnergy = signal.Take(count).Max(); var step = fs / (2d * count); var peakSet = new HashSet <double>(); for (int i = 1; i < count - 1; i++) { var freq = i * step; if (signal[i] > signal[i - 1] && signal[i] > signal[i + 1] && signal[i] >= 0.01 * maxEnergy) { var peak = frequencies.FirstOrDefault(x => Math.Abs(freq - x) <= 1); Assert.AreNotEqual(0, peak); peakSet.Add(peak); } } Assert.IsTrue(peakSet.SetEquals(frequencies.Except(Enumerable.Repeat(frequencies[targetFrequency], 1)))); }
/// <summary> /// Clears the registry of DLL data, and refreshes it by scanning GameData. /// This operates as a transaction. /// This *saves* the registry upon completion. /// TODO: This would likely be better in the Registry class itself. /// </summary> /// <returns> /// True if found anything different, false if same as before /// </returns> public bool Scan() { if (Directory.Exists(game.PrimaryModDirectory(this))) { var manager = RegistryManager.Instance(this); using (TransactionScope tx = CkanTransaction.CreateTransactionScope()) { var oldDlls = new HashSet <string>(manager.registry.InstalledDlls); manager.registry.ClearDlls(); // TODO: It would be great to optimise this to skip .git directories and the like. // Yes, I keep my GameData in git. // Alas, EnumerateFiles is *case-sensitive* in its pattern, which causes // DLL files to be missed under Linux; we have to pick .dll, .DLL, or scanning // GameData *twice*. // // The least evil is to walk it once, and filter it ourselves. IEnumerable <string> files = Directory .EnumerateFiles(game.PrimaryModDirectory(this), "*", SearchOption.AllDirectories) .Where(file => file.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase)) .Select(CKANPathUtils.NormalizePath) .Where(absPath => !game.StockFolders.Any(f => ToRelativeGameDir(absPath).StartsWith($"{f}/"))); foreach (string dll in files) { manager.registry.RegisterDll(this, dll); } var newDlls = new HashSet <string>(manager.registry.InstalledDlls); bool dllChanged = !oldDlls.SetEquals(newDlls); bool dlcChanged = manager.ScanDlc(); if (dllChanged || dlcChanged) { manager.Save(false); } tx.Complete(); return(dllChanged || dlcChanged); } } return(false); }
private static void DoGetFileSystemInfos_Add() { String chkptFlag = "chkpt_dgim_"; int failCount = 0; s_utils.CreateTestDirs(); // directoryinfo DirectoryInfo di = new DirectoryInfo(s_utils.testDir); IEnumerable <FileSystemInfo> fis = di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories); HashSet <String> disAsHS = new HashSet <string>(); int count = 0; try { foreach (FileSystemInfo d in fis) { disAsHS.Add(d.FullName); count++; if (count == 2) { s_utils.ChangeFSAdd(); } } if (!disAsHS.SetEquals(new HashSet <String>(s_utils.expected_Dirs_Changed.Union(s_utils.expected_Files_Changed)))) { failCount++; Console.WriteLine(chkptFlag + "1: didn't get expected files...."); foreach (FileSystemInfo f in fis) { Console.WriteLine(f.Name); } } } catch (Exception ex) { failCount++; Console.WriteLine(chkptFlag + "2: got wrong exception"); Console.WriteLine(ex); } String testName = "addFilesWhileEnumerating"; s_utils.PrintTestStatus(testName, "DirectoryInfo.EnumerateFileSystemInfos", failCount); }
public SaveResponse Update(IUnitOfWork uow, UserRoleUpdateRequest request) { Check.NotNull(request, "request"); Check.NotNull(request.UserID, "userID"); Check.NotNull(request.Roles, "permissions"); var userID = request.UserID.Value; var oldList = new HashSet<Int32>( GetExisting(uow.Connection, userID) .Select(x => x.RoleId.Value)); var newList = new HashSet<Int32>(request.Roles.ToList()); if (oldList.SetEquals(newList)) return new SaveResponse(); foreach (var k in oldList) { if (newList.Contains(k)) continue; new SqlDelete(fld.TableName) .Where( new Criteria(fld.UserId) == userID & new Criteria(fld.RoleId) == k) .Execute(uow.Connection); } foreach (var k in newList) { if (oldList.Contains(k)) continue; uow.Connection.Insert(new MyRow { UserId = userID, RoleId = k }); } BatchGenerationUpdater.OnCommit(uow, fld.GenerationKey); BatchGenerationUpdater.OnCommit(uow, Entities.UserPermissionRow.Fields.GenerationKey); return new SaveResponse(); }
public void GetParentsMultipleArbitraryCapitalists(MegaCorp megaCorp, ISet <ICapitalist> capitalists) { ISet <FatCat> expected = new HashSet <FatCat>(); foreach (ICapitalist capitalist in capitalists) { megaCorp.Add(capitalist); FatCat parent = capitalist.GetType() == typeof(FatCat) ? (FatCat)capitalist : capitalist.GetParent(); while (parent != null) { expected.Add(parent); parent = parent.GetParent(); } } ISet <FatCat> parents = megaCorp.GetParents(); Assert.True(expected.SetEquals(parents), "#GetParents() returned a set that did not equal the set of all parents of the added Capitalists"); }
public override bool Equals(object obj) { if (this == obj) { return(true); } if (obj == null || GetType() != obj.GetType()) { return(false); } Index ind = (Index)obj; if (currentVertex != ind.currentVertex) { return(false); } return(!(vertexSet != null ? !vertexSet.SetEquals(ind.vertexSet) : ind.vertexSet != null)); }
public void TestGetNamesOfAllNonemptyCells1() { Spreadsheet ss = new Spreadsheet(); Assert.IsFalse(ss.Changed); for (int i = 1; i <= 5; i++) // Set cells a1-5 { ss.SetContentsOfCell("a" + i, "Hello World"); } var cells = new HashSet <string>(ss.GetNamesOfAllNonemptyCells()); // Retrieve them. Assert.IsTrue(cells.SetEquals(new HashSet <string> { "A1", "A2", "A3", "A4", "A5" })); Assert.IsTrue(ss.Changed); }
public void TestPathingString5() { string pathingString = @"You leave me [no choice]."; List <string> pathingOptions = new List <string>() { "You leave me no choice." }; HashSet <string> pathingResults = new HashSet <string>(); for (int i = 0; i < 1000; i++) { string pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add(pathedString); } Assert.IsTrue(pathingResults.SetEquals(new HashSet <string>(pathingOptions))); }
public void TestGetAllKatalogByThisClient() { Katalog k1 = new Katalog("Lalka", new AutorKsiazki("Boleslaw", "Prus")); Katalog k2 = new Katalog("Pan Tadeusz", new AutorKsiazki("Adam", "Mickiewicz")); HashSet <Katalog> expectedHashSetKatalog = new HashSet <Katalog>(); expectedHashSetKatalog.Add(k1); expectedHashSetKatalog.Add(k2); DataRepository dataRepository = new DataRepository(context, plik); DataService dataService = new DataService(dataRepository); HashSet <Katalog> actual = dataService.GetAllKatalogBuyByThisClient(1); Assert.AreEqual(expectedHashSetKatalog.SetEquals(actual), true); }
public void TestPathingString6() { string pathingString = @"[There can be only one.]"; List <string> pathingOptions = new List <string>() { "There can be only one." }; HashSet <string> pathingResults = new HashSet <string>(); for (int i = 0; i < 1000; i++) { string pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add(pathedString); } Assert.IsTrue(pathingResults.SetEquals(new HashSet <string>(pathingOptions))); }
private static bool SetEquals(string source, params string[] components) { if (string.IsNullOrEmpty(source)) { return(false); } if (components == null || !components.Any()) { return(false); } var set = new HashSet <string>( collection: source.Split(' '), comparer: StringComparer.Ordinal); return(set.SetEquals(components)); }
/// <summary> /// Parse some json text and also return whether any fields are missing from the json /// </summary> /// <typeparam name="T">The type of the config file object</typeparam> /// <param name="json">The json text to parse</param> /// <param name="anyMissingFields">Whether any fields are missing from the config</param> /// <returns>The config object</returns> internal static T LoadConfigAndCheckForMissingFields <T>(string json, out bool anyMissingFields) { JObject jObject = JObject.Parse(json); anyMissingFields = false; var configFields = new HashSet <string>(typeof(T).GetFields() .Where(field => !field.IsStatic) .Select(field => field.Name)); var jsonFields = new HashSet <string>(jObject .Children() .Select(field => field as JProperty) .Where(field => field != null) .Select(field => field.Name)); anyMissingFields = !configFields.SetEquals(jsonFields); return(jObject.ToObject <T>()); }
public void ReplaceDependentsTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("a", "d"); t.AddDependency("g", "f"); t.AddDependency("m", "n"); HashSet <string> newDependents = new HashSet <string>(); newDependents.Add("m"); newDependents.Add("f"); newDependents.Add("z"); newDependents.Add("b"); t.ReplaceDependents("a", newDependents); Assert.IsTrue(newDependents.SetEquals(t.GetDependents("a"))); }
public void OfCloudFilesWithReadAllText() { FSharpFunc <string[], bool> .FromConverter(xs => { var cfiles = this.Run(xs.Select(text => MBrace.CloudFile.WriteAllText(text, null, null))); var x = this.Run(cfiles .AsCloudFlow <string>(CloudFileReader.ReadAllText) .ToArray()); var y = cfiles.Select(f => this.RunOnCurrentProcess(CloudFile.ReadAllText(f, null))); var s1 = new HashSet <string>(x); var s2 = new HashSet <string>(y); return(s1.SetEquals(s2)); }).QuickThrowOnFail(10); }