static JsonTypeInspector()
        {
            var numericElementTypes = new[] { typeof(byte), typeof(sbyte), typeof(Int16), typeof(Int32), typeof(UInt16), typeof(UInt32), typeof(float), typeof(Int64), typeof(UInt64), typeof(double) };
            var enumerableType = typeof(IEnumerable<string>).GetGenericTypeDefinition();
            var dictType = typeof(IDictionary<string, int>).GetGenericTypeDefinition();

            SupportedTypes = new[]
            {
                typeof(char),
                typeof(bool),
                typeof(string),
                typeof(double),
                typeof(float),
                typeof(byte),
                typeof(decimal),
                typeof(UInt16),
                typeof(UInt32),
                typeof(UInt64),
                typeof(Int16),
                typeof(Int32),
                typeof(Int64),
            }
            .Union(numericElementTypes.Select(valueType => enumerableType.MakeGenericType(valueType)))
            .Union(numericElementTypes.Select(valueType => valueType.MakeArrayType()))
            .ToArray();

            DictTypes = numericElementTypes
                .Select(valueType => dictType.MakeGenericType(typeof(string), valueType))
                .ToArray();
        }
        public void BitsDownloadsSomeUrls()
        {
            var urls = new[] {
                "https://a248.e.akamai.net/assets.github.com/images/modules/about_page/octocat.png",
                "https://a248.e.akamai.net/assets.github.com/images/modules/about_page/github_logo.png",
            };

            var files = new[] {
                "octocat.png",
                "gh_logo.png",
            };

            string tempPath = null;
            using (Utility.WithTempDirectory(out tempPath))
            using (var fixture = new BitsUrlDownloader("BITSTests")) {
                fixture.QueueBackgroundDownloads(urls, files.Select(x => Path.Combine(tempPath, x)))
                    .Timeout(TimeSpan.FromSeconds(120), RxApp.TaskpoolScheduler)
                    .Last();

                files.Select(x => Path.Combine(tempPath, x))
                    .Select(x => new FileInfo(x))
                    .ForEach(x => {
                        x.Exists.ShouldBeTrue(); 
                        x.Length.ShouldNotEqual(0);
                    });
            }
        }
Exemple #3
0
 public void Problem11()
 {
     string text = Console.ReadLine();
     var list = new []{new {C = text[0], Val = 0}}.ToList();
     for (int i = 1; i < text.Length; i++)
     {
         if (text[i] > text[i - 1])
         {
             list.Add(new { C = text[i], Val = list[i - 1].Val + 1 });
         }
         else if (text[i] < text[i - 1])
         {
             list.Add(new { C = text[i], Val = list[i - 1].Val - 1 });
         }
         else list.Add(new { C = text[i], Val = list[i - 1].Val });
     }
     int min = list.Select(x => x.Val).Min();
     int max = list.Select(x => x.Val).Max();
     for (int i = max; i >= min; i--)
     {
         foreach (var item in list)
         {
             if (item.Val == i) Console.Write(item.C);
             else Console.Write(' ');
         }
         Console.WriteLine();
     }
 }
        public void AutoInherit()
        {
            using (var container = new RhetosTestContainer())
            {
                var names = new[] { "1", "1b", "2", "3", "4" };
                var itemsE4 = names.Select(name => new TestRowPermissions4.E4 { ID = Guid.NewGuid(), Name4 = name }).ToList();
                var itemsE3 = names.Select((name, x) => new TestRowPermissions3.E3 { ID = Guid.NewGuid(), Name3 = name, E4 = itemsE4[x] }).ToList();
                var itemsE2 = names.Select((name, x) => new TestRowPermissions2.E2 { ID = Guid.NewGuid(), Name2 = name, E3 = itemsE3[x] }).ToList();
                var itemsE1 = names.Select((name, x) => new TestRowPermissions1.E1 { ID = Guid.NewGuid(), Name1 = name, E2 = itemsE2[x] }).ToList();

                var reposE1 = container.Resolve<GenericRepository<TestRowPermissions1.E1>>();
                var reposE1Browse = container.Resolve<GenericRepository<TestRowPermissions1.E1Browse>>();
                var reposE1BrowseRP = container.Resolve<GenericRepository<TestRowPermissions1.E1BrowseRP>>();
                var reposE2 = container.Resolve<GenericRepository<TestRowPermissions2.E2>>();
                var reposE3 = container.Resolve<GenericRepository<TestRowPermissions3.E3>>();
                var reposE4 = container.Resolve<GenericRepository<TestRowPermissions4.E4>>();

                reposE4.Save(itemsE4, null, reposE4.Read());
                reposE3.Save(itemsE3, null, reposE3.Read());
                reposE2.Save(itemsE2, null, reposE2.Read());
                reposE1.Save(itemsE1, null, reposE1.Read());

                Assert.AreEqual("4", TestUtility.DumpSorted(reposE4.Read<Common.RowPermissionsReadItems>(), item => item.Name4));
                Assert.AreEqual("3->3", TestUtility.DumpSorted(reposE3.Read<Common.RowPermissionsReadItems>(), item => item.Name3 + "->" + item.E4.Name4));
                Assert.AreEqual("2, 3", TestUtility.DumpSorted(reposE2.Read<Common.RowPermissionsReadItems>(), item => item.Name2));
                Assert.AreEqual("1, 2, 3", TestUtility.DumpSorted(reposE1.Read<Common.RowPermissionsReadItems>(), item => item.Name1));
                Assert.AreEqual("1, 2, 3", TestUtility.DumpSorted(reposE1Browse.Read<Common.RowPermissionsReadItems>(), item => item.Name1Browse));
                Assert.AreEqual("1, 1b, 2, 3", TestUtility.DumpSorted(reposE1BrowseRP.Read<Common.RowPermissionsReadItems>(), item => item.Name1Browse));
            }
        }
Exemple #5
0
 public void TestCallInfoHashCodeUniqueness()
 {
     var types = new[] { typeof(A1), typeof(B1), typeof(A2), typeof(B2) };
     var infos = types.Select( t => new CallInfo( t, Type.EmptyTypes, Flags.InstanceAnyVisibility, MemberTypes.Property, "P1", Type.EmptyTypes, null, true ) );
     Assert.AreEqual( types.Length, infos.Select( ci => ci.GetHashCode() ).Distinct().Count() );
     infos = types.Select( t => new CallInfo( t, Type.EmptyTypes, Flags.InstanceAnyVisibility, MemberTypes.Property, "P2", Type.EmptyTypes, null, true ) );
     Assert.AreEqual( types.Length, infos.Select( ci => ci.GetHashCode() ).Distinct().Count() );
 }
        public void CanAccelerateViewsByPartitioning()
        {
            // SomeRootView is intentionally slow - it takes ~ 1 second to process each event, so unless we process these
            // two bad boys in parallel, we're not going to make it in 15 seconds
            var viewManagers = new[]
            {
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view1", "Position"), 
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view2", "Position"),
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view3", "Position"),
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view4", "Position"),
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view5", "Position"), 
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view6", "Position"),
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view7", "Position"),
                new MongoDbViewManager<SomeRootView>(_mongoDatabase, "view8", "Position"),
            };

            var firstCommandProcessor = CreateCommandProcessor("1", viewManagers);
           
            CreateCommandProcessor("2", viewManagers);
            
            CreateCommandProcessor("3", viewManagers);
            
            CreateCommandProcessor("4", viewManagers);
            
            CreateCommandProcessor("5", viewManagers);
            
            CreateCommandProcessor("6", viewManagers);
            
            CreateCommandProcessor("7", viewManagers);
            
            CreateCommandProcessor("8", viewManagers);

            var lastResult = Enumerable.Range(0, 20)
                .Select(i => firstCommandProcessor.ProcessCommand(new MakeSomeRootDoStuff("bimse")))
                .Last();

            var goal = TimeSpan.FromSeconds(45);

            using (var statusTimer = new Timer(5000))
            {
                var state = new MongoDbAutoDistributionState(_mongoDatabase, "AutoDistribution");
                statusTimer.Elapsed += (o, ea) =>
                {
                    Console.WriteLine(@"--------------------------------------------
Distribution:
{0}

Views:
{1}",
    string.Join(Environment.NewLine, state.GetCurrentState().Select(s => string.Format("    {0}: {1}", s.ManagerId, string.Join(", ", s.ViewIds)))),
    string.Join(Environment.NewLine, viewManagers.Select(v => string.Format("    {0}: {1}", v.GetPosition().Result, v.GetType().GetPrettyName()))));
                };
                statusTimer.Start();

                Task.WaitAll(viewManagers.Select(v => v.WaitUntilProcessed(lastResult, goal)).ToArray());
            }
        }
    public override IOperation Apply() {
      var encoding = EncodingParameter.ActualValue;
      var results = ResultsParameter.ActualValue;
      var random = RandomParameter.ActualValue;

      IEnumerable<IScope> scopes = new[] { ExecutionContext.Scope };
      for (var i = 0; i < QualityParameter.Depth; i++)
        scopes = scopes.Select(x => (IEnumerable<IScope>)x.SubScopes).Aggregate((a, b) => a.Concat(b));

      var individuals = scopes.Select(encoding.GetIndividual).ToArray();
      AnalyzeAction(individuals, QualityParameter.ActualValue.Select(x => x.Value).ToArray(), results, random);
      return base.Apply();
    }
        static BsonValueMemberProvider()
        {
            HashSet<string> ignored =new HashSet<string>
            {
                //special props
                "Item",
                "AsByteArray",
                "AsLocalTime",
                "AsRegex",
                "AsString",
                "AsUniversalTime",
                "AsStringOrNull",
                "IsNumeric",
                "IsString",
                "AsBsonValue"
            };
            //special names appearing in multiple props
            string[] toIgnore = new[]
                {
                    "Boolean",
                    "DateTime",
                    "Double",
                    "Guid",
                    "Int32",
                    "Int64",
                    "ObjectId"
                };
            AddRange(ignored, toIgnore.Select(x =>
                    string.Concat("As", x)
                ));
            AddRange(ignored, toIgnore.Select(x =>
                    string.Concat("AsNullable", x)
                ));
            AddRange(ignored, toIgnore.Select(x =>
                    string.Concat("Is", x)
                ));

            //bson types
            string[] types = Enum.GetNames(typeof(BsonType))
                .Concat(new []
                {
                    "BinaryData"
                }).ToArray();
            AddRange(ignored, types.Select(x =>
                    string.Concat("AsBson", x)
                ));
            AddRange(ignored, types.Select(x =>
                    string.Concat("IsBson", x)
                ));
            IgnoredProperties = ignored;
        }
Exemple #9
0
        static void Main(string[] args)
        {
            var bus = new Bus(new Dispatcher.Dispatcher());
            var printers = new[] { new Printer(bus, 1), new Printer(bus, 2), new Printer(bus, 3), new Printer(bus, 4) };

            var printerPool = printers
                .Select(printer => new WideningHandler<PrintJob, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            var refillPool = printers
                .Select(printer => new WideningHandler<RefillPaper, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            foreach (var printer in refillPool)
            {
                bus.Subscribe<RefillPaper>(new NarrowingHandler<RefillPaper, Message>(printer));
                // subscribe the printer directly to RefillPaper as we don't want to distribute that with the print jobs
            }

            var office = Enumerable.Range(0, 50)
                .Select(i => new Employee(bus, i))
                .ToArray();

            var loadBalancer = new RoundRobinLoadBalancer(printerPool);
            var printerRetryHandler = new RetryHandler(loadBalancer, bus);
            var retryManager = new RetryManager(bus);
            var timerService = new TimerService(bus);

            bus.Subscribe<FutureMessage>(timerService);
            bus.Subscribe<RetryMessage>(retryManager);
            bus.Subscribe<SuccessMessage>(retryManager);

            bus.Subscribe(new NarrowingHandler<PrintJob, Message>(printerRetryHandler));

            var console = new QueuedHandler(new WideningHandler<LogMessage, Message>(new ConsoleHandler()), bus);
            bus.Subscribe<LogMessage>(new NarrowingHandler<LogMessage, Message>(console));

            var porter = new Porter(bus);
            bus.Subscribe(porter);

            var converter = new LogConverter(bus);
            bus.Subscribe<PrintJob>(converter);
            bus.Subscribe<OutOfPaper>(converter);
            bus.Subscribe<PagePrinted>(converter);
            bus.Subscribe<RetryMessage>(converter);
        }
        // ReSharper disable once InconsistentNaming
        public async Task AddAllEpisodesAsync_should_add_all_episodes_to_show()
        {
            var episodesClient = Substitute.For<IEpisodesClient>();
            var advancedEpisodesClient = Substitute.For<IAdvancedEpisodeClient>();
            var advancedSeriesClient = Substitute.For<IAdvancedSeriesClient>();

            var fetcher = new EpisodeFetcher(episodesClient, advancedEpisodesClient, advancedSeriesClient);

            var show = new Show
            {
                TheTvDbId = 42
            };

            var basics = new[]
            {
                new BasicEpisode
                {
                    Id = 1
                },
                new BasicEpisode
                {
                    Id = 2
                },
                new BasicEpisode
                {
                    Id = 3
                }
            };

            var episodeRecords = basics.Select(x => new EpisodeRecord
            {
                Id = x.Id,
                AiredEpisodeNumber = 0,
                AiredSeason = 0
            });

            Expression<Predicate<IEnumerable<int>>> isIdsOfBasics = x => x.SequenceEqual(basics.Select(e => e.Id));

            advancedSeriesClient.GetBasicEpisodesAsync(show.TheTvDbId).Returns(basics);

            advancedEpisodesClient.GetFullEpisodesAsync(Arg.Is(isIdsOfBasics)).Returns(episodeRecords);

            await fetcher.AddAllEpisodesAsync(show);

            Assert.Equal(basics.Length, show.Episodes.Count);

            Assert.True(show.Episodes.Select(x => x.TheTvDbId).SequenceEqual(basics.Select(e => e.Id)));
        }
Exemple #11
0
        public void Run()
        {
            using (var reader = new StreamReader("dijkstraData.txt"))
            using (var writer = new StreamWriter("output.txt"))
            {
                var graph = new DirectedWeightedGraph();
                while (true)
                {
                    string row = reader.ReadLine();
                    if (row == null)
                    {
                        break;
                    }

                    var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    var from = int.Parse(parts[0], CultureInfo.InvariantCulture) - 1;
                    foreach (var part in parts.Skip(1))
                    {
                        var tuple = part.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        var to = int.Parse(tuple[0], CultureInfo.InvariantCulture) - 1;
                        var weight = int.Parse(tuple[1], CultureInfo.InvariantCulture);
                        graph.AddEdge(from, to, weight);
                    }
                }

                var vertices = new[] { 6, 36, 58, 81, 98, 114, 132, 164, 187, 196 };

                var distances = Dijkstra.Find(graph, 0).ToArray();
                var result = string.Join(",", vertices.Select(v => distances[v]));
                writer.WriteLine(result);
            }
        }
Exemple #12
0
 public static IMarkdown ToMarkdown(this ITestCase testCase, CultureInfo culture)
 {
     Func<IMarkdown> renderGain = () =>
     {
         var testExecutionTime = testCase.Test.ExecutionTime;
         var benchmarkExecutionTime = testCase.Benchmark.ExecutionTime;
         if (testExecutionTime < 1.0 || benchmarkExecutionTime < 1.0)
             return Markdown.Empty;
         var gain = (testExecutionTime/benchmarkExecutionTime) - 1.0;
         gain *= 100.0;
         if (Math.Abs(gain) < 5.0)
             return Markdown.Empty;
         return
             Markdown.Empty
             .Add("  ")
             .Add(
                 Markdown.Create(() => string.Format(culture, "{0:+0.0;-0.0;0.0}%", gain))
                 .InlineCode());
     };
     return Markdown.Create(() =>
     {
         var result = testCase.Name.ToMarkdown();
         if (testCase.Benchmark != null)
             result = result.Add(renderGain());
         result = result.H3().NewLine().NewLine();
         IEnumerable<ITest> tests = new[] { testCase.Test };
         if (testCase.Benchmark != null)
             tests = tests.Concat(new[] {testCase.Benchmark});
         return result.Add(tests.Select(t => t.ToMarkdown().NewLine()).AsLines());
     });
 }
        public MapPage()
        {
            // set current culture to force map to show localized data
            Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU");

            InitializeComponent();

            var viewModels = new[]
                                 {
                                     new PushpinDummyViewModel
                                         {
                                             ContentVisibility = Visibility.Visible,
                                             Position = new GeoCoordinate(53.905153, 27.558230),
                                         },
                                     new PushpinDummyViewModel
                                         {
                                             ContentVisibility = Visibility.Collapsed,
                                             State = PushPinState.Expanded,
                                             Position = new GeoCoordinate(53.916153, 27.569230),
                                         },
                                     new PushpinDummyViewModel
                                         {
                                             ContentVisibility = Visibility.Collapsed,
                                             State = PushPinState.Collapsed,
                                             Position = new GeoCoordinate(53.913153, 27.567230),
                                         }
                                 };
            mapItemsControl.ItemsSource = viewModels;

            var geoCoordinatesRect = new GeoCoordinatesRect(viewModels.Select(m => m.Position));
            PushpinArea.SetValue(MapLayer.LocationRectangleProperty, geoCoordinatesRect);
        }
Exemple #14
0
 public static TestCase<Scenario>[] RunAParameterizedTest()
 {
     var testCases = new[]
     {
         new
         {
             x = new DateTimeOffset(2002, 10, 12, 18, 15, 0, TimeSpan.FromHours(1)),
             y = new DateTimeOffset(2007,  4, 21, 18, 15, 0, TimeSpan.FromHours(1))
         },
         new
         {
             x = new DateTimeOffset(1970, 11, 25, 16, 10, 0, TimeSpan.FromHours(1)),
             y = new DateTimeOffset(1972,  6,  6,  8,  5, 0, TimeSpan.FromHours(1))
         },
         new
         {
             x = new DateTimeOffset(2014, 3, 2, 17, 18, 45, TimeSpan.FromHours(1)),
             y = new DateTimeOffset(2014, 3, 2, 17, 18, 45, TimeSpan.FromHours(0))
         }
     };
     return testCases
         .Select(tc =>
             new TestCase<Scenario>(
                 s => s.AParameterizedTest(tc.x, tc.y)))
         .ToArray();
 }
Exemple #15
0
        public void DontBreakPresentation()
        {
            //class and collection initializers
            var magnus = new Person {Name = "Magnus Lidbom"};
            IEnumerable<string> names = new[] {"Calle", "Oscar"};

            //extension methods
            var first = names.First();

            //inf
            var alsoNames = names;

            //Anonymous types
            var address = new {Street = "AStreet", Zip = "111111"};

            //lambda
            var upperCaseNames = names.Select(name => name.ToUpper());

            //expr
            Expression<Func<string, bool>> isUpperCased = test => test == test.ToUpper();

            //comprehension syntax
            var lowerCaseNames = from name in names
                                 select name.ToLower();
        }
        public SampleTranscodingListViewModel() : base(new MockTranscodingListView(), null)
        {
            var musicFiles = new[] 
            {
                new SampleMusicFile(new MusicMetadata(new TimeSpan(0, 3, 45), 320000)
                {
                    Artists = new[] { @"Culture Beat" },
                    Title = @"Serenity (Epilog)",
                }, @"C:\Users\Public\Music\Dancefloor\Culture Beat - Serenity.waf"),
                new SampleMusicFile(new MusicMetadata(new TimeSpan(0, 2, 2), 320000)
                {
                    Artists = new[] { "First artist", "Second artist" },
                    Title = "This track has a very long title. Let's see how the UI handles this.",
                }, @"C:\Users\Public\Music\test.m4a"),
                new SampleMusicFile(new MusicMetadata(new TimeSpan(1, 33, 0), 320000)
                {
                    Artists = new string[0],
                    Title = "",
                }, @"C:\Users\Public\Music\Dancefloor\Culture Beat - Serenity.mp4"),
            };
            var transcodingManager = new TranscodingManager();
            musicFiles.Select(x => new TranscodeItem(x, x.FileName + ".mp3")).ToList().ForEach(transcodingManager.AddTranscodeItem);
            transcodingManager.TranscodeItems[0].Progress = 1;
            transcodingManager.TranscodeItems[1].Progress = 0.27;
            transcodingManager.TranscodeItems[2].Error = new InvalidOperationException("Test");
            TranscodingManager = transcodingManager;

            SelectedTranscodeItems.Add(transcodingManager.TranscodeItems.Last());
        }
Exemple #17
0
        public void ClaimComparison()
        {
            var equals = new[]
            {
                "a/b a/b",
                "a/b a/B",
                "a/b A/B",
                "a/ A/",
            };

            foreach (var test in equals.Select(t => ca(t)))
                Assert.AreEqual(test[0], test[1]);

            var notEquals = new[]
            {
                "a/b a.b/",
                "a/b.c a.b/c",
                "a/b /a.b",
                "a/b aa/bb",
                "a/ a/b",
            };

            foreach (var test in notEquals.Select(t => ca(t)))
                Assert.AreNotEqual(test[0], test[1]);
        }
        //Protected methods (called by the public methods in parent class)
        protected override void DoTrain(System.Drawing.Bitmap[] charImgs)
        {
            double[][] input = charImgs.Select(img => Converters.ThresholdedBitmapToDoubleArray(img)).ToArray();

            kpca = new KernelPrincipalComponentAnalysis(input, kernel, AnalysisMethod.Center);
            kpca.Compute();
        }
        public void NamespacesElided() 
        {
            var types = new[] { 
                                typeof(int),
                                typeof(TypeScriberTests),
                                typeof(System.Reflection.Assembly)
                            };

            var typeScriber = new TypeScriber(types.Select(t => t.Namespace));

            var namespaceHash = new HashSet<string>(types.Select(t => t.Namespace));

            foreach(var @namespace in typeScriber.Namespaces) {
                Assert.IsTrue(namespaceHash.Contains(@namespace));
            }
        }
        private static Tuple<string, string, string> getNameAndDomainAndPath( string name, string domain, string path, bool omitNamePrefix )
        {
            var defaultAttributes = EwfConfigurationStatics.AppConfiguration.DefaultCookieAttributes;
            var defaultBaseUrl = new Uri( EwfApp.GetDefaultBaseUrl( false ) );

            domain = domain ?? defaultAttributes.Domain ?? "";

            // It's important that the cookie path not end with a slash. If it does, Internet Explorer will not transmit the cookie if the user requests the root URL
            // of the application without a trailing slash, e.g. integration.redstapler.biz/Todd. One justification for adding a trailing slash to the cookie path is
            // http://stackoverflow.com/questions/2156399/restful-cookie-path-fails-in-ie-without-trailing-slash.
            path = path ?? defaultAttributes.Path;
            path = path != null ? "/" + path : defaultBaseUrl.AbsolutePath;

            // Ensure that the domain and path of the cookie are in scope for both the request URL and resource URL. These two URLs can be different on shortcut URL
            // requests, requests that transfer to the log-in page, etc.
            var requestUrls = new[] { AppRequestState.Instance.Url, EwfPage.Instance.InfoAsBaseType.GetUrl( false, false, true ) };
            foreach( var url in requestUrls ) {
                var uri = new Uri( url );
                if( domain.Any() && !( "." + uri.Host ).EndsWith( "." + domain ) )
                    throw new ApplicationException( "The cookie domain of \"{0}\" is not in scope for \"{1}\".".FormatWith( domain, url ) );
                if( path != "/" && !( uri.AbsolutePath + "/" ).StartsWith( path + "/" ) )
                    throw new ApplicationException( "The cookie path of \"{0}\" is not in scope for \"{1}\".".FormatWith( path, url ) );
            }
            if( !domain.Any() ) {
                var requestHosts = requestUrls.Select( i => new Uri( i ).Host );
                if( requestHosts.Distinct().Count() > 1 ) {
                    throw new ApplicationException(
                        "The cookie domain could arbitrarily be either {0} depending upon the request URL.".FormatWith(
                            StringTools.ConcatenateWithDelimiter( " or ", requestHosts.ToArray() ) ) );
                }
            }

            return Tuple.Create( ( omitNamePrefix ? "" : defaultAttributes.NamePrefix ?? "" ) + name, domain, path );
        }
        public async Task When_a_partition_is_queried_then_the_cursor_is_updated()
        {
            var partitions = new[]
            {
                StreamQuery.Partition(0, 500),
                StreamQuery.Partition(500, 1000)
            };

            var store = new InMemoryProjectionStore<Projection<int, int>>();
            var aggregator = Aggregator.CreateFor<int, int>((p, i) => p.Value += i.Sum());

            await Task.WhenAll(partitions.Select(async partition =>
            {
                var stream = await partitioner.GetStream(partition);

                Console.WriteLine(stream);

                var catchup = StreamCatchup.Create(stream);
                catchup.Subscribe(aggregator, store);
                await catchup.RunSingleBatch();
            }));

            store.Should()
                 .ContainSingle(p => p.CursorPosition == 500)
                 .And
                 .ContainSingle(p => p.CursorPosition == 1000);
        }
        static void Main(string[] args)
        {
            var URLs = new[]
            {
            "http://www.google.com",
            "http://softuni.bg ",
            "http://www.slashdot.org"
            };

            var tasks = URLs.Select(
            url => Task.Factory.StartNew(task =>
            {
                using (var client = new WebClient())
                {
                    var t = (string)task;
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    String result = client.DownloadString(t);
                    stopwatch.Stop();
                    Console.WriteLine(String.Format("{0} = {1}", url, stopwatch.Elapsed));
                }
            }, url)
                ).ToArray();
            Task.WaitAll(tasks);
        }
        public static IEnumerable<ITestCase> CreateWithInvalidRequestReturnsNoSpecimen()
        {
            var invalidRequests = new[]
            {
                null,
                new object(),
                string.Empty,
                123,
                typeof(int),
                typeof(object[]),
                typeof(string[][])
            };
            return invalidRequests.Select(r => new TestCase(() =>
            {
                var sut = new MultidimensionalArrayRelay();
                var dummyContext = new DelegatingSpecimenContext();
#pragma warning disable 618
                var expected = new NoSpecimen(r);
#pragma warning restore 618

                var actual = sut.Create(r, dummyContext);

                Assert.Equal(expected, actual);
            }));
        }
Exemple #24
0
        public void Fun()
        {
            var table = new[]
                            {
                                new double[] {0, 1, 2},
                                new double[] {0, 1, 2, 3},
                                new double[] {0, 1}
                            };
            var vector = table.Select(l => l.First()).ToArray();

            Enumerate(vector, table, 0);

            //            var idx = vector.Length - 3;
            //
            //            foreach (var v1 in table[idx])
            //            {
            //                vector[idx] = v1;
            //                foreach (var v2 in table[idx + 1])
            //                {
            //                    vector[idx + 1] = v2;
            //                    foreach (var v3 in table[idx + 2])
            //                    {
            //                        vector[idx + 2] = v3;
            //                        WriteVector(vector);
            //                    }
            //                }
            //            }
        }
Exemple #25
0
        public IEnumerable<SmileyDto> GetSmileyReplacements()
        {
            IList<Smiley> smileys = GetSmileys();

            var replacements = smileys.Select(x =>
            {
                string aliases = x.Aliases ?? string.Empty;
                IEnumerable<string> keywords = new[] { x.Emoticon }.Concat(aliases.SplitNonEmpty(' '));

                Lazy<string> smiley = new Lazy<string>(() =>
                {
                    string name = Smileys.ResourceManager.GetString(x.ResourceKey);
                    TagBuilder tag = new TagBuilder("img");
                    tag.Attributes.Add("title", x.Emoticon);
                    tag.Attributes.Add("alt", name);
                    tag.Attributes.Add("src", Config.Site.Pixel);
                    tag.AddCssClass(x.CssClass);
                    string source = tag.ToString(TagRenderMode.SelfClosing);
                    return source;
                });
                return new SmileyDto
                {
                    Keywords = keywords,
                    EncodedKeywords = keywords.Select(HttpUtility.HtmlEncode),
                    Smiley = smiley
                };
            });
            return replacements;
        }
        public ProducerResponse Process(IMessage message, bool addressed)
        {
            var match = Regex.Match(message.Text, @"^([a-z]\w*)\s+([a-z]\w*)\s+([a-z]\w*)$",
                RegexOptions.IgnoreCase);

            if (match.Success)
            {
                var words = new[] { match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value };

                var expandedAcronym = String.Join(" ", words);
                var tlaChance = int.Parse(Config.Get("PercentChanceOfNewTLA", "5"));
                var shouldCreateNewAcronym = StaticRandom.Next(0, 100) < tlaChance;

                if (shouldCreateNewAcronym)
                {
                    var acronym = new String(words.Select(s => s.First()).ToArray()).ToUpperInvariant();
                    if (!tlaDataStore.Put(acronym, expandedAcronym))
                        return null;

                    // grab a random band name reply factoid and :shipit:
                    var bandNameFactoidStr = factoidDataStore.GetRandomValue("band name reply")?.Value ?? DefaultBandNameReply;
                    var bandNameFactoid =
                        FactoidUtilities.GetVerbAndResponseFromPartialFactoid(bandNameFactoidStr);

                    // GHETTO ALERT
                    var coercedResponse = Regex.Replace(bandNameFactoid.Response, @"\$(?:band|tla)", expandedAcronym, RegexOptions.IgnoreCase);
                    return new ProducerResponse(variableHandler.Substitute(coercedResponse, message), false);
                }
            }

            return null;
        }
Exemple #27
0
        private static void AddPerlFoldersToPath(ProcessStartInfo psi, string perlfolder)
        {
            var currentDir = (new DirectoryInfo(".")).FullName;

            var relPathExtensions = new[]
            {
                @"perl\site\bin",
                @"perl\bin",
                @"c\bin"
            };
            var pathExtensions = relPathExtensions
                .Select(p => Path.Combine(currentDir, perlfolder, p));

            var path = psi.EnvironmentVariables["Path"];
            var pathSegments = new List<string>();
            pathSegments.AddRange(path.Split(';'));
            pathSegments.AddRange(pathExtensions);

            pathSegments
                .Where(p => !Directory.Exists(p)).ToList()
                .ForEach(p => Trace.TraceWarning(
                    string.Format("Path contains non-existent dir \"{0}\"", p)));

            path = string.Join(";", pathSegments);
            psi.EnvironmentVariables["Path"] = path;
        }
        public ActionResult AppointmentData(string id)
        {
            IEnumerable<Appointment> data = new[] {
                new Appointment { ClientName = "Joe", Date = DateTime.Parse("1/1/2012")},
                new Appointment { ClientName = "Joe", Date = DateTime.Parse("2/1/2012")},
                new Appointment { ClientName = "Joe", Date = DateTime.Parse("3/1/2012")},
                new Appointment { ClientName = "Jane", Date = DateTime.Parse("1/20/2012")},
                new Appointment { ClientName = "Jane", Date = DateTime.Parse("1/22/2012")},
                new Appointment {ClientName = "Bob", Date = DateTime.Parse("2/25/2012")},
                new Appointment {ClientName = "Bob", Date = DateTime.Parse("2/25/2013")}
            };

            if (!string.IsNullOrEmpty(id) && id != "All") {
                data = data.Where(e => e.ClientName == id);
            }

            if (Request.IsAjaxRequest()) {
                return Json(data.Select(m => new {
                    ClientName = m.ClientName,
                    Date = m.Date.ToShortDateString()
                }), JsonRequestBehavior.AllowGet);
            } else {
                return View(data);
            }
        }
        public void CommandResolver_Valid_SimpleTest()
        {
            var path = new[] { new ValueBindingExpression(vm => ((dynamic)vm[0]).A[0], "A()[0]") };
            var commandId = "someCommand";
            var command = new CommandBindingExpression(vm => ((TestA)vm[0]).Test(((TestA)vm[0]).StringToPass, ((dynamic)vm[1]).NumberToPass), commandId);

            var testObject = new
            {
                A = new[]
                {
                    new TestA() { StringToPass = "******" }
                },
                NumberToPass = 16
            };
            var viewRoot = new DotvvmView() { DataContext = testObject };
            viewRoot.SetBinding(Controls.Validation.TargetProperty, new ValueBindingExpression(vm => vm.Last(), "$root"));

            var placeholder = new HtmlGenericControl("div");
            placeholder.SetBinding(DotvvmBindableObject.DataContextProperty, path[0]);
            viewRoot.Children.Add(placeholder);

            var button = new Button();
            button.SetBinding(ButtonBase.ClickProperty, command);
            placeholder.Children.Add(button);

            var resolver = new CommandResolver();
            var context = new DotvvmRequestContext() { ViewModel = testObject };
            context.ModelState.ValidationTargetPath = KnockoutHelper.GetValidationTargetExpression(button);

            resolver.GetFunction(viewRoot, context, path.Select(v => v.Javascript).ToArray(), commandId).Action();

            Assert.AreEqual(testObject.NumberToPass, testObject.A[0].ResultInt);
            Assert.AreEqual(testObject.A[0].ResultString, testObject.A[0].ResultString);
        }
    // OR use Constructor injection
    //[ImportingConstructor]
    //public CustomerFactory(ICustomerInfoFactory customerInfoFactory)
    //{
    //  MyCustomerInfoFactory = customerInfoFactory;
    //}

    public object Fetch(string criteria)
    {
      var list = (CustomerList)MethodCaller.CreateInstance(typeof(CustomerList));


      // just sets up some mock data - could com from Xml,L2S, EF or othere sources unknown to the BO itself. 
      var customers = new[]
               {
                 new CustomerData {Id = 1, Name = "Baker, Jonathan"},
                 new CustomerData {Id = 2, Name = "Peterson, Peter"},
                 new CustomerData {Id = 3, Name = "Olsen, Egon"},
                 new CustomerData {Id = 4, Name = "Hansen, hans"}
               };

      list.RaiseListChangedEvents = false;
      this.SetIsReadOnly(list, false);

      // tranform to my lists child type
      list.AddRange(customers.Select(p => MyCustomerInfoFactory.GetCustomerInfo(p)));

      this.SetIsReadOnly(list, true);
      list.RaiseListChangedEvents = true;

      return list;
    }
Exemple #31
0
        protected override async Task Execute(IDMCommandContext context)
        {
            string            radiusRequest       = WebRequestService.EDSM_MultipleSystemsRadius(SystemName, 50);
            RequestJSONResult requestResultRadius = await WebRequestService.GetWebJSONAsync(radiusRequest);

            if (!requestResultRadius.IsSuccess)
            {
                if (requestResultRadius.IsException)
                {
                    await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. Exception Message: `{0}`", requestResultRadius.ThrownException.Message), true);
                }
                else
                {
                    await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. HTTP Error: `{0} {1}`", (int)requestResultRadius.Status, requestResultRadius.Status.ToString()), true);
                }
                return;
            }

            if (requestResultRadius.JSON.IsObject)
            {
                await context.Channel.SendEmbedAsync("System not found in database!", true);

                return;
            }

            Dictionary <string, System> systemInfos = GetNames(requestResultRadius.JSON);

            List <System> allSystems = new List <System>(systemInfos.Values);

            foreach (System system in allSystems)
            {
                system.SetETTA(JumpRange);
            }

            allSystems.Sort(new SystemComparer()
            {
                RawDistance = true
            });

            const int requestCnt = 20;

            System[] requestSystems = new System[requestCnt];

            allSystems.CopyTo(0, requestSystems, 0, requestCnt);

            string            infoRequest       = WebRequestService.EDSM_MultipleSystemsInfo_URL(requestSystems.Select(system => { return(system.Name); }), true, true, true, true);
            RequestJSONResult requestResultInfo = await WebRequestService.GetWebJSONAsync(infoRequest);

            if (!requestResultInfo.IsSuccess)
            {
                if (requestResultInfo.IsException)
                {
                    await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. Exception Message: `{0}`", requestResultInfo.ThrownException.Message), true);
                }
                else
                {
                    await context.Channel.SendEmbedAsync(string.Format("Could not connect to EDSMs services. HTTP Error: `{0} {1}`", (int)requestResultInfo.Status, requestResultInfo.Status.ToString()), true);
                }
                return;
            }

            System targetSystem = default;

            if (requestResultInfo.JSON.IsArray)
            {
                foreach (JSONField systemField in requestResultInfo.JSON.Array)
                {
                    if (systemField.IsObject)
                    {
                        if (systemField.Container.TryGetField("name", out string name))
                        {
                            if (systemInfos.TryGetValue(name, out System system))
                            {
                                system.FromJSON(systemField.Container);
                                if (system.Distance == 0)
                                {
                                    targetSystem = system;
                                }
                            }
                        }
                    }
                }
            }

            if (targetSystem.Name == null)
            {
                await context.Channel.SendEmbedAsync(string.Format("Internal Error! " + Macros.GetCodeLocation(), true));

                return;
            }

            string hideFaction = Mode == CommandMode.Crime ? targetSystem.Name : null;

            List <System> validSystems = new List <System>();

            foreach (System system in requestSystems)
            {
                if (await system.GetBestStation())
                {
                    system.SetETTA(JumpRange);
                    validSystems.Add(system);
                }
            }

            validSystems.Sort(new SystemComparer());

            EmbedBuilder embed = new EmbedBuilder()
            {
                Author = new EmbedAuthorBuilder()
                {
                    Url  = targetSystem.GetEDSM_URL(),
                    Name = $"Suggestions for a temporary base near {targetSystem.Name}"
                },
                Color = BotCore.EmbedColor
            };

            for (int i = 0; i < 5 && i < validSystems.Count; i++)
            {
                System system = validSystems[i];
                embed.AddField($"\"{system.Name}\" - \"{system.BestStation.Name}\"", $"{(system.RequirePermit ? $"{UnicodeEmoteService.Warning} Permit: `{system.PermitName}` " : string.Empty)} {system.BestStation.Services_Link}");
            }

            await context.Channel.SendEmbedAsync(embed);
        }