Пример #1
0
 private void _onTimerTick(object sender, ElapsedEventArgs e) { 
    var now = DateTimeOffset.Now;
    if (_lastReplicationTime.IsUndefined || now.ElapsedFrom(_lastReplicationTime.LocalDateTime) > ReplicationSchedule) {
       _lastReplicationTime = new TimeStamp(now);
       _replicate();
    }
 }
Пример #2
0
 public void TestStampAll()
 {
     TimeStamp stamp = new TimeStamp();
     var fork1 = stamp.Fork();
     //System.out.println("fork1[0] = " + fork1[0]);
     //System.out.println("fork1[1] = " + fork1[1]);
     TimeStamp event1 = fork1.First.FireEvent();
     //System.out.println("event1 = " + event1);
     TimeStamp event2 = fork1.Second.FireEvent().FireEvent();
     //System.out.println("event2 = " + event2);
     var fork2 = event1.Fork();
     //System.out.println("fork2[0] = " + fork2[0]);
     //System.out.println("fork2[1] = " + fork2[1]);
     TimeStamp event11 = fork2.First.FireEvent();
     //System.out.println("event11 = " + event11);
     TimeStamp join1 = TimeStamp.Join(fork2.Second, event2);
     //System.out.println("join1 = " + join1);
     var fork22 = join1.Fork();
     //System.out.println("fork22[0] = " + fork22[0]);
     //System.out.println("fork22[1] = " + fork22[1]);
     TimeStamp join2 = TimeStamp.Join(fork22.First, event11);
     //System.out.println("join2 = " + join2);
     TimeStamp event3 = join2.FireEvent();
     //System.out.println("event3 = " + event3);
     Assert.Equal(new TimeStamp(Identity.Create(Identity.ONE, Identity.ZERO), new Event(2)), event3);
 }
Пример #3
0
 public void TestStampLeq()
 {
     TimeStamp s1 = new TimeStamp();
     TimeStamp s2 = new TimeStamp();
     Assert.True(TimeStamp.Leq(s1, s2.FireEvent()));
     Assert.False(TimeStamp.Leq(s2.FireEvent(), s1));
 }
Пример #4
0
        public double CalculateTimeDiffrenceinSeconds(TimeStamp time)
        {
            double result = (Day - time.Day)*24*60*60;
            result += (Hour - time.Hour)*60*60;
            result += (Minute - time.Minute)*60;
            result += (Second - time.Second);
            result += (MilliSecond - time.MilliSecond)/1000;

            return result;
        }
 internal static extern SecurityStatus AcceptSecurityContext_1(
     ref RawSspiHandle credHandle,
     IntPtr oldContextHandle,
     IntPtr inputBuffer,
     ContextAttrib requestedAttribs,
     SecureBufferDataRep dataRep,
     ref RawSspiHandle newContextHandle,
     IntPtr outputBuffer,
     ref ContextAttrib outputAttribs,
     ref TimeStamp expiry
 );
 internal static extern SecurityStatus AcquireCredentialsHandle(
     string principleName,
     string packageName,
     CredentialUse credentialUse,
     IntPtr loginId,
     IntPtr packageData,
     IntPtr getKeyFunc,
     IntPtr getKeyData,
     ref RawSspiHandle credentialHandle,
     ref TimeStamp expiry
 );
Пример #7
0
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     try
     {
         var dt = (DateTime)value;
         var ts = new TimeStamp(dt);
         return ts.ToLong();
     }
     catch
     {
         return new TimeStamp(new DateTime()).ToLong();
     }
 }
Пример #8
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     try
     {
         var timeStamp = (long)value;
         var ts = new TimeStamp(timeStamp);
         return ts.Date.ToLongTimeString();
     }
     catch
     {
         return new DateTime().ToLongTimeString();
     }
 }
Пример #9
0
		public void FixtureInit()
		{
			base.FixtureSetup();

			BaseVirtualHandler.InstallVirtuals(@"Language Explorer\Configuration\Grammar\areaConfiguration.xml",
				new string[] { "SIL.FieldWorks.FDO." }, Cache, true);

			Guid appGuid = Guid.NewGuid();
			Cache.MakeDbSyncRecords(appGuid);

			SetUpDataFiles();
			m_tsStartUp = new TimeStamp(m_sqlConnection);
		}
Пример #10
0
    public ChatMessage(string nChannel, string nPlayerName, string nText, TimeStamp nTimeStamp)
    {
        channel = nChannel;
        playerName = nPlayerName;
        text = nText;
        timeStamp = nTimeStamp;

        // Pretty string
        if(playerName != "") {
            prettyString = "[" + channel + "] <b>" + playerName + "</b>: " + text;
        } else {
            if(channel != "")
                prettyString = "[" + channel + "] " + text;
            else
                prettyString = text;
        }

        guiContent = new GUIContent(prettyString);
    }
Пример #11
0
		/// <summary>
		///
		/// </summary>
		internal TimeStamp RetrieveModel(SqlConnection connection, string LangProject, TaskReport parentTask, ParserScheduler.NeedsUpdate eNeedsUpdate)
		{
			TimeStamp began = new TimeStamp(connection);
			using (FdoCache cache = FdoCache.Create(connection.DataSource, connection.Database, null))
			{

				BaseVirtualHandler.InstallVirtuals(@"Language Explorer\Configuration\Main.xml",
					new string[] { "SIL.FieldWorks.FDO.", "SIL.FieldWorks.IText." }, cache, true);

				string sDescription;
				string sFxtFile;
				SetDescriptionAndFxtFile(eNeedsUpdate, out sDescription, out sFxtFile);
				using (m_topLevelTask = parentTask.AddSubTask(sDescription))
				{
					m_taskStack.Push(m_topLevelTask);
					string sFxtPath = Path.Combine(DirectoryFinder.FWCodeDirectory, sFxtFile);
					m_sFxtOutputPath = Path.Combine(m_outputDirectory, m_database + "ParserFxtResult.xml");
					if ((eNeedsUpdate == ParserScheduler.NeedsUpdate.HaveChangedData) &&
						File.Exists(m_sFxtTemplateOutputPath))
					{
						try
						{
							DoUpdate(cache, sFxtPath, ref m_modelDom);
							DoUpdate(cache, m_sGafawsFxtPath, ref m_templateDom);
						}
						// (SteveMiller): Unremarked, the following often causes an error:
						// Warning as Error: The variable 'e' is declared but never used
						catch (XUpdaterException)
						{
							//Trace.WriteLine("XUpdater exception caught: " + e.Message);
							// do something useful for the user
							DoDump(eNeedsUpdate, cache, sFxtPath);
						}

					}
					else
						DoDump(eNeedsUpdate, cache, sFxtPath);
				}
			}
			m_topLevelTask = null;
			return began;
		}
        private void Init( CredentialUse use )
        {
            string packageName;
            TimeStamp rawExpiry = new TimeStamp();
            SecurityStatus status = SecurityStatus.InternalError;

            // -- Package --
            // Copy off for the call, since this.SecurityPackage is a property.
            packageName = this.SecurityPackage;

            this.Handle = new SafeCredentialHandle();

            // The finally clause is the actual constrained region. The VM pre-allocates any stack space,
            // performs any allocations it needs to prepare methods for execution, and postpones any 
            // instances of the 'uncatchable' exceptions (ThreadAbort, StackOverflow, OutOfMemory).
            RuntimeHelpers.PrepareConstrainedRegions();
            try { }
            finally
            {
                status = CredentialNativeMethods.AcquireCredentialsHandle(
                   null,
                   packageName,
                   use,
                   IntPtr.Zero,
                   IntPtr.Zero,
                   IntPtr.Zero,
                   IntPtr.Zero,
                   ref this.Handle.rawHandle,
                   ref rawExpiry
               );
            }

            if ( status != SecurityStatus.OK )
            {
                throw new SspiException( "Failed to call AcquireCredentialHandle", status );
            }

            this.Expiry = rawExpiry.ToDateTime();
        }
 protected override long OnApply(TimeStamp timeStamp)
 {
     return timeStamp.Ticks - timeStamp.Ticks % TicksPerMillisecond;
 }
Пример #14
0
		public void Deserialize(GenericReader reader)
		{
			int version = reader.GetVersion();

			switch (version)
			{
				case 0:
					{
						ID = reader.ReadString();
						_State = reader.ReadFlag<DonationTransactionState>();
						Account = reader.ReadAccount();
						Email = reader.ReadString();
						Total = reader.ReadDecimal();
						_Credit = reader.ReadLong();
						_Time = reader.ReadDouble();
						Version = reader.ReadInt();
						_InternalVersion = reader.ReadInt();
						_Notes = reader.ReadString();
						_Extra = reader.ReadString();

						DeliverFrom = reader.ReadMobile();
						DeliverTo = reader.ReadMobile();

						DeliveryTime = reader.ReadDouble();
					}
					break;
			}
		}
Пример #15
0
		public List<VoteProfileEntry> GetHistory(TimeStamp key, int limit = 0)
		{
			var list = History.ContainsKey(key) ? History[key].ToList() : new List<VoteProfileEntry>();

			if (limit > 0 && list.Count > limit)
			{
				list.RemoveRange(limit, list.Count - limit);
			}

			list.Sort(InternalHistorySort);
			return list;
		}
Пример #16
0
        private void CreatePhysicalFillHelper(int totalSize, double price, TimeStamp time, TimeStamp utcTime, PhysicalOrder order)
        {
            if (debug)
            {
                log.Debug("Filling order: " + order);
            }
            var split              = random.Next(maxPartialFillsPerOrder) + 1;
            var lastSize           = totalSize / split;
            var cumulativeQuantity = 0;

            if (lastSize == 0)
            {
                lastSize = totalSize;
            }
            while (order.Size > 0)
            {
                order.Size -= Math.Abs(lastSize);
                if (order.Size < Math.Abs(lastSize))
                {
                    lastSize  += Math.Sign(lastSize) * order.Size;
                    order.Size = 0;
                }
                cumulativeQuantity += lastSize;
                if (order.Size == 0)
                {
                    CancelBrokerOrder(order.BrokerOrder);
                }
                CreateSingleFill(lastSize, totalSize, cumulativeQuantity, order.Size, price, time, utcTime, order);
            }
        }
Пример #17
0
 public virtual void Change(SymbolInfo symbol, int position, double price, TimeStamp time)
 {
     Change(position, price, time);
 }
Пример #18
0
 public override string ToString()
 {
     if (Ban == null)
     {
         return(string.Format("[{0} {1}] Login failed: Invalid credentials", TimeStamp.ToShortDateString(), TimeStamp.ToLongTimeString()));
     }
     else
     {
         return(string.Format("[{0} {1}] Login failed, you were banned: {2}", TimeStamp.ToShortDateString(), TimeStamp.ToLongTimeString(), Ban));
     }
 }
Пример #19
0
 public override string ToString()
 {
     return(FlightMode.ToString() + ";" + TimeStamp.ToString() + ";" + Armed.ToString() + ";" + AngleMeasured.ToString() + AngleReference.ToString() + MotorSpeeds.ToString() + "\n");
 }
Пример #20
0
        public void WithdrawMoney_OnUninitializedBankAccount_Throws()
        {
            var bankAccount           = BankAccount.Rehydrate(DefaultBankAccountId, Enumerable.Empty <BankAccountEvent>());
            var bankAccountRepository = ConfigureBankAccountRepositoryForAccount(bankAccount);
            var systemUnderTest       = new WithdrawMoneyHandler(bankAccountRepository);
            var command = new WithdrawMoney(DefaultBankAccountId, Transaction.Of(Guid.Parse("996228f4-70cb-4e44-9716-8a2a3b27d18c")), new Money(200, Currency.Euro), TimeStamp.Of(3));

            systemUnderTest.Awaiting(it => it.Handle(command, CancellationToken.None)).Should().Throw <ConstraintViolationException>();
        }
Пример #21
0
        public void WithdrawMoney_WithLimitExceeded_Throws()
        {
            var bankAccount           = new BankAccountBuilder(DefaultBankAccountId).WithCurrency(Currency.Euro).WithDepositedMoney(100).Build();
            var bankAccountRepository = ConfigureBankAccountRepositoryForAccount(bankAccount);
            var systemUnderTest       = new WithdrawMoneyHandler(bankAccountRepository);
            var command = new WithdrawMoney(DefaultBankAccountId, Transaction.Of(Guid.Parse("996228f4-70cb-4e44-9716-8a2a3b27d18c")), new Money(200, Currency.Euro), TimeStamp.Of(3));

            systemUnderTest.Awaiting(it => it.Handle(command, CancellationToken.None)).Should().Throw <LimitExceededException>();
        }
Пример #22
0
        public void WithdrawMoney_WithLimitNotExceeded_WithdrawsMoney()
        {
            var bankAccount           = new BankAccountBuilder(DefaultBankAccountId).WithCurrency(Currency.Euro).WithDepositedMoney(50).WithDepositedMoney(50).Build();
            var bankAccountRepository = ConfigureBankAccountRepositoryForAccount(bankAccount);
            var systemUnderTest       = new WithdrawMoneyHandler(bankAccountRepository);
            var command = new WithdrawMoney(DefaultBankAccountId, Transaction.Of(Guid.Parse("996228f4-70cb-4e44-9716-8a2a3b27d18c")), new Money(100, Currency.Euro), TimeStamp.Of(3));

            systemUnderTest.Handle(command, CancellationToken.None).GetAwaiter().GetResult();

            var moneyDeposited = new MoneyWithdrawn(DefaultBankAccountId.Value, command.Transaction.Value, command.Amount.Amount, command.TimeStamp.Value);

            bankAccountRepository.Received().SaveAsync(Arg.Is <BankAccount>(it => it.IsCorrectBankAccount(DefaultBankAccountId, 4, moneyDeposited)));
        }
Пример #23
0
 private void FilterFile(string inputPath, string outputPath, TimeStamp startTime, TimeStamp endTime)
 {
     using (var reader = Factory.TickUtil.TickFile())
         using (var writer = Factory.TickUtil.TickFile())
         {
             writer.Initialize(outputPath, TickFileMode.Write);
             reader.Initialize(inputPath, TickFileMode.Read);
             TickIO firstTick = Factory.TickUtil.TickIO();
             TickIO lastTick  = Factory.TickUtil.TickIO();
             TickIO prevTick  = Factory.TickUtil.TickIO();
             long   count     = 0;
             long   dups      = 0;
             TickIO tickIO    = Factory.TickUtil.TickIO();
             try
             {
                 while (reader.TryReadTick(tickIO))
                 {
                     if (tickIO.Time >= startTime)
                     {
                         if (tickIO.Time > endTime)
                         {
                             break;
                         }
                         if (count == 0)
                         {
                             prevTick.Copy(tickIO);
                             prevTick.IsSimulateTicks = true;
                             firstTick.Copy(tickIO);
                             firstTick.IsSimulateTicks = true;
                         }
                         count++;
                         prevTick.Copy(tickIO);
                         writer.WriteTick(prevTick);
                     }
                 }
             }
             catch (QueueException ex)
             {
                 if (ex.EntryType != EventType.EndHistorical)
                 {
                     throw new ApplicationException("Unexpected QueueException: " + ex);
                 }
             }
             lastTick.Copy(tickIO);
             Output(reader.Symbol + ": " + count + " ticks.");
             Output("From " + firstTick.Time + " to " + lastTick.Time);
             Output(dups + " duplicates elimated.");
         }
 }
Пример #24
0
 public global::OpenMI.Standard.ITime GetCurrentTime()
 {
     Oatc.OpenMI.Sdk.Backbone.TimeStamp current_time = new TimeStamp();
     current_time.ModifiedJulianDay = Oatc.OpenMI.Sdk.DevelopmentSupport.CalendarConverter.Gregorian2ModifiedJulian(_daisyEngine.GetTime());
     return((global::OpenMI.Standard.ITime)(current_time));
 }
Пример #25
0
        /// <summary>
        /// Performs and continues the authentication cycle.
        /// </summary>
        /// <remarks>
        /// This method is performed iteratively to start, continue, and end the authentication cycle with the
        /// server. Each stage works by acquiring a token from one side, presenting it to the other side
        /// which in turn may generate a new token.
        ///
        /// The cycle typically starts and ends with the client. On the first invocation on the client,
        /// no server token exists, and null is provided in its place. The client returns its status, providing
        /// its output token for the server. The server accepts the clients token as input and provides a
        /// token as output to send back to the client. This cycle continues until the server and client
        /// both indicate, typically, a SecurityStatus of 'OK'.
        /// </remarks>
        /// <param name="serverToken">The most recently received token from the server, or null if beginning
        /// the authentication cycle.</param>
        /// <param name="outToken">The clients next authentication token in the authentication cycle.</param>
        /// <returns>A status message indicating the progression of the authentication cycle.
        /// A status of 'OK' indicates that the cycle is complete, from the client's perspective. If the outToken
        /// is not null, it must be sent to the server.
        /// A status of 'Continue' indicates that the output token should be sent to the server and
        /// a response should be anticipated.</returns>
        public SecurityStatus Init(byte[] serverToken, out byte[] outToken)
        {
            TimeStamp rawExpiry = new TimeStamp();

            SecurityStatus status;

            SecureBuffer        outTokenBuffer;
            SecureBufferAdapter outAdapter;

            SecureBuffer        serverBuffer;
            SecureBufferAdapter serverAdapter;

            if (this.Disposed)
            {
                throw new ObjectDisposedException("ClientContext");
            }
            else if ((serverToken != null) && (this.ContextHandle.IsInvalid))
            {
                throw new InvalidOperationException("Out-of-order usage detected - have a server token, but no previous client token had been created.");
            }
            else if ((serverToken == null) && (this.ContextHandle.IsInvalid == false))
            {
                throw new InvalidOperationException("Must provide the server's response when continuing the init process.");
            }

            // The security package tells us how big its biggest token will be. We'll allocate a buffer
            // that size, and it'll tell us how much it used.
            outTokenBuffer = new SecureBuffer(
                new byte[this.Credential.PackageInfo.MaxTokenLength],
                BufferType.Token
                );

            serverBuffer = null;
            if (serverToken != null)
            {
                serverBuffer = new SecureBuffer(serverToken, BufferType.Token);
            }

            // Some notes on handles and invoking InitializeSecurityContext
            //  - The first time around, the phContext parameter (the 'old' handle) is a null pointer to what
            //    would be an RawSspiHandle, to indicate this is the first time it's being called.
            //    The phNewContext is a pointer (reference) to an RawSspiHandle struct of where to write the
            //    new handle's values.
            //  - The next time you invoke ISC, it takes a pointer to the handle it gave you last time in phContext,
            //    and takes a pointer to where it should write the new handle's values in phNewContext.
            //  - After the first time, you can provide the same handle to both parameters. From MSDN:
            //       "On the second call, phNewContext can be the same as the handle specified in the phContext
            //        parameter."
            //    It will overwrite the handle you gave it with the new handle value.
            //  - All handle structures themselves are actually *two* pointer variables, eg, 64 bits on 32-bit
            //    Windows, 128 bits on 64-bit Windows.
            //  - So in the end, on a 64-bit machine, we're passing a 64-bit value (the pointer to the struct) that
            //    points to 128 bits of memory (the struct itself) for where to write the handle numbers.
            using (outAdapter = new SecureBufferAdapter(outTokenBuffer))
            {
                if (this.ContextHandle.IsInvalid)
                {
                    status = ContextNativeMethods.InitializeSecurityContext_1(
                        ref this.Credential.Handle.rawHandle,
                        IntPtr.Zero,
                        this.serverPrinc,
                        this.requestedAttribs,
                        0,
                        SecureBufferDataRep.Network,
                        IntPtr.Zero,
                        0,
                        ref this.ContextHandle.rawHandle,
                        outAdapter.Handle,
                        ref this.finalAttribs,
                        ref rawExpiry
                        );
                }
                else
                {
                    using (serverAdapter = new SecureBufferAdapter(serverBuffer))
                    {
                        status = ContextNativeMethods.InitializeSecurityContext_2(
                            ref this.Credential.Handle.rawHandle,
                            ref this.ContextHandle.rawHandle,
                            this.serverPrinc,
                            this.requestedAttribs,
                            0,
                            SecureBufferDataRep.Network,
                            serverAdapter.Handle,
                            0,
                            ref this.ContextHandle.rawHandle,
                            outAdapter.Handle,
                            ref this.finalAttribs,
                            ref rawExpiry
                            );
                    }
                }
            }

            if (status.IsError() == false)
            {
                if (status == SecurityStatus.OK)
                {
                    base.Initialize(rawExpiry.ToDateTime());
                }

                outToken = null;

                if (outTokenBuffer.Length != 0)
                {
                    outToken = new byte[outTokenBuffer.Length];
                    Array.Copy(outTokenBuffer.Buffer, outToken, outToken.Length);
                }
            }
            else
            {
                throw new SspiException("Failed to invoke InitializeSecurityContext for a client", status);
            }

            return(status);
        }
Пример #26
0
        private void CreateSingleFill(int size, int totalSize, int cumulativeSize, int remainingSize, double price, TimeStamp time, TimeStamp utcTime, PhysicalOrder order)
        {
            if (debug)
            {
                log.Debug("Changing actual position from " + this.actualPosition + " to " + (actualPosition + size) + ". Fill size is " + size);
            }
            this.actualPosition += size;
            if (onPositionChange != null)
            {
                onPositionChange(actualPosition);
            }
            var fill = new PhysicalFillDefault(size, price, time, utcTime, order, createSimulatedFills);

            if (debug)
            {
                log.Debug("Fill: " + fill);
            }
            if (onPhysicalFill == null)
            {
                throw new ApplicationException("Please set the OnPhysicalFill property.");
            }
            else
            {
                if (SyncTicks.Enabled)
                {
                    tickSync.AddPhysicalFill(fill);
                }
                onPhysicalFill(fill, totalSize, cumulativeSize, remainingSize);
            }
        }
Пример #27
0
 public override string ToString()
 {
     return(String.Format("{0}/{1,-5} {2}", TimeStamp.ToLongTimeString(), Priority.ToString(), Message));
 }
Пример #28
0
        void RunSingleCamera(ManagedPGRGuid guid)
        {
            const int NumImages = 10;

            ManagedCamera cam = new ManagedCamera();

            // Connect to a camera
            cam.Connect(guid);

            // Get the camera information
            CameraInfo camInfo = cam.GetCameraInfo();

            PrintCameraInfo(camInfo);

            // Get embedded image info from camera
            EmbeddedImageInfo embeddedInfo = cam.GetEmbeddedImageInfo();

            // Enable timestamp collection
            if (embeddedInfo.timestamp.available == true)
            {
                embeddedInfo.timestamp.onOff = true;
            }

            // Set embedded image info to camera
            cam.SetEmbeddedImageInfo(embeddedInfo);

            // Start capturing images
            cam.StartCapture();

            // Create a raw image
            ManagedImage rawImage = new ManagedImage();

            // Create a converted image
            ManagedImage convertedImage = new ManagedImage();

            for (int imageCnt = 0; imageCnt < NumImages; imageCnt++)
            {
                try
                {
                    // Retrieve an image
                    cam.RetrieveBuffer(rawImage);
                }
                catch (FC2Exception ex)
                {
                    Console.WriteLine("Error retrieving buffer : {0}", ex.Message);
                    continue;
                }


                // Get the timestamp
                TimeStamp timeStamp = rawImage.timeStamp;

                Console.WriteLine(
                    "Grabbed image {0} - {1} {2} {3}",
                    imageCnt,
                    timeStamp.cycleSeconds,
                    timeStamp.cycleCount,
                    timeStamp.cycleOffset);

                // Convert the raw image
                rawImage.Convert(PixelFormat.PixelFormatBgr, convertedImage);

                // Create a unique filename
                string filename = String.Format(
                    "FlyCapture2Test_CSharp-{0}-{1}.bmp",
                    camInfo.serialNumber,
                    imageCnt);

                // Get the Bitmap object. Bitmaps are only valid if the
                // pixel format of the ManagedImage is RGB or RGBU.
                System.Drawing.Bitmap bitmap = convertedImage.bitmap;

                // Save the image
                bitmap.Save(filename);
            }

            // Stop capturing images
            cam.StopCapture();

            // Disconnect the camera
            cam.Disconnect();
        }
Пример #29
0
		private XmlDocument UpdateFXT()
		{
			StoreChangedDataItems();
			m_tsStartUp = new TimeStamp(m_sqlConnection);
			m_retriever.DoUpdate(Cache, Path.Combine(m_sFxtTemplatePath, "M3Parser.fxt"), ref m_fxtResult);
			// XmlDocument updatedFxtResult = m_retriever.ModelDom;
			XmlDocument updatedFxtResult = m_fxtResult;
#if !ShowDumpResult
			updatedFxtResult.PreserveWhitespace = false;
			updatedFxtResult.Save(Path.Combine(System.IO.Path.GetTempPath(), "TestFxtUpdateResult.xml"));
#endif
			return updatedFxtResult;
		}
Пример #30
0
    /**---------------------------------------------------------------------------------
     * Method which does things when stuff is clicked, checked every frame.
     */
    void KeyInputs()
    {
        int horizontal = 0;
        int vertical = 0;

        /**
         * Used on touchpad devices.
         */
        if (Input.touches.Length > 0)
        {
            Touch firstFinger = Input.touches[0];

            if (firstFinger.phase == TouchPhase.Began)
                startPosition = firstFinger.position;
            else if (firstFinger.phase == TouchPhase.Ended && startPosition != -Vector2.one)
            {
                Vector2 endPosition = firstFinger.position;

                float x = endPosition.x - startPosition.x;
                float y = endPosition.y - startPosition.y;

                startPosition = -Vector2.one;

                if (Mathf.Abs(x) > Mathf.Abs(y))
                    horizontal = x > 0 ? 1 : -1;
                else
                    vertical = y > 0 ? 1 : -1;
            }
        }

        //Temp stuff for easier testing.
        if (Input.GetKeyDown(KeyCode.R))
            GoalFunc();

        /**
         * Cooldown to avoid queuing up unwanted commands.
         */
        if (coolingDown)
        {
            Input.ResetInputAxes();
            cooldownCount -= 1;
        }

        if (cooldownCount == 0)
        {
            coolingDown = false;
            cooldownCount = 15;
        }
        else
        {
            if (ifTurnRightInput() || horizontal == 1)
            {
                SetNextAction(PlayerState.TurnRight);
                coolingDown = true;
            }

            else if (ifTurnLeftInput() || horizontal == -1)
            {
                SetNextAction(PlayerState.TurnLeft);
                coolingDown = true;
            }
            if (isJumpLocked)
            {
                if ((ifSlideInput() || vertical == -1) && !isSliding && !isJumping)
                {
                    SetNextAction(PlayerState.Slide);
                }

                else if ((ifJumpInput() || vertical == 1) && !isJumping && !isSliding)
                {
                    SetNextAction(PlayerState.Jump);
                }
            }
        }

        if (!isJumpLocked)
        {
            if ((ifSlideInput() || vertical == -1) && !isSliding && !isJumping)
            {
                float time = playerTimerObj.f_time;
                TimeStamp ts = new TimeStamp();
                ts.time = time;
                ts.input = PlayerState.Slide;
                inputs.Add(ts);
                Slide();
                AudioManager.Instance.SlideSound();
            }

            else if ((ifJumpInput() || vertical == 1) && !isJumping && !isSliding)
            {
                float time = playerTimerObj.f_time;
                TimeStamp ts = new TimeStamp();
                ts.time = time;
                ts.input = PlayerState.Jump;
                inputs.Add(ts);
                Jump();
                AudioManager.Instance.JumpSound();
            }
        }
    }
Пример #31
0
 public virtual string Export()
 {
     return(string.Join(";", TimeStamp.ToString(), Name));
 }
 internal static extern SecurityStatus InitializeSecurityContext_1(
     ref RawSspiHandle credentialHandle,
     IntPtr zero,
     string serverPrincipleName,
     ContextAttrib requiredAttribs,
     int reserved1,
     SecureBufferDataRep dataRep,
     IntPtr inputBuffer,
     int reserved2,
     ref RawSspiHandle newContextHandle,
     IntPtr outputBuffer,
     ref ContextAttrib contextAttribs,
     ref TimeStamp expiry
 );
Пример #33
0
 /*
  * Overrides and returns the block string
  *
  * @return block
  */
 public override string ToString()
 {
     return($"{Index} [{TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")}] Proof: {Proof} | PrevHash: {PreviousHash} | Trx: {Transactions.Count}");
 }
Пример #34
0
 public override string Export()
 {
     return(string.Join(";", TimeStamp.ToString(), Name, Destination));
 }
Пример #35
0
    /**---------------------------------------------------------------------------------
     * Method overridden to save away the action for the next ghost.
     */
    protected override void ActivateNextAction()
    {
        if (nextAction != PlayerState.Idle)
        {
            float time = playerTimerObj.f_time;
            TimeStamp ts = new TimeStamp();
            ts.time = time;
            ts.input = nextAction;
            inputs.Add(ts);

            if (nextAction == PlayerState.TurnLeft) TurnLeft();
            if (nextAction == PlayerState.TurnRight) TurnRight();
            if (nextAction == PlayerState.Slide) { Slide(); AudioManager.Instance.SlideSound(); }
            if (nextAction == PlayerState.Jump) { Jump(); AudioManager.Instance.JumpSound(); }

            nextAction = PlayerState.Idle;
        }
    }
Пример #36
0
 public Trigger()
 {
     _resultsBuffer     = new SmartBuffer();
     _earliestInputTime = new TimeStamp(0);
 }
Пример #37
0
 private static bool ParseBirthValue(ref ParseContext pctx, AccountStub stub)
 {
     stub.Fields |= UpdatedFields.Birth;
     return(TryReadInt(ref pctx, out stub.birth) && TimeStamp.IsValidBirth(stub.birth));
 }
Пример #38
0
 private void SetBidVolChg(MarketState prevMktState)
 {
     if (_securityObj.HasQuoteSize)
     {
         if ((Bid == prevMktState.Bid))
         {
             BidVolChg     = (int)(BidVol - prevMktState.BidVol);
             BidVolChgSum += BidVolChg;
             SetBidVolChgCnt(BidVolChg);
         }
         else
         {
             if ((Bid == prevMktState.Ask)) // just ticked up
             {
                 BidVolChg     = (int)(BidVol + prevMktState.AskVol);
                 BidVolChgSum += BidVolChg;
                 SetBidVolChgCnt(BidVolChg);
                 //Console.WriteLine(SecurityObj.Name + " went Bid @" + timeStamp.ToLongTimeString());
             }
             else
             {
                 if ((Bid == prevMktState.PrevAsk)) // just ticked up, but need to look two data points back
                 {
                     BidVolChg     = (int)(BidVol + prevMktState.PrevAskVol);
                     BidVolChgSum += BidVolChg;
                     SetBidVolChgCnt(BidVolChg);
                     //Console.WriteLine(SecurityObj.Name + " went Bid @" + timeStamp.ToLongTimeString());
                 }
                 else
                 {
                     if ((Bid < PrevBid)) // just ticked down
                     {
                         BidVolChg     = (int)(PrevBidVol);
                         BidVolChgSum -= BidVolChg;
                         SetBidVolChgCnt(BidVolChg);
                         Console.WriteLine("{0} went offered @ {1} {2} {3} {4}", Name, TimeStamp.ToLongTimeString(), Bid.ToString(), PrevBid.ToString(), BidVolChg.ToString());
                     }
                 }
             }
         }
     }
 }
Пример #39
0
 public static void SyncLastTime()
 {
     lastTime = currentTime;
 }
Пример #40
0
 public int CompareTo(BitrateLogEntry other)
 {
     return(TimeStamp.CompareTo(other.TimeStamp));
 }
Пример #41
0
		public DonationTransaction(
			string id,
			DonationTransactionState state,
			IAccount account,
			string email,
			decimal total,
			DonationCredits credit,
			TimeStamp time,
			int version = 0,
			string notes = null,
			string extra = null)
		{
			ID = id;
			_State = state;
			Account = account;
			Email = email;
			Total = total;
			_Credit = credit;
			_Time = time;
			Version = version;
			_InternalVersion = version;
			_Notes = notes ?? String.Empty;
			_Extra = extra ?? String.Empty;
		}
Пример #42
0
        public int CompareTo(object obj)
        {
            var other = (Log)obj;

            return(TimeStamp.CompareTo(other.TimeStamp));
        }
Пример #43
0
        static void Main(string[] args)
        {
            string direction = string.Empty;
            bool query = false;
            bool raw = false;
            bool init = false;
            bool deInit = false;
            bool help = false;
            bool htmlReport = false;
            string inject = string.Empty;
            string tags = string.Empty;
            string timeSpan = string.Empty;
            bool pause = false;

            var configuration = CommandLineParserConfigurator
                .Create()
                .WithSwitch("q", () => query = true).HavingLongAlias("query").DescribedBy("Call the db and get your working times.")
                .WithSwitch("r", () => raw = true).HavingLongAlias("raw").DescribedBy("Get all logged events")
                .WithSwitch("i", () => init = true).HavingLongAlias("init").DescribedBy("Create windows tasks (you need elevated permissions for this one!")
                .WithSwitch("d", () => deInit = true).HavingLongAlias("deinit").DescribedBy("Remove windows tasks (you need elevated permissions for this one!")
                .WithSwitch("b", () => pause = true).HavingLongAlias("pause").DescribedBy("Manage your breaks")
                .WithSwitch("h", () => help = true).HavingLongAlias("help").DescribedBy("Show this usage screen.")
                .WithSwitch("o", () => htmlReport = true).HavingLongAlias("out").DescribedBy("Show html report.")
                .WithNamed("j", I => inject = I).HavingLongAlias("inject").DescribedBy("Time|Direction\"", "Use this for debugging only! You can inject timestamps. 1 for lock, 0 for unlock")
                .WithNamed("t", t => tags = t).HavingLongAlias("tags").DescribedBy("timestamp|Tag1,Tag2,...\"", "Tag a timestamp; use ticks for the timestamp (-r shows them)")
                .WithPositional(d => direction = d).DescribedBy("lock", "tell me to \"lock\" for \"out\" and keep empty for \"in\"")
                .BuildConfiguration();
            var parser = new CommandLineParser(configuration);

            var parseResult = parser.Parse(args);

            if (!parseResult.Succeeded)
            {
                ShowUsage(configuration, parseResult.Message);
                Environment.Exit((int)ExitCode.ArgumentError);
            }
            else
            {
                if (help)
                {
                    ShowUsage(configuration);
                    Environment.Exit((int)ExitCode.OK);
                }
                if (init)
                {
                    using (TaskService ts = new TaskService())
                    {
                        try
                        {
                            DefineTask(ts, "myLock lock screen", "lock_pc", TriggerType.Lock);
                            DefineTask(ts, "myLock unlock screen", "unlock_pc", TriggerType.Unlock);
                            DefineTask(ts, "myLock login to pc", "login_pc", TriggerType.Logon);
                            DefineTask(ts, "myLock logout from pc", "logout_pc", TriggerType.Logoff);
                            DefineTask(ts, "myLock energysaver from pc", "energysave_pc", TriggerType.Energysave);
                            Console.WriteLine("Initialization complete.");
                            Environment.Exit((int)ExitCode.OK);
                        }
                        catch (UnauthorizedAccessException)
                        {
                            Console.Error.WriteLine("Access denied, please use an elevated prompt.");
                            Environment.Exit((int)ExitCode.Exception);
                        }
                    }
                }
                if (deInit)
                {
                    using (TaskService ts = new TaskService())
                    {
                        try
                        {
                            //Remove tasks
                            foreach (var t in ts.RootFolder.AllTasks)
                                if (t.Name.StartsWith(taskPrefix))
                                    ts.RootFolder.DeleteTask(t.Name);

                            Console.WriteLine("Deinitialization complete.");
                            Environment.Exit((int)ExitCode.OK);
                        }
                        catch (UnauthorizedAccessException)
                        {
                            Console.Error.WriteLine("Access denied, please use an elevated prompt.");
                            Environment.Exit((int)ExitCode.Exception);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(inject))
                {
                    TimeStampCollection col;
                    try
                    {
                        col = Saver.Load<TimeStampCollection>(dbFile);
                    }
                    catch (FileNotFoundException)
                    {
                        col = new TimeStampCollection();
                    }
                    TimeStamp stamp = new TimeStamp();
                    string[] injection = inject.Split('|');
                    stamp.Stamp = DateTime.Parse(injection[0]);
                    if (injection.Length > 1)
                        stamp.Direction = (Direction)(Convert.ToInt32(injection[1]));
                    if (injection.Length > 2)
                        stamp.User = injection[2];

                    col.TimeStamps.Add(stamp);
                    col.TimeStamps.Sort();
                    Saver.Save<TimeStampCollection>(dbFile, col);

                    Console.WriteLine("Injection successfull.");
                    Console.WriteLine("Values were: {0}", inject);

                    Environment.Exit((int)ExitCode.OK);
                }

                if (raw)
                {
                    TimeStampCollection col = Saver.Load<TimeStampCollection>(dbFile);
                    foreach (var t in col.TimeStamps)
                        Console.WriteLine("{0,-10} {1} {2} {3} {4}", UnixTimestampFromDateTime(t.Stamp), t.Stamp, t.User, t.Direction, (t.Tags.Count > 0) ? "Tags: " + String.Join(", ", t.Tags) : string.Empty);

                    Console.WriteLine("EOF");

                    Environment.Exit((int)ExitCode.OK);
                }
                if (pause)
                {
                    interactivebreaktime(0);
                }
                if (!string.IsNullOrEmpty(tags))
                {
                    TimeStampCollection col;
                    try
                    {
                        col = Saver.Load<TimeStampCollection>(dbFile);
                    }
                    catch (FileNotFoundException)
                    {
                        col = new TimeStampCollection();
                    }
                    int iPipe = tags.IndexOf("|");
                    if (iPipe == -1)
                    {
                        Console.Error.WriteLine("Wrong input format, use \"Ticks|foo,bar,zwusch\"!");
                        Environment.Exit(-3);
                    }
                    long lTicks = long.Parse(tags.Substring(0, iPipe));
                    List<string> tagList = tags.Substring(iPipe + 1).Split(',').ToList<string>();

                    try
                    {
                        var q = (from c in col.TimeStamps where UnixTimestampFromDateTime(c.Stamp) == lTicks select c).Single();
                        q.Tags.AddRange(tagList);

                        Saver.Save<TimeStampCollection>(dbFile, col);
                    }
                    catch (InvalidOperationException)
                    {
                        Console.Error.WriteLine("Timestamp {0} could not be found. Check with \"-r\".", lTicks);
                        Environment.Exit((int)ExitCode.Exception);
                    }
                }

                if (!query)
                    LogTimeStamp(direction);
                else
                {
                    if (!htmlReport)
                        QueryWorkingTimes(timeSpan);
                    else
                    { }
                }
            }
        }
Пример #44
0
        private static TimeStampCollection Repair(TimeStampCollection col, DateTime currentDay, int i)
        {
            string answer;
            Console.Write("Please enter the time you stopped working on {0:yyyy-MM-dd ddd}. [{1}]", currentDay, col.TimeStamps[i].Stamp.AddSeconds(1));
            answer = Console.ReadLine();
            if (answer == "")
            {
                answer = col.TimeStamps[i].Stamp.AddSeconds(1).ToString();
            }
            try
            {
                TimeStamp toadd = new TimeStamp();
                toadd.Stamp = DateTime.Parse(answer);
                if (toadd.Stamp.Date != currentDay) throw new Exception();
                toadd.Direction = Direction.Out;
                toadd.User = "******";
                col.TimeStamps.Insert(i + 1, toadd);
            }
            catch (FormatException)
            {
                Console.WriteLine("The Timestamp could not be read, please try again or simply press Enter to enter the shown Timestamp.");
                col = Repair(col, currentDay, i);
            }

            return col;
        }
Пример #45
0
 private static bool ParseJoinedValue(ref ParseContext pctx, AccountStub stub)
 {
     stub.Fields |= UpdatedFields.Joined;
     return(TryReadInt(ref pctx, out stub.joined) && TimeStamp.IsValidJoined(stub.joined));
 }
 protected override TimeStamp GetXTimeStamp(int index)
 {
     // TODO: Review whether this is needed for grid panels
     return(TimeStamp.FromDays(index));
 }
Пример #47
0
        /// <summary>
        /// Performs and continues the authentication cycle.
        /// </summary>
        /// <remarks>
        /// This method is performed iteratively to start, continue, and end the authentication cycle with the
        /// server. Each stage works by acquiring a token from one side, presenting it to the other side
        /// which in turn may generate a new token.
        /// 
        /// The cycle typically starts and ends with the client. On the first invocation on the client,
        /// no server token exists, and null is provided in its place. The client returns its status, providing
        /// its output token for the server. The server accepts the clients token as input and provides a 
        /// token as output to send back to the client. This cycle continues until the server and client 
        /// both indicate, typically, a SecurityStatus of 'OK'.
        /// </remarks>
        /// <param name="serverToken">The most recently received token from the server, or null if beginning
        /// the authentication cycle.</param>
        /// <param name="outToken">The clients next authentication token in the authentication cycle.</param>
        /// <returns>A status message indicating the progression of the authentication cycle.
        /// A status of 'OK' indicates that the cycle is complete, from the client's perspective. If the outToken
        /// is not null, it must be sent to the server.
        /// A status of 'Continue' indicates that the output token should be sent to the server and 
        /// a response should be anticipated.</returns>
        public SecurityStatus Init( byte[] serverToken, out byte[] outToken )
        {
            TimeStamp rawExpiry = new TimeStamp();

            SecurityStatus status;

            SecureBuffer outTokenBuffer;
            SecureBufferAdapter outAdapter;

            SecureBuffer serverBuffer;
            SecureBufferAdapter serverAdapter;

            if( this.Disposed )
            {
                throw new ObjectDisposedException( "ClientContext" );
            }
            else if( ( serverToken != null ) && ( this.ContextHandle.IsInvalid ) )
            {
                throw new InvalidOperationException( "Out-of-order usage detected - have a server token, but no previous client token had been created." );
            }
            else if( ( serverToken == null ) && ( this.ContextHandle.IsInvalid == false ) )
            {
                throw new InvalidOperationException( "Must provide the server's response when continuing the init process." );
            }

            // The security package tells us how big its biggest token will be. We'll allocate a buffer
            // that size, and it'll tell us how much it used.
            outTokenBuffer = new SecureBuffer(
                new byte[ this.Credential.PackageInfo.MaxTokenLength ],
                BufferType.Token
            );

            serverBuffer = null;
            if ( serverToken != null )
            {
                serverBuffer = new SecureBuffer( serverToken, BufferType.Token );
            }

            // Some notes on handles and invoking InitializeSecurityContext
            //  - The first time around, the phContext parameter (the 'old' handle) is a null pointer to what
            //    would be an RawSspiHandle, to indicate this is the first time it's being called.
            //    The phNewContext is a pointer (reference) to an RawSspiHandle struct of where to write the
            //    new handle's values.
            //  - The next time you invoke ISC, it takes a pointer to the handle it gave you last time in phContext,
            //    and takes a pointer to where it should write the new handle's values in phNewContext.
            //  - After the first time, you can provide the same handle to both parameters. From MSDN:
            //       "On the second call, phNewContext can be the same as the handle specified in the phContext
            //        parameter."
            //    It will overwrite the handle you gave it with the new handle value.
            //  - All handle structures themselves are actually *two* pointer variables, eg, 64 bits on 32-bit
            //    Windows, 128 bits on 64-bit Windows.
            //  - So in the end, on a 64-bit machine, we're passing a 64-bit value (the pointer to the struct) that
            //    points to 128 bits of memory (the struct itself) for where to write the handle numbers.
            using ( outAdapter = new SecureBufferAdapter( outTokenBuffer ) )
            {
                if ( this.ContextHandle.IsInvalid )
                {
                    status = ContextNativeMethods.InitializeSecurityContext_1(
                        ref this.Credential.Handle.rawHandle,
                        IntPtr.Zero,
                        this.serverPrinc,
                        this.requestedAttribs,
                        0,
                        SecureBufferDataRep.Network,
                        IntPtr.Zero,
                        0,
                        ref this.ContextHandle.rawHandle,
                        outAdapter.Handle,
                        ref this.finalAttribs,
                        ref rawExpiry
                    );
                }
                else
                {
                    using ( serverAdapter = new SecureBufferAdapter( serverBuffer ) )
                    {
                        status = ContextNativeMethods.InitializeSecurityContext_2(
                            ref this.Credential.Handle.rawHandle,
                            ref this.ContextHandle.rawHandle,
                            this.serverPrinc,
                            this.requestedAttribs,
                            0,
                            SecureBufferDataRep.Network,
                            serverAdapter.Handle,
                            0,
                            ref this.ContextHandle.rawHandle,
                            outAdapter.Handle,
                            ref this.finalAttribs,
                            ref rawExpiry
                        );
                    }
                }
            }

            if( status.IsError() == false )
            {
                if( status == SecurityStatus.OK )
                {
                    base.Initialize( rawExpiry.ToDateTime() );
                }

                outToken = null;

                if( outTokenBuffer.Length != 0 )
                {
                    outToken = new byte[outTokenBuffer.Length];
                    Array.Copy( outTokenBuffer.Buffer, outToken, outToken.Length );
                }
            }
            else
            {
                throw new SSPIException( "Failed to invoke InitializeSecurityContext for a client", status );
            }

            return status;
        }
Пример #48
0
 protected override long OnApply(TimeStamp timeStamp)
 {
     return timeStamp.Ticks - timeStamp.Ticks % TicksPerHour;
 }
Пример #49
0
        public static object Answer(string[] inputs)
        {
            List <(DateTime TimeStamp, string Information)> guards_records = new List <(DateTime TimeStamp, string Information)>();

            foreach (var timestamp in inputs)
            {
                string   ts_str = timestamp.Substring(1, 16);
                string   infos  = timestamp.Substring(19, timestamp.Length - 19);
                DateTime ts     = DateTime.ParseExact(ts_str, "yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture);
                guards_records.Add((ts, infos));
            }

            guards_records = guards_records.OrderBy(x => x.TimeStamp).ToList();

            int      guard       = 0;
            DateTime asleepStart = new DateTime();
            Dictionary <int, List <DateTime> > SleepyGuards = new Dictionary <int, List <DateTime> >();

            foreach (var(TimeStamp, Information) in guards_records)
            {
                if (IsWakingUp(Information))
                {
                    TimeSpan span = TimeStamp.Subtract(asleepStart);
                    for (int i = 0; i < span.TotalMinutes; i++)
                    {
                        if (SleepyGuards.ContainsKey(guard))
                        {
                            SleepyGuards[guard].Add(asleepStart.AddMinutes(i));
                        }
                        else
                        {
                            SleepyGuards.Add(guard, new List <DateTime>()
                            {
                                asleepStart.AddMinutes(i)
                            });
                        }
                    }
                    continue;
                }

                if (IsFallingAsleep(Information))
                {
                    asleepStart = TimeStamp;
                    continue;
                }

                if (IsBeginningShift(Information))
                {
                    guard = GetGuardID(Information);
                    continue;
                }
            }

            var sleepiestGuard = SleepyGuards.OrderByDescending(i => i.Value.Count()).FirstOrDefault();

            var sleepiestGuardGrouped = sleepiestGuard.Value.GroupBy(x => x.Minute).ToList()
                                        .OrderByDescending(x => x.Count())
                                        .FirstOrDefault();


            var partTwoAnswer = PartTwo(SleepyGuards);

            return($"Part 1 : Guard #{sleepiestGuard.Key} likes to sleep at {sleepiestGuardGrouped.Key} min " +
                   $": {sleepiestGuard.Key} x {sleepiestGuardGrouped.Key} = {sleepiestGuard.Key * sleepiestGuardGrouped.Key} \n{partTwoAnswer}");
        }
Пример #50
0
        private SpeechResultList ParseRecognizeResponse(IDictionary resp)
        {
            if (resp == null)
            {
                return(null);
            }

            try
            {
                List <SpeechResult> results = new List <SpeechResult>();
                IList iresults = resp["results"] as IList;
                if (iresults == null)
                {
                    return(null);
                }

                foreach (var r in iresults)
                {
                    IDictionary iresult = r as IDictionary;
                    if (iresults == null)
                    {
                        continue;
                    }

                    SpeechResult result = new SpeechResult();
                    result.Final = (bool)iresult["final"];

                    IList ialternatives = iresult["alternatives"] as IList;
                    if (ialternatives == null)
                    {
                        continue;
                    }

                    List <SpeechAlt> alternatives = new List <SpeechAlt>();
                    foreach (var a in ialternatives)
                    {
                        IDictionary ialternative = a as IDictionary;
                        if (ialternative == null)
                        {
                            continue;
                        }

                        SpeechAlt alternative = new SpeechAlt();
                        alternative.Transcript = (string)ialternative["transcript"];
                        if (ialternative.Contains("confidence"))
                        {
                            alternative.Confidence = (double)ialternative["confidence"];
                        }

                        if (ialternative.Contains("timestamps"))
                        {
                            IList itimestamps = ialternative["timestamps"] as IList;

                            TimeStamp[] timestamps = new TimeStamp[itimestamps.Count];
                            for (int i = 0; i < itimestamps.Count; ++i)
                            {
                                IList itimestamp = itimestamps[i] as IList;
                                if (itimestamp == null)
                                {
                                    continue;
                                }

                                TimeStamp ts = new TimeStamp();
                                ts.Word       = (string)itimestamp[0];
                                ts.Start      = (double)itimestamp[1];
                                ts.End        = (double)itimestamp[2];
                                timestamps[i] = ts;
                            }

                            alternative.Timestamps = timestamps;
                        }
                        if (ialternative.Contains("word_confidence"))
                        {
                            IList iconfidence = ialternative["word_confidence"] as IList;

                            WordConfidence[] confidence = new WordConfidence[iconfidence.Count];
                            for (int i = 0; i < iconfidence.Count; ++i)
                            {
                                IList iwordconf = iconfidence[i] as IList;
                                if (iwordconf == null)
                                {
                                    continue;
                                }

                                WordConfidence wc = new WordConfidence();
                                wc.Word       = (string)iwordconf[0];
                                wc.Confidence = (double)iwordconf[1];
                                confidence[i] = wc;
                            }

                            alternative.WordConfidence = confidence;
                        }

                        alternatives.Add(alternative);
                    }
                    result.Alternatives = alternatives.ToArray();
                    results.Add(result);
                }

                return(new SpeechResultList(results.ToArray()));
            }
            catch (Exception e)
            {
                Log.Error("SpeechToText", "ParseJsonResponse exception: {0}", e.ToString());
                return(null);
            }
        }
Пример #51
0
 private static TimeStampCollection insert(TimeStampCollection col, int i)
 {
     Console.Write("Please enter the TimeStamp to add:");
     string answer = Console.ReadLine();
     try
     {
         TimeStamp toadd = new TimeStamp();
         toadd.Stamp = DateTime.Parse(answer);
         toadd.Direction = Direction.In;
         toadd.User = "******";
         col.TimeStamps.Insert(i - 1, toadd);
     }
     catch (FormatException)
     {
         Console.WriteLine("The TimeStamp could not be read. Please try again");
         col = insert(col, i);
     }
     return col;
 }
Пример #52
0
 public override int GetHashCode()
 {
     return(this == null ? 0 : TimeStamp.GetHashCode() ^ SignalID.GetHashCode() ^ Phase.GetHashCode());
 }
Пример #53
0
        private static void LogTimeStamp(string direction)
        {
            Direction dir = Direction.In;
            if (direction.Trim().ToLowerInvariant() == "lock")
                dir = Direction.Out;

            TimeStamp stamp = new TimeStamp()
            {
                Direction = dir,
                Stamp = DateTime.Now,
                User = Environment.UserName
            };

            //EventHandling for EnergySave
            var s = new System.Diagnostics.Eventing.Reader.EventLogReader("Microsoft-Windows-TaskScheduler/Operational"); //EventLog.GetEventLogs(".").ToArray();// Single(x => x.Log == "Application").Entries.OfType<EventLogEntry>().ToArray().Where(x=>x.EventID==1532);
            EventRecord record;
            List<EventRecord> records = new List<EventRecord>();
            while ((record = s.ReadEvent()) != null)
            {
                if (record.Id == 108 && (string)record.Properties[0].Value == "\\__percip.io__energysave_pc")
                {
                    records.Add(record);
                }

            }
            string set = (string)Settings.Default["lastenergysave"];
            while (set != "" && records.First().ActivityId.ToString() != set)
            {
                records.RemoveAt(0);
            }

            int lastid = records.FindIndex(i => i.ActivityId.ToString() == set);
            TimeStampCollection col = null;
            if (File.Exists(dbFile))
            {
                try
                {
                    col = Saver.Load<TimeStampCollection>(dbFile);
                }
                catch (CryptographicException ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    Environment.Exit(2);
                }
            }
            else
                col = new TimeStampCollection();

            foreach (var rec in records)
            {
                if (rec.ActivityId.ToString() != set)
                {
                    TimeStamp repair = new TimeStamp()
                    {
                        Direction = Direction.Out,
                        Stamp = rec.TimeCreated.GetValueOrDefault(),
                        User = Environment.UserName
                    };
                    col.TimeStamps.Add(repair);
                }
            }
            Settings.Default.lastenergysave = records.Last().ActivityId.ToString();
            Settings.Default.Save();
            col.TimeStamps.Sort();
            col.TimeStamps.Add(stamp);
            Saver.Save(dbFile, col);
            Console.WriteLine("Saved: {0}|{1}|{2}", stamp.Stamp, stamp.User, stamp.Direction);
        }
Пример #54
0
//		[Test]
        public void Session()
        {
            TimeStamp expected = new TimeStamp(2005, 5, 31, 7, 0, 02, 910);

            Assert.AreEqual(expected, weeklogic.closeSessionBars[0].TickTime, "newSessionFlag");
        }
Пример #55
0
		public IEnumerable<VoteProfileEntry> GetHistory(TimeStamp key, int limit = 0)
		{
			var list = History.GetValue(key);

			if (list == null || list.Count <= 0)
			{
				return Enumerable.Empty<VoteProfileEntry>();
			}

			IEnumerable<VoteProfileEntry> ie = list.OrderByDescending(e => e.VoteTime);

			if (limit > 0)
			{
				ie = ie.Take(limit);
			}

			return ie;
		}
Пример #56
0
 public Bar(TimeStamp time, TimeStamp endTime, double open, double high, double low, double close, TimeStamp tickTime)
 {
     Time     = time;
     EndTime  = endTime;
     Open     = open;
     High     = high;
     Low      = low;
     Close    = close;
     TickTime = tickTime;
 }
Пример #57
0
		public List<VoteProfileEntry> GetHistory(TimeStamp key, int limit = 0)
		{
			var list = History.GetValue(key);

			if (list != null && list.Count > 0)
			{
				IEnumerable<VoteProfileEntry> ie = list.OrderByDescending(e => e.VoteTime);

				if (limit > 0)
				{
					ie = ie.Take(limit);
				}

				return ie.ToList();
			}

			return new List<VoteProfileEntry>();
		}
Пример #58
0
        /// <summary>
        /// Defines the actions that occur every time an event is recognized
        /// </summary>
        /// <param name="anEvent">the event that was triggered</param>
        public void OnEvent(IEvent anEvent)
        {
            if (anEvent.Type == EventType.DataChanged)
            {
                //get the current time
                TimeStamp ts = (TimeStamp)anEvent.SimulationTime;

                // get the simulation start time
                if (getStartTime)
                {
                    _start = ts.ModifiedJulianDay;
                }
                getStartTime = false;

                //get values
                ScalarSet vals   = new ScalarSet();
                Link      link   = new Link();
                string    linkID = null;
                foreach (string key in this._links.Keys)
                {
                    link = (Link)_links[key];

                    //make sure it gets values from the link that sent the event
                    if (link.TargetComponent == this && link.SourceComponent.ModelID == anEvent.Sender.ModelID)
                    {
                        //define theme
                        string themeDescription = link.SourceElementSet.Description;
                        string themeName        = link.SourceElementSet.ID;
                        Theme  theme            = new Theme(themeName, themeDescription);

                        //save dt info for the timestep
                        if (!_timestep.ContainsKey(themeName))
                        {
                            _timestep.Add(themeName, new List <DateTime>());
                        }
                        if (_timestep[themeName].Count < 2)
                        {
                            _timestep[themeName].Add(CalendarConverter.ModifiedJulian2Gregorian(ts.ModifiedJulianDay));
                        }

                        //get link values
                        vals = (ScalarSet)anEvent.Sender.GetValues(ts, key);

                        //save link theme
                        if (!themes.ContainsKey(link.ID))
                        {
                            themes.Add(link.ID, theme);
                        }

                        //save link id
                        linkID = link.SourceElementSet.ID;

                        break;
                    }
                }

                //if values are found, then store them
                if (vals.data.Length > 0)
                {
                    int j = 0;
                    try
                    {
                        while (j <= serieses.Count - 1)
                        {
                            //for(int k=0;k<= vals.data.Length-1;k++)
                            //{

                            //checks to see if the value should be ignored.  This is defined in omi.
                            if (vals.data[j] != _ignore)
                            {
                                //get the site name
                                string id = link.SourceElementSet.GetElementID(j);
                                if (id == "")
                                {
                                    id = link.SourceElementSet.ID + j.ToString();
                                }

                                string sql = "SELECT s.SiteName " +
                                             "FROM Sites s " +
                                             "INNER JOIN DataSeries ds ON s.SiteID = ds.SiteID " +
                                             "WHERE ds.SeriesID= '" + id + "' ";

                                //"ORDER BY dv.DataValue ASC";
                                DbOperations          _db = new DbOperations(conn, DatabaseTypes.SQLite);
                                System.Data.DataTable tbl = _db.LoadTable("values", sql);

                                //string siteName = linkID + j.ToString();
                                string siteName = null;
                                if (tbl.Rows.Count > 0)
                                {
                                    siteName = tbl.Rows[0].ItemArray[0].ToString();
                                }
                                else
                                {
                                    siteName = (link.SourceElementSet.ID + "_" + link.SourceComponent.ModelID + "_loc" + j.ToString()).Replace(' ', '_');
                                }


                                //check to see if series exists
                                if (serieses.ContainsKey(siteName))
                                {
                                    //-- get the series
                                    Series series = serieses[siteName];

                                    //-- store the associated theme
                                    if (!series.ThemeList.Contains(themes[link.ID]))
                                    {
                                        series.ThemeList.Add(themes[link.ID]);
                                    }

                                    //-- save data values
                                    series.AddDataValue(CalendarConverter.ModifiedJulian2Gregorian(ts.ModifiedJulianDay), vals.data[j]);
                                }
                            }
                            //}
                            j++;
                        }
                    }
                    catch (IndexOutOfRangeException) { }
                }
            }
        }
 protected override long OnApply(TimeStamp timeStamp)
 {
     return timeStamp.Ticks;
 }
Пример #60
0
 /// <summary>
 /// Print all of the logs information including time, importance and original message
 /// </summary>
 /// <param name="formatted">Use markup formatting (optimised for Unity)</param>
 /// <returns></returns>
 public string GetMessage(bool formatted = true)
 {
     if (formatted)
     {
         return("\n<color=#FFFFFF55><b>(" + importance.ToString() + ")</b> " + TimeStamp.ToString("H:mm:ss.f") + "</color>   " + OriginalMessage);
     }
     else
     {
         return("(" + importance.ToString() + ") " + TimeStamp.ToString("H:mm:ss.f") + ": " + OriginalMessage);
     }
 }