Exemple #1
0
        private async Task SeedSingleSeed(int seedingStep, ServiceProvider serviceProvider, SeedInfo seedInfo)
        {
            Assert(seedingStep > 0);
            Assert(serviceProvider != null);
            Assert(seedInfo != null);

            Preparing?.Invoke(this, new SeedingEventArgs(seedingStep, seedInfo));

            var seed = (ISeed)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, seedInfo.SeedType);

            foreach (var seedOutputProperty in seedInfo.SeedOutputProperties)
            {
                // We always want to create a new instance of a seed output class.
                // Why? Because in a general case seed output classes will have dependency constructors
                // that can potentially have transient dependencies.
                var propertyValue = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, seedOutputProperty.PropertyType);
                seedOutputProperty.SetValue(seed, propertyValue);
            }

            if (await seed.OutputAlreadyExists())
            {
                Skipping?.Invoke(this, new SeedingEventArgs(seedingStep, seedInfo));
                return;
            }

            Seeding?.Invoke(this, new SeedingEventArgs(seedingStep, seedInfo));

            await seed.Seed();

            SeedingEnded?.Invoke(this, new SeedingEventArgs(seedingStep, seedInfo));
        }
Exemple #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Seeding seed)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                seed.Seed();
            }

            app.UseHttpsRedirection();

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Projeto Quiver");
            });

            app.UseRouting();

            app.UseCors(x => x
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());

            app.UseAuthorization();
            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemple #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, PermissionContext context)
        {
            context.Database.Migrate();
            Seeding seeding = new Seeding(context);

            seeding.Init();


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
            /// <summary>
            ///   Randomizes the clusters inside a dataset.
            /// </summary>
            ///
            /// <param name="points">The data to randomize the algorithm.</param>
            /// <param name="strategy">The seeding strategy to be used. Default is <see cref="Seeding.KMeansPlusPlus"/>.</param>
            /// <param name="parallelOptions">The parallelization options for this procedure.
            /// Only relevant for the <see cref="Seeding.PamBuild"/>. </param>
            ///
            public virtual int[] Randomize(TData[] points, Seeding strategy = Seeding.KMeansPlusPlus, ParallelOptions parallelOptions = null)
            {
                if (points == null)
                {
                    throw new ArgumentNullException("points");
                }

                Owner.NumberOfInputs = Tools.GetNumberOfInputs(points);

                switch (strategy)
                {
                case Seeding.Fixed:
                    return(DoFixedSeeding(points));

                case Seeding.Uniform:
                    return(DoUniformSeeding(points));

                case Seeding.KMeansPlusPlus:
                    return(DoKMeansPlusPlusSeeding(points));

                case Seeding.PamBuild:
                    return(DoPamBuildSeeding(points, parallelOptions));
                }

                throw new ArgumentException("Uknown strategy: {0}".Format(strategy));
            }
Exemple #5
0
        void HandleStateChanged(object sender, StateChangedEventArgs args)
        {
            Download manager = (Download)sender;

            if (args.OldState == State.Downloading)
            {
                logger.Debug("Removing " + manager.Torrent.Name + " from download label");
                Downloading.RemoveTorrent(manager);
            }
            else if (args.OldState == State.Seeding)
            {
                logger.Debug("Removing " + manager.Torrent.Name + " from upload label");
                Seeding.RemoveTorrent(manager);
            }

            if (args.NewState == State.Downloading)
            {
                logger.Debug("Adding " + manager.Torrent.Name + " to download label");
                Downloading.AddTorrent(manager);
            }
            else if (args.NewState == State.Seeding)
            {
                logger.Debug("Adding " + manager.Torrent.Name + " to upload label");
                Seeding.AddTorrent(manager);
            }
        }
Exemple #6
0
        // Creates and seeds an ApplicationContext with test data; then calls  test action.
        private async Task PrepareTestContext(TestAction testAction)
        {
            // Database is in memory as long the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            try
            {
                connection.Open();

                var options = new DbContextOptionsBuilder <ApplicationContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database and seeds with test data
                using (var context = new ApplicationContext(options))
                {
                    context.Database.EnsureCreated();
                    Seeding.Initialize(context);

                    await testAction(context);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context         = services.GetRequiredService <ApplicationDbContext>();
                    var serviceProvider = services.GetRequiredService <IServiceProvider>();
                    var configuration   = services.GetRequiredService <IConfiguration>();

                    context.Database.Migrate();
                    Seeding.CreateRoles(serviceProvider, configuration).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.
                                  GetRequiredService <ApplicationContext>();

                    // Seeding de datos.
                    Seeding.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
Exemple #9
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Word>()
            .Property(x => x.Id).ValueGeneratedOnAdd();
            modelBuilder.Entity <Word>()
            .HasIndex(x => x.Name).IsUnique();


            modelBuilder.Entity <Example>()
            .Property(x => x.Id).ValueGeneratedOnAdd();

            modelBuilder.Entity <User>()
            .Property(x => x.Id).ValueGeneratedOnAdd();

            modelBuilder.Entity <WordExample>()
            .HasKey(x => new { x.WordId, x.ExampleId });

            modelBuilder.Entity <WordExample>()
            .HasOne(x => x.Word)
            .WithMany(x => x.Examples)
            .HasForeignKey(x => x.WordId);

            modelBuilder.Entity <WordExample>()
            .HasOne(x => x.Example)
            .WithMany(x => x.Words)
            .HasForeignKey(x => x.ExampleId);

            Seeding.Seed(modelBuilder);
        }
Exemple #10
0
 public static async Task TestSeedDb(IHost host)
 {
     using (IServiceScope scope = host.Services.CreateScope())
     {
         var services = scope.ServiceProvider;
         await Seeding.Initialize(services);
     }
 }
    void Start()
    {
        seeding = GameObject.FindObjectOfType <Seeding>();

        perlinValues = new float[dungeonSize.x, dungeonSize.y];
        map          = new string[dungeonSize.x, dungeonSize.y];

        GenerateDungeon();
    }
Exemple #12
0
 private void OnDeserializedMethod(StreamingContext context)
 {
     if (this.Iterations == 0 && MaxIterations == 0 && Tolerance == 0)
     {
         this.Tolerance          = 1e-5;
         this.ComputeCovariances = true;
         this.UseSeeding         = Seeding.KMeansPlusPlus;
         this.ComputeError       = true;
     }
 }
Exemple #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager <MyMeetupUser> userManager,
                              RoleManager <MyMeetupRole> roleManager, MyMeetupContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                //   app.UseDeveloperExceptionPage();
                //  app.UseDatabaseErrorPage();
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            // app.UseDeveloperExceptionPage();
            var supportedCultures = new List <CultureInfo>
            {
                new CultureInfo("fr"),
                new CultureInfo("fr-FR"),
                //new CultureInfo("en"),
                //new CultureInfo("en-US")
            };

            var localizationOptions = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("fr-FR"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            app.UseRequestLocalization(localizationOptions);
            app.UseElmah();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            context.Database.Migrate();
            app.UseAuthentication();
            Seeding.SeedRoles(roleManager);
            Seeding.SeedUsers(userManager);
            Seeding.SeedData(context);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}"
                    );
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #14
0
        IAllowedMemberValues Register(IServiceProvider arg)
        {
            IParameterizedSource <MemberInfo, IAllowedValueSpecification>
            seed         = new Seeding(Specifications, Instances, _allowed).Get(),
                fallback = _allowed == AllowAssignedValues
                                                   ? Source.Default
                                                   : new FixedInstanceSource <MemberInfo, IAllowedValueSpecification>(_allowed);
            var source = this.Appending(fallback)
                         .Aggregate(seed, (current, item) => current.Or(item));
            var result = new AllowedMemberValues(source);

            return(result);
        }
Exemple #15
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args)
                       .ConfigureAppConfiguration(configs => GetConfigurations())
                       .Build();

            host.MigrateDbContext <IdentityContext>((context, serviceProvider) =>
            {
                Seeding.SeedPermissions(context);
                context.SaveChanges();
            });

            CreateHostBuilder(args).Build().Run();
        }
Exemple #16
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services        = scope.ServiceProvider;
                var serviceProvider = services.GetRequiredService <IServiceProvider>();
                var service         = scope.ServiceProvider.GetRequiredService <Context>();
                Seeding.MigrateDatabase(service);
                Seeding.Seed(serviceProvider).Wait();
            }

            host.Run();
        }
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope()){
                var services = scope.ServiceProvider;
                try{
                    var context = services.GetRequiredService <DataContext>();
                    context.Database.Migrate();
                    Seeding.Seed(context);
                } catch (Exception e) {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(e, $"Error occured migrating DB");
                }
            }
            host.Run();
        }
Exemple #18
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var dbContextDescriptor = services.Single(d => d.ServiceType == typeof(DbContextOptions <CarManagerContext>));
                services.Remove(dbContextDescriptor);

                services.AddDbContext <CarManagerContext>(options => options.UseInMemoryDatabase(nameof(CarManagerContext)));

                using var scope    = services.BuildServiceProvider().CreateScope();
                var scopedProvider = scope.ServiceProvider;
                var context        = scopedProvider.GetRequiredService <CarManagerContext>();

                if (context.Database.EnsureCreated())
                {
                    Seeding.Initialize(context);
                }
            });
        }
Exemple #19
0
        private static void CreateDbIfNotExists(IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    // Seed the Identity-related database if have not done so
                    var UR_context = services.GetRequiredService <UserRoleDB>();
                    Seeding.Initialize(UR_context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }
        }
Exemple #20
0
        /// <summary>
        ///   Initializes a new instance of PartitioningAroundMedoids algorithm
        /// </summary>
        ///
        /// <param name="k">The number of clusters to divide input data.</param>
        /// <param name="distance">The distance function to use. Default is to
        ///   use the <see cref="Accord.Math.Distance.Euclidean(double[], double[])"/> distance.</param>
        ///
        public KMedoids(int k, IDistance <T[]> distance)
        {
            if (k <= 0)
            {
                throw new ArgumentOutOfRangeException("k");
            }

            if (distance == null)
            {
                throw new ArgumentNullException("distance");
            }

            // Create the object-oriented structure to hold
            //  information about the k-Medoids' clusters.
            clusters = new KMedoidsClusterCollection <T>(k, distance);

            Initialization = Seeding.PamBuild;
            Tolerance      = 1e-5;
            MaxIterations  = 100;
        }
Exemple #21
0
        /// <summary>
        ///   Initializes a new instance of KModes algorithm
        /// </summary>
        ///
        /// <param name="k">The number of clusters to divide input data.</param>
        /// <param name="distance">The distance function to use. Default is to
        /// use the <see cref="Accord.Math.Distance.SquareEuclidean(double[], double[])"/> distance.</param>
        ///
        public KModes(int k, IDistance <T[]> distance)
        {
            if (k <= 0)
            {
                throw new ArgumentOutOfRangeException("k");
            }

            if (distance == null)
            {
                throw new ArgumentNullException("distance");
            }

            // Create the object-oriented structure to hold
            //  information about the k-modes' clusters.
            this.clusters = new KModesClusterCollection <T>(k, distance);

            this.Initialization = Seeding.KMeansPlusPlus;
            this.Tolerance      = 1e-5;
            this.MaxIterations  = 100;
        }
Exemple #22
0
        /// <summary>
        ///   Initializes a new instance of the KMeans algorithm
        /// </summary>
        ///
        /// <param name="k">The number of clusters to divide the input data into.</param>
        /// <param name="distance">The distance function to use. Default is to use the
        /// <see cref="Accord.Math.Distance.SquareEuclidean(double[], double[])"/> distance.</param>
        ///
        public KMeans(int k, IDistance <double[]> distance)
        {
            if (k <= 0)
            {
                throw new ArgumentOutOfRangeException("k");
            }

            if (distance == null)
            {
                throw new ArgumentNullException("distance");
            }

            this.Tolerance          = 1e-5;
            this.ComputeCovariances = true;
            this.ComputeError       = true;
            this.UseSeeding         = Seeding.KMeansPlusPlus;
            this.MaxIterations      = 0;

            // Create the object-oriented structure to hold
            //  information about the k-means' clusters.
            this.clusters = new KMeansClusterCollection(k, distance);
        }
        public async Task <ActionResult <Seeding> > AddSeeding([FromBody] SeedingViewModel input)
        {
            try
            {
                Seeding seeding = null;
                if (input != null)
                {
                    seeding = input.Adapt <Seeding>();
                    var user = _context.Users.Where(s => s.ID == input.UserId).FirstOrDefault();
                    if (user == null)
                    {
                        return(new JsonResult(new { ErrorMessage = "The given user id not found." }));
                    }
                    seeding.User = user;
                    var PartLandDetails = _context.PartitionLandDetails.Where(p => p.ID == input.PartitionLandDetailId).FirstOrDefault();
                    if (PartLandDetails == null)
                    {
                        return(new JsonResult(new { ErrorMessage = "The given land details id not found." }));
                    }
                    seeding.PartitionLandDetail = PartLandDetails;
                    //Deciding whether the action is Add or Update
                    if (input.ID <= 0) //Add
                    {
                        _context.Seedings.Add(seeding);
                    }
                    else
                    { //Update
                        _context.Seedings.Update(seeding);
                    }
                }
                await _context.SaveChangesAsync();

                return(new JsonResult(seeding));
            }
            catch (Exception _ex)
            {
                return(new JsonResult(new { ErrorMessage = _ex.Message }));
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager <AppUser> userManager, RoleManager <AppRole> roleManager, IKategoriService kategoriService, ITagService tagService)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            Seeding.SeedData(userManager, roleManager, kategoriService, tagService).Wait();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(env.ContentRootPath, "wwwroot/AnaKlasor/Resimler")),
                RequestPath = "/wwwroot/AnaKlasor/Resimler"
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(env.ContentRootPath, "wwwroot/AnaKlasor/Yazilar")),
                RequestPath = "/wwwroot/AnaKlasor/Yazilar"
            });

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #25
0
        private static void Main(string[] args)
        {
            CountryDBSettings countryDBSettings = new CountryDBSettings()
            {
                ConnectionString = "mongodb://127.0.0.1:27017",
                DatabaseName     = "CountryDB"
            };

            FlagService    flagService    = new FlagService(countryDBSettings);
            CountryService countryService = new CountryService(countryDBSettings);

            Stopwatch sw = new Stopwatch();

            sw.Start();
            var dataSeeding = new Seeding(countryService, flagService);

            dataSeeding.Run();
            sw.Stop();

            Console.WriteLine($"Load Complete : {sw.Elapsed.TotalSeconds}");

            Console.ReadKey();
        }
Exemple #26
0
        private void CalculateRanks(IEnumerable <SeedingInfo> seedings)
        {
            var context        = DataEntitiesProvider.Provide();
            var sortedSeedings = seedings.OrderBy(x => x.GameCode)
                                 .ThenByDescending(x => x.Score)
                                 .ThenByDescending(x => x.LastGoldYear)
                                 .ThenByDescending(x => x.LastSilverYear)
                                 .ThenByDescending(x => x.LastBronzeYear)
                                 .ToList();

            var lastEventCode = "";
            var rank          = 1;

            foreach (var seeding in sortedSeedings)
            {
                if (seeding.GameCode != lastEventCode)
                {
                    lastEventCode = seeding.GameCode;
                    rank          = 1;
                }
                else
                {
                    rank++;
                }

                var dbSeeding = new Seeding()
                {
                    ContestantId = seeding.ContestantId,
                    EventCode    = seeding.GameCode,
                    Rank         = rank,
                    Score        = seeding.Score
                };

                context.Seedings.Add(dbSeeding);
                context.SaveChanges();
            }
        }
Exemple #27
0
        private void StartUp()
        {
            Log("Instantiating");
            Log("\tUtilities");
            Utils = new Utilities();

            Log("\tSeeding Class");
            Seeding = new Seeding();


            Log("Subscribing to Seeding Events");
            Seeding.AddUrlEvent        += Seeding_AddUrlEvent;
            Seeding.DeleteAllUrlsEvent += Seeding_DeleteAllUrlsEvent;

            Log("Subscribing to Globally Shared Events");
            Log("\t Logging");
            Seeding.LogEvent += LogEvent;

            // Log("\t Broadcast Messages");

            Log("Starting The TCP Server");

            Log("Application Loaded");
        }
Exemple #28
0
 /// <summary>
 ///   Randomizes the clusters inside a dataset.
 /// </summary>
 ///
 /// <param name="points">The data to randomize the algorithm.</param>
 /// <param name="strategy">The seeding strategy to be used. Default is <see cref="Seeding.KMeansPlusPlus"/>.</param>
 ///
 public void Randomize(T[][] points, Seeding strategy = Seeding.KMeansPlusPlus)
 {
     collection.Randomize(points, strategy);
 }
        //---------------------------------------------------------------------
        //public static void Initialize(double[,]              establishProbabilities,
        public static void Initialize(SeedingAlgorithm       seedingAlgorithm,
            Delegates.AddNewCohort addNewCohort)
        {
            // Reproduction.establishProbabilities = establishProbabilities;

            seeding = new Seeding(seedingAlgorithm);
            Reproduction.addNewCohort = addNewCohort;

            SiteVars.Cohorts = Model.Core.GetSiteVar<SiteCohorts>("Succession.Cohorts");

            speciesDataset = Model.Core.Species;
            int speciesCount = speciesDataset.Count;

            resprout = Model.Core.Landscape.NewSiteVar<BitArray>();
            serotiny = Model.Core.Landscape.NewSiteVar<BitArray>();
            noEstablish = Model.Core.Landscape.NewSiteVar<bool>();
            foreach (ActiveSite site in Model.Core.Landscape.ActiveSites) {
                resprout[site] = new BitArray(speciesCount);
                serotiny[site] = new BitArray(speciesCount);
            }

            noEstablish.ActiveSiteValues = false;
            planting = new Planting();
        }
        //---------------------------------------------------------------------

        public static void Initialize(SeedingAlgorithm seedingAlgorithm)
        {

            seeding = new Seeding(seedingAlgorithm);

            speciesDataset = Model.Core.Species;
            int speciesCount = speciesDataset.Count;

            resprout = Model.Core.Landscape.NewSiteVar<BitArray>();
            serotiny = Model.Core.Landscape.NewSiteVar<BitArray>();
            noEstablish = Model.Core.Landscape.NewSiteVar<bool>();
            foreach (ActiveSite site in Model.Core.Landscape.ActiveSites) {
                resprout[site] = new BitArray(speciesCount);
                serotiny[site] = new BitArray(speciesCount);
            }

            noEstablish.ActiveSiteValues = false;
            planting = new Planting();

        }
Exemple #31
0
 public virtual void Seed(int?seed = null)
 {
     RandomState = Seeding.GetState(seed);
 }
Exemple #32
0
 public SeedingController(CountryService countryService, FlagService flagService)
 {
     _countryService = countryService;
     _flagService    = flagService;
     _seeding        = new Seeding(_countryService, _flagService);
 }