public void Test0()
        {
            var intArrows =
                new []
                {
                    new IntArrow<int>(0, 10),
                    new IntArrow<int>(2, 20),
                    new IntArrow<int>(5, 10, 30),
                };

            const int DefaultValue = -1;

            var target = new BinaryDecisionTreeBuilder(DefaultValue, platformInfo);
            var node = target.Build(intArrows);
            PrintProgram(node);

            Assert.AreEqual(DefaultValue, Eval(node, -1));
            Assert.AreEqual(10, Eval(node, 0));
            Assert.AreEqual(DefaultValue, Eval(node, 1));
            Assert.AreEqual(20, Eval(node, 2));
            Assert.AreEqual(DefaultValue, Eval(node, 3));
            Assert.AreEqual(DefaultValue, Eval(node, 4));
            Assert.AreEqual(30, Eval(node, 5));
            Assert.AreEqual(30, Eval(node, 10));
            Assert.AreEqual(DefaultValue, Eval(node, 11));
        }
Esempio n. 2
0
		public void TestSetup()
		{
            UmbracoExamineSearcher.DisableInitializationCheck = true;
            BaseUmbracoIndexer.DisableInitializationCheck = true;
            //we'll copy over the pdf files first
		    var svc = new TestDataService();
		    var path = svc.MapPath("/App_Data/Converting_file_to_PDF.pdf");
		    var f = new FileInfo(path);
		    var dir = f.Directory;
            //ensure the folder is there
            System.IO.Directory.CreateDirectory(dir.FullName);
            var pdfs = new[] { TestFiles.Converting_file_to_PDF, TestFiles.PDFStandards, TestFiles.SurviorFlipCup, TestFiles.windows_vista };
            var names = new[] { "Converting_file_to_PDF.pdf", "PDFStandards.pdf", "SurviorFlipCup.pdf", "windows_vista.pdf" };
		    for (int index = 0; index < pdfs.Length; index++)
		    {
		        var p = pdfs[index];
		        using (var writer = File.Create(Path.Combine(dir.FullName, names[index])))
		        {
		            writer.Write(p, 0, p.Length);
		        }
		    }

		    _luceneDir = new RAMDirectory();
			_indexer = IndexInitializer.GetPdfIndexer(_luceneDir);
			_indexer.RebuildIndex();
			_searcher = IndexInitializer.GetUmbracoSearcher(_luceneDir);
		}
Esempio n. 3
0
        public CodeTimerResult Time(int iteration, Action action)
        {
            // 1.
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            var gcCounts = new int[GC.MaxGeneration + 1];
            for (var i = 0; i <= GC.MaxGeneration; i++)
            {
                gcCounts[i] = GC.CollectionCount(i);
            }

            // 2.
            var watch = new Stopwatch();
            watch.Start();
            var cycleCount = GetCycleCount();
            for (var i = 0; i < iteration; i++) action();
            var cpuCycles = GetCycleCount() - cycleCount;
            watch.Stop();

            var gens = new [] { 0, 0, 0 };

            for (var i = 0; i < 3; i++)
            {
                if (i <= GC.MaxGeneration)
                {
                    gens[i] = GC.CollectionCount(i) - gcCounts[i];
                }
            }

            return new CodeTimerResult(watch.ElapsedMilliseconds, cpuCycles, gens[0], gens[1], gens[2]);
        }
            public void FiltersOutMissingProcesses()
            {
                var processes = new[]
                {
                    Process.Start("cmd.exe"),
                    Process.Start("cmd.exe"),
                };

                try
                {
                    var processHelper = new ProcessHelper();

                    var processIds = processes.Select(p => p.Id).ToList();
                    processIds.Add(1);

                    var result = processHelper.GetProcesses(processes.Select(p => p.Id));

                    Assert.Collection(result,
                        x => Assert.Equal(processes[0].Id, x.Id),
                        x => Assert.Equal(processes[1].Id, x.Id)
                    );
                }
                finally
                {
                    foreach (var p in processes)
                        p.Kill();
                }
            }
        private void RunGremlinTest(string filePath)
        {
            var exifReader = new ExifReader();
            var sw = Stopwatch.StartNew();

            var app1 = File.ReadAllBytes(filePath);
            var segments = new[] { app1 };

            for (var i = 0; i < app1.Length; i++)
            {
                if (i % 1000 == 0)
                    _output.WriteLine($"{i}/{app1.Length} bytes");

                var original = app1[i];

                for (var b = byte.MinValue; b < byte.MaxValue; b++)
                {
                    app1[i] = b;

                    // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
                    exifReader.ReadJpegSegments(segments, JpegSegmentType.App1).ToList();
                }

                app1[i] = original;
            }

            _output.WriteLine($"Finished in {sw.Elapsed.TotalSeconds:#,##0.#} seconds");
        }
Esempio n. 6
0
        public void Can_have_meaningful_ids_on_documents()
        {
            var city = new
            {
                Id = "usa/pa/philadelphia",
                Name = "Philadelphia",
                State = "Pennsylvania"
            };

            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    session.Store(city);
                    session.SaveChanges();
                }

                // start another session for test purposes
                using (var session = store.OpenSession())
                {
                    var result = session.Load<dynamic>("usa/pa/philadelphia");
                    // we just loaded a document with a meaninful id
                    ((string)result.Name).Should().Be("Philadelphia");
                }
            }
        }
        public void FindView_ReturnsExpectedNotFoundResult_WithGetViewLocations()
        {
            // Arrange
            var expectedLocations = new[] { "location1", "location2" };
            var context = GetActionContext();
            var executor = GetViewExecutor();

            var viewName = "myview";
            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine
                .Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ true))
                .Returns(ViewEngineResult.NotFound("myview", expectedLocations));
            viewEngine
                .Setup(e => e.FindView(context, "myview", /*isMainPage*/ true))
                .Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty<string>()));

            var viewResult = new ViewResult
            {
                ViewName = viewName,
                ViewEngine = viewEngine.Object,
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData = Mock.Of<ITempDataDictionary>(),
            };

            // Act
            var result = executor.FindView(context, viewResult);

            // Assert
            Assert.False(result.Success);
            Assert.Null(result.View);
            Assert.Equal(expectedLocations, result.SearchedLocations);
        }
        private void SimpleCalloutButtonClicked(object sender, System.EventArgs e)
        {
            var callout = SimpleIoc.Default.GetInstance<ICallout>();

            var buttonConfigs = new[] { new ButtonConfig("OK") };

            callout.Show("Simple Callout", "Message with some text.", buttonConfigs);
        }
 private IAnalysisSet SequenceIter(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
     if (_iterator == null) {
         var types = new [] { new VariableDef() };
         types[0].AddTypes(unit, _indexTypes, false);
         _iterator = new IteratorInfo(types, IteratorInfo.GetIteratorTypeFromType(ClassInfo, unit), node);
     }
     return _iterator ?? AnalysisSet.Empty;
 }
 public void IsSurroundedBy_detects_when_not_surrounded_on_three_diagonals()
 {
     var rectangles = new[]
     {
         new Rectangle(0, 0, 50, 50),
     };
     var result = new Point(50, 50).IsSurroundedBy(rectangles);
     Assert.Equal(false, result);
 }
Esempio n. 11
0
 public void PlayDifferentMusicOnClick()
 {
     new FontText(Font.Default, "Click to Play", Rectangle.One);
     var music = ContentLoader.Load<Music>("DefaultMusic");
     var music2 = ContentLoader.Load<Music>("DefaultMusicBackwards");
     var musics = new[] { music, music2 };
     int index = 0;
     new Command(() => musics[(index++) % 2].Play(1f)).Add(new MouseButtonTrigger());
 }
Esempio n. 12
0
 internal static void Init()
 {
     var threadMacro = new[] { new ShaderMacro("NUMTHREADS", 8) };
     //MyRender11.RegisterSettingsChangedListener(new OnSettingsChangedDelegate(RecreateShadersForSettings));
     m_bloomShader = MyShaders.CreateCs("bloom_init.hlsl",threadMacro);
     m_downscaleShader = MyShaders.CreateCs("bloom_downscale.hlsl", threadMacro);
     m_blurH = MyShaders.CreateCs("bloom_blur_h.hlsl", threadMacro);
     m_blurV = MyShaders.CreateCs("bloom_blur_v.hlsl", threadMacro);
 }
        internal static void Init()
        {
            var threadMacros = new[] { new ShaderMacro("NUMTHREADS", NUM_THREADS) };
            m_initialShader = MyShaders.CreateCs("luminance_reduction_init.hlsl", threadMacros);
            m_sumShader = MyShaders.CreateCs("luminance_reduction.hlsl", threadMacros);

            threadMacros = new[] { new ShaderMacro("NUMTHREADS", NUM_THREADS), new ShaderMacro("_FINAL", null) };
            m_finalShader = MyShaders.CreateCs("luminance_reduction.hlsl", threadMacros);
        }
        public MainWindow()
        {
            InitializeComponent();

            //AddHandler(MouseRightButtonDownEvent, new MouseButtonEventHandler(Window_MouseRightButtonDown), true);
            AddHandler(CustomButton.BubbledClickEvent, new RoutedEventHandler(AddBorder));

            MouseDown += (s, e) =>
            {
                TheText.Background = Brushes.Beige;
            };

            TheText.MouseDown += (s, e) =>
            {
                TheText.Background = Brushes.Azure;
                //This keeps the MouseDown handler on the window from raising
                e.Handled = true;
            };

            //MouseEnter is registered with a Direct routing strategy
            MouseEnter += (s, e) =>
            {
                TheText.Foreground = Brushes.Blue;
            };

            TheText.MouseEnter += (s, e) =>
            {
                TheText.Foreground = Brushes.Red;
            };

            TheOuterButton.Click += (s, e) =>
            {
                TheOuterButton.BorderBrush = new SolidColorBrush(new Color { R = 120, G = 145, B = 135 });
            };

            TheInnerButton.Click += (s, e) =>
            {
                TheOuterButton.BorderBrush = new SolidColorBrush(new Color { R = 45, G = 20, B = 35 });
                e.Handled = true;
            };

            //Setting handled here keeps the TextInput event on the TextBox from firing
            TheTextBox.PreviewTextInput += (s, e) =>
            {
                var numbers = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
                if (e.Text.ToCharArray().All(x => !numbers.Contains(x)))
                    e.Handled = true;
            };

            TheCustomButton.DirectClick += (s, e) => Debug.WriteLine("Outer Direct Click");
            TheCustomButton.TunneledClick += (s, e) => Debug.WriteLine("Outer Tunneled Click");
            TheCustomButton.BubbledClick += (s, e) => Debug.WriteLine("Outer Bubbled Click");
            TheInnerCustomButton.DirectClick += (s, e) => Debug.WriteLine("Inner Direct Click");
            TheInnerCustomButton.TunneledClick += (s, e) => Debug.WriteLine("Inner Tunneled Click");
            TheInnerCustomButton.BubbledClick += (s, e) => Debug.WriteLine("Inner Bubbled Click");
        }
        public void EuclidGcdManyArgsTimeTest()
        {
            int[] array = new[] {9, 15, 21, 33, 99, 102};
            long period;

            int result = Gcd.EuclidGcd(out period, array);
            Debug.WriteLine(period);

            Assert.AreEqual(3, result);
        }
 public void TestRepeatCloseMulti()
 {
     var reader = PrepareImporterWithFile("GuitarPro5\\RepeatCloseMulti.gp5");
     var score = reader.ReadScore();
     var expectedIndexes = new[]
     {
         0,1,0,1,0,1,0,1,2
     };
     TestRepeat(score, expectedIndexes);
 }
        public void TestRepeatCloseAlternateEndings()
        {
            var reader = PrepareImporterWithFile("GuitarPro5\\RepeatCloseAlternateEndings.gp5");
            var score = reader.ReadScore();
            var expectedIndexes = new[]
            {
                0,1,0,2,3,0,1,0,4
            };

            TestRepeat(score, expectedIndexes);
        }
        public void TestRepeatCloseWithoutStartAtBeginning()
        {
            var reader = PrepareImporterWithFile("GuitarPro5\\RepeatCloseWithoutStartAtBeginning.gp5");
            var score = reader.ReadScore();
            var expectedIndexes = new[]
            {
                0,1,0,1
            };

            TestRepeat(score, expectedIndexes);
        }
 public void SortTest()
 {
     var unsorted = new[] { 5, 3, 4, 1, 10, 3, 59 };
     var sorter = new MergeSortForIntegerArray();
     var result = sorter.Sort(unsorted);
     Debug.Print(result.Select(x => string.Format("{0}", x)).Aggregate((x, y) => x + ", " + y));
     //Assert.That(result.Length, Is.EqualTo(3));
     //Assert.That(result[0], Is.EqualTo(3));
     //Assert.That(result[1], Is.EqualTo(4));
     //Assert.That(result[2], Is.EqualTo(5));
 }
Esempio n. 20
0
        public void TestExtractRows()
        {
            var cols = new[] {1, 3};
            var M = Matrix<float>.Build;
            var matrix = M.Dense(5, 7, (i, j) => 0.001f*i + 0.01f*j);

            Debug.WriteLine(MathNetUtils.FormatMatrix("0.0000", matrix));

            var result = MathNetUtils.ExtractRows(matrix, cols);
            Debug.WriteLine(MathNetUtils.FormatMatrix("0.0000", result));
        }
		public void Can_set_up_config()
		{
			var run = new[]{
				"add_vhost mt",
				"add_user -p mt testUser topSecret",
				@"set_permissions -p mt testUser "".*"" "".*"" "".*"""
			};

			foreach (var s in run)
				Process.Start("rabbitmqctl.bat", s);
		}
        public void CSharp_VerifyISymbol()
        {
            var source = @"
class Foo : Microsoft.CodeAnalysis.ISymbol { }
class Bar : Microsoft.CodeAnalysis.IAssemblySymbol { }
";
            DiagnosticResult[] expected = new[] { GetCSharpExpectedDiagnostic(2, 7, "Foo", "ISymbol"), GetCSharpExpectedDiagnostic(3, 7, "Bar", "ISymbol") };

            // Verify that ISymbol is not implementable.
            VerifyCSharp(source, addLanguageSpecificCodeAnalysisReference: true, expected: expected);
        }
        public void CSharp_VerifyISymbol()
        {
            var source = @"
// Causes many compile errors, because not all members are implemented.
class Foo : Microsoft.CodeAnalysis.ISymbol { }
class Bar : Microsoft.CodeAnalysis.IAssemblySymbol { }
";
            DiagnosticResult[] expected = new[] { GetCSharpExpectedDiagnostic(3, 7, "Foo", "ISymbol"), GetCSharpExpectedDiagnostic(4, 7, "Bar", "ISymbol") };

            // Verify that ISymbol is not implementable.
            VerifyCSharp(source, addLanguageSpecificCodeAnalysisReference: true, validationMode: TestValidationMode.AllowCompileErrors, expected: expected);
        }
Esempio n. 24
0
        private static void QuickTest()
        {
            var words = new[] { "Управляващите", "ПРОТЕСТИРАЩИТЕ" };

            var stemmer = new BulgarianStemmer();

            foreach (string word in words)
            {
                string stem = stemmer.Stem(word);
                System.Console.WriteLine("{0} => {1}", word, stem);
            }
        }
Esempio n. 25
0
        protected static void CopyData(string sourcePath, string destinationPath)
        {
            var tables = new[] { "customers", "orders" };
            var extensions = new[] { ".dbf", ".cdx" };

            for (int tableIndex = 0, tableTotal = tables.Length; tableIndex < tableTotal; tableIndex++) {
                for (int extensionIndex = 0, extensionTotal = extensions.Length; extensionIndex < extensionTotal; extensionIndex++) {
                    var file = tables[tableIndex] + extensions[extensionIndex];
                    File.Copy(Path.Combine(sourcePath, file), Path.Combine(destinationPath, file), true);
                }
            }
        }
 public void IsSurroundedBy_detects_when_surrounded_by_four_corners()
 {
     var rectangles = new[]
     {
         new Rectangle(0, 0, 50, 50),
         new Rectangle(50, 40, 30, 10),
         new Rectangle(-10, 50, 60, 90),
         new Rectangle(50, 50, 80, 5),
     };
     var result = new Point(50, 50).IsSurroundedBy(rectangles);
     Assert.Equal(true, result);
 }
        private void ContentCalloutButtonClicked(object sender, System.EventArgs e)
        {
            var callout = SimpleIoc.Default.GetInstance<ICallout>();

            var okButtonConfig = new ButtonConfig("I Agree", () => { Debug.WriteLine("AGREED!"); }, isEnabled: false);
            var cancelButtonConfig = new ButtonConfig("I Decline");
            var buttonConfigs = new[] { okButtonConfig, cancelButtonConfig };

            var customCallout = SimpleIoc.Default.GetInstance<ICustomCallout>();
            var customCalloutContent = customCallout.GetContent(okButtonConfig);

            callout.Show("Content Callout", customCalloutContent, buttonConfigs);
        }
 public void IsSurroundedBy_detects_when_not_surrounded_at_all()
 {
     var rectangles = new[]
     {
         new Rectangle(0, 0, 10, 10),
         new Rectangle(0, 10, 10, 10),
         new Rectangle(0, 20, 10, 10),
         new Rectangle(0, 30, 10, 10),
         new Rectangle(0, 40, 10, 10),
     };
     var result = new Point(50, 50).IsSurroundedBy(rectangles);
     Assert.Equal(false, result);
 }
        public override void Seed()
        {
            if (_entities.Query<Place>().Any()) return;

            var earth = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = GeoPlanetPlace.EarthWoeId });
            Debug.Assert(earth != null);

            var geoPlanetContinents = _geoPlanet.Continents()
                .OrderBy(c => c.Name)
                .ToArray()
            ;
            foreach (var geoPlanetContinent in geoPlanetContinents)
            {
                var continent = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = geoPlanetContinent.WoeId });
                Debug.Assert(continent != null);
            }

            //var countriesToImport = new[]
            //{
            //    "United States", "China", "United Kingdom", "Peru", "South Africa", "Australia", "India", "Egypt",
            //};
            var countriesToImport = new[]
            {
                "United States", "China", "United Kingdom",
            };
            var geoPlanetCountries = _geoPlanet.Countries()
                .Where(c => countriesToImport.Contains(c.Name))
                .OrderBy(c => c.Name)
                .ToArray()
            ;
            foreach (var geoPlanetCountry in geoPlanetCountries)
            {
                var country = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = geoPlanetCountry.WoeId });
                Debug.Assert(country != null);
            }

            foreach (var geoPlanetCountry in geoPlanetCountries)
            {
                var geoPlanetStates = _geoPlanet.States(geoPlanetCountry.WoeId)
                    .OrderBy(s => s.Name)
                    .Take(5)
                    .ToArray()
                ;
                if (!geoPlanetStates.Any()) continue;
                foreach (var geoPlanetState in geoPlanetStates)
                {
                    var state = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = geoPlanetState.WoeId });
                    Debug.Assert(state != null);
                }
            }
        }
Esempio n. 30
0
        public string ShouldReturnMetadata(string path, MetadataKind properties)
        {
            IMetadataElement element;

            Assert.That(TryGetMetadata(path, out element), Is.True);
            Assert.That(element, Is.Not.Null);

            var ignoredFeatures = new[] { typeof(EntityIdentityFeature), typeof(ElementMappingFeature), typeof(EntityRelationContainmentFeature) };
            element.Dump(properties, ignoredFeatures);

            Debug.WriteLine((string)element.Serialize(properties, ignoredFeatures));

            return element.Serialize(properties, ignoredFeatures);
        }