Inheritance: MonoBehaviour
 //For testing purposes we print out plant species
 public string onLeftMouseDown(Seed playerSeed, Plant playerPlant)
 {
     if(occupied)
     {
         return "Space is occupied!";
         // Call remove function?
     }
     //If player is holding seed, set it.
     else if(playerSeed)
     {
         currentSeed = playerSeed;
         occupied = true;
         currentSeed.GetComponent<Seed>().currentSpace = this.gameObject.GetComponent<Plantable_Space>();
         //Spawn GameObject of Seed
         return "Planted " + playerSeed.species;
     }
     //Else if holding a plant, set that.
     else if(playerPlant)
     {
         currentPlant = playerPlant;
         occupied = true;
         currentPlant.GetComponent<Plant>().currentSpace = this.gameObject.GetComponent<Plantable_Space>();
         return "Planted " + playerPlant.species;
     }
     else
     {
         //Player has no plant or seed selected in inventory, nothing happens.
         return null;
     }
 }
        public void Test_AmoebaConverter_Seed()
        {
            var seed = new Seed();
            seed.Name = "aaaa.zip";
            seed.Keywords.AddRange(new KeywordCollection
            {
                "bbbb",
                "cccc",
                "dddd",
            });
            seed.CreationTime = DateTime.Now;
            seed.Length = 10000;
            seed.Comment = "eeee";
            seed.Rank = 1;
            seed.Key = new Key(new byte[32], HashAlgorithm.Sha256);
            seed.CompressionAlgorithm = CompressionAlgorithm.Xz;
            seed.CryptoAlgorithm = CryptoAlgorithm.Aes256;
            seed.CryptoKey = new byte[32 + 32];

            DigitalSignature digitalSignature = new DigitalSignature("123", DigitalSignatureAlgorithm.Rsa2048_Sha256);
            seed.CreateCertificate(digitalSignature);

            var stringSeed = AmoebaConverter.ToSeedString(seed);
            var seed2 = AmoebaConverter.FromSeedString(stringSeed);

            Assert.AreEqual(seed, seed2, "AmoebaConverter #2");
        }
 public void GenerateNodeKeyTest()
 {
     var zeroBytes = new byte[16];
     var pair = new Seed(zeroBytes).SetNodeKey().KeyPair();
     Assert.AreEqual("n9LPxYzbDpWBZ1bC3J3Fdkgqoa3FEhVKCnS8yKp7RFQFwuvd8Q2c", 
                     pair.Id());
 }
        void before_each()
        {
            seed = new Seed();

            seed.PurgeDb();

            cars = new Cars();

            seed.CreateTable("Cars",
                new { Id = "int" },
                new { Model = "nvarchar(255)" }).ExecuteNonQuery();

            seed.CreateTable("BluePrints",
                new { Id = "int" },
                new { CarId = "int" },
                new { Sku = "nvarchar(255)" }).ExecuteNonQuery();

            car1Id = 100;
            new { Id = car1Id, Model = "car 1" }.InsertInto("Cars");

            car2Id = 200;
            new { Id = car2Id, Model = "car 2" }.InsertInto("Cars");

            bluePrint1Id = 300;
                
            new { Id = bluePrint1Id, CarId = car1Id, Sku = "Sku 1" }.InsertInto("BluePrints");

            bluePrint2Id = 400;

            new { Id = bluePrint2Id, CarId = car2Id, Sku = "Sku 2" }.InsertInto("BluePrints");
        }
 /// <summary>
 /// Initializes a new crop
 /// </summary>
 public Crop(string name, double weight, Seed parentSeed)
 {
     Name = name;
       EndWeight = weight;
       CalculateQuality();
       ParentSeed = parentSeed;
 }
Exemple #6
0
        public FertileDirtGump(Seed seed, int amount, object attachTo)
            : base(50, 50)
        {
            m_Seed = seed;
            m_AttachTo = attachTo;

            AddBackground(0, 0, 300, 210, 9200);
            AddImageTiled(5, 5, 290, 30, 2624);
            AddImageTiled(5, 40, 290, 100, 2624);
            AddImageTiled(5, 145, 150, 60, 2624);
            AddImageTiled(160, 145, 135, 60, 2624);

            AddHtmlLocalized(90, 10, 150, 16, 1150359, LabelColor, false, false); // Raised Garden Bed
            AddHtmlLocalized(10, 45, 280, 90, 1150363, LabelColor, false, false);

            AddHtmlLocalized(10, 150, 80, 16, 1150361, LabelColor, false, false); // Needed:
            AddHtmlLocalized(10, 180, 80, 16, 1150360, LabelColor, false, false); // You Have:

            AddHtml(80, 150, 60, 16, String.Format("<BASEFONT COLOR=#{0:X6}>20</BASEFONT>", FontColor), false, false);
            AddHtml(80, 180, 60, 16, String.Format("<BASEFONT COLOR=#{0:X6}>{1}</BASEFONT>", FontColor, amount.ToString()), false, false);

            AddButton(165, 150, 4023, 4025, 1, GumpButtonType.Reply, 0);
            AddButton(165, 180, 4017, 4019, 2, GumpButtonType.Reply, 0);

            AddHtml(205, 150, 100, 16, String.Format("<BASEFONT COLOR=#{0:X6}>Use</BASEFONT>", FontColor), false, false);
            AddHtmlLocalized(205, 180, 100, 16, 1150364, LabelColor, false, false); // Not Use
        }
 public void SetState(Seed seed, SearchState state)
 {
     lock (_thisLock)
     {
         _seedsDictionary.AddOrUpdate(seed, state, (_, orignalState) => orignalState | state);
     }
 }
        void before_each()
        {
            seed = new Seed();

            markets = new Markets();

            seed.PurgeDb();

            seed.CreateTable("Markets",
                seed.Id(),
                new { Name = "nvarchar(255)" }).ExecuteNonQuery();

            seed.CreateTable("SupplyChains",
                seed.Id(),
                new { MarketId = "int" },
                new { SupplierId = "int" }).ExecuteNonQuery();

            seed.CreateTable("Suppliers",
                seed.Id(),
                new { Name = "nvarchar(255)" }).ExecuteNonQuery();

            supplier1Id = new { Name = "Supplier 1" }.InsertInto("Suppliers");

            supplier2Id = new { Name = "Supplier 2" }.InsertInto("Suppliers");

            market1Id = new { Name = "Market 1" }.InsertInto("Markets");

            market2Id = new { Name = "Market 2" }.InsertInto("Markets");

            new { MarketId = market1Id, SupplierId = supplier1Id }.InsertInto("SupplyChains");

            new { MarketId = market2Id, SupplierId = supplier1Id }.InsertInto("SupplyChains");
        }
Exemple #9
0
	protected Seed	create_seed(string id)
	{
		string	local_account = AccountManager.get().getAccountData(GlobalParam.get().global_account_id).account_id;

		Seed	seed = null;

		seed = this.seeds.Find(x => x.id == id);

		if(seed == null) {

			// 찾지 못했으므로 만든다.
			seed = new Seed(local_account, id);

			this.seeds.Add(seed);

			// [TODO] seeds가 전 단말에서 공통되게 동기화한다.

		} else {

			if(seed.creator == local_account) {
	
				// 같은 id의 시드를 두 번이상 만들려고 함.
				Debug.LogError("Seed \"" + id + "\" already exist.");
				seed = null;

			} else {

				// 다른 플레이어가 만든 같은 시드가 있었다.
			}
		}

		return(seed);
	}
        void specify_db_can_be_specified()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["AnotherDb"].ConnectionString;

            seed = new Seed(new ConnectionProfile
            {
                ConnectionString = connectionString
            });

            seed.PurgeDb();

            seed.CreateTable("Authors",
                seed.Id(),
                new { Name = "nvarchar(255)" }
            ).ExecuteNonQuery(seed.ConnectionProfile);

            seed.CreateTable("Emails",
                seed.Id(),
                new { AuthorId = "int" },
                new { Address = "nvarchar(255)" }
            ).ExecuteNonQuery(seed.ConnectionProfile);

            db = new DynamicDb(connectionString);

            var authorId = db.Authors().Insert(new { Name = "hello" });

            db.Emails().Insert(new { authorId, Address = "*****@*****.**" });

            (db.Authors().All().First().Email().Address as string).should_be("*****@*****.**");
        }
        void before_each()
        {
            seed = new Seed();

            GameSchema.CreateSchema(seed);

            players = new Players();

            player1Id = new { Name = "Jane" }.InsertInto("Players");

            player2Id = new { Name = "John" }.InsertInto("Players");

            game1Id = new { Title = "Mirror's Edge" }.InsertInto("Games");

            game2Id = new { Title = "Gears of War" }.InsertInto("Games");

            new { PlayerId = player1Id, GameId = game2Id }.InsertInto("Library");

            new { PlayerId = player2Id, GameId = game1Id }.InsertInto("Library");

            new { PlayerId = player2Id, GameId = game2Id }.InsertInto("Library");

            sqlQueries = new List<string>();

            DynamicRepository.WriteDevLog = true;

            DynamicRepository.LogSql = new Action<object, string, object[]>(
                (sender, sql, @params) =>
                {
                    sqlQueries.Add(sql);
                });
        }
        void before_each()
        {
            seed = new Seed();

            books = new Books();

            seed.PurgeDb();

            seed.CreateTable("Books",
                seed.Id(),
                new { Title = "nvarchar(255)" }).ExecuteNonQuery();

            seed.CreateTable("Chapters",
                seed.Id(),
                new { BookId = "int" },
                new { Name = "nvarchar(255)" }).ExecuteNonQuery();

            book1Id = new { Title = "book 1" }.InsertInto("Books");

            new { BookId = book1Id, Name = "Chapter 1" }.InsertInto("Chapters");

            new { BookId = book1Id, Name = "Chapter 2" }.InsertInto("Chapters");

            book2Id = new { Title = "book 2" }.InsertInto("Books");

            new { BookId = book2Id, Name = "Chapter 1" }.InsertInto("Chapters");

            new { BookId = book2Id, Name = "Chapter 2" }.InsertInto("Chapters");
        }
        public void Test_AmoebaConverter_Box()
        {
            var key = new Key(HashAlgorithm.Sha256, new byte[32]);
            var metadata = new Metadata(1, key, CompressionAlgorithm.Xz, CryptoAlgorithm.Aes256, new byte[32 + 32]);
            var seed = new Seed(metadata);
            seed.Name = "aaaa.zip";
            seed.Keywords.AddRange(new KeywordCollection
                {
                    "bbbb",
                    "cccc",
                    "dddd",
                });
            seed.CreationTime = DateTime.Now;
            seed.Length = 10000;

            var box = new Box();
            box.Name = "Box";
            box.Seeds.Add(seed);
            box.Boxes.Add(new Box() { Name = "Box" });

            Box box2;

            using (var streamBox = AmoebaConverter.ToBoxStream(box))
            {
                box2 = AmoebaConverter.FromBoxStream(streamBox);
            }

            Assert.AreEqual(box, box2, "AmoebaConverter #3");
        }
 public SeedManagementViewModel(SeedModel.IDataAccessService servPxy)
 {
     dataAccessService = servPxy;
     AddSeedCommand = new RelayCommand(SaveSeed);
     DeleteSeedCommand = new RelayCommand<Seed>(DeleteSeed);
     NewSeed = new Seed();
     SeedList = dataAccessService.GetSeeds();
 }
Exemple #15
0
        void before_each()
        {
            seed = new Seed();

            customers = new Customers();

            suppliers = new Suppliers();
        }
        void before_each()
        {
            seed = new Seed();

            records = new MemoizedRecords();

            seed.PurgeDb();
        }
Exemple #17
0
        void before_each()
        {
            seed = new Seed();

            seed.PurgeDb();

            persons = new Persons();
        }
Exemple #18
0
 public void SutIsCustomAttributeProvider()
 {
     // Fixture setup
     // Exercise system
     var sut = new Seed(typeof(object), new object());
     // Verify outcome
     Assert.IsInstanceOfType(sut, typeof(ICustomAttributeProvider));
     // Teardown
 }
Exemple #19
0
 public void IsDefinedWillReturnCorrectResult()
 {
     // Fixture setup
     var sut = new Seed(typeof(decimal), -1);
     // Exercise system
     var result = sut.IsDefined(typeof(FlagsAttribute), true);
     // Verify outcome
     Assert.IsFalse(result, "IsDefined");
     // Teardown
 }
Exemple #20
0
 public void GetCustomAttributesWillReturnInstance()
 {
     // Fixture setup
     var sut = new Seed(typeof(string), string.Empty);
     // Exercise system
     var result = sut.GetCustomAttributes(true);
     // Verify outcome
     Assert.IsNotNull(result, "GetCustomAttributes");
     // Teardown
 }
Exemple #21
0
 public void GetSpecificCustomAttributesWillReturnInstance()
 {
     // Fixture setup
     var sut = new Seed(typeof(int), 1);
     // Exercise system
     var result = sut.GetCustomAttributes(typeof(DescriptionAttribute), false);
     // Verify outcome
     Assert.IsNotNull(result, "GetCustomAttributes");
     // Teardown
 }
        public SearchState GetState(Seed seed)
        {
            lock (_thisLock)
            {
                SearchState state;
                _seedsDictionary.TryGetValue(seed, out state);

                return state;
            }
        }
Exemple #23
0
        void before_each()
        {
            seed = new Seed();

            users = new Users();

            games = new Games();

            library = new Library();
        }
Exemple #24
0
 public void ValueIsCorrect()
 {
     // Fixture setup
     var expectedValue = "Anonymous value";
     var sut = new Seed(typeof(string), expectedValue);
     // Exercise system
     var result = sut.Value;
     // Verify outcome
     Assert.AreEqual(expectedValue, result, "Value");
     // Teardown
 }
        void describe_db_rows_to_json()
        {
            before = () =>
            {
                Seed seed = new Seed();

                seed.PurgeDb();

                seed.CreateTable("Rabbits", seed.Id(), new { Name = "nvarchar(255)" }).ExecuteNonQuery();

                seed.CreateTable("Tasks",
                    seed.Id(),
                    new { Description = "nvarchar(255)" },
                    new { RabbitId = "int" },
                    new { DueDate = "datetime" }).ExecuteNonQuery();

                var rabbitId = new { Name = "Yours Truly" }.InsertInto("Rabbits");

                new { rabbitId, Description = "bolt onto vans", DueDate = new DateTime(2013, 1, 14) }.InsertInto("Tasks");

                rabbitId = new { Name = "Hiro Protaganist" }.InsertInto("Rabbits");

                new { rabbitId, Description = "save the world", DueDate = new DateTime(2013, 1, 14) }.InsertInto("Tasks");

                new { rabbitId, Description = "deliver pizza", DueDate = new DateTime(2013, 1, 14) }.InsertInto("Tasks");

                rabbitId = new { Name = "Lots" }.InsertInto("Rabbits");

                for (int i = 0; i < 10; i++)
                {
                    new
                    {
                        rabbitId,
                        Description = "Task: " + i.ToString(),
                        DueDate = new DateTime(2013, 1, 14)
                    }.InsertInto("Tasks");
                }
            };

            it["disregards self referencing objects"] = () =>
            {
                var results = tasks.All().Include("Rabbits").ToList();

                (results as IEnumerable<dynamic>).ForEach(s =>
                {
                    s.Rabbit = s.Rabbit();
                });

                objectToConvert = new Gemini(new { Tasks = results });
                string expected = @"{ ""tasks"": [ { ""id"": 1, ""description"": ""bolt onto vans"", ""rabbitId"": 1, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 1, ""name"": ""Yours Truly"" } }, { ""id"": 2, ""description"": ""save the world"", ""rabbitId"": 2, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 2, ""name"": ""Hiro Protaganist"" } }, { ""id"": 3, ""description"": ""deliver pizza"", ""rabbitId"": 2, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 2, ""name"": ""Hiro Protaganist"" } }, { ""id"": 4, ""description"": ""Task: 0"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 5, ""description"": ""Task: 1"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 6, ""description"": ""Task: 2"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 7, ""description"": ""Task: 3"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 8, ""description"": ""Task: 4"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 9, ""description"": ""Task: 5"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 10, ""description"": ""Task: 6"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 11, ""description"": ""Task: 7"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 12, ""description"": ""Task: 8"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } }, { ""id"": 13, ""description"": ""Task: 9"", ""rabbitId"": 3, ""dueDate"": ""1/14/13 12:00:00 AM"", ""rabbit"": { ""id"": 3, ""name"": ""Lots"" } } ] }";
                jsonString = DynamicToJson.Convert(objectToConvert);
                jsonString.should_be(expected);
            };
        }
Exemple #26
0
        void before_each()
        {
            db = new DynamicDb();

            AssociationByConventions.ColumnCache = new Dictionary<string, List<string>>();
            AssociationByConventions.TableCache = new Dictionary<string, bool>();

            seed = new Seed();

            seed.PurgeDb();
        }
        public SeedInformationWindow(Seed seed, AmoebaManager amoebaManager)
        {
            if (seed == null) throw new ArgumentNullException(nameof(seed));
            if (amoebaManager == null) throw new ArgumentNullException(nameof(amoebaManager));

            _seed = seed;
            _amoebaManager = amoebaManager;

            InitializeComponent();

            {
                var icon = new BitmapImage();

                icon.BeginInit();
                icon.StreamSource = new FileStream(Path.Combine(_serviceManager.Paths["Icons"], "Amoeba.ico"), FileMode.Open, FileAccess.Read, FileShare.Read);
                icon.EndInit();
                if (icon.CanFreeze) icon.Freeze();

                this.Icon = icon;
            }

            lock (_seed.ThisLock)
            {
                _nameTextBox.Text = _seed.Name;
                _keywordsTextBox.Text = string.Join(", ", _seed.Keywords);
                _signatureTextBox.Text = seed.Certificate?.ToString();
                _creationTimeTextBox.Text = seed.CreationTime.ToLocalTime().ToString(LanguagesManager.Instance.DateTime_StringFormat, System.Globalization.DateTimeFormatInfo.InvariantInfo);
                _lengthTextBox.Text = string.Format("{0} ({1:#,0} Byte)", NetworkConverter.ToSizeString(_seed.Length), _seed.Length);
            }

            _storeSignatureListView.ItemsSource = _storeSignatureCollection;

            try
            {
                _storeTabItem.Cursor = Cursors.Wait;

                Task.Run(() =>
                {
                    return this.GetSignature(_seed);
                }).ContinueWith(task =>
                {
                    foreach (var signature in task.Result)
                    {
                        _storeSignatureCollection.Add(signature);
                    }

                    _storeTabItem.Cursor = null;
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (Exception)
            {

            }
        }
Exemple #28
0
        void before_each()
        {
            seed = new Seed();
            seed.PurgeDb();

            person = new Person();

            persons = new Persons();

            person.Email = "*****@*****.**";
            person.EmailConfirmation = "*****@*****.**";
        }
        void belongs_where_entity_belongs_more_than_one_relation()
        {
            before = () =>
            {
                seed = new Seed();

                GameSchema.CreateSchema(seed);

                players = new Players();

                player1Id = new { Name = "Jane" }.InsertInto("Players");

                player2Id = new { Name = "John" }.InsertInto("Players");

                game1Id = new { Title = "Mirror's Edge" }.InsertInto("Games");

                game2Id = new { Title = "Gears of War" }.InsertInto("Games");

                new { PlayerId = player1Id, GameId = game2Id }.InsertInto("Library");

                new { PlayerId = player2Id, GameId = game1Id }.InsertInto("Library");

                new { PlayerId = player2Id, GameId = game2Id }.InsertInto("Library");

                sqlQueries = new List<string>();

                DynamicRepository.WriteDevLog = true;

                DynamicRepository.LogSql = new Action<object, string, object[]>(
                    (sender, sql, @params) =>
                    {
                        sqlQueries.Add(sql);
                    });

                allPlayers = players.All();

                allPlayers.Include("Library");

                allPlayers.Library().Include("Game");
            };

            it["updates all references that map to the belongs to entity"] = () =>
            {
                (allPlayers.First().Library().First().Game().Title as object).should_be("Gears of War");

                (allPlayers.Last().Library().First().Game().Title as object).should_be("Mirror's Edge");

                (allPlayers.Last().Library().Last().Game().Title as object).should_be("Gears of War");


                sqlQueries.Count.should_be(3);
            };
        }
Exemple #30
0
        void before_each()
        {
            seed = new Seed();

            users = new Users();

            users.Projection = d => new UserWithAutoProps(d).InitializeExtensions();

            games = new Games();

            library = new Library();
        }
Exemple #31
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySQL(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoles <IdentityRole>()
            .AddDefaultUI()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddControllersWithViews()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AddAreaFolderRouteModelConvention("Identity", "/Account", model =>
                {
                    var selectorCount = model.Selectors.Count;

                    var whitelistedIdentityEndpoints = new List <string>
                    {
                        "Identity/Account/Manage", "Identity/Account/Manage/ChangePassword", "Identity/Account/Login", "Identity/Account/AccessDenied", "Identity/Account/Logout"
                    };

                    for (var i = selectorCount - 1; i >= 0; i--)
                    {
                        var selectorTemplate = model.Selectors[i].AttributeRouteModel.Template;

                        if (!whitelistedIdentityEndpoints.Contains(selectorTemplate))
                        {
                            model.Selectors.RemoveAt(i);
                        }
                    }
                });
            });;

            Seed.Initialize(services.BuildServiceProvider(), "Test123!");
        }
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

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

            try
            {
                var context     = services.GetRequiredService <DataContext>();
                var userManager = services.GetRequiredService <UserManager <AppUser> >();
                var roleManager = services.GetRequiredService <RoleManager <AppRole> >();
                await context.Database.MigrateAsync().ConfigureAwait(false);

                await Seed.SeedUsers(userManager, roleManager).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService <ILogger <Program> >();
                logger.LogError(ex, "An error occurred during migration");
            }

            await host.RunAsync().ConfigureAwait(false);
        }
Exemple #33
0
        public static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(config)
                         // .WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day, outputTemplate: "{Timestamp} {Message}{NewLine:1}{Exception:1}")
                         .WriteTo.Console()
                         .CreateLogger();

            var host = CreateHostBuilder(args).Build();

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

            try
            {
                Log.Information("Application is starting");
                var context     = services.GetRequiredService <FinanceDBContext>();
                var userManager = services.GetRequiredService <UserManager <AppUser> >();
                await context.Database.MigrateAsync();

                await Seed.SeedData(context, userManager);

                Log.Information("Application started successfully");
            }
            catch (Exception e)
            {
                Log.Error(e, "The application failed to start!");
            }
            finally
            {
                Log.CloseAndFlush();
            }
            await host.RunAsync();
        }
Exemple #34
0
        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>();
                    var userManager = services.GetRequiredService <UserManager <User> >();
                    var roleManager = services.GetRequiredService <RoleManager <Role> >();
                    context.Database.Migrate();
                    Seed.SeedUsers(userManager, roleManager);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occured during migration");
                }
            }

            host.Run();
        }
Exemple #35
0
        public void TestSeedCreate(KeyType type)
        {
            var seed = Seed.Create(type);

            Assert.Equal(type, seed.Type);
            Assert.NotEqual(default, seed);
Exemple #36
0
 public static bool CompareSeeds(Seed seed1, Seed seed2)
 {
     // Literally check field by field That matters.
     if (seed1 == null)
     {
         return(false);
     }
     if (seed2 == null)
     {
         return(false);
     }
     if (seed1.randomSeedFromObjectHash != seed2.randomSeedFromObjectHash)
     {
         return(false);
     }
     if (seed1.randomSeed != seed2.randomSeed)
     {
         return(false);
     }
     if (seed1.growthDirection != seed2.growthDirection)
     {
         return(false);
     }
     if (seed1.growth != seed2.growth)
     {
         return(false);
     }
     if (seed1.twistX != seed2.twistX)
     {
         return(false);
     }
     if (seed1.twistY != seed2.twistY)
     {
         return(false);
     }
     if (seed1.correctiveBehavior != seed2.correctiveBehavior)
     {
         return(false);
     }
     if (seed1.straightness != seed2.straightness)
     {
         return(false);
     }
     if (seed1.rungSize != seed2.rungSize)
     {
         return(false);
     }
     if (seed1.branchSplitForced != seed2.branchSplitForced)
     {
         return(false);
     }
     if (seed1.branchSplitDynamic != seed2.branchSplitDynamic)
     {
         return(false);
     }
     if (seed1.branchHappening != seed2.branchHappening)
     {
         return(false);
     }
     if (seed1.treeRadius != seed2.treeRadius)
     {
         return(false);
     }
     if (seed1.minRadius != seed2.minRadius)
     {
         return(false);
     }
     if (seed1.radialSegments != seed2.radialSegments)
     {
         return(false);
     }
     return(true);
 }
 /// <inheritdoc />
 public Task <Bundle> PrepareTransferAsync(Seed seed, Bundle bundle, int securityLevel, Address remainderAddress = null, List <Address> inputAddresses = null)
 {
     return(null);
 }
 public DownloadItemInfo(Seed seed, string path)
 {
     this.Seed = seed;
     this.Path = path;
 }
Exemple #39
0
        protected override bool OnClientMessage(byte[] data)
        {
            switch (phase)
            {
            case Phase.Seed:
                if (data.Length != 4)
                {
                    throw new SocketException("Error while initializing LoginSocket. Invalid seed lenght.", this, data);
                }

                // Seed comes in little endian and encryption alghortm expects it in little endian, so i keep it as it is.
                Seed = ByteConverter.LittleEndian.ToUInt32(data, 0);
                CommunicationManager.LoginSeed = Seed;

                SendToServer(data);
                phase = Phase.Keys;
                return(true);

            case Phase.Keys:
                if (data.Length != 62)
                {
                    throw new SocketException("Error while initializing LoginSocket. Invalid login packet lenght.", this, data);
                }


                // Detect and create client encryption
                uint key1;
                uint key2;
                LoginEncryptionType clientEnc = GetClientEncryption(data, out key1, out key2);
                ClientEncryption = Encryption.CreateServerLogin(clientEnc, Seed, key1, key2);


                // Read and create server encryption
                uint serverKey1;
                uint serverKey2;
                LoginEncryptionType serverEnc;


                int v = Int32.Parse(Core.LaunchData.ServerEncryption);

                switch (v)
                {
                case 0:
                    serverKey1 = 0;
                    serverKey2 = 0;
                    serverEnc  = LoginEncryptionType.None;
                    Trace.WriteLine("Using no server encryption.", "Communication");
                    break;

                case 1:
                    serverKey1 = key1;
                    serverKey2 = key2;
                    serverEnc  = clientEnc;
                    Trace.WriteLine(String.Format("Server key1: {1} key2: {2}", Seed.ToString("X"), serverKey1.ToString("X"), serverKey2.ToString("X")), "Communication");
                    break;

                default:
                    try {
                        serverKey1 = UInt32.Parse(Core.LaunchData.ServerKey1, System.Globalization.NumberStyles.HexNumber);
                        serverKey2 = UInt32.Parse(Core.LaunchData.ServerKey2, System.Globalization.NumberStyles.HexNumber);
                        serverEnc  = LoginEncryptionType.New;
                    }
                    catch (Exception e) {
                        throw new Exception("Error parsing server login keys.", e);
                    }
                    Trace.WriteLine(String.Format("Server key1: {1} key2: {2}", Seed.ToString("X"), serverKey1.ToString("X"), serverKey2.ToString("X")), "Communication");
                    break;
                }

                ServerEncryption = Encryption.CreateClientLogin(serverEnc, Seed, serverKey1, serverKey2);

                byte[] decrypted = ClientEncryption.Decrypt(data);

                // Save used account and password. They will be used to detect game encryprion.
                CommunicationManager.Username = ByteConverter.BigEndian.ToAsciiString(decrypted, 1, 30);
                CommunicationManager.Password = ByteConverter.BigEndian.ToAsciiString(decrypted, 31, 30);

                SendToServer(decrypted);

                // Zero password for security reasons
                for (int i = 31; i < 61; i++)
                {
                    decrypted[i] = 0;
                }

                Core.OnClientMessage(decrypted, CallbackResult.Sent);

                phase = Phase.Normal;
                return(true);
            }

            return(base.OnClientMessage(data));
        }
Exemple #40
0
        public YomotsuWarrior() : base(AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4)
        {
            Body        = 245;
            BaseSoundID = 0x452;

            SetStr(486, 530);
            SetDex(151, 165);
            SetInt(17, 31);

            SetHits(486, 530);
            SetMana(17, 31);

            SetDamage(8, 10);

            SetDamageType(ResistanceType.Physical, 100);

            SetResistance(ResistanceType.Physical, 65, 85);
            SetResistance(ResistanceType.Fire, 30, 50);
            SetResistance(ResistanceType.Cold, 45, 65);
            SetResistance(ResistanceType.Poison, 35, 55);
            SetResistance(ResistanceType.Energy, 25, 50);

            SetSkill(SkillName.Anatomy, 85.1, 95.0);
            SetSkill(SkillName.MagicResist, 82.6, 90.5);
            SetSkill(SkillName.Tactics, 95.1, 105.0);
            SetSkill(SkillName.Wrestling, 97.6, 107.5);

            Fame  = 4200;
            Karma = -4200;

            PackItem(new GreenGourd());
            PackItem(new ExecutionersAxe());

            if (Utility.RandomBool())
            {
                PackItem(new LongPants());
            }
            else
            {
                PackItem(new ShortPants());
            }

            switch (Utility.Random(4))
            {
            case 0:
                PackItem(new Shoes());
                break;

            case 1:
                PackItem(new Sandals());
                break;

            case 2:
                PackItem(new Boots());
                break;

            case 3:
                PackItem(new ThighBoots());
                break;
            }

            if (Utility.RandomDouble() < .25)
            {
                PackItem(Seed.RandomBonsaiSeed());
            }
        }
 public SeedInteractionComponent(Seed owner)
 {
     this.owner = owner;
 }
 /// <inheritdoc />
 public FindUsedAddressesResponse FindUsedAddressesWithTransactions(Seed seed, int securityLevel, int start)
 {
     return(null);
 }
 /// <inheritdoc />
 public Task <FindUsedAddressesResponse> FindUsedAddressesWithTransactionsAsync(Seed seed, int securityLevel, int start)
 {
     return(null);
 }
Exemple #44
0
 //Constructor
 public GameTile(int xPos, int yPos, TileType type, bool tileIsTilled, bool canHarvest, bool tileIsWatered, Seed newPlantedSeed, int amountPlanted)
 {
     x                = xPos;
     y                = yPos;
     m_tileType       = type;
     m_isTilled       = tileIsTilled;
     m_canBeHarvested = canHarvest;
     //farmingTileStatus = farmTileStatus;
     m_plantedSeed = newPlantedSeed;
     m_daysPlanted = amountPlanted;
 }
Exemple #45
0
 public void SetPlantedSeed(Seed seed)
 {
     m_plantedSeed = seed;
 }
Exemple #46
0
        public override IElement Evaluate(IElement[] Arguments, Variables Variables)
        {
            string ColorExpression = null;

            SKColor[]         Palette;
            double            rc, ic;
            double            dr;
            int               dimx, dimy;
            int               i, c;
            object            Obj;
            Complex           z;
            ILambdaExpression f;
            ScriptNode        fDef = null;

            c = Arguments.Length;
            i = 0;

            Obj = Arguments[i++].AssociatedObjectValue;
            if (Obj is Complex)
            {
                z  = (Complex)Obj;
                rc = z.Real;
                ic = z.Imaginary;
            }
            else
            {
                rc = Expression.ToDouble(Obj);
                ic = Expression.ToDouble(Arguments[i++].AssociatedObjectValue);
            }

            if (i >= c)
            {
                throw new ScriptRuntimeException("Insufficient parameters in call to MandelbrotTopographyFractal().", this);
            }

            Obj = Arguments[i].AssociatedObjectValue;
            if (Obj is ILambdaExpression)
            {
                f    = (ILambdaExpression)Obj;
                fDef = this.Arguments[i++];

                if (f.NrArguments != 2)
                {
                    throw new ScriptRuntimeException("Lambda expression in calls to MandelbrotTopographyFractal() must be of two variables (z,c).", this);
                }
            }
            else
            {
                f    = null;
                fDef = null;

                if (Obj == null)
                {
                    i++;
                }
            }

            dr = Expression.ToDouble(Arguments[i++].AssociatedObjectValue);

            if (i < c && this.Arguments[i] != null && Arguments[i] is ObjectVector)
            {
                ColorExpression = this.Arguments[i].SubExpression;
                Palette         = FractalGraph.ToPalette((ObjectVector)Arguments[i++]);
            }
            else
            {
                Palette         = ColorModels.RandomLinearAnalogousHSL.CreatePalette(1024, 16, out int Seed, this, Variables);
                ColorExpression = "RandomLinearAnalogousHSL(1024,16," + Seed.ToString() + ")";

                if (i < c && this.Arguments[i] == null)
                {
                    i++;
                }
            }

            if (i < c)
            {
                dimx = (int)Expression.ToDouble(Arguments[i++].AssociatedObjectValue);
            }
            else
            {
                dimx = 320;
            }

            if (i < c)
            {
                dimy = (int)Expression.ToDouble(Arguments[i++].AssociatedObjectValue);
            }
            else
            {
                dimy = 200;
            }

            if (i < c)
            {
                throw new ScriptRuntimeException("Parameter mismatch in call to MandelbrotTopographyFractal(r,c,dr[,Palette][,dimx[,dimy]]).",
                                                 this);
            }

            if (dimx <= 0 || dimx > 5000 || dimy <= 0 || dimy > 5000)
            {
                throw new ScriptRuntimeException("Image size must be within 1x1 to 5000x5000", this);
            }

            if (f != null)
            {
                return(CalcMandelbrot(rc, ic, dr, f, Variables, Palette, dimx, dimy, this, this.FractalZoomScript,
                                      new object[] { Palette, dimx, dimy, ColorExpression, fDef }));
            }
            else
            {
                return(CalcMandelbrot(rc, ic, dr, Palette, dimx, dimy, this, this.FractalZoomScript,
                                      new object[] { Palette, dimx, dimy, ColorExpression, fDef }));
            }
        }
Exemple #47
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Seed seeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 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.UseExceptionHandler(builder =>
                {
                    builder.Run(async context => {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get <IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }
            var swaggerOptions = new Helpers.SwaggerOptions();

            Configuration.GetSection(nameof(Helpers.SwaggerOptions)).Bind(swaggerOptions);

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            // app.UseSwagger(option => { option.RouteTemplate = swaggerOptions.JsonRoute; });
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(option =>
            {
                option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description);
            });

            // Render angular's Index.html file for every 404 errors from refresh. See https://jasonwatmore.com/post/2016/07/26/angularjs-enable-html5-mode-page-refresh-without-404-errors-in-nodejs-and-iis
            app.Use(async(context, next) => {
                await next();

                if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
                {
                    context.Request.Path = "/index.html";
                    await next();
                }
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseRouting();
            // enable ssl on production
            // app.UseHttpsRedirection();
            seeder.SeedUsers();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapDefaultControllerRoute().RequireAuthorization();
            });
        }
Exemple #48
0
        private void InitSequence(Graph graph)
        {
            var orangeBox = _factory.CreateProduct(2) as OrangeBoxProduct;
            int elemts    = 2;

            Source = new Source <ProductBase>(elemts, orangeBox);
            var conveyor1 = _factory.CreateConveyor();
            var first     = _factory.CreateMachine("Станок1");
            var conveyor2 = _factory.CreateConveyor();
            var second    = _factory.CreateMachine("Станок2");
            var conveyor3 = _factory.CreateConveyor();
            var third     = _factory.CreateMachine("Станок3");
            var conveyor4 = _factory.CreateConveyor();

            Seed          = new Seed <ProductBase>(elemts);
            Seed.OnEmpty += Source_OnEmpty;

            Node sourceNode = new Node("Source")
            {
                UserData = Source,
            };

            Node nodeConveyor1 = new Node("c1")
            {
                UserData = conveyor1,
            };

            Node nodeFirst = new Node("m1")
            {
                UserData = first,
            };

            Node nodeConveyor2 = new Node("c2")
            {
                UserData = conveyor2,
            };

            Node nodeSecond = new Node("m2")
            {
                UserData = second,
            };

            Node nodeConveyor3 = new Node("c3")
            {
                UserData = conveyor3,
            };

            Node nodeThird = new Node("m3")
            {
                UserData = third,
            };

            Node nodeConveyor4 = new Node("c4")
            {
                UserData = conveyor4,
            };
            Node seedNode = new Node("Seed")
            {
                UserData = Seed,
            };

            Edge sourceToc1 = new Edge(sourceNode, nodeConveyor1, ConnectionToGraph.Connected);
            Edge c1Tom1     = new Edge(nodeConveyor1, nodeFirst, ConnectionToGraph.Connected);
            Edge m1Toc2     = new Edge(nodeFirst, nodeConveyor2, ConnectionToGraph.Connected);
            Edge c2Tom3     = new Edge(nodeConveyor2, nodeSecond, ConnectionToGraph.Connected);
            Edge m3Toc4     = new Edge(nodeSecond, nodeConveyor3, ConnectionToGraph.Connected);
            Edge c4Tom4     = new Edge(nodeConveyor3, nodeThird, ConnectionToGraph.Connected);
            Edge m4Toc4     = new Edge(nodeThird, nodeConveyor4, ConnectionToGraph.Connected);
            Edge c4Toseed   = new Edge(nodeConveyor4, seedNode, ConnectionToGraph.Connected);


            sourceToc1.LabelText = "0";
            c1Tom1.LabelText     = "0";
            m1Toc2.LabelText     = "0";
            c2Tom3.LabelText     = "0";
            m3Toc4.LabelText     = "0";
            c4Tom4.LabelText     = "0";
            m4Toc4.LabelText     = "0";
            c4Toseed.LabelText   = "0";
            //labelToChange = sourceToSeed.Label;
            var setts = graph.LayoutAlgorithmSettings;

            graph.AddNode(sourceNode);
            graph.AddNode(nodeConveyor1);
            graph.AddNode(nodeFirst);
            graph.AddNode(nodeConveyor2);
            graph.AddNode(nodeSecond);
            graph.AddNode(nodeConveyor3);
            graph.AddNode(nodeThird);
            graph.AddNode(nodeConveyor4);
            graph.AddNode(seedNode);
        }
Exemple #49
0
        public void TestRoundTrip(string base58)
        {
            var seed = new Seed(base58);

            Assert.Equal(base58, seed.ToString());
        }
 /// <inheritdoc />
 public Task <GetAccountDataResponse> GetAccountDataAsync(Seed seed, bool includeInclusionStates, int securityLevel, int addressStartIndex, int addressStopIndex = 0)
 {
     return(null);
 }
Exemple #51
0
        public MainWindow()
        {
            Common.Logging.LogManager.Adapter = new NLogLoggerFactoryAdapter(new Common.Logging.Configuration.NameValueCollection());

            //make sure we can connect to the database
            CheckDBConnection();

            //set the log directory
            SetLogDirectory();

            //set the connection string
            DBUtils.SetConnectionString();

            //set EF configuration, necessary for MySql to work
            DBUtils.SetDbConfiguration();

            InitializeComponent();
            DataContext = this;

            //load datagrid layout
            string layoutFile = AppDomain.CurrentDomain.BaseDirectory + "GridLayout.xml";

            if (File.Exists(layoutFile))
            {
                try
                {
                    InstrumentsGrid.DeserializeLayout(File.ReadAllText(layoutFile));
                }
                catch
                {
                }
            }

            LogMessages = new ConcurrentNotifierBlockingList <LogEventInfo>();

            //target is where the log managers send their logs, here we grab the memory target which has a Subject to observe
            var target = LogManager.Configuration.AllTargets.Single(x => x.Name == "myTarget") as MemoryTarget;

            //Log unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

            //we subscribe to the messages and send them all to the LogMessages collection
            if (target != null)
            {
                target.Messages.Subscribe(msg => LogMessages.TryAdd(msg));
            }

            //build the instruments grid context menu
            //we want a button for each BarSize enum value in the UpdateFreqSubMenu menu
            foreach (int value in Enum.GetValues(typeof(BarSize)))
            {
                var button = new MenuItem
                {
                    Header = Regex.Replace(((BarSize)value).ToString(), "([A-Z])", " $1").Trim(),
                    Tag    = (BarSize)value
                };
                button.Click += UpdateHistoricalDataBtn_ItemClick;
                ((MenuItem)Resources["UpdateFreqSubMenu"]).Items.Add(button);
            }

            //create metadata db if it doesn't exist
            var entityContext = new MyDBContext();

            entityContext.Database.Initialize(false);

            //seed the datasources no matter what, because these are added frequently
            Seed.SeedDatasources(entityContext);

            //check for any exchanges, seed the db with initial values if nothing is found
            if (!entityContext.Exchanges.Any())
            {
                Seed.DoSeed();
            }

            //create data db if it doesn't exist
            var dataContext = new DataDBContext();

            dataContext.Database.Initialize(false);
            dataContext.Dispose();

            //create quartz db if it doesn't exist
            QuartzUtils.InitializeDatabase(Settings.Default.databaseType);

            //build the tags menu
            var allTags = entityContext.Tags.ToList();

            BuildTagContextMenu(allTags);

            //build session templates menu
            BuildSetSessionTemplateMenu();

            Instruments = new ObservableCollection <Instrument>();

            var instrumentRepo = new InstrumentRepository(entityContext);
            var instrumentList = instrumentRepo.FindInstruments().Result;

            foreach (Instrument i in instrumentList)
            {
                Instruments.Add(i);
            }

            //create brokers
            var cfRealtimeBroker = new ContinuousFuturesBroker(new QDMSClient.QDMSClient(
                                                                   "RTDBCFClient",
                                                                   "127.0.0.1",
                                                                   Properties.Settings.Default.rtDBReqPort,
                                                                   Properties.Settings.Default.rtDBPubPort,
                                                                   Properties.Settings.Default.hDBPort,
                                                                   Properties.Settings.Default.httpPort,
                                                                   Properties.Settings.Default.apiKey,
                                                                   useSsl: Properties.Settings.Default.useSsl),
                                                               connectImmediately: false);
            var cfHistoricalBroker = new ContinuousFuturesBroker(new QDMSClient.QDMSClient(
                                                                     "HDBCFClient",
                                                                     "127.0.0.1",
                                                                     Properties.Settings.Default.rtDBReqPort,
                                                                     Properties.Settings.Default.rtDBPubPort,
                                                                     Properties.Settings.Default.hDBPort,
                                                                     Properties.Settings.Default.httpPort,
                                                                     Properties.Settings.Default.apiKey,
                                                                     useSsl: Properties.Settings.Default.useSsl),
                                                                 connectImmediately: false);
            var localStorage = DataStorageFactory.Get();

            RealTimeBroker = new RealTimeDataBroker(cfRealtimeBroker, localStorage,
                                                    new IRealTimeDataSource[] {
                //new Xignite(Properties.Settings.Default.xigniteApiToken),
                //new Oanda(Properties.Settings.Default.oandaAccountId, Properties.Settings.Default.oandaAccessToken),
                new IB(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, Properties.Settings.Default.rtdClientIBID),
                //new ForexFeed(Properties.Settings.Default.forexFeedAccessKey, ForexFeed.PriceType.Mid)
            });
            HistoricalBroker = new HistoricalDataBroker(cfHistoricalBroker, localStorage,
                                                        new IHistoricalDataSource[] {
                new Yahoo(),
                new FRED(),
                //new Forexite(),
                new IB(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, Properties.Settings.Default.histClientIBID),
                new Quandl(Properties.Settings.Default.quandlAuthCode),
                new BarChart(Properties.Settings.Default.barChartApiKey)
            });

            var countryCodeHelper = new CountryCodeHelper(entityContext.Countries.ToList());

            EconomicReleaseBroker = new EconomicReleaseBroker("FXStreet",
                                                              new[] { new fx.FXStreet(countryCodeHelper) });

            //create the various servers
            _realTimeServer       = new RealTimeDataServer(Properties.Settings.Default.rtDBPubPort, Properties.Settings.Default.rtDBReqPort, RealTimeBroker);
            _historicalDataServer = new HistoricalDataServer(Properties.Settings.Default.hDBPort, HistoricalBroker);

            //and start them
            _realTimeServer.StartServer();
            _historicalDataServer.StartServer();

            //we also need a client to make historical data requests with
            _client = new QDMSClient.QDMSClient(
                "SERVERCLIENT",
                "localhost",
                Properties.Settings.Default.rtDBReqPort,
                Properties.Settings.Default.rtDBPubPort,
                Properties.Settings.Default.hDBPort,
                Properties.Settings.Default.httpPort,
                Properties.Settings.Default.apiKey,
                useSsl: Properties.Settings.Default.useSsl);
            _client.Connect();
            _client.HistoricalDataReceived += _client_HistoricalDataReceived;

            ActiveStreamGrid.ItemsSource = RealTimeBroker.ActiveStreams;

            //create the scheduler
            var quartzSettings = QuartzUtils.GetQuartzSettings(Settings.Default.databaseType);
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory(quartzSettings);

            _scheduler            = schedulerFactory.GetScheduler();
            _scheduler.JobFactory = new JobFactory(HistoricalBroker,
                                                   Properties.Settings.Default.updateJobEmailHost,
                                                   Properties.Settings.Default.updateJobEmailPort,
                                                   Properties.Settings.Default.updateJobEmailUsername,
                                                   Properties.Settings.Default.updateJobEmailPassword,
                                                   Properties.Settings.Default.updateJobEmailSender,
                                                   Properties.Settings.Default.updateJobEmail,
                                                   new UpdateJobSettings(
                                                       noDataReceived: Properties.Settings.Default.updateJobReportNoData,
                                                       errors: Properties.Settings.Default.updateJobReportErrors,
                                                       outliers: Properties.Settings.Default.updateJobReportOutliers,
                                                       requestTimeouts: Properties.Settings.Default.updateJobTimeouts,
                                                       timeout: Properties.Settings.Default.updateJobTimeout,
                                                       toEmail: Properties.Settings.Default.updateJobEmail,
                                                       fromEmail: Properties.Settings.Default.updateJobEmailSender),
                                                   localStorage,
                                                   EconomicReleaseBroker);
            _scheduler.Start();

            //Take jobs stored in the qmds db and move them to the quartz db - this can be removed in the next version
            MigrateJobs(entityContext, _scheduler);

            var bootstrapper = new CustomBootstrapper(
                DataStorageFactory.Get(),
                EconomicReleaseBroker,
                HistoricalBroker,
                RealTimeBroker,
                Properties.Settings.Default.apiKey);
            var uri  = new Uri((Settings.Default.useSsl ? "https" : "http") + "://localhost:" + Properties.Settings.Default.httpPort);
            var host = new NancyHost(bootstrapper, uri);

            host.Start();

            entityContext.Dispose();

            ShowChangelog();
        }
 /// <inheritdoc />
 public GetInputsResponse GetInputs(Seed seed, long threshold, int securityLevel, int startIndex, int stopIndex = 0)
 {
     return(null);
 }
Exemple #53
0
        private void Update(EvaluationContext context)
        {
            var startPosition = Position.GetValue(context);
            var limitRange    = MaxRange.GetValue(context);
            var seed          = Seed.GetValue(context);
            var jumpDistance  = JumpDistance.GetValue(context);

            _rate = Rate.GetValue(context);

            var reset = Reset.GetValue(context);
            var jump  = Jump.GetValue(context);

            if (!_initialized || reset || float.IsNaN(_offset.X) || float.IsNaN(_offset.Y) || seed != _seed)
            {
                _random      = new Random(seed);
                _seed        = seed;
                _offset      = Vector2.Zero;
                _initialized = true;
                jump         = true;
            }

            _beatTime = EvaluationContext.BeatTime;

            if (UseRate)
            {
                var activationIndex = (int)(_beatTime * _rate);
                if (activationIndex != _lastActivationIndex)
                {
                    _lastActivationIndex = activationIndex;
                    jump = true;
                }
            }

            if (jump)
            {
                _jumpStartOffset  = _offset;
                _jumpTargetOffset = _offset + new Vector2(
                    (float)((_random.NextDouble() - 0.5f) * jumpDistance * 2f),
                    (float)((_random.NextDouble() - 0.5f) * jumpDistance * 2f));

                if (limitRange > 0.001f)
                {
                    var d = _jumpTargetOffset.Length();
                    if (d > limitRange)
                    {
                        var overshot            = Math.Min(d - limitRange, limitRange);
                        var random              = _random.NextDouble() * overshot;
                        var distanceWithinLimit = limitRange - (float)random;
                        var normalized          = _jumpTargetOffset / d;
                        _jumpTargetOffset = normalized * distanceWithinLimit;
                    }
                }

                _lastJumpTime = _beatTime;
            }

            var blending = Blending.GetValue(context);

            if (blending >= 0.001)
            {
                var t = (Fragment / blending).Clamp(0, 1);
                if (SmoothBlending.GetValue(context))
                {
                    t = MathUtils.SmootherStep(0, 1, t);
                }

                _offset = Vector2.Lerp(_jumpStartOffset, _jumpTargetOffset, t);
            }
            else
            {
                _offset = _jumpTargetOffset;
            }

            NewPosition.Value = _offset + startPosition;
        }
 /// <inheritdoc />
 public Task <GetInputsResponse> GetInputsAsync(Seed seed, long threshold, int securityLevel, int startIndex, int stopIndex = 0)
 {
     return(null);
 }
 /// <summary>
 /// The get chat pas salt.
 /// </summary>
 /// <returns>
 /// The <see cref="string"/>.
 /// </returns>
 private static string GetChatPasSalt()
 {
     return(Seed.Random() + Seed.Random().ToString().Substring(0, 20));
 }
 /// <inheritdoc />
 public Task <List <Address> > GetNewAddressesAsync(Seed seed, int addressStartIndex, int count, int securityLevel)
 {
     return(null);
 }
        public override IElement Evaluate(IElement[] Arguments, Variables Variables)
        {
            string ColorExpression = null;

            SKColor[] Palette;
            object    Obj;
            double    rc, ic;
            double    dr;
            double    Rr, Ri, pr, pi;
            int       dimx, dimy;
            int       i, c;

            rc = Expression.ToDouble(Arguments[0].AssociatedObjectValue);
            ic = Expression.ToDouble(Arguments[1].AssociatedObjectValue);
            dr = Expression.ToDouble(Arguments[2].AssociatedObjectValue);

            if ((Obj = Arguments[3].AssociatedObjectValue) is Complex)
            {
                Complex z = (Complex)Obj;
                Rr = z.Real;
                Ri = z.Imaginary;
            }
            else
            {
                Rr = Expression.ToDouble(Arguments[3].AssociatedObjectValue);
                Ri = 0;
            }

            if ((Obj = Arguments[4].AssociatedObjectValue) is Complex)
            {
                Complex z = (Complex)Obj;
                pr = z.Real;
                pi = z.Imaginary;
            }
            else
            {
                pr = Expression.ToDouble(Arguments[4].AssociatedObjectValue);
                pi = 0;
            }

            c = Arguments.Length;
            i = 5;

            if (i < c && this.Arguments[i] != null && Arguments[i] is ObjectVector)
            {
                ColorExpression = this.Arguments[i].SubExpression;
                Palette         = FractalGraph.ToPalette((ObjectVector)Arguments[i++]);
            }
            else
            {
                Palette         = ColorModels.RandomLinearAnalogousHSL.CreatePalette(128, 4, out int Seed, this, Variables);
                ColorExpression = "RandomLinearAnalogousHSL(128,4," + Seed.ToString() + ")";

                if (i < c && this.Arguments[i] is null)
                {
                    i++;
                }
            }

            if (i < c)
            {
                dimx = (int)Expression.ToDouble(Arguments[i++].AssociatedObjectValue);
            }
            else
            {
                dimx = 320;
            }

            if (i < c)
            {
                dimy = (int)Expression.ToDouble(Arguments[i++].AssociatedObjectValue);
            }
            else
            {
                dimy = 200;
            }

            if (i < c)
            {
                throw new ScriptRuntimeException("Parameter mismatch in call to NovaTopographyFractal(r,c,dr,Coefficients[,Palette][,dimx[,dimy]]).",
                                                 this);
            }

            if (dimx <= 0 || dimx > 5000 || dimy <= 0 || dimy > 5000)
            {
                throw new ScriptRuntimeException("Image size must be within 1x1 to 5000x5000", this);
            }

            return(CalcNova(rc, ic, dr, Rr, Ri, pr, pi, Palette, dimx, dimy,
                            this, this.FractalZoomScript,
                            new object[] { Palette, dimx, dimy, Rr, Ri, pr, pi, ColorExpression }));
        }
 /// <inheritdoc />
 public Task <List <Bundle> > GetTransfersAsync(Seed seed, int securityLevel, bool includeInclusionStates, int addressStartIndex, int addressStopIndex = 0)
 {
     return(null);
 }
Exemple #59
0
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     Seed.SeedApplicationEvent(modelBuilder);
 }
 public CourseService(Seed _seed)
 {
     _courseRepository = new CourseRepository(_seed);
 }