Exemplo n.º 1
0
        /// <summary>
        /// Updates the selected counter
        /// </summary>
        /// <param name="counter"></param>
        /// <returns></returns>
        public async Task Update(UpdateCounter counter, int counterId)
        {
            try
            {
                // rollbacks if there are errors
                using (var transaction = await _context.Database.BeginTransactionAsync())
                {
                    var updtCounter = await _context.Counters.FirstOrDefaultAsync(
                        x => x.CounterId == counterId);

                    if (updtCounter == null)
                    {
                        throw new Exception("The counter is not found!");
                    }

                    // Update the properties
                    updtCounter.COunterNo     = counter.CounterNo;
                    updtCounter.CounterName   = counter.CounterName;
                    updtCounter.CounterTypeId = counter.CounterTypeId;

                    _context.Counters.Update(updtCounter);
                    await _context.SaveChangesAsync();

                    transaction.Commit(); // Commits to the database
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Makes the give <paramref name="updatable"/> to trigger <see cref="Debugger.Break"/> when <see cref="IUpdatable.Updated"/> is fired.
        /// </summary>
        /// <param name="interval">On every n updates to break. by default 1.</param>
        public static T BreakOnUpdate <T>(this T updatable, int interval = 1) where T : IUpdatable
        {
            if (interval < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(interval));
            }
            if (interval > 1)
            {
                var cnt = new UpdateCounter {
                    Interval = interval, Updates = 0
                };
                updatable.Updated += (time, updated) => {
                    if (++cnt.Updates < cnt.Interval)
                    {
                        return;
                    }
                    _breakOnUpdate(updatable, time, updated);
                    cnt.Updates = 0;
                };

                return(updatable);
            }

            updatable.Updated += (time, updated) => _breakOnUpdate(updatable, time, updated);
            return(updatable);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates new counter for the queue
        /// </summary>
        /// <param name="newCounter"></param>
        /// <returns></returns>
        public async Task Create(UpdateCounter value)
        {
            try
            {
                // rollbacks if there are errors
                using (var transaction = await _context.Database.BeginTransactionAsync())
                {
                    var newCounter = new Counter
                    {
                        CounterName   = value.CounterName,
                        COunterNo     = value.CounterNo,
                        CounterTypeId = value.CounterTypeId
                    };

                    await _context.Counters.AddAsync(newCounter);

                    await _context.SaveChangesAsync();

                    transaction.Commit(); // Commits to the database
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 4
0
        /// <summary>
        ///     Setup of readonly fields and non-optional steps.
        /// </summary>
        private World(WorldInformation information, string worldDirectory, string chunkDirectory,
            IWorldGenerator generator)
        {
            positionsToActivate = new HashSet<(int x, int z)>();
            positionsActivating = new HashSet<(int, int)>();
            chunksToGenerate = new UniqueQueue<Chunk>();
            chunkGenerateTasks = new List<Task>(MaxGenerationTasks);
            chunksGenerating = new Dictionary<int, Chunk>(MaxGenerationTasks);
            positionsToLoad = new UniqueQueue<(int x, int z)>();
            chunkLoadingTasks = new List<Task<Chunk?>>(MaxLoadingTasks);
            positionsLoading = new Dictionary<int, (int x, int z)>(MaxLoadingTasks);
            activeChunks = new Dictionary<ValueTuple<int, int>, Chunk>();
            positionsToReleaseOnActivation = new HashSet<(int x, int z)>();
            chunksToSave = new UniqueQueue<Chunk>();
            chunkSavingTasks = new List<Task>(MaxSavingTasks);
            chunksSaving = new Dictionary<int, Chunk>(MaxSavingTasks);
            positionsSaving = new HashSet<(int x, int z)>(MaxSavingTasks);
            positionsActivatingThroughSaving = new HashSet<(int x, int z)>();

            Information = information;

            WorldDirectory = worldDirectory;
            ChunkDirectory = chunkDirectory;
            this.generator = generator;

            UpdateCounter = new UpdateCounter();

            Setup();
        }
        /// <summary>
        ///     Setup the manager after deserialization.
        /// </summary>
        /// <param name="containingWorld">The world in which ticks are issued.</param>
        /// <param name="counter">The current game update counter.</param>
        public void Setup(World containingWorld, UpdateCounter counter)
        {
            world         = containingWorld;
            updateCounter = counter;

            Load();
        }
        /// <summary>
        ///     Create a new scheduled tick manager.
        /// </summary>
        /// <param name="maxTicks">The maximum amount of ticks per frame.</param>
        /// <param name="world">The world in which ticks are issued.</param>
        /// <param name="updateCounter">The current game update counter.</param>
        public ScheduledTickManager(int maxTicks, World world, UpdateCounter updateCounter)
        {
            this.maxTicks = maxTicks;

            this.world         = world;
            this.updateCounter = updateCounter;
        }
        public virtual void EstimateAwarenessRate(BlackWhiteSubject?Opinion, UpdateCounter counter)
        {
            foreach (var can in Candidates)
            {
                //この候補は意見形成できるか?
                bool formed = OpinionFormed(can, Opinion, counter);
                //↑can.EstimateAwarenessRateに入れてしまってもいいが入れられない.結構依存が大きい OpinionFormedはImportaceLevelを使う

                //推定値を更新 //意見が更新できたか
                can.EstimateAwarenessRate(formed);
            }

            OnEstimationChanged(new EstimationEventArgs(Candidates));
        }
Exemplo n.º 8
0
        internal GameScene(Application.Client client, ClientWorld world, GameConsole console)
        {
            this.client = client;

            Player = null !;

            Screen.SetCursor(visible: false, locked: true);

            ui = new GameUserInterface(
                client,
                client.Keybinds.Input.Listener,
                drawBackground: false);

            List <ISettingsProvider> settingsProviders = new()
            {
                client.Settings,
                Application.Client.Instance.Keybinds
            };

            ui.SetSettingsProviders(settingsProviders);
            ui.SetConsoleProvider(console);
            ui.SetPerformanceProvider(client);

            ui.WorldExit += client.LoadStartScene;

            ui.AnyOverlayOpen += () =>
            {
                Screen.SetOverlayLock();
                Screen.SetCursor(visible: true, locked: false);
            };

            ui.AnyOverlayClosed += () =>
            {
                Screen.ClearOverlayLock();
                Screen.SetCursor(visible: false, locked: true);
            };

            World   = world;
            counter = world.UpdateCounter;

            uiToggle = client.Keybinds.GetToggle(client.Keybinds.UI);

            screenshotButton = client.Keybinds.GetPushButton(client.Keybinds.Screenshot);
            consoleToggle    = client.Keybinds.GetToggle(client.Keybinds.Console);
            escapeButton     = client.Keybinds.GetPushButton(client.Keybinds.Escape);
        }
Exemplo n.º 9
0
        public void WhoopsIGotFiveTrafficTickets()
        {
            var          fetchCounterOptions = new FetchCounterOptions("counters", "counters", "traffic_tickts");
            FetchCounter cmd = new FetchCounter(fetchCounterOptions);

            // NB: for cleanup
            options = fetchCounterOptions;

            RiakResult rslt = client.Execute(cmd);

            CheckResult(rslt);

            CounterResponse response = cmd.Response;

            Assert.AreEqual(0, response.Value);

            var builder = new UpdateCounter.Builder();

            builder.WithBucketType("counters")
            .WithBucket("counters")
            .WithKey("traffic_tickets")
            .WithIncrement(5);

            UpdateCounter updateCmd = builder.Build();

            rslt = client.Execute(updateCmd);
            CheckResult(rslt);

            response = updateCmd.Response;
            Assert.AreEqual(5, response.Value);

            // Modify the builder's increment, then construct a new command
            builder.WithIncrement(-5);
            updateCmd = builder.Build();

            rslt = client.Execute(updateCmd);
            CheckResult(rslt);

            response = updateCmd.Response;
            Assert.AreEqual(0, response.Value);
        }
Exemplo n.º 10
0
        public void UpdateCounter_Counterの正常系テスト()
        {
            UpdateCounter counter = new UpdateCounter();

            counter.CountUp();
            counter.CountUp();
            counter.CountUp();

            Assert.AreEqual(counter.UpdateNum, 3);
            Assert.AreEqual(counter.UpdateRight, 3);
            Assert.AreEqual(counter.UpdateLeft, 0);

            counter.CountDown();
            counter.CountDown();
            counter.CountDown();

            Assert.AreEqual(counter.UpdateNum, 0);
            Assert.AreEqual(counter.UpdateRight, 3);
            Assert.AreEqual(counter.UpdateLeft, 0);

            counter.CountDown();
            counter.CountDown();
            counter.CountDown();

            Assert.AreEqual(counter.UpdateNum, -3);
            Assert.AreEqual(counter.UpdateRight, 3);
            Assert.AreEqual(counter.UpdateLeft, 3);

            counter.CountUp();
            counter.CountUp();
            counter.CountUp();

            Assert.AreEqual(counter.UpdateNum, 0);
            Assert.AreEqual(counter.UpdateRight, 3);
            Assert.AreEqual(counter.UpdateLeft, 3);
            //Assert.AreEqual(agent.Belief, agent.PriorBelief);

            //Assert.IsTrue(Math.Abs(agent.Belief - agent.PriorBelief) < 0.00001);
        }
Exemplo n.º 11
0
        public CounterValue IncrementGCounter(UpdateCounter update, ICommandContext ctx)
        {
            if (update.Value < 0)
            {
                ctx.Fail("Cannot decrement IGCounter");
            }

            return(ctx.State <IGCounter>(typeof(IGCounter))
                   .Match(
                       x =>
            {
                if (update.Value > 0)
                {
                    x.Increment(update.Value);
                }
                return new CounterValue
                {
                    Value = x.Value
                };
            },
                       () => throw new InvalidOperationException("No state found.")));
        }
        private CounterResponse SaveCounter(string key = null)
        {
            var updateBuilder = new UpdateCounter.Builder(DefaultIncrement)
                                .WithBucketType(BucketType)
                                .WithBucket(Bucket)
                                .WithTimeout(TimeSpan.FromMilliseconds(20000));

            if (!string.IsNullOrEmpty(key))
            {
                updateBuilder.WithKey(key);
            }

            UpdateCounter cmd  = updateBuilder.Build();
            RiakResult    rslt = client.Execute(cmd);

            Assert.IsTrue(rslt.IsSuccess, rslt.ErrorMessage);

            CounterResponse response = cmd.Response;

            Keys.Add(response.Key);

            return(response);
        }
        public void Should_Build_DtUpdateReq_Correctly()
        {
            var updateCounterCommandBuilder = new UpdateCounter.Builder(DefaultIncrement);

            var q1 = new Quorum(1);
            var q2 = new Quorum(2);
            var q3 = new Quorum(3);

            updateCounterCommandBuilder
            .WithBucketType(BucketType)
            .WithBucket(Bucket)
            .WithKey(Key)
            .WithW(q3)
            .WithPW(q1)
            .WithDW(q2)
            .WithReturnBody(true)
            .WithIncludeContext(false)
            .WithTimeout(TimeSpan.FromSeconds(20));

            UpdateCounter updateCounterCommand = updateCounterCommandBuilder.Build();

            DtUpdateReq protobuf = (DtUpdateReq)updateCounterCommand.ConstructPbRequest();

            Assert.AreEqual(Encoding.UTF8.GetBytes(BucketType), protobuf.type);
            Assert.AreEqual(Encoding.UTF8.GetBytes(Bucket), protobuf.bucket);
            Assert.AreEqual(Encoding.UTF8.GetBytes(Key), protobuf.key);
            Assert.AreEqual(q3, protobuf.w);
            Assert.AreEqual(q1, protobuf.pw);
            Assert.AreEqual(q2, protobuf.dw);
            Assert.IsTrue(protobuf.return_body);
            Assert.IsFalse(protobuf.include_context);
            Assert.AreEqual(20000, protobuf.timeout);

            CounterOp counterOpMsg = protobuf.op.counter_op;

            Assert.AreEqual(DefaultIncrement, counterOpMsg.increment);
        }
        public virtual bool OpinionFormed(Candidate can, BlackWhiteSubject?Opinion, UpdateCounter counter)
        {
            //ImportanceLevelに依存

            //3つの条件の論理式

            //意見を決められたか
            bool determined = Opinion != null;

            //現在のより大きいか?
            bool bigger = can.ImportanceLevel >= ImportanceLevel;

            //この候補にとって十分な意見が来たか?

            /*  bool enoughUpd = counter.UpdateNum  > 0 ? //この場合わけをすべきか?
             *           counter.UpdateRight >= can.JumpNumRight : //正だったらrightと比べる
             *           counter.UpdateLeft  >= can.JumpNumLeft; //負だったらleftと比べる */

            bool enoughUpd = counter.UpdateRight >= can.JumpNumRight ||
                             counter.UpdateLeft >= can.JumpNumLeft;        //一番近いσを,超えられるか

            //意見を決められていて、候補の方が大きいか、 もしくは、十分な意見が来たか。
            return((determined && bigger) || enoughUpd);
        }
Exemplo n.º 15
0
        public async Task <IActionResult> UpdateCounter([FromBody] UpdateCounter value, int counterId)
        {
            await _cService.Update(value, counterId);

            return(Ok());
        }
Exemplo n.º 16
0
        public async Task <IActionResult> CreateCounter([FromBody] UpdateCounter value)
        {
            await _cService.Create(value);

            return(Ok());
        }