Beispiel #1
0
        void Tick(object sender, EventArgs e)
        {
            if (currentGame == null)
            {
                return;
            }

            graphicItems.Clear();
            BlockList blocks = new BlockList();

            lock (playerLock)
                foreach (GamePlayer player in currentGame.gamePlayers.getPlayers())
                {
                    blocks.Add(new PlayerBlock(FrontBuffer, player.color, player.position));
                }

            lock (x)
                foreach (Enemy enemy in enemies)
                {
                    blocks.Add(new EnemyBlock(FrontBuffer, enemy.getColor(), enemy.position));
                }

            lock (bulletLock)
                foreach (Bullet bullet in bullets)
                {
                    blocks.Add(new BulletBlock(FrontBuffer, bullet.color, bullet.position));
                }
            if (goldenTooth != null)
            {
                blocks.Add(new GoldenToothBlock(FrontBuffer, goldenTooth.position));
            }

            graphicItems.Add(blocks);
            graphicItems.Add(new PlayerScore(TopBuffer, currentGame.bestScore));
            if (showScoreTable)
            {
                graphicItems.Add(new ScoreTable(TopBuffer, currentGame.gamePlayers));
            }

            if (BackBuffer != null)
            {
                using (var graphic = Graphics.FromImage(FrontBuffer))
                {
                    graphic.Clear(Color.Transparent);
                }
                using (var graphic = Graphics.FromImage(TopBuffer))
                {
                    graphic.Clear(Color.Transparent);
                }
            }
            Invalidate();
            graphicItems.ForEach(x => x.Draw());
            if (FrontBuffer != null)
            {
                FrontBuffer = RotateImage(FrontBuffer, angle);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Occurs when the tag field has been changed.
        /// </summary>
        /// <param name="e">An <see cref="EventArgs"/> that contains the event data.</param>
        protected override void OnTagFieldChanged(EventArgs e)
        {
            //Reinitialize List
            BlockList.Clear();
            foreach (ITagBlock tagBlock in TagField.BlockList)
            {
                BlockList.Add(new TagBlockModel()
                {
                    Owner = Owner, TagBlock = tagBlock
                });
            }

            //Check
            if (BlockList.Count > 0)
            {
                SelectedBlockIndex = 0;
            }
            else
            {
                SelectedBlockIndex = -1;
            }

            //Notify
            Expanded = BlockList.Count > 0;
            NotifyPropertyChanged(nameof(HasBlocks));

            //Base procedures
            base.OnTagFieldChanged(e);
        }
Beispiel #3
0
        private void AddBlock()
        {
            //Count
            int count = BlockList.Count;

            //Add
            Block tagBlock = TagField.Add(out bool success);

            if (success)
            {
                //Add
                BlockList.Add(new TagBlockModel()
                {
                    Owner = Owner, TagBlock = tagBlock
                });

                //Notify Changes
                if (count == 0)
                {
                    NotifyPropertyChanged(nameof(HasBlocks));
                }

                //Set
                SelectedBlockIndex = TagField.BlockList.IndexOf(tagBlock);
                NotifyValueChanged();
            }
        }
        private static void AssertBlock(BlockBase block)
        {
            var blockList = new BlockList {
                block
            };

            foreach (var inputNode in block.InputNodes)
            {
                var signalBlock = new GenerateSignalBlock
                {
                    TemplateName     = "Binary",
                    Start            = 0,
                    Finish           = 4,
                    SamplingRate     = 1,
                    IgnoreLastSample = true
                };
                signalBlock.OutputNodes[0].ConnectTo(inputNode);
                blockList.Add(signalBlock);
            }
            blockList.ExecuteAll();
            var clone = block.CloneWithLinks();

            foreach (var outputNode in clone.OutputNodes)
            {
                Assert.IsNotNull(outputNode.Object[0].Samples);
            }

            Assert.IsNotNull(block.Name);
            Assert.IsNotNull(block.Description);
            Assert.IsNotNull(block.ProcessingType);
        }
Beispiel #5
0
    public static BlockList Serdes(int blockNumber, BlockList blockList, ISerializer s)
    {
        if (s == null)
        {
            throw new ArgumentNullException(nameof(s));
        }
        blockList ??= new BlockList();
        if (s.IsCommenting())
        {
            s.Begin(blockNumber.ToString(CultureInfo.InvariantCulture));
        }

        if (s.IsReading())
        {
            int j = 0;
            while (!s.IsComplete())
            {
                blockList.Add(Block.Serdes(j, null, s));
                j++;
            }
        }
        else
        {
            s.List(null, blockList, blockList.Count, Block.Serdes);
        }

        if (s.IsCommenting())
        {
            s.End();
        }
        return(blockList);
    }
        /// <summary>
        /// Add a set of objects and text to the sets
        /// </summary>
        /// <param name="tag">tag should be unique (if not, it won't complain)</param>
        /// <param name="worldpositions">Vector array of worldpositions for each object</param>
        /// <param name="matrix">Array of matrix giving information for positioning each label</param>
        /// <param name="bitmaps">Array of bitmaps for labels associated with each object. Bitmaps are owned by caller</param>
        /// <param name="pos">Start position in array to start processing from</param>
        /// <param name="arraylength">Amount to use in the array, or -1 for all</param>
        public void Add(Object tag, Vector4[] worldpositions, Matrix4[] matrix, Bitmap[] bitmaps, int pos = 0, int arraylength = -1)
        {
            System.Diagnostics.Debug.Assert(tag != null);

            List <GLObjectsWithLabels.BlockRef> blocklist = new List <GLObjectsWithLabels.BlockRef>();

            if (set.Count == 0)
            {
                //System.Diagnostics.Debug.WriteLine($"No sets found, Create 0");
                AddSet();
            }

            if (arraylength == -1)          // this means use length of array
            {
                arraylength = worldpositions.Length;
            }

            int endpos = set.Last().Add(worldpositions, matrix, bitmaps, blocklist, pos, arraylength);

            while (endpos >= 0)    // if can't add
            {
                //System.Diagnostics.Debug.WriteLine($"Create another set {set.Count} for {endpos}");
                AddSet();
                endpos = set.Last().Add(worldpositions, matrix, bitmaps, blocklist, endpos, arraylength);      // add the rest from endpos
            }

            blocklist[0].tag = tag;                 // first entry only gets tag
            BlockList.Add(blocklist);               // in order, add block list
            TagsToBlocks[tag] = blocklist;
            Objects          += arraylength;
        }
Beispiel #7
0
        public double Run(double[] data, int detailLevel)
        {
            var sb = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i]);
                if (i < data.Length - 1)
                {
                    sb.Append(",");
                }
            }

            string datastring = sb.ToString();

            var textBlock = new ImportFromTextBlock
            {
                Text                    = datastring,
                ColumnSeparator         = ",",
                SignalStart             = 0,
                SignalNameInFirstColumn = false
            };

            var dwtBlock = new DWTBlock
            {
                WaveletName   = "db10",
                Level         = detailLevel,
                ExtensionMode = SignalExtension.ExtensionMode.ZeroPadding
            };


            var b = new BlockList();

            b.Add(textBlock);
            b.Add(dwtBlock);

            textBlock.ConnectTo(dwtBlock);

            b.ExecuteAll();

            int length = dwtBlock.OutputNodes[dwtBlock.OutputNodes.Count - 1].Object[detailLevel - 1].Samples.Length;

            double val = dwtBlock.OutputNodes[dwtBlock.OutputNodes.Count - 1].Object[detailLevel - 1].Samples[length - 1];

            return(val);
        }
Beispiel #8
0
        public void SaveBlock()
        {
            string currentHash = Helper.GetSha256Hash(CurrentBlock);

            CurrentBlock.Hash = Helper.GetSha256Hash(CurrentBlock);
            BlockList.Add(CurrentBlock);           //dodanie aktualnego bloku
            CurrentBlock = new Block(currentHash); //nowy blok
        }
Beispiel #9
0
    public GameWorld(int width, int height, ContentManager Content)
    {
        screenWidth = width;
        screenHeight = height;
        random = new Random();
        gameState = GameState.Menu;
        inputHelper = new InputHelper();
        block = Content.Load<Texture2D>("block");
        reset = Content.Load<Texture2D>("reset");
        font = Content.Load<SpriteFont>("SpelFont");
        font2 = Content.Load<SpriteFont>("SpriteFont1");
        font3 = Content.Load<SpriteFont>("SpriteFont2");
        playButton = Content.Load<Texture2D>("Play");
        optionsButton = Content.Load<Texture2D>("Options");
        backButton = Content.Load<Texture2D>("Back");
        polytris = Content.Load<Texture2D>("Polytris");
        grid = new TetrisGrid(block);
        level = 1;
        levelspeed = 1;
        score = 0;
        i = (int)random.Next(7) + 1;
        i2 = (int)random.Next(7) + 1;
        blockcounter = 1;

        blocks = new BlockList(block, Content);          //Voegen de verschillende blockobjecten toe aan de lijst
        block1 = new Block1(block, Content);
        blocks.Add(block1, 1);
        block2 = new Block2(block, Content);
        blocks.Add(block2, 2);
        block3 = new Block3(block, Content);
        blocks.Add(block3, 3);
        block4 = new Block4(block, Content);
        blocks.Add(block4, 4);
        block5 = new Block5(block, Content);
        blocks.Add(block5, 5);
        block6 = new Block6(block, Content);
        blocks.Add(block6, 6);
        block7 = new Block7(block, Content);
        blocks.Add(block7, 7);

        //Voegen de verschillende blockobjecten toe aan een tweede lijst voor het tekenen van het volgende blokje
        block1res = new Block1(block, Content);
        blocks.AddToReserve(block1res, 1);
        block2res = new Block2(block, Content);
        blocks.AddToReserve(block2res, 2);
        block3res = new Block3(block, Content);
        blocks.AddToReserve(block3res, 3);
        block4res = new Block4(block, Content);
        blocks.AddToReserve(block4res, 4);
        block5res = new Block5(block, Content);
        blocks.AddToReserve(block5res, 5);
        block6res = new Block6(block, Content);
        blocks.AddToReserve(block6res, 6);
        block7res = new Block7(block, Content);
        blocks.AddToReserve(block7res, 7);

        options = new Options(block, reset, backButton, width, height, font, blocks);
        menu = new Menu(playButton, optionsButton, polytris, width, height);
        gameOver = new GameOver(backButton, width, height);
    }
Beispiel #10
0
 public Pattern(int blockId, int metadata)
 {
     BlockList.Add(new BlockDataEntry()
     {
         Id          = (byte)blockId,
         Metadata    = (byte)metadata,
         HasMetadata = true
     });
     OriginalPattern = $"{blockId}:{metadata}";
 }
Beispiel #11
0
        public double Run(double[] data, int detailLevel)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i]);
                if (i < data.Length - 1) sb.Append(",");
            }

            string datastring = sb.ToString();

            var textBlock = new ImportFromTextBlock
            {
                Text = datastring,
                ColumnSeparator = ",",
                SignalStart = 0,
                SignalNameInFirstColumn = false
            };

            var dwtBlock = new DWTBlock
            {
                WaveletName = "db10",
                Level = detailLevel,
                ExtensionMode = SignalExtension.ExtensionMode.ZeroPadding
            };


            var b = new BlockList();
            b.Add(textBlock);
            b.Add(dwtBlock);

            textBlock.ConnectTo(dwtBlock);

            b.ExecuteAll();

            int length = dwtBlock.OutputNodes[dwtBlock.OutputNodes.Count-1].Object[detailLevel - 1].Samples.Length;

            double val = dwtBlock.OutputNodes[dwtBlock.OutputNodes.Count-1].Object[detailLevel - 1].Samples[length - 1];

            return val;
        }
Beispiel #12
0
 public virtual void TestAddRejectsBadIndexes()
 {
     BlockList<int> list = new BlockList<int>(4);
     list.AddItem(Sharpen.Extensions.ValueOf(41));
     try
     {
         list.Add(-1, Sharpen.Extensions.ValueOf(42));
     }
     catch (IndexOutOfRangeException badIndex)
     {
         NUnit.Framework.Assert.AreEqual((-1).ToString(), badIndex.Message);
     }
     try
     {
         list.Add(4, Sharpen.Extensions.ValueOf(42));
     }
     catch (IndexOutOfRangeException badIndex)
     {
         NUnit.Framework.Assert.AreEqual(4.ToString(), badIndex.Message);
     }
 }
 public static List<double> FFTTransform(List<double> serie)
 {
     //Declaring the blocks
     var inputSeriesBlock = new InputSeriesBlock();
     inputSeriesBlock.SetSeries(serie);
     var outputSeriesBlock = new OutputSeriesBlock();
     var fFTBlock = new FFTBlock
     {
         Mode = ManagedFFTModeEnum.UseLookupTable
     };
     //Connecting the blocks
     inputSeriesBlock.OutputNodes[0].ConnectTo(fFTBlock.InputNodes[0]);
     fFTBlock.OutputNodes[1].ConnectTo(outputSeriesBlock.InputNodes[0]);
     //Appending the blocks to a block list and execute all
     var blockList = new BlockList();
     blockList.Add(inputSeriesBlock);
     blockList.Add(fFTBlock);
     blockList.Add(outputSeriesBlock);
     blockList.ExecuteAll();
     return outputSeriesBlock.GetSeries();
 }
Beispiel #14
0
        private bool ExtractInitData(string s)
        {
            string[] delim  = { "var initData = {};", "initData.globalLocale =" };
            string[] delim2 = { "initData." };
            string[] delim3 = { " = " };
            char[]   delim4 = { ' ', ';', '\n', '	'};

            string[] s1 = s.Split(delim, StringSplitOptions.None);
            if (s1.Length < 3)
            {
                return(false);
            }

            string s2 = s1[1];

            string[] datum = s2.Split(delim2, StringSplitOptions.RemoveEmptyEntries);

            string product = datum[1].Split(delim3, StringSplitOptions.None)[1];
            string meta    = datum[2].Split(delim3, StringSplitOptions.None)[1];
            string grade   = datum[3].Split(delim3, StringSplitOptions.None)[1];

            product = product.TrimEnd(delim4);
            meta    = meta.TrimEnd(delim4);
            grade   = grade.TrimEnd(delim4);

            _product = JsonConvert.DeserializeObject <Product>(product);
            _meta    = JsonConvert.DeserializeObject <Meta>(meta);
            _grades  = JsonConvert.DeserializeObject <Grade[]>(grade);

            GradeList.Clear();
            BlockList.Clear();

            Grade defaultGrade = new Grade();

            defaultGrade.gradeId = 0;
            defaultGrade.name    = "전체";
            Meta.Draw.BlockInfo defaultBlock = new Meta.Draw.BlockInfo();
            defaultBlock.blockId   = 0;
            defaultBlock.blockName = "전체";
            GradeList.Add(defaultGrade);
            BlockList.Add(defaultBlock);

            foreach (Grade item in _grades)
            {
                GradeList.Add(item);
            }
            foreach (Meta.Draw.BlockInfo item in _meta.draw.blockInfo)
            {
                BlockList.Add(item);
            }

            return(true);
        }
Beispiel #15
0
 //Add Block to List
 public void AddBlock(Block block, bool sync = false)
 {
     if (sync)
     {
         BlockList.Add(block);
     }
     else
     {
         block.PreviousHash = GetLatestBlock().Hash;
         block.Mining(DiffString);
         block.Index = BlockList.Count;
         BlockList.Add(block);
     }
 }
Beispiel #16
0
        public void OpenFileByPath(string filename)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (!Path.IsPathRooted(filename))
                {
                    filename = Path.Combine(WaveletStudio.Utils.AssemblyDirectory, filename);
                }

                var documentModel = new DocumentSerializer().Load(filename);
                documentModel.OnSaveChanged = OnSavedChanged;

                var diagramForm = Designer.Document.Elements.Count > 0 ? new DiagramForm() : this;
                diagramForm.Cursor        = Cursors.WaitCursor;
                diagramForm.DocumentModel = documentModel;
                diagramForm.Designer.SetDocument(documentModel.Document);
                diagramForm.CurrentFile = filename;
                diagramForm.Show();
                diagramForm.Focus();
                diagramForm.ConfigureDesigner();
                diagramForm.ZoomTrackBar.Value = Convert.ToInt32(Designer.Document.Zoom * 10);
                AddRecentFile(filename, diagramForm.Designer);

                var blockList = new BlockList();
                foreach (var element in diagramForm.Designer.Document.Elements)
                {
                    if (element is DiagramBlock == false)
                    {
                        continue;
                    }

                    var block = (BlockBase)((DiagramBlock)element).State;
                    block.CurrentDirectory = CurrentDirectory;
                    blockList.Add(block);
                }
                blockList.ExecuteAll();
                diagramForm.Cursor = Cursors.Default;
            }
            catch (Exception exception)
            {
                MessageBox.Show(string.Format("{0}:{1}{2}", DesignerResources.FileCouldntBeOpened, Environment.NewLine, exception.Message), DesignerResources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        // Returns false if any key was previously used or is not relesed
        public static bool AllKeysReleased(params Keys[] keys)
        {
            if (keys.Any(k => BlockList.Contains(k)))
            {
                return(false);
            }

            return(keys.All(k =>
            {
                if (!KeyState.IsKeyUp(k) || !PreviousKeyState.IsKeyDown(k))
                {
                    return false;
                }

                BlockList.Add(k);
                return true;
            }));
        }
        // Returns false if all keys were previously used or are down
        public static bool AnyKeysUp(params Keys[] keys)
        {
            if (keys.All(k => BlockList.Contains(k)))
            {
                return(false);
            }

            return(keys.Any(k =>
            {
                if (!KeyState.IsKeyUp(k))
                {
                    return true;
                }

                BlockList.Add(k);
                return false;
            }));
        }
Beispiel #19
0
 public override void Refresh()
 {
     CheckRunningStatus();
     ResultList.Clear();
     TargetProject.ResultList.ForEach(v => ResultList.Add(new InstrumentViewModel()
     {
         TargetObject = v, GetCurrentDataSource = () => { return(CurrentDataSource); }
     }));
     BlockList.Clear();
     TargetProject.BlockList.ForEach(v => BlockList.Add(new InstrumentViewModel()
     {
         TargetObject = v, GetCurrentDataSource = () => { return(CurrentDataSource); }
     }));
     OnPropertyChanged("FinishPercent");
     OnPropertyChanged("IsRunning");
     OnPropertyChanged("ProcessInfo");
     OnPropertyChanged("CanStart");
     OnPropertyChanged("CanPause");
     OnPropertyChanged("CanStop");
     base.Refresh();
 }
Beispiel #20
0
        private IReadOnlyList <TryCatchBlock> TranslateSehBlocks(IMethod method, IMethodContext context, IList <SEHBlock> blocks, ILStream code)
        {
            var           list     = new List <TryCatchBlock>();
            var           handlers = new BlockList();
            TryCatchBlock tryBlock = null;
            int           n        = blocks.Count;

            for (int i = 0; i < n; ++i)
            {
                var block = blocks[i];
                tryBlock = EnshureTryBlock(blocks, i, tryBlock, code, block, list);
                var handler    = CreateHandlerBlock(method, context, code, block);
                int entryIndex = code.GetOffsetIndex(block.HandlerOffset);
                int exitIndex  = GetIndex(code, block.HandlerOffset, block.HandlerLength);
                handler.EntryPoint = code[entryIndex];
                handler.ExitPoint  = code[exitIndex];
                tryBlock.Handlers.Add(handler);
                handlers.Add(handler);
            }

            //set parents
            for (int i = 0; i < list.Count; ++i)
            {
                var block  = list[i];
                var parent = FindParent(list, block);
                if (parent != null)
                {
                    parent.Add(block);
                    list.RemoveAt(i);
                    --i;
                }
            }

            foreach (var block in list)
            {
                SetupInstructions(code, block);
            }

            return(list.AsReadOnlyList());
        }
Beispiel #21
0
        public Expression DecompileBooleanExpression(BlockExpression be)
        {
            if (be == null)
            {
                return(null);
            }
            TypeReconstructorAndExpressionSimplifier tr = new TypeReconstructorAndExpressionSimplifier();

            be = tr.VisitBlockExpression(be) as BlockExpression;
            if (be == null)
            {
                return(null);
            }
            Block b = be.Block;

            #region Make sure the block expression has the right shape
            foreach (Statement s in b.Statements)
            {
                Block b_prime = s as Block;
                Debug.Assert(b_prime != null);
                Debug.Assert(HelperMethods.IsBasicBlock(b_prime));
            }
            #endregion
            Block firstBlock = (Block)b.Statements[0];
            block2Index = new TrivialHashtable(b.Statements.Count);
            blocks      = new BlockList(b.Statements.Count);
            for (int i = 0, n = b.Statements.Count; i < n; i++)
            {
                block2Index[b.Statements[i].UniqueKey] = i;
                blocks.Add(b.Statements[i] as Block);
            }
            Expression e = DecompileBooleanExpression(firstBlock);
            // BUGBUG: this isn't a good place to do this because then it gets done for all contracts,
            // not just postconditions!! Plus, we could just leave Result in the contracts and let the
            // BPL translation recognize it.
            //ReplaceResult repResult = new ReplaceResult(this.localToUseForResult, this.contractNodes.ResultTemplate,
            //  this.contractNodes.ParameterTemplate);
            //e = repResult.VisitExpression(e);
            return(e);
        }
Beispiel #22
0
        public override void LoadInfo()
        {
            if (TargetProject == null)
            {
                return;
            }
            ConditionList.Clear();
            TargetProject.ConditionList.ForEach(v => ConditionList.Add(new ConditionViewModel()
            {
                TargetObject = v
            }));
            PredicateList.Clear();
            TargetProject.PredicateList.ForEach(v => PredicateList.Add(new ConditionViewModel()
            {
                TargetObject = v
            }));

            InstrumentList.Clear();
            TargetProject.InstrumentList.ForEach(v => InstrumentList.Add(v));
            ResultList.Clear();
            TargetProject.ResultList.ForEach(v => ResultList.Add(new InstrumentViewModel()
            {
                TargetObject = v, GetCurrentDataSource = () => { return(CurrentDataSource); }
            }));
            TargetProject.BlockList.ForEach(v => BlockList.Add(new InstrumentViewModel()
            {
                TargetObject = v, GetCurrentDataSource = () => { return(CurrentDataSource); }
            }));
            CurrentDataSource = TargetProject.CurrentDataSource;

            IsChanged = false;
            if (TargetSummaryVM != null)
            {
                TargetSummaryVM.Refresh();
            }
        }
Beispiel #23
0
 /// <summary>
 /// Adds the child block.
 /// </summary>
 /// <param name="kid">The block to add as child.</param>
 public void Add(Block kid)
 {
     kid.Parent = this;
     _kids.Add(kid);
 }
Beispiel #24
0
		public virtual void TestAddSlowPath()
		{
			BlockList<string> list = new BlockList<string>(4);
			string fooStr = "foo";
			string barStr = "bar";
			string foobarStr = "foobar";
			string firstStr = "first";
			string zeroStr = "zero";
			list.AddItem(fooStr);
			list.AddItem(barStr);
			list.AddItem(foobarStr);
			NUnit.Framework.Assert.AreEqual(3, list.Count);
			list.Add(1, firstStr);
			NUnit.Framework.Assert.AreEqual(4, list.Count);
			NUnit.Framework.Assert.AreSame(fooStr, list[0]);
			NUnit.Framework.Assert.AreSame(firstStr, list[1]);
			NUnit.Framework.Assert.AreSame(barStr, list[2]);
			NUnit.Framework.Assert.AreSame(foobarStr, list[3]);
			list.Add(0, zeroStr);
			NUnit.Framework.Assert.AreEqual(5, list.Count);
			NUnit.Framework.Assert.AreSame(zeroStr, list[0]);
			NUnit.Framework.Assert.AreSame(fooStr, list[1]);
			NUnit.Framework.Assert.AreSame(firstStr, list[2]);
			NUnit.Framework.Assert.AreSame(barStr, list[3]);
			NUnit.Framework.Assert.AreSame(foobarStr, list[4]);
		}
Beispiel #25
0
		/// <summary>
		/// Called once after we handled all blocks (by MakeFlat)
		/// </summary>
		private void AdjustBranches() 
		{
			for (int i = 0; i<this.branchInstructions.Count; i++) 
			{
				Branch branch = (Branch)this.branchInstructions[i];

				branch.Target = RemapBlock(branch.Target);
			}

      // Clone target list
			for (int i = 0; i<this.switchInstructions.Count; i++) 
			{
				SwitchInstruction sw = (SwitchInstruction)this.switchInstructions[i];

        BlockList targets = sw.Targets;
        BlockList newTargets = new BlockList(targets.Count);
        sw.Targets = newTargets;

				for (int j = 0; j<targets.Count; j++) 
				{
					Block b = targets[j];
					newTargets.Add(RemapBlock(b));
				}
			}

		}
Beispiel #26
0
 public static void Add(Block block)
 {
     BlockList.Add(block);
 }
 public void Add()
 {
     Current = new HttpChunk();
     BlockList.Add(Current);
 }
Beispiel #28
0
 /// <summary>
 /// Creates a block containing the given tryBlock and catchBlocks and
 /// returns it. The method is modified by having new ExceptionHandlers
 /// added to it which points to the right places in the blocks.
 /// The type of exception caught by each catch block should be the type
 /// of the corresponding local l.
 /// </summary>
 /// <param name="m">The method in which the try-catch block will be
 /// inserted into.</param>
 /// <param name="tryBody">A block of statements that will be the body
 /// of the try-catch statement.</param>
 /// <param name="catchBodies">A sequence of blocks; each one contains the
 /// statements that will be the body of a catch clause on the try-catch statement.
 /// </param>
 /// <param name="l">The local into which the exception will be
 /// assigned. Presumably, the body of the catch clause does something
 /// with this local.</param>
 /// <returns>A single block which must be inserted into m by the client.
 /// </returns>
 internal static Block CreateTryCatchBlock(Method m, Block tryBody, Block catchBody, Local l) {
   BlockList bs = new BlockList(1);
   bs.Add(catchBody);
   LocalList ls = new LocalList(1);
   ls.Add(l);
   return CreateTryCatchBlock(m, tryBody, bs, ls);
 }
Beispiel #29
0
    public override Method VisitMethod(Method method) {
      if (method == null) return null;
      if (method.IsNormalized) return method;
      if (method.CciKind != CciMemberKind.Regular) {
        method.Attributes.Add(new AttributeNode(new MemberBinding(null, SystemTypes.CciMemberKindAttribute.GetConstructor(SystemTypes.CciMemberKind)), new ExpressionList(new Literal(method.CciKind, SystemTypes.CciMemberKind)), AttributeTargets.Method));
      }
      method.IsNormalized = true;
      method.Attributes = this.VisitAttributeList(method.Attributes);
      if (method.ReturnAttributes == null)
        method.ReturnAttributes = new AttributeList();
      else
        method.ReturnAttributes = this.VisitAttributeList(method.ReturnAttributes);
      AttributeList al = this.ExtractAttributes(method.Attributes, AttributeTargets.ReturnValue);
      for (int i = 0, n = al == null ? 0 : al.Count; i < n; i++){
        method.ReturnAttributes.Add(al[i]);
      }
      method.SecurityAttributes = this.VisitSecurityAttributeList(method.SecurityAttributes);
      if (method.Attributes != null && method.Attributes.Count > 0) {
        SecurityAttributeList secAttrs = method.SecurityAttributes;
        this.ExtractSecurityAttributes(method.Attributes, ref secAttrs);
        method.SecurityAttributes = secAttrs;
      }
      if (method.SecurityAttributes != null && method.SecurityAttributes.Count > 0)
        method.Flags |= MethodFlags.HasSecurity;
      Method savedMethod = this.currentMethod;
      This savedThisParameter = this.currentThisParameter;
      Local savedReturnLocal = this.currentReturnLocal;
      Block savedReturnLabel = this.currentReturnLabel;
      Local savedClosureLocal = this.currentClosureLocal;
      Block savedContractPrelude = this.currentContractPrelude;
      BlockList savedContractExceptionalTerminationChecks = this.currentContractExceptionalTerminationChecks;
      Local savedcurrentExceptionalTerminationException = this.currentExceptionalTerminationException;
      Block savedContractNormalTerminationCheck = this.currentContractNormalTerminationCheck;
      Block savedParentBlock = null;
      this.currentMethod = method;
      this.currentThisParameter = method.ThisParameter;
      if (method.ThisParameter != null) {
        method.ThisParameter.DeclaringMethod = method;
        if (method.DeclaringType != null && method.DeclaringType.IsValueType)
          method.ThisParameter.Type = method.DeclaringType.GetReferenceType();
      }
      this.currentReturnLabel = new Block(new StatementList());
      this.currentClosureLocal = null;
      this.currentContractPrelude = new Block(new StatementList());
      this.currentContractExceptionalTerminationChecks = new BlockList();
      this.currentExceptionalTerminationException = new Local(Identifier.For("SS$caught_exception"), SystemTypes.Exception);
      this.currentContractNormalTerminationCheck = new Block(new StatementList());
      if (TypeNode.StripModifiers(method.ReturnType) == SystemTypes.Void)
        this.currentReturnLocal = null;
      else
        this.currentReturnLocal = new Local(Identifier.For("return value"), method.ReturnType);
      method.Parameters = this.VisitParameterList(method.Parameters);
      method.TemplateArguments = this.VisitTypeReferenceList(method.TemplateArguments);
      method.TemplateParameters = this.VisitTypeParameterList(method.TemplateParameters);
      TypeNodeList tpars = method.TemplateParameters;
      if (!method.IsGeneric){
        for (int i = 0, n = tpars == null ? 0 : tpars.Count; i < n; i++){
          TypeNode tpar = tpars[i];
          if (tpar == null) continue;
          tpar.Name = new Identifier(method.Name+":"+tpar.Name, tpar.SourceContext);
          tpar.DeclaringType = method.DeclaringType;
          method.DeclaringType.Members.Add(tpar);
        }
      }
      if (method.Template == null) {
        // skip this part for instance methods.
        Block closureInit = null;
        bool methodHasClosure = method.Scope != null && method.Scope.CapturedForClosure;
        if (methodHasClosure) this.SetUpClosureClass(method);
        // Normalizer.VisitRequiresList needs to be called in case it wants to generate
        // some default preconditions (that are not injected by Checker in order to not
        // have these preconditions seen by any static checking tools). If there is
        // no contract on this method, then it won't get called, so create a dummy
        // contract and Requires list just so it will get a chance to do its stuff.
        if (method.Contract == null) {
          method.Contract = new MethodContract(method);
          method.Contract.Requires = new RequiresList();
        }
        if (!methodHasClosure || (method is InstanceInitializer)) {
          // ctors will construct the closure class instance after they call another ctor, since they need to pass in "this" as a parameter to the closure class constructor
          method.Contract = this.VisitMethodContract(method.Contract);
          method.Body = this.VisitBlock(method.Body);
        }else{
          method.Contract = this.VisitMethodContract(method.Contract);
          Block b = this.CreateClosureClassInstance(method);
          method.Body = this.VisitBlock(method.Body);
          savedParentBlock = method.Body;
          closureInit = b;
          if (method.Body != null){
            closureInit.SourceContext = method.Body.SourceContext;
            method.Body.HasLocals = true;
          }
        } {

        #region If this method has a contract, then modify its body to add the contracts at the right point
        if (method.Body != null && method.Body.Statements != null){
          if (this.currentContractExceptionalTerminationChecks.Count > 0){
            // then wrap the body into a try catch with these checks as the catch blocks
            Block b = new Block(new StatementList(this.currentContractExceptionalTerminationChecks.Count));
            b.HasLocals = true;
            for (int i = 0, n = this.currentContractExceptionalTerminationChecks.Count; i < n; i++) {
              b.Statements.Add(this.currentContractExceptionalTerminationChecks[i]);
            }
            #region Rethrow caught exception
            // last "functional" thing in the block is re-throw whatever exception we caught.
            Throw t = new Throw();
            t.NodeType = NodeType.Rethrow;
            b.Statements.Add(t);
            #endregion

            LocalList ls = new LocalList(1);
            this.currentExceptionalTerminationException.DeclaringBlock = b;
            ls.Add(this.currentExceptionalTerminationException);
            BlockList bs = new BlockList(1);
            bs.Add(b);
            Block newBody = CreateTryCatchBlock(method, method.Body, bs, ls);
            //Block newBody = CreateTryCatchBlock(method,method.Body,this.currentContractExceptionalTerminationChecks,this.currentContractExceptionalLocals);
            method.Body = newBody;
          }
          if (this.currentContractPrelude.Statements.Count > 0){
            Block newBody = new Block(new StatementList(3));
            // Wrap the contract prelude in a block with a dummy catch block.
            // It has a special handler type that lets downstream tools know
            // this block was not part of the original code.
            Throw t = new Throw();
            t.NodeType = NodeType.Rethrow;
            this.currentContractPrelude = CreateTryCatchBlock(
              method, 
              this.currentContractPrelude, // try body
              new Block(new StatementList(t)), // catch: just rethrow
              new Local(Identifier.For("SS$Contract Marker"), SystemTypes.ContractMarkerException)
              );
            newBody.Statements.Add(closureInit);
            closureInit = null;
            newBody.Statements.Add(this.currentContractPrelude);
            newBody.Statements.Add(method.Body);
            method.Body = newBody;
          }
        }
      }
        #endregion
        if (closureInit != null){
          closureInit.Statements.Add(method.Body);
          method.Body = closureInit;
        }

        if (method.Body != null && method.Body.Statements != null){
          Return r = new Return();
          r.Expression = this.currentReturnLocal;
          Block returnBlock = new Block(new StatementList());
          returnBlock.Statements.Add(this.currentReturnLabel); {
          InstanceInitializer ctor = method as InstanceInitializer;
          if (ctor != null && method.DeclaringType.Contract != null && method.DeclaringType.Contract.FrameField != null && !ctor.IsDeferringConstructor){
            // then add a Pack to the end
            // BUGBUG: if the programmer has indicated that this default shouldn't apply, then don't do this!
            SourceContext rightBrace = new SourceContext(method.SourceContext.Document, method.SourceContext.EndPos - 1, method.SourceContext.EndPos);
            returnBlock.Statements.Add(
              new ExpressionStatement(
              new MethodCall(new MemberBinding(new MethodCall(new MemberBinding(method.ThisParameter, method.DeclaringType.Contract.FramePropertyGetter), null, NodeType.Call, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Guard)), SystemTypes.Guard.GetMethod(Identifier.For("EndWriting"))), null, NodeType.Call, SystemTypes.Void),
              rightBrace
              ));
          }
          if (this.currentContractNormalTerminationCheck.Statements.Count > 0){
            // Wrap the contract normal termination checks in a block with a dummy catch block.
            // It has a special handler type that lets downstream tools know this block was not
            // part of the original code.
            Throw t = new Throw();
            t.NodeType = NodeType.Rethrow;
            this.currentContractNormalTerminationCheck = CreateTryCatchBlock(
              method, 
              this.currentContractNormalTerminationCheck, // try body
              new Block(new StatementList(t)), // catch: just rethrow
              new Local(Identifier.For("SS$Contract Marker"),SystemTypes.ContractMarkerException)
              );
            returnBlock.Statements.Add(this.currentContractNormalTerminationCheck);
          }
        }
          if (this.currentReturnLocal != null){
            Local displayReturnLocal = new Local(Identifier.For("SS$Display Return Local"), method.ReturnType);
            returnBlock.Statements.Add(new AssignmentStatement(displayReturnLocal, this.currentReturnLocal));
            returnBlock.HasLocals = true;
          }
          returnBlock.Statements.Add(r);
          if (method.Body.SourceContext.Document != null){
            r.SourceContext = method.SourceContext;
            r.SourceContext.StartPos = method.Body.SourceContext.EndPos-1;
          }
          if (savedParentBlock != null){
            if (savedParentBlock.Statements == null) savedParentBlock.Statements = new StatementList(1);
            savedParentBlock.Statements.Add(returnBlock);
          }else
            method.Body.Statements.Add(returnBlock);
        }
        if (method.ImplementedInterfaceMethods != null && method.ImplementedInterfaceMethods.Count > 0 && method.ImplementedInterfaceMethods[0] != null){
          string typeName = method.ImplementedInterfaceMethods[0].DeclaringType.GetFullUnmangledNameWithTypeParameters();
          method.Name = new Identifier(typeName + "." + method.Name.ToString(), method.Name.SourceContext);
        }
        if (method.HasCompilerGeneratedSignature && method.Parameters != null){
          if (method.Parameters.Count == 1 && (method.Parameters[0].Attributes == null || method.Parameters[0].Attributes.Count == 0))
            method.Parameters[0].Attributes = this.ExtractAttributes(method.Attributes, AttributeTargets.Parameter);
          else if (method.Parameters.Count == 2 && (method.Parameters[1].Attributes == null || method.Parameters[1].Attributes.Count == 0))
            method.Parameters[1].Attributes = this.ExtractAttributes(method.Attributes, AttributeTargets.Parameter);
        }
      }
      this.currentMethod = savedMethod;
      this.currentThisParameter = savedThisParameter;
      this.currentReturnLocal = savedReturnLocal;
      this.currentReturnLabel = savedReturnLabel;
      this.currentClosureLocal = savedClosureLocal;
      this.currentContractPrelude = savedContractPrelude;
      this.currentContractExceptionalTerminationChecks = savedContractExceptionalTerminationChecks;
      this.currentExceptionalTerminationException = savedcurrentExceptionalTerminationException;
      this.currentContractNormalTerminationCheck = savedContractNormalTerminationCheck;
      return method;
    }
Beispiel #30
0
        private List<double> processOneSeries(List<double> serie)
        {
            //Declaring the blocks
            var inputSeriesBlock = new InputSeriesBlock();
            inputSeriesBlock.SetSeries(serie);
            var dWTBlock = new DWTBlock
            {
                WaveletName = "Daubechies 10 (db10)",
                Level = 1,
                Rescale = false,
                ExtensionMode = WaveletStudio.SignalExtension.ExtensionMode.AntisymmetricWholePoint
            };
            var outputSeriesBlock = new OutputSeriesBlock();

            //Connecting the blocks
            inputSeriesBlock.OutputNodes[0].ConnectTo(dWTBlock.InputNodes[0]);
            dWTBlock.OutputNodes[1].ConnectTo(outputSeriesBlock.InputNodes[0]);

            //Appending the blocks to a block list and execute all
            var blockList = new BlockList();
            blockList.Add(inputSeriesBlock);
            blockList.Add(dWTBlock);
            blockList.Add(outputSeriesBlock);
            blockList.ExecuteAll();
            return outputSeriesBlock.GetSeries();
        }
 public virtual Differences VisitBlockList(BlockList list1, BlockList list2,
   out BlockList changes, out BlockList deletions, out BlockList insertions){
   changes = list1 == null ? null : list1.Clone();
   deletions = list1 == null ? null : list1.Clone();
   insertions = list1 == null ? new BlockList() : list1.Clone();
   //^ assert insertions != null;
   Differences differences = new Differences();
   for (int j = 0, n = list2 == null ? 0 : list2.Count; j < n; j++){
     //^ assert list2 != null;
     Block nd2 = list2[j];
     if (nd2 == null) continue;
     insertions.Add(null);
   }
   TrivialHashtable savedDifferencesMapFor = this.differencesMapFor;
   this.differencesMapFor = null;
   TrivialHashtable matchedNodes = new TrivialHashtable();
   for (int i = 0, k = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
     //^ assert list1 != null && changes != null && deletions != null;
     Block nd1 = list1[i]; 
     if (nd1 == null) continue;
     Differences diff;
     int j;
     Block nd2 = this.GetClosestMatch(nd1, list1, list2, i, ref k, matchedNodes, out diff, out j);
     if (nd2 == null || diff == null){Debug.Assert(nd2 == null && diff == null); continue;}
     matchedNodes[nd1.UniqueKey] = nd1;
     matchedNodes[nd2.UniqueKey] = nd2;
     changes[i] = diff.Changes as Block;
     deletions[i] = diff.Deletions as Block;
     insertions[i] = diff.Insertions as Block;
     insertions[n+j] = nd1; //Records the position of nd2 in list2 in case the change involved a permutation
     Debug.Assert(diff.Changes == changes[i] && diff.Deletions == deletions[i] && diff.Insertions == insertions[i]);
     differences.NumberOfDifferences += diff.NumberOfDifferences;
     differences.NumberOfSimilarities += diff.NumberOfSimilarities;
   }
   //Find deletions
   for (int i = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
     //^ assert list1 != null && changes != null && deletions != null;
     Block nd1 = list1[i]; 
     if (nd1 == null) continue;
     if (matchedNodes[nd1.UniqueKey] != null) continue;
     changes[i] = null;
     deletions[i] = nd1;
     insertions[i] = null;
     differences.NumberOfDifferences += 1;
   }
   //Find insertions
   for (int j = 0, n = list1 == null ? 0 : list1.Count, m = list2 == null ? 0 : list2.Count; j < m; j++){
     //^ assert list2 != null;
     Block nd2 = list2[j]; 
     if (nd2 == null) continue;
     if (matchedNodes[nd2.UniqueKey] != null) continue;
     insertions[n+j] = nd2;  //Records nd2 as an insertion into list1, along with its position in list2
     differences.NumberOfDifferences += 1; //REVIEW: put the size of the tree here?
   }
   if (differences.NumberOfDifferences == 0){
     changes = null;
     deletions = null;
     insertions = null;
   }
   this.differencesMapFor = savedDifferencesMapFor;
   return differences;
 }
Beispiel #32
0
 protected virtual Expression CoerceFromTypeUnion(Expression source, TypeUnion sourceType, TypeNode targetType, bool explicitCoercion, TypeNode originalTargetType, TypeViewer typeViewer){
   if (source == null || sourceType == null || targetType == null) return null;
   if (targetType == SystemTypes.Object) return this.CoerceTypeUnionToObject(source, typeViewer);
   int cErrors = (this.Errors != null) ? this.Errors.Count : 0;
   if (explicitCoercion){
     Method coercion = this.UserDefinedExplicitCoercionMethod(source, sourceType, targetType, false, originalTargetType, typeViewer);
     if (coercion != null && coercion.ReturnType == targetType && coercion.Parameters != null && coercion.Parameters[0] != null &&
       this.ImplicitCoercionFromTo(sourceType, coercion.Parameters[0].Type, typeViewer))
       return this.ImplicitCoercion(new MethodCall(new MemberBinding(null, coercion), new ExpressionList(source), NodeType.Call, coercion.ReturnType),
         targetType, typeViewer);
   }
   Method getTag = TypeViewer.GetTypeView(typeViewer, sourceType).GetMethod(StandardIds.GetTag);
   if (getTag == null) return null;
   Method getValue = TypeViewer.GetTypeView(typeViewer, sourceType).GetMethod(StandardIds.GetValue);
   if (getValue == null) return null;
   Local src = new Local(sourceType);
   Local srcOb = new Local(SystemTypes.Object, source.SourceContext);
   Local tgt = new Local(targetType);
   Expression callGetTag = new MethodCall(new MemberBinding(new UnaryExpression(src, NodeType.AddressOf), getTag), null);
   Expression callGetValue = new MethodCall(new MemberBinding(new UnaryExpression(src, NodeType.AddressOf), getValue), null);
   TypeNodeList types = sourceType.Types;
   int n = types == null ? 0 : types.Count;
   Block endOfSwitch = new Block();
   StatementList statements = new StatementList(5+n);
   statements.Add(new AssignmentStatement(src, source));
   statements.Add(new AssignmentStatement(srcOb, callGetValue));
   BlockList cases = new BlockList(n);
   statements.Add(new SwitchInstruction(callGetTag, cases));
   bool hadCoercion = false;
   Block eb = new Block(new StatementList(1));
   Construct c = new Construct(new MemberBinding(null, SystemTypes.InvalidCastException.GetConstructor()), null, SystemTypes.InvalidCastException);
   eb.Statements.Add(new Throw(c));
   for (int i = 0; i < n; i++){
     TypeNode t = types[i];
     if (t == null) continue;
     if (!explicitCoercion && !this.ImplicitCoercionFromTo(t, targetType, typeViewer)) return null;
     Expression expr = this.ExplicitCoercion(srcOb, t, typeViewer);
     if (expr == null) return null;
     expr = this.ExplicitCoercion(expr, targetType, typeViewer);
     if (expr == null) {
       cases.Add(eb);
       statements.Add(eb);
     }
     else {
       Block b = new Block(new StatementList(2));
       hadCoercion = true;
       expr.SourceContext = srcOb.SourceContext;
       b.Statements.Add(new AssignmentStatement(tgt, expr));
       b.Statements.Add(new Branch(null, endOfSwitch));
       cases.Add(b);
       statements.Add(b);
     }
   }
   if (this.Errors != null) {
     for (int ie = cErrors, ne = this.Errors.Count; ie < ne; ie++) {
       this.Errors[ie] = null;
     }
   }
   if (!hadCoercion) return null;
   statements.Add(endOfSwitch);
   statements.Add(new ExpressionStatement(tgt));
   return new BlockExpression(new Block(statements));
   //TODO: wrap this in a CoerceTypeUnion node so that source code can be reconstructed easily
 }
Beispiel #33
0
 public virtual void BuildAxisClosureUnion(Expression source, AxisBuildState state, SwitchAccessor swa, bool yieldResult, Block block, BlockScope scope) {
   TypeUnion tu = source.Type as TypeUnion;
   Debug.Assert(tu != null, "Switch accessor must have type union");
   if (!this.IsLocal(source)) {
     Expression loc = this.NewClosureLocal(source.Type, scope);
     block.Statements.Add(new AssignmentStatement(loc, source));
     source = loc;
   }
   // determine type union tag and value
   Method mgetvalue = this.GetTypeView(tu).GetMethod(StandardIds.GetValue);
   MethodCall mcgetvalue = new MethodCall(new MemberBinding(source, mgetvalue), null); 
   mcgetvalue.Type = mgetvalue.ReturnType;
   Local locValue = new Local(SystemTypes.Object);
   block.Statements.Add(new AssignmentStatement(locValue, mcgetvalue));
   Method mgettag = this.GetTypeView(tu).GetMethod(StandardIds.GetTag);
   MethodCall mcgettag = new MethodCall(new MemberBinding(source, mgettag), null);
   mcgettag.Type = mgettag.ReturnType;
   Local locTag = new Local(SystemTypes.UInt32);
   block.Statements.Add(new AssignmentStatement(locTag, mcgettag));
   // switch on type union tag
   BlockList blocks = new BlockList(swa.Accessors.Count);
   Block endBlock = new Block(null);
   foreach( int id in swa.Accessors.Keys ) {
     Accessor acc = (Accessor) swa.Accessors[id];
     Block caseBlock = new Block(new StatementList(3));
     blocks.Add(caseBlock);
     block.Statements.Add(new Branch(new BinaryExpression(locTag, new Literal(id, SystemTypes.Int32), NodeType.Eq), caseBlock));
     Expression locvar = this.NewClosureLocal(swa.Type.Types[id], scope);
     caseBlock.Statements.Add(new AssignmentStatement(locvar, this.Unbox(locValue, locvar.Type)));
     this.BuildAxisClosureExpression(locvar, state, acc, yieldResult, caseBlock, scope);
     caseBlock.Statements.Add(new Branch(null, endBlock));
   }
   block.Statements.Add(new Branch(null, endBlock));
   for( int i = 0, n = blocks.Count; i < n; i++ ) {
     block.Statements.Add(blocks[i]);
   }
   block.Statements.Add(endBlock);
 }
Beispiel #34
0
 public virtual void VisitTypeswitchCaseList(TypeswitchCaseList oldCases, BlockList targets, StatementList statements, Block nextStatement, Local temp){
   for (int i = 0, n = oldCases.Count; i < n; i++){
     TypeswitchCase tcase = oldCases[i];
     StatementList stats = new StatementList(3);
     Block b = new Block(stats);
     if (tcase != null){
       Expression expr = null;
       if (tcase.LabelType.IsValueType)
         expr = new AddressDereference(new BinaryExpression(temp, new Literal(tcase.LabelType, SystemTypes.Type), NodeType.Unbox), tcase.LabelType);
       else
         expr = new BinaryExpression(temp, new Literal(tcase.LabelType, SystemTypes.Type), NodeType.Castclass);
       stats.Add(new AssignmentStatement(this.VisitTargetExpression(tcase.LabelVariable), expr));
       stats.Add(this.VisitBlock(tcase.Body));
     }
     stats.Add(new Branch(null, nextStatement));
     statements.Add(b);
     targets.Add(b);
   }
 }
 public void Spawn(IBlock spawnable)
 {
     BlockList.Add(spawnable);
 }
Beispiel #36
0
		public virtual void TestAddToEnd()
		{
			BlockList<int> list = new BlockList<int>(4);
			int cnt = BlockList<int>.BLOCK_SIZE * 3;
			for (int i = 0; i < cnt; i++)
			{
				list.AddItem(Sharpen.Extensions.ValueOf(42 + i));
			}
			NUnit.Framework.Assert.AreEqual(cnt, list.Count);
			for (int i_1 = 0; i_1 < cnt; i_1++)
			{
				NUnit.Framework.Assert.AreEqual(Sharpen.Extensions.ValueOf(42 + i_1), list[i_1]);
			}
			list.Clear();
			NUnit.Framework.Assert.AreEqual(0, list.Count);
			NUnit.Framework.Assert.IsTrue(list.IsEmpty());
			for (int i_2 = 0; i_2 < cnt; i_2++)
			{
				list.Add(i_2, Sharpen.Extensions.ValueOf(42 + i_2));
			}
			NUnit.Framework.Assert.AreEqual(cnt, list.Count);
			for (int i_3 = 0; i_3 < cnt; i_3++)
			{
				NUnit.Framework.Assert.AreEqual(Sharpen.Extensions.ValueOf(42 + i_3), list[i_3]);
			}
		}
Beispiel #37
0
        private SwitchInstruction ParseSwitchInstruction()
        {
            int numTargets = this.GetInt32();
            int offset = this.counter + numTargets * 4;

            BlockList targetList = new BlockList();

            for(int i = 0; i < numTargets; i++)
            {
                int targetAddress = this.GetInt32() + offset;
                targetList.Add(Reader.GetOrCreateBlock(this.blockMap, targetAddress));
            }

            return new SwitchInstruction(PopOperand(), targetList);
        }
        public static List<double> WaveletTransform(List<double> serie)
        {
            //Declaring the blocks
            var inputSeriesBlock = new InputSeriesBlock();
            inputSeriesBlock.SetSeries(serie);
            var dWTBlock = new DWTBlock
            {
                WaveletName = "coif4",
                Level = 1,
                Rescale = false,
                ExtensionMode = SignalExtension.ExtensionMode.AntisymmetricWholePoint
            };
            var outputSeriesBlock = new OutputSeriesBlock();

            //Connecting the blocks
            inputSeriesBlock.OutputNodes[0].ConnectTo(dWTBlock.InputNodes[0]);
            // dWTBlock.OutputNodes[1].ConnectTo(dWTBlock2.InputNodes[0]);
            dWTBlock.OutputNodes[1].ConnectTo(outputSeriesBlock.InputNodes[0]);

            //Appending the blocks to a block list and execute all
            var blockList = new BlockList();
            blockList.Add(inputSeriesBlock);
            blockList.Add(dWTBlock);
            //blockList.Add(dWTBlock2);
            blockList.Add(outputSeriesBlock);
            blockList.ExecuteAll();
            return outputSeriesBlock.GetSeries();
        }
Beispiel #39
0
 public virtual BlockList VisitBlockList(BlockList blockList, BlockList changes, BlockList deletions, BlockList insertions){
   if (changes == null || deletions == null || insertions == null) return blockList;
   int n = blockList == null ? 0 : blockList.Count;
   if (n > changes.Count){Debug.Assert(false); n = changes.Count;}
   if (n > deletions.Count){Debug.Assert(false); n = deletions.Count;}
   if (n > insertions.Count){Debug.Assert(false); n = insertions.Count;}
   if (blockList != null)
     for (int i = 0; i < n; i++)
       blockList[i] = this.VisitBlock(blockList[i], changes[i], deletions[i], insertions[i]);
   BlockList result = new BlockList(insertions.Count-n);
   for (int i = n, m = insertions.Count; i < m; i++)
     result.Add(insertions[i]);
   return result;
 }
Beispiel #40
0
        public virtual void Deserialize(Player player, string currentPattern)
        {
            // See documentation: https://worldedit.enginehub.org/en/latest/usage/general/patterns/

            if (currentPattern.StartsWith("x"))
            {
                currentPattern = currentPattern.Remove(0, 1);                                             // remove starting x
            }
            OriginalPattern = currentPattern.Trim();

            var patternsEx = new Regex(@",(?![^\[]*])");

            foreach (string pattern in patternsEx.Split(currentPattern.Trim()))
            {
                Log.Debug($"Matching {pattern}");
                var blockDataEntry = new BlockDataEntry();

                var regex   = new Regex(@"(?<pattern>((?<weight>\d+)%)?((?<blockId>\d+)|(?<blockName>(minecraft:)?\w+)){1}(:(?<meta>\d+))?(\[(?<states>[a-zA-Z0-9_=,]*)])?)*");
                var stateEx = new Regex(@"(?<name>\w+)\=(?<value>\w+)");

                Match match = regex.Match(pattern.Trim());
                if (match.Success)
                {
                    foreach (Group matchGroup in match.Groups)
                    {
                        if (matchGroup.Name == "weight" && matchGroup.Success)
                        {
                            Log.Debug($"Matched weight group {matchGroup.Value}");
                            if (int.TryParse(matchGroup.Value.Trim(), out int weight))
                            {
                                blockDataEntry.Weight = weight;
                            }
                        }
                        else if (matchGroup.Name == "blockName" && matchGroup.Success)
                        {
                            Log.Debug($"Matched blockName group {matchGroup.Value}");
                            blockDataEntry.Id = BlockFactory.GetBlockIdByName(matchGroup.Value.Trim());
                        }
                        if (matchGroup.Name == "blockId" && matchGroup.Success)
                        {
                            Log.Debug($"Matched blockId group {matchGroup.Value}");
                            if (int.TryParse(matchGroup.Value.Trim(), out int id))
                            {
                                blockDataEntry.Id = id;
                            }
                        }
                        else if (matchGroup.Name == "meta" && matchGroup.Success)
                        {
                            Log.Debug($"Matched meta group {matchGroup.Value}");
                            if (byte.TryParse(matchGroup.Value.Trim(), out byte metadata))
                            {
                                blockDataEntry.Metadata       = metadata;
                                blockDataEntry.HasBlockStates = true;
                            }
                        }
                        else if (matchGroup.Name == "states" && matchGroup.Success)
                        {
                            Log.Debug($"Matched states group {matchGroup.Value}");

                            // Parse block states
                            var stateMatches = stateEx.Matches(matchGroup.Value.Trim());
                            {
                                foreach (Match stateMatch in stateMatches)
                                {
                                    Log.Debug($"State:{stateMatch.Value}");
                                    blockDataEntry.BlockStates.Add(new BlockStateEntry()
                                    {
                                        Name  = stateMatch.Groups.Values.First(g => g.Name == "name").Value,
                                        Value = stateMatch.Groups.Values.First(g => g.Name == "value").Value
                                    });
                                    blockDataEntry.HasBlockStates = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("Deprecated code used to be here.");
                }

                BlockList.Add(blockDataEntry);
            }

            int acc = 0;

            foreach (var entry in BlockList.OrderBy(entry => entry.Weight))
            {
                acc += entry.Weight;
                entry.Accumulated = acc;
            }

            BlockList = BlockList.OrderBy(entry => entry.Accumulated).ToList();
        }