Esempio n. 1
0
        public static void BuildContent(ReportData client, OpenXmlPartContainer container, BlockItem block, string blockName, Dictionary <string, string> options)
        {
            TextBlock instance = BlockHelper.GetAssociatedBlockInstance <TextBlock>(blockName);

            if (null == instance)
            {
                return;
            }
            LogHelper.Instance.LogDebugFormat("Start TextBlock generation : Type {0}", blockName);
            Stopwatch treatmentWatch = Stopwatch.StartNew();
            string    content        = instance.Content(client, options);

            ApplyContent(client, container, block, content);
            treatmentWatch.Stop();
            LogHelper.Instance.LogDebugFormat
                ("End TextBlock generation ({0}) in {1} ms"
                , blockName
                , treatmentWatch.ElapsedMilliseconds.ToString()
                );
        }
Esempio n. 2
0
        public void Append(Message message)
        {
            if (_stream == null)
            {
                throw new ObjectDisposedException("LogWriter");
            }

            if (message.Time != _time)
            {
                BlockHelper.WriteBlock(_stream, BlockType.Timestamp,
                                       new ArraySegment <byte>(LogHelper.DateTimeToBytes(message.Time)));
                _time = message.Time;
            }

            var blockType = message.Direction == MessageDirection.ClientToServer ? BlockType.Client : BlockType.Server;

            BlockHelper.WriteBlock(_stream, blockType, message.Data);

            _stream.Flush();
        }
Esempio n. 3
0
        /// <summary>
        /// Sets a single block into location specified
        /// </summary>
        /// <param name="inChunkPosition"></param>
        /// <param name="blockValue"></param>
        /// <param name="tag"></param>
        /// <param name="sourceDynamicId">Id of the entity that is responsible for the change</param>
        public override void SetBlock(Vector3I inChunkPosition, byte blockValue, BlockTag tag = null, uint sourceDynamicId = 0)
        {
            int index = ChunkCubes.Index(inChunkPosition.X + DataProviderUser.ChunkPositionBlockUnit.X,
                                         inChunkPosition.Y,
                                         inChunkPosition.Z + DataProviderUser.ChunkPositionBlockUnit.Y);

            ChunkCubes.Cubes[index] = new TerraCube(blockValue);

            SetTag(tag, inChunkPosition);

            RefreshMetaData(BlockHelper.ConvertToGlobal(new Vector3I(DataProviderUser.ChunkPositionBlockUnit.X, 0, DataProviderUser.ChunkPositionBlockUnit.Y), inChunkPosition), blockValue);

            OnBlockDataChanged(new ChunkDataProviderDataChangedEventArgs
            {
                Locations       = new[] { inChunkPosition },
                Bytes           = new[] { blockValue },
                Tags            = tag != null ? new[] { tag } : null,
                SourceDynamicId = sourceDynamicId
            });
        }
Esempio n. 4
0
        private List <SudokuCell> ApplyCandidate(SudokuCell cell, int value)
        {
            List <SudokuCell> result = new List <SudokuCell>();

            for (int i = 0; i < BlockCount; i++)
            {
                // Check row
                var reducedCell = new SudokuCell(cell.X, i);
                if (i != cell.Y && _cellCandidatesDictionary.ContainsKey(reducedCell) &&
                    _cellCandidatesDictionary[reducedCell].Remove(value))
                {
                    result.Add(reducedCell);
                }
                // Check column
                reducedCell = new SudokuCell(i, cell.Y);
                if (i != cell.X && _cellCandidatesDictionary.ContainsKey(reducedCell) &&
                    _cellCandidatesDictionary[reducedCell].Remove(value))
                {
                    result.Add(reducedCell);
                }
            }
            int xStartPosition = BlockHelper.GetBlockStartPosition(cell.X, BlockRowCount);
            int xEndPosition   = BlockHelper.GetBlockEndPosition(cell.X, BlockRowCount);
            int yStartPosition = BlockHelper.GetBlockStartPosition(cell.Y, BlockRowCount);
            int yEndPosition   = BlockHelper.GetBlockEndPosition(cell.Y, BlockRowCount);

            // Check sector
            for (int i = xStartPosition; i < xEndPosition; i++)
            {
                for (int j = yStartPosition; j < yEndPosition; j++)
                {
                    var reducedCell = new SudokuCell(i, j);
                    if (!(i == cell.X || j == cell.Y) && _cellCandidatesDictionary.ContainsKey(reducedCell) &&
                        _cellCandidatesDictionary[reducedCell].Remove(value))
                    {
                        result.Add(reducedCell);
                    }
                }
            }
            return(result);
        }
Esempio n. 5
0
        private Tuple <Procedure, Implementation> GetCheckerTuple(
            List <Requires> requires, List <Variable> locals, List <Cmd> cmds, string suffix = "")
        {
            var proc = DeclHelper.Procedure(
                civlTypeChecker.AddNamePrefix($"IS_{checkName}_{inputAction.proc.Name}{suffix}"),
                invariantAction.impl.InParams,
                invariantAction.impl.OutParams,
                requires,
                modifies,
                new List <Ensures>());
            var impl = DeclHelper.Implementation(
                proc,
                proc.InParams,
                proc.OutParams,
                locals,
                new List <Block> {
                BlockHelper.Block(checkName, cmds)
            });

            return(Tuple.Create(proc, impl));
        }
Esempio n. 6
0
        public static void ExportCrosses()
        {
            Database database = HostApplicationServices.WorkingDatabase;
            Editor   editor   = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;

            using (Transaction transaction = database.TransactionManager.StartTransaction())
            {
                ObjectId[] blockReferenceIdCollection = BlockHelper.PromptForBlockSelection(editor, "Изберете координатни кръстове: ");
                if (blockReferenceIdCollection == null)
                {
                    editor.WriteMessage("\nНевалидна селекция");

                    return;
                }

                StringBuilder output = new StringBuilder();

                foreach (ObjectId blockReferenceId in blockReferenceIdCollection)
                {
                    BlockReference blockReference = (BlockReference)transaction.GetObject(blockReferenceId, OpenMode.ForWrite);

                    if (blockReference.Name != Cross.BlockName)
                    {
                        continue;
                    }

                    output.AppendFormat("{0} {1}{2}", blockReference.Position.X, blockReference.Position.Y, Environment.NewLine);
                }

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(saveFileDialog.FileName, output.ToString());
                }

                transaction.Commit();
            }
        }
        public static async Task ProcessLitigationCompleted(MySqlConnection connection, int blockchainID, Web3 cl,
                                                            EventLog <List <ParameterOutput> > eventLog, EthApiService eth)
        {
            if (OTContract_Litigation_LitigationCompleted.TransactionExists(connection, eventLog.Log.TransactionHash, blockchainID))
            {
                return;
            }

            var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                   cl, blockchainID);

            var offerId =
                HexHelper.ByteArrayToString((byte[])eventLog.Event
                                            .First(e => e.Parameter.Name == "offerId").Result);

            var holderIdentity = (string)eventLog.Event
                                 .First(e => e.Parameter.Name == "holderIdentity").Result;

            var dhWasPenalized = (bool)eventLog.Event
                                 .First(e => e.Parameter.Name == "DH_was_penalized").Result;

            var transaction = await eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

            var receipt = await eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

            var row = new OTContract_Litigation_LitigationCompleted()
            {
                TransactionHash = eventLog.Log.TransactionHash,
                BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                Timestamp       = block.Timestamp,
                OfferId         = offerId,
                HolderIdentity  = holderIdentity,
                DHWasPenalized  = dhWasPenalized,
                GasPrice        = (UInt64)transaction.GasPrice.Value,
                GasUsed         = (UInt64)receipt.GasUsed.Value,
                BlockchainID    = blockchainID
            };

            await OTContract_Litigation_LitigationCompleted.InsertIfNotExist(connection, row);
        }
Esempio n. 8
0
        public static void BuildContent(ReportData client, OpenXmlPartContainer container, BlockItem block, string blockName, Dictionary <string, string> options)
        {
            TableBlock instance = BlockHelper.GetAssociatedBlockInstance <TableBlock>(blockName);

            if (null != instance)
            {
                LogHelper.Instance.LogDebugFormat("Start TableBlock generation : Type {0}", blockName);
                Stopwatch       treatmentWatch = Stopwatch.StartNew();
                TableDefinition content        = instance.Content(client, options);
                if (null != content)
                {
                    ApplyContent(client, container, block, content, options);
                }
                treatmentWatch.Stop();
                LogHelper.Instance.LogDebugFormat
                    ("End TableBlock generation ({0}) in {1} millisecond{2}"
                    , blockName
                    , treatmentWatch.ElapsedMilliseconds.ToString()
                    , treatmentWatch.ElapsedMilliseconds > 1 ? "s" : string.Empty
                    );
            }
        }
        public async Task <Transaction> GenerateTransactionAsync(Address contractAddress, string methodName,
                                                                 IMessage input)
        {
            var blockchainService = Application.ServiceProvider.GetRequiredService <IBlockchainService>();
            var refBlock          = await blockchainService.GetBestChainLastBlockHeaderAsync();

            var tx = new Transaction
            {
                From           = Address.FromPublicKey(KeyPair.PublicKey),
                To             = contractAddress,
                MethodName     = methodName,
                Params         = input.ToByteString(),
                RefBlockNumber = refBlock.Height,
                RefBlockPrefix = BlockHelper.GetRefBlockPrefix(refBlock.GetHash())
            };

            var signature = CryptoHelper.SignWithPrivateKey(KeyPair.PrivateKey, tx.GetHash().ToByteArray());

            tx.Signature = ByteString.CopyFrom(signature);

            return(tx);
        }
        public void UnpackDWordTest()
        {
            var rand = new Random();

            uint[] b   = new uint[2048];
            byte[] buf = new byte[b.Length * 4];

            for (var i = 0; i < b.Length; i++)
            {
                b[i] = (uint)rand.Next(int.MinValue, int.MaxValue);
            }

            for (var i = 0; i < buf.Length; i++)
            {
                buf[i] = (byte)((b[i / 4] >> ((i % 4) * 8)) & byte.MaxValue);
            }

            for (var i = 0; i < b.Length; i++)
            {
                Assert.IsTrue(BlockHelper.UnpackDWord(buf, i * 4) == b[i]);
            }
        }
        public void UnpackQwordTest()
        {
            var rand = new Random();

            ulong[] b   = new ulong[2048];
            byte[]  buf = new byte[b.Length * 8];

            for (var i = 0; i < b.Length; i++)
            {
                b[i] = (ulong)rand.Next(int.MinValue, int.MaxValue);
            }

            for (var i = 0; i < buf.Length; i++)
            {
                buf[i] = (byte)((b[i / 8] >> ((i % 8) * 8)) & byte.MaxValue);
            }

            for (var i = 0; i < b.Length; i++)
            {
                Assert.IsTrue(BlockHelper.UnpackQWord(buf, i * 8) == b[i]);
            }
        }
Esempio n. 12
0
        public void GetAssertiveAntennas()
        {
            if (this.AssertiveAntennaList.Count == 0)
            {
                this.AssertiveAntennaList = BlockHelper.GetGridAntennas(this.RemoteControl.SlimBlock.CubeGrid);

                if (this.AssertiveAntennaList.Count > 0)
                {
                    for (int i = this.AssertiveAntennaList.Count - 1; i >= 0; i--)
                    {
                        var ant = this.AssertiveAntennaList[i];

                        if (ant?.SlimBlock == null)
                        {
                            this.AssertiveAntennaList.RemoveAt(i);
                            continue;
                        }

                        if (ant.IsFunctional == false || ant.IsWorking == false || ant.IsBroadcasting == false)
                        {
                            this.AssertiveAntennaList.RemoveAt(i);
                            continue;
                        }

                        if (this.AssertiveAntennaNames.Count > 0 && this.AssertiveAntennaNames.Contains(ant.CustomName) == false)
                        {
                            this.AssertiveAntennaList.RemoveAt(i);
                            continue;
                        }
                    }

                    if (this.AssertiveAntennaList.Count == 0)
                    {
                        this.UseAssertiveAntennas = false;
                        return;
                    }
                }
            }
        }
Esempio n. 13
0
        private void ReadHeader()
        {
            BlockType blockType;

            byte[] data;

            {
                // magic bytes
                BlockHelper.ReadBlock(_stream, out blockType, out data);
                if (blockType != BlockType.MagicBytes)
                {
                    throw new FormatException("First block must be a MagicBytes block");
                }
                if (!data.SequenceEqual(LogHelper.Encoding.GetBytes(LogHelper.MagicBytes)))
                {
                    throw new FormatException("Incorrect magic bytes");
                }
            }

            do
            {
                BlockHelper.ReadBlock(_stream, out blockType, out data);
                switch (blockType)
                {
                case BlockType.Start:
                    break;

                case BlockType.Region:
                    Header.Region = LogHelper.Encoding.GetString(data);
                    break;

                case BlockType.MagicBytes:
                case BlockType.Timestamp:
                case BlockType.Server:
                case BlockType.Client:
                    throw new FormatException($"Unexpected block type in header '{blockType}'");
                }
            } while (blockType != BlockType.Start);
        }
Esempio n. 14
0
        public void ProcessCommandReceiveTriggerWatcher(string commandCode, IMyRemoteControl senderRemote, double radius, long entityId)
        {
            if (!_behavior.IsAIReady())
            {
                return;
            }

            if (senderRemote?.SlimBlock?.CubeGrid == null || this.RemoteControl?.SlimBlock?.CubeGrid == null)
            {
                return;
            }

            var antenna = BlockHelper.GetActiveAntenna(this.AntennaList);

            if (antenna == null)
            {
                return;
            }

            if (Vector3D.Distance(this.RemoteControl.GetPosition(), senderRemote.GetPosition()) > radius)
            {
                return;
            }

            for (int i = 0; i < this.CommandTriggers.Count; i++)
            {
                var trigger = this.CommandTriggers[i];

                if (trigger.UseTrigger == true && commandCode == trigger.CommandReceiveCode)
                {
                    trigger.ActivateTrigger();

                    if (trigger.Triggered == true)
                    {
                        ProcessTrigger(trigger, entityId, true);
                    }
                }
            }
        }
        public void UnpackByteTest()
        {
            var rand = new Random();

            byte[] b   = new byte[2048];
            byte[] buf = new byte[b.Length];

            for (var i = 0; i < b.Length; i++)
            {
                b[i] = (byte)rand.Next(byte.MinValue, byte.MaxValue);
            }

            for (var i = 0; i < buf.Length; i++)
            {
                buf[i] = b[i];
            }

            for (var i = 0; i < b.Length; i++)
            {
                Assert.IsTrue(BlockHelper.UnpackByte(buf, i) == b[i]);
            }
        }
        public void UnpackWordTest()
        {
            var rand = new Random();

            ushort[] b   = new ushort[2048];
            byte[]   buf = new byte[b.Length * 2];

            for (var i = 0; i < b.Length; i++)
            {
                b[i] = (ushort)rand.Next(ushort.MinValue, ushort.MaxValue);
            }

            for (var i = 0; i < buf.Length; i++)
            {
                buf[i] = (byte)((b[i / 2] >> ((i % 2) * 8)) & byte.MaxValue);
            }

            for (var i = 0; i < b.Length; i++)
            {
                Assert.IsTrue(BlockHelper.UnpackWord(buf, i * 2) == b[i]);
            }
        }
Esempio n. 17
0
    public void InitRandom(Int3 size, int mineCount)
    {
        this.size            = size;
        this.totalMineCount  = mineCount;
        this.remainMineCount = mineCount;
        List <Int3> posList = new List <Int3>();

        map = new Dictionary <Int3, BlockType>();
        BlockHelper.sizeForeach(size, (Int3 pos) => {
            posList.Add(pos);
            map.Add(pos, BlockType.Num0);
        });

        for (int i = 0; i < mineCount; i++)
        {
            int  idx     = Random.Range(0, posList.Count);
            Int3 mineNow = posList[idx];

            map[mineNow] = BlockType.Bomb;
            for (int j = 0; j < BlockHelper.SixDirections.Length; j++)
            {
                Int3 dir = BlockHelper.SixDirections[j];
                Int3 pos = mineNow + dir;
                if (map.ContainsKey(pos))
                {
                    if (Block.IsNum(map[pos]))
                    {
                        map[pos] = (BlockType)(map[pos] + 1);
                    }
                }
            }


            posList.RemoveAt(idx);
        }


        // map = new bool[size.x,size.y,size.z];
    }
        public void UnpackWStringTest()
        {
            var builder = new StringBuilder();
            var rand    = new Random();

            string[] s   = new string[99];
            byte[]   buf = new byte[2 * 4950 + 1]; // triangle number T(99) = 4950

            var offset = 0;

            for (var i = 0; i < s.Length; i++)
            {
                for (var j = 0; j < i; j++)
                {
                    builder.Append((char)rand.Next(char.MinValue + 1, char.MaxValue));

                    if (builder[builder.Length - 1] >= 0xD800 && builder[builder.Length - 1] <= 0xDFFF)
                    {
                        builder.Remove(builder.Length - 1, 1);
                        j--;
                    }
                }

                s[i] = builder.ToString();
                builder.Clear();
                Encoding.Unicode.GetBytes(s[i]).CopyTo(buf, offset);
                buf[offset + 2 * i]       = 0x00;
                buf[offset + 2 * (i + 1)] = 0x00;
                offset += 2 * (i + 1);
            }

            offset = 0;
            for (var i = 0; i < s.Length; i++)
            {
                Assert.IsTrue(s[i].Length == i);
                Assert.IsTrue(BlockHelper.UnpackWString(buf, offset) == s[i]);
                offset += 2 * (s[i].Length + 1);
            }
        }
Esempio n. 19
0
        private IEnumerable <Declaration> PendingAsyncNoninterferenceCheckers()
        {
            if (CommandLineOptions.Clo.TrustNoninterference)
            {
                yield break;
            }

            HashSet <AtomicAction> pendingAsyncsToCheck = new HashSet <AtomicAction>(
                civlTypeChecker.procToAtomicAction.Values
                .Where(a => a.layerRange.Contains(layerNum) && a.HasPendingAsyncs)
                .SelectMany(a => a.pendingAsyncs));

            foreach (var action in pendingAsyncsToCheck)
            {
                var inputs   = action.impl.InParams;
                var outputs  = action.impl.OutParams;
                var requires = action.gate.Select(a => new Requires(false, a.Expr)).ToList();
                var ensures  = new List <Ensures>();
                var modifies = civlTypeChecker.GlobalVariables.Select(Expr.Ident).ToList();
                var locals   = globalSnapshotInstrumentation.NewLocalVars.Union(noninterferenceInstrumentation.NewLocalVars).ToList();
                var cmds     = new List <Cmd>();

                cmds.AddRange(globalSnapshotInstrumentation.CreateInitCmds());
                cmds.AddRange(noninterferenceInstrumentation.CreateInitCmds(action.impl));
                cmds.Add(CmdHelper.CallCmd(action.proc, inputs, outputs));
                cmds.AddRange(noninterferenceInstrumentation.CreateCallToYieldProc());
                var blocks = new List <Block> {
                    BlockHelper.Block("init", cmds)
                };

                var name = civlTypeChecker.AddNamePrefix($"PendingAsyncNoninterferenceChecker_{action.proc.Name}_{layerNum}");
                var proc = DeclHelper.Procedure(name, inputs, outputs, requires, modifies, ensures);
                var impl = DeclHelper.Implementation(proc, inputs, outputs, locals, blocks);
                yield return(proc);

                yield return(impl);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Finds the free blocks.
        /// </summary>
        /// <param name="hint">The hint.</param>
        /// <param name="strategy">The strategy.</param>
        /// <param name="count">The count.</param>
        /// <returns></returns>
        List <ulong> FindFreeBlocks(object op, ulong hint, AllocationStrategy strategy,
                                    uint count, List <AllocationBlockInfo> lockedBlocks)
        {
            // We load blocks in vicinity. If there is no hint, we chose one.
            if (hint == 0)
            {
                // We choose the "default" key.
                uint unused;

                // We must extract first allocation block, the only way is to use the enumerator.
                IEnumerator <KeyValuePair <ulong, AllocationBlockInfo> > en = inspectedFreeBlocks.GetEnumerator();
                en.MoveNext();

                hint = inspectedFreeBlocks.Count > 0 ? en.Current.Key
                    : BlockHelper.GetAllocationBlock(provider.BlockSize, 1, out unused);
            }

            // TODO Super blocks.
            List <ulong> freeBlocks = new List <ulong>();

            // We begin allocation (forward from hint)
            uint  unused2;
            ulong block = BlockHelper.GetAllocationBlock(provider.BlockSize, hint, out unused2);

            for (; count > 0; block = BlockHelper.GetNextAllocationBlock(provider.BlockSize, block, blockCount))
            {
                AddBlock(op, block, freeBlocks, lockedBlocks, ref count);
            }

            // And backwards if none found.
            for (block = BlockHelper.GetPrevAllocationBlock(provider.BlockSize, block); count > 0;
                 block = BlockHelper.GetPrevAllocationBlock(provider.BlockSize, block))
            {
                AddBlock(op, block, freeBlocks, lockedBlocks, ref count);
            }

            return(freeBlocks);
        }
Esempio n. 21
0
        private void PlayerDisplacementChunkEvents()
        {
            double distance = MVector3.Distance2D(_lastPlayerTriggeredPosition, PlayerManager.Player.Position);

            //Triggered when player has move a distance of 8 blocks (half chunk distance)
            if (distance > (AbstractChunk.ChunkSize.X / 2d))
            {
                var newEventNotificationArea = new Range3I
                {
                    Position = BlockHelper.EntityToChunkPosition(PlayerManager.Player.Position) - _eventNotificationArea.Size / 2,
                    Size     = _eventNotificationArea.Size
                };

                var chunks2Syncro = newEventNotificationArea.AllExclude(_eventNotificationArea);
                if (chunks2Syncro != null)
                {
                    bool synchroFullyRequested = true;
                    //Get all new chunk in the area that are in a state ready to be requested !
                    //Check that the concerned chunks are in a correct state to be requested.

                    foreach (var chunkPosition in chunks2Syncro)
                    {
                        if (ResyncChunk(chunkPosition, false) == false)
                        {
                            synchroFullyRequested = false;
                            break;
                        }
                    }
                    if (synchroFullyRequested)
                    {
                        _eventNotificationArea = newEventNotificationArea;
                    }
                }

                _lastPlayerTriggeredPosition = PlayerManager.Player.Position;
                ChunkNeed2BeSorted           = true;
            }
        }
        public async Task WhenCreateFileSystemHeaderBlockThenBlockIsValid()
        {
            var pfs3AioBytes = await File.ReadAllBytesAsync(@"TestData\pfs3aio");

            var fileSystemHeaderBlock =
                BlockHelper.CreateFileSystemHeaderBlock(FormatHelper.FormatDosType("PDS", 3), 19, 2,
                                                        pfs3AioBytes);

            Assert.Equal(1245186U, fileSystemHeaderBlock.Version);
            var loadSegBlockCount = Math.Ceiling((double)pfs3AioBytes.Length / (512 - 5 * 4));

            Assert.Equal(loadSegBlockCount, fileSystemHeaderBlock.LoadSegBlocks.Count());

            var actualPfs3AioBytes = new List <byte>();

            foreach (var loadSegBlock in fileSystemHeaderBlock.LoadSegBlocks)
            {
                actualPfs3AioBytes.AddRange(loadSegBlock.Data);
            }

            Assert.Equal(pfs3AioBytes.Length, actualPfs3AioBytes.Count);
            Assert.True(pfs3AioBytes.SequenceEqual(actualPfs3AioBytes));
        }
Esempio n. 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="pPackage"></param>
        /// <param name="block"></param>
        /// <param name="blockName"></param>
        /// <param name="options"></param>
        public static void BuildContent(ReportData client, OpenXmlPackage pPackage, BlockItem block, string blockName, Dictionary <string, string> options)
        {
            var previousCulture = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            GraphBlock instance = BlockHelper.GetAssociatedBlockInstance <GraphBlock>(blockName);

            if (null == instance)
            {
                return;
            }
            LogHelper.Instance.LogDebugFormat("Start GraphBlock generation : Type {0}", blockName);
            Stopwatch       treatmentWatch = Stopwatch.StartNew();
            TableDefinition content        = instance.Content(client, options);

            try
            {
                if (null != content)
                {
                    ApplyContent(client, pPackage, block, content, options);
                }
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = previousCulture;

                treatmentWatch.Stop();
                LogHelper.Instance.LogDebugFormat
                    ("End GraphBlock generation ({0}) in {1} millisecond{2}"
                    , blockName
                    , treatmentWatch.ElapsedMilliseconds
                    , treatmentWatch.ElapsedMilliseconds > 1 ? "s" : string.Empty
                    );
            }
        }
Esempio n. 24
0
        private void StartMining()
        {
            var block = NodeApi.Current.GenerateMiningBlock(_startArgs.Name, _startArgs.Account);
            var currentScoopNumber = POC.GetScoopNumber(block.Header.PayloadHash, block.Header.Height);

            _startTime             = Time.EpochTime;
            block.Header.Timestamp = _startTime;

            if (block.Header.Height != this.currentBlockHeight || this.currentBlockStartTime <= 0)
            {
                this.currentBlockStartTime = _startTime;
                this.currentBlockHeight    = block.Header.Height;
            }

            StartMiningMsg startMiningMsg = StartMiningMsg.CreateNew();

            startMiningMsg.BlockHeight = block.Header.Height;
            startMiningMsg.ScoopNumber = currentScoopNumber;
            startMiningMsg.StartTime   = _startTime;
            var genHash = BlockHelper.GenHash(block.Header.PayloadHash, block.Header.Height);

            startMiningMsg.GenHash    = Base16.Encode(genHash);
            startMiningMsg.BaseTarget = NodeApi.Current.GetBaseTarget(block.Header.Height);

            var blockKey = KeyHelper.GetBlockKey(startMiningMsg.Id);

            RedisManager.Current.SaveDataToRedis(blockKey, block);
            //MQApi.SendStartMsg(startMiningMsg);
            RabbitMQApi.SendStartMsg(startMiningMsg);

            CurrentStartMiningMsg = startMiningMsg;
            LogHelper.Info("Start MiningTask Id=" + startMiningMsg.Id + " ScoopNumber = " + startMiningMsg.ScoopNumber + " Height= " + startMiningMsg.BlockHeight);
            LogHelper.Info($"Block bits is {POC.ConvertBitsToBigInt(block.Header.Bits).ToString("X").PadLeft(64, '0')}");
            LogHelper.Info($"StartMiningMsg.BaseTarget is {POC.ConvertBitsToBigInt(startMiningMsg.BaseTarget).ToString("X").PadLeft(64, '0')}");
            LogHelper.Info($"Block height is {block.Header.Height}");
        }
Esempio n. 25
0
        void ChunkBlocksChanged(object sender, ChunkDataProviderDataChangedEventArgs e)
        {
            var chunk = (ServerChunk)sender;

            chunk.LastAccess = DateTime.Now;

            var globalPos = new Vector3I[e.Locations.Length];

            e.Locations.CopyTo(globalPos, 0);
            BlockHelper.ConvertToGlobal(chunk.Position, globalPos);

            // tell entities about blocks change
            var eargs = new BlocksChangedEventArgs
            {
                ChunkPosition   = chunk.Position,
                BlockValues     = e.Bytes,
                Locations       = e.Locations,
                GlobalLocations = globalPos,
                Tags            = e.Tags,
                SourceEntityId  = e.SourceDynamicId
            };

            GetArea(new Vector3D(eargs.ChunkPosition.X * AbstractChunk.ChunkSize.X, 0, eargs.ChunkPosition.Z * AbstractChunk.ChunkSize.Z)).OnBlocksChanged(eargs);
        }
Esempio n. 26
0
        /// <summary>
        /// Creates an unsigned serialized transaction
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <CreateRawTransactionOutput> CreateRawTransactionAsync(CreateRawTransactionInput input)
        {
            var transaction = new Transaction
            {
                From           = Address.FromBase58(input.From),
                To             = Address.FromBase58(input.To),
                RefBlockNumber = input.RefBlockNumber,
                RefBlockPrefix = BlockHelper.GetRefBlockPrefix(Hash.LoadFromHex(input.RefBlockHash)),
                MethodName     = input.MethodName
            };
            var methodDescriptor = await GetContractMethodDescriptorAsync(Address.FromBase58(input.To), input.MethodName);

            if (methodDescriptor == null)
            {
                throw new UserFriendlyException(Error.Message[Error.NoMatchMethodInContractAddress],
                                                Error.NoMatchMethodInContractAddress.ToString());
            }
            try
            {
                var parameters = methodDescriptor.InputType.Parser.ParseJson(input.Params);
                if (!IsValidMessage(parameters))
                {
                    throw new UserFriendlyException(Error.Message[Error.InvalidParams], Error.InvalidParams.ToString());
                }
                transaction.Params = parameters.ToByteString();
            }
            catch
            {
                throw new UserFriendlyException(Error.Message[Error.InvalidParams], Error.InvalidParams.ToString());
            }

            return(new CreateRawTransactionOutput
            {
                RawTransaction = transaction.ToByteArray().ToHex()
            });
        }
Esempio n. 27
0
        public Task <IEnumerable <Transaction> > GetPreTransactionsAsync(IReadOnlyList <ServiceDescriptor> descriptors, ITransactionContext transactionContext)
        {
            if (!descriptors.Any(service => service.File.Name == "test_basic_function_with_parallel_contract.proto"))
            {
                return(Task.FromResult(new List <Transaction>().AsEnumerable()));
            }

            if (transactionContext.Transaction.To == ParallelTestHelper.BasicFunctionWithParallelContractAddress &&
                !transactionContext.Transaction.MethodName.EndsWith("Plugin"))
            {
                return(Task.FromResult(new List <Transaction>().AsEnumerable()));
            }

            var context = _contextService.Create();

            context.TransactionContext = transactionContext;

            var transactions = new List <Transaction>();

            switch (transactionContext.Transaction.MethodName)
            {
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromInlineWithPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromPostPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueWithPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueParallelFromPostPlugin):
            {
                var input = RemoveValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                transactions.Add(new Transaction
                    {
                        From   = transactionContext.Transaction.From,
                        To     = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key  = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName     = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                break;
            }

            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromPrePlugin):
            {
                var input = RemoveValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                transactions.Add(new Transaction
                    {
                        From           = transactionContext.Transaction.From,
                        To             = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params         = input.ToByteString(),
                        MethodName     = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                break;
            }

            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPrePlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPrePlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueParallelWithInlineAndPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithPrePlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithInlineAndPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedParallelWithInlineAndPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithInlineAndPrePlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedInlineAndPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedInlineAndPrePlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueParallelWithFailedInlineAndPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPrePluginAndFailedPostPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPrePluginAndFailedPostPlugin):
            {
                var input = IncreaseValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                transactions.Add(new Transaction
                    {
                        From   = transactionContext.Transaction.From,
                        To     = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key  = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName     = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                break;
            }

            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedPrePlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndFailedPrePlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedPrePluginAndPostPlugin):
            case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndFailedPrePluginAndPostPlugin):
            {
                var input = IncreaseValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                transactions.Add(new Transaction
                    {
                        From   = transactionContext.Transaction.From,
                        To     = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key  = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName     = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailed),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                break;
            }
            }

            return(Task.FromResult(transactions.AsEnumerable()));
        }
        public void DrawModels(Camera3D camera)
        {
            BlockMask maskAtCursor = ParentSegmentManager.GetBlockMaskAt(_keyboardCursor);

            switch (_selectedType)
            {
            case EditorType.Blocks:
                if (ParentSegmentManager.IsLocationObstructed(_keyboardCursor))
                {
                    _blockHighlightBlocked.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                }
                else
                {
                    _blockHighlight.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                }
                break;

            case EditorType.BottomRamps:
                if (BlockHelper.HasTopRamp(maskAtCursor) &&
                    BlockHelper.GetRampBlockDirection(maskAtCursor) ==
                    _RampBlockDirection)
                {
                    _blockHighlight.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                }
                else
                {
                    if (ParentSegmentManager.IsLocationObstructed(_keyboardCursor))
                    {
                        _blockHighlightBlocked.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                    }
                    else
                    {
                        _blockHighlight.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                    }
                }
                break;

            case EditorType.TopRamps:
                if (BlockHelper.HasBottomRamp(maskAtCursor) &&
                    BlockHelper.GetRampBlockDirection(maskAtCursor) ==
                    _RampBlockDirection)
                {
                    _blockHighlight.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                }
                else
                {
                    if (ParentSegmentManager.IsLocationObstructed(_keyboardCursor))
                    {
                        _blockHighlightBlocked.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                    }
                    else
                    {
                        _blockHighlight.Draw(ParentSegmentManager.Device, camera, _keyboardCursor.WorldLocation, Vector3.Zero, 0f, new Vector3(1, 1, 1));
                    }
                }
                break;

            default:
                _previewData = new BlockVertexData();
                break;
            }
        }
        public void HandleHighlight()
        {
            Vector3 newPosition = _keyboardCursor.WorldLocation;

            if (InputHelper.IsNewKeyPress(Keys.NumPad3))
            {
                newPosition += WorldDirection.East;
            }
            if (InputHelper.IsNewKeyPress(Keys.NumPad1))
            {
                newPosition += WorldDirection.North;
            }
            if (InputHelper.IsNewKeyPress(Keys.NumPad7))
            {
                newPosition += WorldDirection.West;
            }
            if (InputHelper.IsNewKeyPress(Keys.NumPad9))
            {
                newPosition += WorldDirection.South;
            }
            if (InputHelper.IsNewKeyPress(Keys.Add))
            {
                newPosition += WorldDirection.Up;
            }
            if (InputHelper.IsNewKeyPress(Keys.Subtract))
            {
                newPosition += WorldDirection.Down;
            }

            // Following is for valid block ranges only.
            if (ParentSegmentManager.GetBlockMaskAt(new SegmentLocation(newPosition)) != BlockHelper.BlockMasks.Null)
            {
                if (newPosition != _keyboardCursor.WorldLocation)
                {
                    // check for an object?
                    int segmentX = (int)Math.Floor((double)newPosition.X / WorldGlobal.SegmentSize.X);
                    int segmentZ = (int)Math.Floor((double)newPosition.Z / WorldGlobal.SegmentSize.Z);

                    //_ItemsUnderCursor = ParentSegmentManager.Segments[segmentX, segmentZ].Items.FindItemsAt(newPosition);
                }

                _keyboardCursor = new SegmentLocation(newPosition);
                if (InputHelper.IsNewKeyPress(Keys.Delete))
                {
                    ParentSegmentManager.SetBlockMaskAt(_keyboardCursor, BlockHelper.BlockMasks.Air);
                }

                if (InputHelper.IsNewKeyPress(Keys.Insert))
                {
                    BlockMask maskAtCursor = ParentSegmentManager.GetBlockMaskAt(_keyboardCursor);
                    switch (_selectedType)
                    {
                    case EditorType.Blocks:
                        ParentSegmentManager.SetBlockMaskAt(_keyboardCursor, _activeBlockMask);
                        break;

                    case EditorType.BottomRamps:
                        if (BlockHelper.HasTopRamp(maskAtCursor) &&
                            BlockHelper.GetRampBlockDirection(maskAtCursor) ==
                            _RampBlockDirection)
                        {
                            ParentSegmentManager.SetBlockMaskAt(_keyboardCursor, maskAtCursor | _activeBlockMask);
                        }
                        else
                        {
                            ParentSegmentManager.SetBlockMaskAt(_keyboardCursor, _activeBlockMask);
                        }
                        break;

                    case EditorType.TopRamps:
                        if (BlockHelper.HasBottomRamp(maskAtCursor) &&
                            BlockHelper.GetRampBlockDirection(maskAtCursor) ==
                            _RampBlockDirection)
                        {
                            ParentSegmentManager.SetBlockMaskAt(_keyboardCursor, maskAtCursor | _activeBlockMask);
                        }
                        else
                        {
                            ParentSegmentManager.SetBlockMaskAt(_keyboardCursor, _activeBlockMask);
                        }
                        break;

                    default:
                        _previewData = new BlockVertexData();
                        break;
                    }
                }
            }
            else
            {
                DebugLog.Log("Can't move World Cursor to (" + newPosition.X + ", " + newPosition.Y + ", " + newPosition.Z + ") - Out of bounds", DebugMessageType.Warning);
            }
        }
Esempio n. 30
0
        public static void DrawCrosses()
        {
            Database database = HostApplicationServices.WorkingDatabase;
            Editor   editor   = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;

            string mapGridCrossFilePath = string.Format("{0}{1}Resources{1}Map_Grid_Cross.dwg", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Path.DirectorySeparatorChar);

            BlockHelper.CopyBlockFromDwg(Cross.BlockName, mapGridCrossFilePath, database);

            PromptIntegerOptions promptScaleOptions = new PromptIntegerOptions("\nВъведете мащаб: ")
            {
                DefaultValue    = 1000,
                AllowNegative   = false,
                AllowZero       = false,
                UseDefaultValue = true,
                AllowNone       = false
            };

            PromptIntegerResult promptScaleResult = editor.GetInteger(promptScaleOptions);

            if (promptScaleResult.Status != PromptStatus.OK)
            {
                editor.WriteMessage("\nНевалиден мащаб");

                return;
            }

            int scale = promptScaleResult.Value;

            PromptPointOptions promptLowerLeftPointOptions = new PromptPointOptions("\nИзберете долен ляв ъгъл на картата: ");

            PromptPointResult promptLowerLeftPointResult = editor.GetPoint(promptLowerLeftPointOptions);

            if (promptLowerLeftPointResult.Status != PromptStatus.OK)
            {
                editor.WriteMessage("\nНевалидна точка");

                return;
            }

            Point3d lowerLeftPoint = promptLowerLeftPointResult.Value;

            PromptPointOptions promptUpperRightPointOptions = new PromptPointOptions("\nИзберете горен десен ъгъл на картата: ");

            PromptPointResult promptUpperRightPointResult = editor.GetPoint(promptUpperRightPointOptions);

            if (promptUpperRightPointResult.Status != PromptStatus.OK)
            {
                editor.WriteMessage("\nНевалидна точка");

                return;
            }

            Point3d upperRightPoint = promptUpperRightPointResult.Value;

            if (upperRightPoint.X <= lowerLeftPoint.X || upperRightPoint.Y <= lowerLeftPoint.Y)
            {
                editor.WriteMessage("\nНевалидни точки");

                return;
            }

            var crosses = MapGrid.GenerateCrosses(new BoundaryPoint(lowerLeftPoint.X, lowerLeftPoint.Y), new BoundaryPoint(upperRightPoint.X, upperRightPoint.Y), scale);

            using (Transaction transaction = database.TransactionManager.StartTransaction())
            {
                BlockTable       blockTable                 = database.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;
                BlockTableRecord blockDefinition            = blockTable[Cross.BlockName].GetObject(OpenMode.ForWrite) as BlockTableRecord;
                BlockTableRecord modelSpaceBlockTableRecord = blockTable[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord;

                foreach (var cross in crosses)
                {
                    Point3d blockReferenceInsertPoint = new Point3d(cross.X, cross.Y, 0);

                    using (BlockReference blockReference = new BlockReference(blockReferenceInsertPoint, blockDefinition.ObjectId))
                    {
                        blockReference.ScaleFactors = new Scale3d(scale / 1000.0);

                        modelSpaceBlockTableRecord.AppendEntity(blockReference);

                        transaction.AddNewlyCreatedDBObject(blockReference, true);
                    }
                }

                transaction.Commit();
            }
        }
Esempio n. 31
0
	public void MoveCameraToBlock(BlockHelper block)
	{
		if (block != null)
		{
			//			/|<-----a is this angle
			//		 HY/ |AJ
			//	      /  |
			//       /   |
			//      /    |
			//     /_____|
			//        OP
			
			float cosOfCam = Mathf.Cos( (90 - myTransform.eulerAngles.x) * Mathf.Deg2Rad); //COS of a. not sure why, but when we have the A angle in editor set to 55, its actually 35. I think it measures from the top

			float heightOfCamAboveBlock = myTransform.position.y - block.myTransform.position.y; //calculate AJ
			float hypotenuse = heightOfCamAboveBlock / cosOfCam; //calculates HY
			
			float newLength = Mathf.Sqrt(Mathf.Pow(hypotenuse, 2) - Mathf.Pow(heightOfCamAboveBlock, 2)); //calculates OP. See pythagoras theorum
			
			myTransform.position = new Vector3(block.myTransform.position.x, myTransform.position.y,  block.myTransform.position.z - newLength); //move camera to new position
		}
	}