/// <summary>
 /// This constructor takes an ObjectStream and initializes the class to handle
 /// the stream.
 /// </summary>
 /// <param name="lineStream">  an <code>ObjectSteam<String></code> that represents the
 ///                    input file to be attached to this class. </param>
 public NameFinderCensus90NameStream(ObjectStream <string> lineStream)
 {
     this.locale   = new Locale("en");   // locale is English
     this.encoding = Charset.defaultCharset();
     // todo how do we find the encoding for an already open ObjectStream() ?
     this.lineStream = lineStream;
 }
Beispiel #2
0
        public override SyntaxTreeNode Make(ObjectStream <MyToken> input, MyDiscardDelegate <MyToken> discarder)
        {
            Ensure(input, discarder);

            // Ignora código descartável inicialmente
            input.Discard(discarder);

            if (input.EndOfStream())
            {
                return(null);
            }

            var initialPos = input.GetPosition();
            var token      = input.Next();

            if (token == null || (CalcTwoNumbersTokenClass)token.Class != (CalcTwoNumbersTokenClass)GetTokenClass())
            {
                input.SetPosition(initialPos);
                return(null);
            }

            if (string.IsNullOrEmpty((string)token.Content))
            {
                throw new SyntaxAnalysisException("Invalid content for NUMBER element");
            }

            uint number = 0;

            if (!uint.TryParse((string)token.Content, out number))
            {
                throw new SyntaxAnalysisException("Invalid number value for NUMBER element");
            }

            return(new UIntegerTreeNode(number));
        }
 public override void Unpack(ObjectStream obj)
 {
     granted_services    = obj.OutputByte();
     authorized_services = obj.OutputByte();
     vehicle_type        = obj.OutputByte();
     vehicle_id          = obj.OutputUInt16();
 }
 /// <summary>
 /// Creates a new <seealso cref="SentenceSample"/> stream from a line stream, i.e.
 /// <seealso cref="ObjectStream"/>< <seealso cref="String"/>>, that could be a
 /// <seealso cref="PlainTextByLineStream"/> object.
 /// </summary>
 /// <param name="lineStream">
 ///          a stream of lines as <seealso cref="String"/> </param>
 /// <param name="includeHeadlines">
 ///          if true will output the sentences marked as news headlines </param>
 public ADSentenceSampleStream(ObjectStream <string> lineStream, bool includeHeadlines)
 {
     this.adSentenceStream = new ADSentenceStream(lineStream);
     ptEosCharacters       = Factory.ptEosCharacters;
     Arrays.sort(ptEosCharacters);
     this.isIncludeTitles = includeHeadlines;
 }
        internal static void Dispatch(
            BaseClientTransportManager transportManager,
            PSHost clientHost,
            PSDataCollectionStream <ErrorRecord> errorStream,
            ObjectStream methodExecutorStream,
            bool isMethodExecutorStreamEnabled,
            RemoteRunspacePoolInternal runspacePool,
            Guid clientPowerShellId,
            RemoteHostCall remoteHostCall)
        {
            ClientMethodExecutor clientMethodExecutor = new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId, clientPowerShellId, remoteHostCall);

            if (clientPowerShellId == Guid.Empty)
            {
                clientMethodExecutor.Execute(errorStream);
            }
            else if (remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled)
            {
                runspacePool.Close();
            }
            else if (isMethodExecutorStreamEnabled)
            {
                methodExecutorStream.Write((object)clientMethodExecutor);
            }
            else
            {
                clientMethodExecutor.Execute(errorStream);
            }
        }
Beispiel #6
0
        public virtual void TestStandardFormat_SmallObject()
        {
            int type = Constants.OBJ_BLOB;

            byte[]       data = GetRng().NextBytes(300);
            byte[]       gz   = CompressStandardFormat(type, data);
            ObjectId     id   = ObjectId.ZeroId;
            ObjectLoader ol   = UnpackedObject.Open(new ByteArrayInputStream(gz), Path(id), id,
                                                    wc);

            NUnit.Framework.Assert.IsNotNull(ol, "created loader");
            NUnit.Framework.Assert.AreEqual(type, ol.GetType());
            NUnit.Framework.Assert.AreEqual(data.Length, ol.GetSize());
            NUnit.Framework.Assert.IsFalse(ol.IsLarge(), "is not large");
            NUnit.Framework.Assert.IsTrue(Arrays.Equals(data, ol.GetCachedBytes()), "same content"
                                          );
            ObjectStream @in = ol.OpenStream();

            NUnit.Framework.Assert.IsNotNull(@in, "have stream");
            NUnit.Framework.Assert.AreEqual(type, @in.GetType());
            NUnit.Framework.Assert.AreEqual(data.Length, @in.GetSize());
            byte[] data2 = new byte[data.Length];
            IOUtil.ReadFully(@in, data2, 0, data.Length);
            NUnit.Framework.Assert.IsTrue(Arrays.Equals(data2, data), "same content");
            NUnit.Framework.Assert.AreEqual(-1, @in.Read(), "stream at EOF");
            @in.Close();
        }
 public override void Pack(ObjectStream obj)
 {
     obj.Input(vehicle_id);
     obj.Input(vehicle_type);
     obj.Input(authorized_services);
     obj.Input(granted_services);
 }
        public static SqlLongString Create(IRequest context, Stream inputStream, Encoding encoding, bool compressed = true)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }
            if (!inputStream.CanRead)
            {
                throw new ArgumentException("The input stream is not readable", "inputStream");
            }

            var maxSize = inputStream.Length;
            var lob     = context.Query.Session.CreateLargeObject(maxSize, compressed);

            using (var stream = new ObjectStream(lob)) {
                inputStream.CopyTo(stream, 1024);
                stream.Flush();
            }

            lob.Complete();
            return(new SqlLongString(lob, encoding));
        }
Beispiel #9
0
 public override void Unpack(ObjectStream obj)
 {
     altitude   = obj.OutputSingle();
     longitude  = obj.OutputSingle();
     latitude   = obj.OutputSingle();
     vehicle_id = obj.OutputUInt16();
 }
        /// <summary>
        /// Create a new ClientMethodExecutor object and then dispatch it.
        /// </summary>
        internal static void Dispatch(
            BaseClientTransportManager transportManager,
            PSHost clientHost,
            PSDataCollectionStream <ErrorRecord> errorStream,
            ObjectStream methodExecutorStream,
            bool isMethodExecutorStreamEnabled,
            RemoteRunspacePoolInternal runspacePool,
            Guid clientPowerShellId,
            RemoteHostCall remoteHostCall)
        {
            ClientMethodExecutor methodExecutor =
                new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId,
                                         clientPowerShellId, remoteHostCall);

            // If the powershell id is not specified, this message is for the runspace pool, execute
            // it immediately and return
            if (clientPowerShellId == Guid.Empty)
            {
                methodExecutor.Execute(errorStream);
                return;
            }

            // Check client host to see if SetShouldExit should be allowed
            bool hostAllowSetShouldExit = false;

            if (clientHost != null)
            {
                PSObject hostPrivateData = clientHost.PrivateData as PSObject;
                if (hostPrivateData != null)
                {
                    PSNoteProperty allowSetShouldExit = hostPrivateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty;
                    hostAllowSetShouldExit = allowSetShouldExit != null && allowSetShouldExit.Value is bool && (bool)allowSetShouldExit.Value;
                }
            }

            // Should we kill remote runspace? Check if "SetShouldExit" and if we are in the
            // cmdlet case. In the API case (when we are invoked from an API not a cmdlet) we
            // should not interpret "SetShouldExit" but should pass it on to the host. The
            // variable IsMethodExecutorStreamEnabled is only true in the cmdlet case. In the
            // API case it is false.

            if (remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled && !hostAllowSetShouldExit)
            {
                runspacePool.Close();
                return;
            }

            // Cmdlet case: queue up the executor in the pipeline stream.
            if (isMethodExecutorStreamEnabled)
            {
                Dbg.Assert(methodExecutorStream != null, "method executor stream can't be null when enabled");
                methodExecutorStream.Write(methodExecutor);
            }

            // API case: execute it immediately.
            else
            {
                methodExecutor.Execute(errorStream);
            }
        }
        /**
         * <summary>Adds the <see cref="DataObject">data object</see> to the specified object stream
         * [PDF:1.6:3.4.6].</summary>
         * <param name="objectStreamIndirectObject">Target object stream.</param>
         */
        public void Compress(
            PdfIndirectObject objectStreamIndirectObject
            )
        {
            if (objectStreamIndirectObject == null)
            {
                Uncompress();
            }
            else
            {
                PdfDataObject objectStreamDataObject = objectStreamIndirectObject.DataObject;
                if (!(objectStreamDataObject is ObjectStream))
                {
                    throw new ArgumentException("MUST contain an ObjectStream instance.", "objectStreamIndirectObject");
                }

                // Ensure removal from previous object stream!
                Uncompress();

                // Add to the object stream!
                ObjectStream objectStream = (ObjectStream)objectStreamDataObject;
                objectStream[xrefEntry.Number] = DataObject;
                // Update its xref entry!
                xrefEntry.Usage        = XRefEntry.UsageEnum.InUseCompressed;
                xrefEntry.StreamNumber = objectStreamIndirectObject.Reference.ObjectNumber;
                xrefEntry.Offset       = -1; // Internal object index unknown (to set on object stream serialization -- see ObjectStream).
            }
        }
Beispiel #12
0
 public override void Pack(ObjectStream obj)
 {
     obj.Input(vehicle_id);
     obj.Input(roll);
     obj.Input(pitch);
     obj.Input(yaw);
 }
Beispiel #13
0
        public virtual void TestWhole_SmallObject()
        {
            int type = Constants.OBJ_BLOB;

            byte[]  data = GetRng().NextBytes(300);
            RevBlob id   = tr.Blob(data);

            tr.Branch("master").Commit().Add("A", id).Create();
            tr.PackAndPrune();
            NUnit.Framework.Assert.IsTrue(wc.Has(id), "has blob");
            ObjectLoader ol = wc.Open(id);

            NUnit.Framework.Assert.IsNotNull(ol, "created loader");
            NUnit.Framework.Assert.AreEqual(type, ol.GetType());
            NUnit.Framework.Assert.AreEqual(data.Length, ol.GetSize());
            NUnit.Framework.Assert.IsFalse(ol.IsLarge(), "is not large");
            NUnit.Framework.Assert.IsTrue(Arrays.Equals(data, ol.GetCachedBytes()), "same content"
                                          );
            ObjectStream @in = ol.OpenStream();

            NUnit.Framework.Assert.IsNotNull(@in, "have stream");
            NUnit.Framework.Assert.AreEqual(type, @in.GetType());
            NUnit.Framework.Assert.AreEqual(data.Length, @in.GetSize());
            byte[] data2 = new byte[data.Length];
            IOUtil.ReadFully(@in, data2, 0, data.Length);
            NUnit.Framework.Assert.IsTrue(Arrays.Equals(data2, data), "same content");
            NUnit.Framework.Assert.AreEqual(-1, @in.Read(), "stream at EOF");
            @in.Close();
        }
Beispiel #14
0
 public override PdfObject Visit(
     ObjectStream obj,
     object data
     )
 {
     throw new NotSupportedException();
 }
Beispiel #15
0
 private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested) : base(runspace)
 {
     this._syncRoot            = new object();
     this._pipelineStateInfo   = new System.Management.Automation.Runspaces.PipelineStateInfo(PipelineState.NotStarted);
     this._commands            = new CommandCollection();
     this._executionEventQueue = new Queue <ExecutionEventQueueItem>();
     this._performNestedCheck  = true;
     this._addToHistory        = addToHistory;
     this._isNested            = isNested;
     this._isSteppable         = false;
     this._runspace            = runspace;
     this._computerName        = ((RemoteRunspace)this._runspace).ConnectionInfo.ComputerName;
     this._runspaceId          = this._runspace.InstanceId;
     this._inputCollection     = new PSDataCollection <object>();
     this._inputCollection.ReleaseOnEnumeration = true;
     this._inputStream                   = new PSDataCollectionStream <object>(Guid.Empty, this._inputCollection);
     this._outputCollection              = new PSDataCollection <PSObject>();
     this._outputStream                  = new PSDataCollectionStream <PSObject>(Guid.Empty, this._outputCollection);
     this._errorCollection               = new PSDataCollection <ErrorRecord>();
     this._errorStream                   = new PSDataCollectionStream <ErrorRecord>(Guid.Empty, this._errorCollection);
     this._methodExecutorStream          = new ObjectStream();
     this._isMethodExecutorStreamEnabled = false;
     base.SetCommandCollection(this._commands);
     this._pipelineFinishedEvent = new ManualResetEvent(false);
 }
Beispiel #16
0
 public override void Unpack(ObjectStream obj)
 {
     yaw        = obj.OutputSingle();
     pitch      = obj.OutputSingle();
     roll       = obj.OutputSingle();
     vehicle_id = obj.OutputUInt16();
 }
Beispiel #17
0
 internal RemotePipeline(
     RemoteRunspace runspace,
     string command,
     bool addToHistory,
     bool isNested)
     : base((Runspace)runspace)
 {
     this._addToHistory   = addToHistory;
     this._isNested       = isNested;
     this._runspace       = (Runspace)runspace;
     this._computerName   = this._runspace.ConnectionInfo.ComputerName;
     this._runspaceId     = this._runspace.InstanceId;
     this.inputCollection = new PSDataCollection <object>();
     this.inputCollection.ReleaseOnEnumeration = true;
     this._inputStream                   = new PSDataCollectionStream <object>(Guid.Empty, this.inputCollection);
     this.outputCollection               = new PSDataCollection <PSObject>();
     this._outputStream                  = new PSDataCollectionStream <PSObject>(Guid.Empty, this.outputCollection);
     this.errorCollection                = new PSDataCollection <ErrorRecord>();
     this._errorStream                   = new PSDataCollectionStream <ErrorRecord>(Guid.Empty, this.errorCollection);
     this._methodExecutorStream          = new ObjectStream();
     this._isMethodExecutorStreamEnabled = false;
     this.SetCommandCollection(this._commands);
     if (command != null)
     {
         this._commands.Add(new Command(command, true));
     }
     this._powershell = new PowerShell(true, (ObjectStreamBase)this._inputStream, (ObjectStreamBase)this._outputStream, (ObjectStreamBase)this._errorStream, ((RemoteRunspace)this._runspace).RunspacePool);
     this._powershell.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(this.HandleInvocationStateChanged);
     this._pipelineFinishedEvent              = new ManualResetEvent(false);
 }
Beispiel #18
0
        internal bool GetObject(string key, long startPosition, long length, out Stream stream)
        {
            stream = null;
            if (String.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (startPosition < 0)
            {
                throw new ArgumentNullException(nameof(startPosition));
            }
            if (length < 0)
            {
                throw new ArgumentNullException(nameof(length));
            }

            Obj obj = GetObjectMetadata(key);

            if (obj == null)
            {
                return(false);
            }

            ObjectStream objStream = _StorageDriver.ReadRangeStream(obj.BlobFilename, startPosition, length);

            stream = objStream.Data;
            return(true);
        }
Beispiel #19
0
 /// <summary>
 /// creates a new xml object reader
 /// </summary>
 /// <param name="stream">source stream of serialized java data</param>
 /// <param name="converter">converter used to convert data to target representation</param>
 /// <param name="reducer">reduces java data structures to a more compact format (optional but necessary for specific converters to work)</param>
 public ObjectReader(Stream stream, IDataConverter <T> converter, StructureReducer reducer = null)
 {
     basestream     = stream;
     this.stream    = new ObjectStream(stream);
     this.converter = converter;
     this.reducer   = reducer;
 }
Beispiel #20
0
        /// <summary>
        /// Устанавливаем объек в последовательность
        /// </summary>
        internal void SetObject(IObjectStream @object)
        {
            ObjectStream oldObject = (ObjectStream)@object.Parent[@object.TypeCollection][@object.IndexEvent];

            if (oldObject.Type == @object.Type)
            {
                SetLinkObject(@object, oldObject);
            }
            else
            {
                if (((ObjectStream)@object).Variable != null)
                {
                    //if ( Document.ActiveDocument.Dashboard[@object.Variable.Name] != null )
                    //    throw new Exception( "For the variables of sequence it is impossible to use the names of system variables." );
                    if (_sequenceVariables.ContainsKey(((ObjectStream)@object).Variable.Name) &&
                        _sequenceVariables[((ObjectStream)@object).Variable.Name].Value.GetType( ) != ((ObjectStream)@object).Variable.Value.GetType( ))
                    {
                        throw new Exception("It is impossible to use this variable for this cell, the types of values do not coincide.");
                    }
                }
                RemoveLinkObject(oldObject);
                AddLinkToObject(@object);
            }
            @object.Parent[@object.TypeCollection][@object.IndexEvent] = @object;
        }
Beispiel #21
0
 public override void Pack(ObjectStream obj)
 {
     obj.Input(vehicle_id);
     obj.Input(latitude);
     obj.Input(longitude);
     obj.Input(altitude);
 }
Beispiel #22
0
        /// <summary>
        /// Private constructor that does most of the work constructing a remote pipeline object.
        /// </summary>
        /// <param name="runspace">RemoteRunspace object</param>
        /// <param name="addToHistory">AddToHistory</param>
        /// <param name="isNested">IsNested</param>
        private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested)
            : base(runspace)
        {
            _addToHistory = addToHistory;
            _isNested     = isNested;
            _isSteppable  = false;
            _runspace     = runspace;
            _computerName = ((RemoteRunspace)_runspace).ConnectionInfo.ComputerName;
            _runspaceId   = _runspace.InstanceId;

            //Initialize streams
            _inputCollection = new PSDataCollection <object>();
            _inputCollection.ReleaseOnEnumeration = true;

            _inputStream      = new PSDataCollectionStream <object>(Guid.Empty, _inputCollection);
            _outputCollection = new PSDataCollection <PSObject>();
            _outputStream     = new PSDataCollectionStream <PSObject>(Guid.Empty, _outputCollection);
            _errorCollection  = new PSDataCollection <ErrorRecord>();
            _errorStream      = new PSDataCollectionStream <ErrorRecord>(Guid.Empty, _errorCollection);

            // Create object stream for method executor objects.
            MethodExecutorStream          = new ObjectStream();
            IsMethodExecutorStreamEnabled = false;

            SetCommandCollection(_commands);

            //Create event which will be signalled when pipeline execution
            //is completed/failed/stoped.
            //Note:Runspace.Close waits for all the running pipeline
            //to finish.  This Event must be created before pipeline is
            //added to list of running pipelines. This avoids the race condition
            //where Close is called after pipeline is added to list of
            //running pipeline but before event is created.
            PipelineFinishedEvent = new ManualResetEvent(false);
        }
Beispiel #23
0
        private RemoteRunspace CreateTemporaryRemoteRunspace(PSHost host, WSManConnectionInfo connectionInfo)
        {
            int            num;
            string         name     = PSSession.GenerateRunspaceName(out num);
            RemoteRunspace runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, host, this.SessionOption.ApplicationArguments, name, num);

            runspace.URIRedirectionReported += new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
            this.stream = new ObjectStream();
            try
            {
                runspace.Open();
                runspace.ShouldCloseOnPop = true;
            }
            finally
            {
                runspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
                this.stream.ObjectWriter.Close();
                if (runspace.RunspaceStateInfo.State != RunspaceState.Opened)
                {
                    runspace.Dispose();
                    runspace = null;
                }
            }
            return(runspace);
        }
        public override MyToken[] Eval(ObjectStream <Char> input, MyDiscardDelegate <char> discarder)
        {
            Ensure(input, discarder);

            // Ignora código descartável inicialmente
            input.Discard(discarder);

            if (input.EndOfStream())
            {
                return(null);
            }

            var  initialPos = input.GetPosition();
            char character  = input.Next();

            if (character != _character)
            {
                input.SetPosition(initialPos);

                return(null);
            }

            var token = new MyToken(
                GetTokenClass(),
                initialPos,
                input.GetPosition(),
                null
                );

            return(new MyToken[] { token });
        }
Beispiel #25
0
 public override void Unpack(ObjectStream obj)
 {
     position4 = obj.OutputInt32();
     position3 = obj.OutputInt32();
     position2 = obj.OutputInt32();
     position1 = obj.OutputInt32();
 }
Beispiel #26
0
 public override void Pack(ObjectStream obj)
 {
     obj.Input(position1);
     obj.Input(position2);
     obj.Input(position3);
     obj.Input(position4);
 }
Beispiel #27
0
 public Chain(BlockHeader blockHeader, int height, ObjectStream<ChainChange> changes)
 {
     if(changes == null)
         changes = new StreamObjectStream<ChainChange>();
     AssertEmpty(changes);
     _Changes = changes;
     Initialize(blockHeader, height);
 }
Beispiel #28
0
 public Chain(ObjectStream<ChainChange> changes)
 {
     if(changes == null)
         changes = new StreamObjectStream<ChainChange>();
     changes.Rewind();
     _Changes = changes;
     Process();
 }
Beispiel #29
0
        public override ObjectStream <SentenceSample> create(string[] args)
        {
            Parameters @params = ArgumentParser.parse(args, typeof(Parameters));

            ObjectStream <POSSample> posSampleStream = StreamFactoryRegistry.getFactory(typeof(POSSample), ConllXPOSSampleStreamFactory.CONLLX_FORMAT).create(ArgumentParser.filter(args, typeof(ConllXPOSSampleStreamFactory.Parameters)));

            return(new POSToSentenceSampleStream(createDetokenizer(@params), posSampleStream, 30));
        }
Beispiel #30
0
 public Account(ObjectStream<AccountEntry> entries)
 {
     if(entries == null)
         entries = new StreamObjectStream<AccountEntry>();
     entries.Rewind();
     _Entries = entries;
     Process();
 }
Beispiel #31
0
        public override ObjectStream <TokenSample> create(string[] args)
        {
            Parameters @params = ArgumentParser.parse(args, typeof(Parameters));

            ObjectStream <NameSample> nameSampleStream = StreamFactoryRegistry.getFactory(typeof(NameSample), StreamFactoryRegistry.DEFAULT_FORMAT).create(ArgumentParser.filter(args, typeof(NameSampleDataStreamFactory.Parameters)));

            return(new NameToTokenSampleStream(createDetokenizer(@params), nameSampleStream));
        }
        public override ObjectStream <SentenceSample> create(string[] args)
        {
            Parameters @params = ArgumentParser.parse(args, typeof(Parameters));

            ObjectStream <Parse> parseSampleStream = StreamFactoryRegistry.getFactory(typeof(Parse), StreamFactoryRegistry.DEFAULT_FORMAT).create(ArgumentParser.filter(args, typeof(ParseSampleStreamFactory.Parameters)));

            return(new POSToSentenceSampleStream(createDetokenizer(@params), new ParseToPOSSampleStream(parseSampleStream), 30));
        }
Beispiel #33
0
 public virtual PdfObject Visit(ObjectStream obj, object data)
 {
     foreach (PdfDataObject value in obj.Values)
     {
         value.Accept(this, data);
     }
     return(obj);
 }
Beispiel #34
0
 // TODO: hook the runtime to the Host for Debug and Error output
 internal PipelineCommandRuntime(PipelineProcessor pipelineProcessor)
 {
     PipelineProcessor = pipelineProcessor;
     MergeErrorToOutput = false;
     MergeUnclaimedPreviousErrors = false;
     OutputStream = new ObjectStream(this);
     ErrorStream = new ObjectStream(this);
     InputStream = new ObjectStream(this);
 }
Beispiel #35
0
 public virtual PdfObject Visit(
     ObjectStream obj,
     object data
     )
 {
     foreach(PdfDataObject value in obj.Values)
       {value.Accept(this, data);}
       return obj;
 }
 public void Start()
 {
     streams = new ObjectStream<Streams>(template, spawnRate, 16, () =>
     {
       var path = new PathList();
       path.Add(new LinearPath {origin = this.gameObject, target = target});
       path.Add(new FadeOutPath {offset = 0.5f});
       return new SpawnData<Streams>
       {
     stream = Streams.STREAM_0,
     manager = AnimationManager.Default,
     path = path,
     origin = new NTransform(target),
     curve = new Linear(lifeTime)
       };
     });
 }
Beispiel #37
0
 public Account(Account copied, ObjectStream<AccountEntry> entries)
 {
     if(entries == null)
         entries = new StreamObjectStream<AccountEntry>();
     _Entries = entries;
     copied.Entries.Rewind();
     entries.Rewind();
     foreach(var entry in copied.Entries.Enumerate())
     {
         if(_NextToProcess < copied._NextToProcess)
         {
             PushAccountEntry(entry);
         }
         else
             entries.WriteNext(entry);
     }
 }
 public void Start()
 {
     streams = new ObjectStream<Streams>(template, spawnRate, 16, () =>
     {
       var path = new PathList();
       path.Add(new ArcFixedPath {Origin = this.gameObject, Target = target, Speed = speed, Height = 2f, Up = new Vector3(0f, 1f, 0f)});
       path.Add(new FadeOutDistance {offset = fadeOutAt, target = target});
       path.Add(new FadeInDistance {distance = fadeInOver});
       return new SpawnData<Streams>
       {
     stream = Streams.STREAM_2,
     manager = AnimationManager.Default,
     path = path,
     origin = new NTransform(gameObject),
     curve = new Linear(lifeTime)
       };
     });
 }
Beispiel #39
0
 public Chain(Chain copied, ObjectStream<ChainChange> changes)
 {
     if(changes == null)
         changes = new StreamObjectStream<ChainChange>();
     AssertEmpty(changes);
     _Changes = changes;
     copied.Changes.Rewind();
     foreach(var change in copied.Changes.Enumerate())
     {
         if(_NextToProcess < copied._NextToProcess)
         {
             ProcessAndRecord(change, null);
         }
         else
         {
             _Changes.WriteNext(change);
         }
     }
 }
Beispiel #40
0
 public override void OnClick()
 {
     if (m_DialogSaveGlobe.ShowDialog() == DialogResult.OK)
     {
         try
         {
             IMemoryBlobStream pMemoryBlobStream = new MemoryBlobStream();
             IObjectStream pObjectStream = new ObjectStream();
             pObjectStream.Stream = pMemoryBlobStream;
             IPersistStream pPersistStream = m_globeHookHelper.Globe as IPersistStream;
             pPersistStream.Save(pObjectStream, 1);
             pMemoryBlobStream.SaveToFile(m_DialogSaveGlobe.FileName);
             IMapDocument mapDoc;
         }
         catch(Exception exp)
         {
             DevExpress.XtraEditors.XtraMessageBox.Show(string.Format("抱歉,保存操作出现意外错误,信息:{0}", exp.Message));
         }
     }
 }
Beispiel #41
0
        public override void OnClick()
        {
            if (m_DialogOpenGlobe.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    IGlobe pGlobe = m_globeHookHelper.Globe;
                    IObjectStream pObjectStream = new ObjectStream();
                    IMemoryBlobStream pMemorysBlobStream = new MemoryBlobStream();
                    pMemorysBlobStream.LoadFromFile(m_DialogOpenGlobe.FileName);
                    IPersistStream pPersistStream = pGlobe as IPersistStream;
                    pObjectStream.Stream = pMemorysBlobStream;
                    pPersistStream.Load(pObjectStream);

                    m_globeHookHelper.GlobeDisplay.RefreshViewers();
                    m_globeHookHelper.ActiveViewer.Redraw(true);
                    (pGlobe as IActiveView).Refresh();
                }
                catch (Exception exp)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(string.Format("抱歉,加载操作出现意外错误,信息:{0}", exp.Message));
                }
            }
        }
Beispiel #42
0
 public Chain(BlockHeader blockHeader, int height, ObjectStream<ChainChange> changes)
 {
     if(changes == null)
         changes = new StreamObjectStream<ChainChange>();
     _Changes = changes;
     changes.Rewind();
     if(changes.EOF)
     {
         Initialize(blockHeader, height);
     }
     else
     {
         var first = changes.ReadNext();
         if(first.BlockHeader.GetHash() != blockHeader.GetHash())
         {
             throw new InvalidOperationException("The first block of this stream is different than the expected one at height " + height);
         }
         if(first.HeightOrBackstep != height)
         {
             throw new InvalidOperationException("The first block of this stream has height " + first.HeightOrBackstep + " but expected is " + height);
         }
         changes.Rewind();
         Process();
     }
 }
Beispiel #43
0
 public Chain(Network network, ObjectStream<ChainChange> changes)
     : this(network.GetGenesis().Header, changes)
 {
 }
Beispiel #44
0
 private void AssertEmpty(ObjectStream<ChainChange> changes)
 {
     changes.Rewind();
     if(!changes.EOF)
         throw new ArgumentException("This object stream should be empty", "changes");
 }
Beispiel #45
0
 public Chain(BlockHeader genesis, ObjectStream<ChainChange> changes)
     : this(genesis, 0, changes)
 {
 }
Beispiel #46
0
 public Account Clone(ObjectStream<AccountEntry> entries)
 {
     return new Account(this, entries);
 }
        /**
          <summary>Adds the <see cref="DataObject">data object</see> to the specified object stream
          [PDF:1.6:3.4.6].</summary>
          <param name="objectStream">Target object stream.</param>
         */
        public void Compress(
      ObjectStream objectStream
      )
        {
            // Remove from previous object stream!
              Uncompress();

              if(objectStream != null)
              {
            // Add to the object stream!
            objectStream[xrefEntry.Number] = DataObject;
            // Update its xref entry!
            xrefEntry.Usage = XRefEntry.UsageEnum.InUseCompressed;
            xrefEntry.StreamNumber = objectStream.Reference.ObjectNumber;
            xrefEntry.Offset = XRefEntry.UndefinedOffset; // Internal object index unknown (to set on object stream serialization -- see ObjectStream).
              }
        }
Beispiel #48
0
        public Chain CreateSubChain(ChainedBlock from,
            bool fromIncluded,
            ChainedBlock to,
            bool toIncluded,
            ObjectStream<ChainChange> output = null)
        {
            if(output == null)
                output = new StreamObjectStream<ChainChange>();

            var blocks
                =
                to.EnumerateToGenesis()
                .Skip(toIncluded ? 0 : 1)
                .TakeWhile(c => c.HashBlock != from.HashBlock);
            if(fromIncluded)
                blocks = blocks.Concat(new ChainedBlock[] { from });

            var array = blocks.Reverse().ToArray();
            foreach(var b in array)
            {
                output.WriteNext(new ChainChange()
                {
                    Add = true,
                    BlockHeader = b.Header,
                    HeightOrBackstep = (uint)b.Height
                });
            }
            return new Chain(output);
        }
Beispiel #49
0
 public Chain Clone(ObjectStream<ChainChange> changes)
 {
     return new Chain(this, changes);
 }
Beispiel #50
0
        /**
          <summary>Adds an indirect object entry to the specified xref stream.</summary>
          <param name="xrefEntry">Indirect object's xref entry.</param>
          <param name="indirectObject">Indirect object.</param>
          <param name="xrefStream">XRef stream.</param>
          <param name="prevFreeEntry">Previous free xref entry.</param>
          <param name="extensionObjectStreams">Object streams used in incremental updates to extend
        modified ones.</param>
          <returns>Current free xref entry.</returns>
        */
        private XRefEntry AddXRefEntry(
      XRefEntry xrefEntry,
      PdfIndirectObject indirectObject,
      XRefStream xrefStream,
      XRefEntry prevFreeEntry,
      IDictionary<int,ObjectStream> extensionObjectStreams
      )
        {
            xrefStream[xrefEntry.Number] = xrefEntry;

              switch(xrefEntry.Usage)
              {
            case XRefEntry.UsageEnum.InUse:
            {
              int offset = (int)stream.Length;
              // Add entry content!
              indirectObject.WriteTo(stream, file);
              // Set entry content's offset!
              xrefEntry.Offset = offset;
            }
              break;
            case XRefEntry.UsageEnum.InUseCompressed:
              /*
            NOTE: Serialization is delegated to the containing object stream.
              */
              if(extensionObjectStreams != null) // Incremental update.
              {
            int baseStreamNumber = xrefEntry.StreamNumber;
            PdfIndirectObject baseStreamIndirectObject = file.IndirectObjects[baseStreamNumber];
            if(baseStreamIndirectObject.IsOriginal()) // Extension stream needed in order to preserve the original object stream.
            {
              // Get the extension object stream associated to the original object stream!
              ObjectStream extensionObjectStream;
              if(!extensionObjectStreams.TryGetValue(baseStreamNumber, out extensionObjectStream))
              {
                file.Register(extensionObjectStream = new ObjectStream());
                // Link the extension to the base object stream!
                extensionObjectStream.BaseStream = (ObjectStream)baseStreamIndirectObject.DataObject;
                extensionObjectStreams[baseStreamNumber] = extensionObjectStream;
              }
              // Insert the data object into the extension object stream!
              extensionObjectStream[xrefEntry.Number] = indirectObject.DataObject;
              // Update the data object's xref entry!
              xrefEntry.StreamNumber = extensionObjectStream.Reference.ObjectNumber;
              xrefEntry.Offset = XRefEntry.UndefinedOffset; // Internal object index unknown (to set on object stream serialization -- see ObjectStream).
            }
              }
              break;
            case XRefEntry.UsageEnum.Free:
              if(prevFreeEntry != null)
              {prevFreeEntry.Offset = xrefEntry.Number;} // Object number of the next free object.

              prevFreeEntry = xrefEntry;
              break;
            default:
              throw new NotSupportedException();
              }
              return prevFreeEntry;
        }
Beispiel #51
0
   public override PdfObject Visit(
 ObjectStream obj,
 object data
 )
   {
       throw new NotSupportedException();
   }
Beispiel #52
0
        public Chain BuildChain(ObjectStream<ChainChange> changes = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if(changes == null)
                changes = new StreamObjectStream<ChainChange>();
            var chain = new Chain(Network, changes);
            TraceCorrelation trace = new TraceCorrelation(NodeServerTrace.Trace, "Build chain");
            using(trace.Open())
            {
                using(var pool = CreateNodeSet(3))
                {
                    int height = pool.GetNodes().Max(o => o.FullVersion.StartHeight);
                    var listener = new PollMessageListener<IncomingMessage>();

                    pool.SendMessage(new GetHeadersPayload()
                    {
                        BlockLocators = chain.Tip.GetLocator()
                    });

                    using(pool.MessageProducer.AddMessageListener(listener))
                    {
                        while(chain.Height != height)
                        {
                            var before = chain.Tip;
                            var headers = listener.RecieveMessage(cancellationToken).Message.Payload as HeadersPayload;
                            if(headers != null)
                            {
                                foreach(var header in headers.Headers)
                                {
                                    chain.GetOrAdd(header);
                                }
                                if(before.HashBlock != chain.Tip.HashBlock)
                                {
                                    NodeServerTrace.Information("Chain progress : " + chain.Height + "/" + height);
                                    pool.SendMessage(new GetHeadersPayload()
                                    {
                                        BlockLocators = chain.Tip.GetLocator()
                                    });
                                }
                            }
                        }
                    }
                }
            }
            return chain;
        }