protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); new TaskTrayIcon().AddTo(this); Clock clock = null; var detector = new ShortcutKeyDetector().AddTo(this); detector.KeySetPressedAsObservable() .Where(_ => Settings.Default.ClockTypeSetting == ClockTypeSetting.Win8) .Where(_ => clock?.IsDisposed ?? true) .Where(args => args.ShortcutKey == Settings.Default.ModkeySetting.ToShortcutKey()) .Subscribe(args => { args.Handled = true; clock = new Clock(); }).AddTo(this); detector.KeySetPressedAsObservable() .Where(_ => Settings.Default.ClockTypeSetting == ClockTypeSetting.Calendar) .Where(args => args.ShortcutKey == Settings.Default.ModkeySetting.ToShortcutKey()) .Subscribe(args => { args.Handled = true; ShowCalendar.Show(); }); }
/// <summary> /// LAMBDA Method /// </summary> /// <param name="theClock"></param> public void Subscribe(Clock theClock) { theClock.TimeChanged += (sender, e) => { Console.WriteLine("Logging Time: {0},{1},{2}", e.Hour.ToString(), e.Minute.ToString(), e.Second.ToString()); }; }
public ClockValidator(Clock clock) { m_data = clock; m_data.PropertyChanged += new PropertyChangedEventHandler(Clock_PropertyChanged); // default valid m_errors = new Dictionary<string, string>(); }
public ClockDegrees(string timeA, string timeB) { a = new Clock(); a.SetTime(timeA); b = new Clock(); b.SetTime(timeB); }
public virtual void Execute(Clock.Clock clock, MOS6502 cpu, byte pageCrossProlong, byte cycle) { byte mem = cpu.Target.Read(); byte a = cpu.State.A.Value; int tmp = 0, vCheck = 0; if (cpu.State.P.Decimal) { tmp = (a & 0x0f) + (mem & 0x0f) + cpu.State.P.CarryValue; if (tmp > 0x09) tmp += 0x06; tmp += (a & 0xf0) + (mem & 0xf0); vCheck = tmp; if ((tmp & 0x1f0) > 0x90) tmp += 0x60; cpu.State.P.Carry = (tmp & 0xff0) > 0xf0; } else { vCheck = tmp = a + mem + cpu.State.P.CarryValue; cpu.State.P.Carry = (tmp & 0xff00) != 0; } cpu.State.A.Value = (byte)tmp; cpu.State.P.Overflow = ((a ^ mem) & 0x80) == 0 && ((a ^ vCheck) & 0x80) != 0; //(mem & 0x80) == (a & 0x80) && (vCheck & 0x80) != (a & 0x80); cpu.State.P.Zero = cpu.State.A.IsZero; cpu.State.P.Negative = cpu.State.A.IsNegative; if (cpu.Target.IsPageCrossed(cpu.State.PC.Value)) clock.Prolong(pageCrossProlong, cpu.Phase); }
public MainWindow() { InitializeComponent(); ticker = new Clock(); /* * We could also use the Action type instead of NoArg and save some code. * But then we'd need to understand Generics... * so I'll stick with NoArg for now. */ NoArg start = ticker.Start; /* * .NET prevents us from updating UI elements from another thread. * Our clock uses Thread.Sleep which would make our app look like it crashed. * We'll use a separate thread for the clock.Start method, then use the Dispatcher * to update the UI in its own sweet time on its own sweet thread. Think of * queing up a message that is then processed by the UI thread when it's able. * * Importantly, we don't have to change the Clock class to take advantage of threading. * All the Dispatch/BeginInvoke magic happens here in the client code. * */ ticker.MillisecondsChanged += Ticker_MillisecondsChangedOnDifferentThread; ticker.SecondsChanged += Ticker_SecondsChangedOnDifferentThread; ticker.MinutesChanged += Ticker_MinutesChangedOnDifferentThread; ticker.HoursChanged += Ticker_HoursChangedOnDifferentThread; ticker.DaysChanged += Ticker_DaysChangedOnDifferentThread; start.BeginInvoke(null, null); }
public UserPlay(Clock startsAt, Copybook copybook) { StartsAt = startsAt; FinishesAt = startsAt + (copybook.FinishesAt - copybook.StartsAt); Copybook = copybook; Notes = copybook.Select(note => MoveCopybookNotesBasedOnLocalClock(note)).ToList(); }
public TimeTracker() { _timeline = new ParallelTimeline(null, Duration.Forever); _timeClock = _timeline.CreateClock(); _timeClock.Controller.Begin(); _lastTime = TimeSpan.FromSeconds(0); }
// Use this for initialization void Start() { player=GameObject.FindGameObjectWithTag("Player"); m_Clock=GameObject.Find("Clock").GetComponent<Clock>(); m_BaseBeat=GameObject.Find("BaseBeat").GetComponent<BaseBeat>(); }
//man hat 60 sekunden um 10 Items zu sammeln, schafft man es gewinnt man, schafft man es nicht so verliert man public override void initialize() { base.initialize(); //anzahl der eingesammelten Items numberItemsCollected = new Text[playerList.Count]; int i = 0; foreach (Player p in playerList) { numberItemsCollected[i] = new Text("Items Collected: 0/10", new Vector2(0, 0)); numberItemsCollected[i].setIndividualScale(scale);//mehr geht nicht wegen minimap im multiplayer numberItemsCollected[i].setPosition(new Vector2(p.getViewport().X + p.getViewport().Width / 2 - numberItemsCollected[i].getWidth() / 2,p.getViewport().Y + p.getViewport().Height - numberItemsCollected[i].getHeight())); i++; } if (playerList.Count == 1) {//singleplayer ligic clock = new Clock(new Vector2(0, 0)); clock.setIndividualScale(scale); clock.setPosition(new Vector2(playerList.First().getViewport().Width / 2 - clock.getWidth() / 2, playerList.First().getViewport().Height - clock.getHeight() - numberItemsCollected[0].getHeight())); clock.start(); } currentInGameState = EInGameState.RushHour; }
public Copybook(Clock startsAt, Clock finishesAt, IEnumerable<Note> notes) { StartsAt = startsAt; FinishesAt = finishesAt; Notes.AddRange(notes); }
static void Main(string[] args) { string input = Console.ReadLine(); int n1 = Int32.Parse(input.Split(' ')[0]); int n2 = Int32.Parse(input.Split(' ')[1]); Clock c1 = new Clock(); Clock c2 = new Clock(); int n = 0; do { n++; c1.hours++; c2.hours++; c1.mins += n1; c2.mins += n2; c1.hours += c1.mins / 60; c2.hours += c2.mins / 60; c1.mins %= 60; c2.mins %= 60; c1.hours %= 24; c2.hours %= 24; } while(!c1.Equals(c2)); Console.WriteLine((c2.hours > 10 ? "" + c2.hours : "0" + c2.hours) + ":" + (c2.mins > 10 ? "" + c2.mins : "0" + c2.mins)); Console.WriteLine(n); Console.ReadLine(); }
// Use this for initialization void Start () { finished = GameOverScreen.GetComponent<Clock> (); WarpCD.value = 0f; TimeCD.value = 0f; Wspeed = 50f; aud = this.gameObject.GetComponent<AudControl> (); }
public TimeMeasuringContext(Clock clock, Action<long> disposeAction) { this.clock = clock; this.start = clock.Nanoseconds; this.action = disposeAction; this.disposed = false; }
public MySendlerEvent(string time) { string currTime = time; string[] Timepack = currTime.Split(':'); Clock = new Clock(Convert.ToInt32(Timepack[0]), Convert.ToInt32(Timepack[1]), Convert.ToInt32(Timepack[2])); }
private Clock clock; // 时钟对象 void Start() { clock = new Clock(); clock.AddClockListener(this); // 对时钟监听 }
// Use this for initialization void Start () { Application.runInBackground = true; // Let the application be running while the window is not active. Debug.Log("GameController starting"); GameObject sharedES = GameObject.Find("SharedES"); SharedElectroServer gm = (SharedElectroServer)sharedES.GetComponent<SharedElectroServer>(); GameObject clockGobj = GameObject.Find("Clock"); clock = (Clock)clockGobj.GetComponent<Clock>(); _es = gm.es; me = gm.userName; _gameToJoin = gm.gameToJoin; _es.Engine.JoinRoomEvent += OnJoinRoom; _es.Engine.CreateOrJoinGameResponse += OnCreateOrJoinGameResponse; /** * If you want to add chat in the game, you will need this line */ //_es.Engine.PublicMessageEvent += OnPublicMessage; _es.Engine.ConnectionClosedEvent += OnConnectionClosedEvent; _es.Engine.GenericErrorResponse += onGenericErrorResponse; _es.Engine.PluginMessageEvent += onPluginMessageEvent; Debug.Log("listeners added"); started = true; initBoard(); JoinRoom(); }
public void TestGet() { // Create a tree with a root node for our models. ModelWrapper models = new ModelWrapper(); // Create some models. ModelWrapper simulations = models.Add(new Simulations()); ModelWrapper simulation = simulations.Add(new Simulation()); Clock clock = new Clock(); clock.StartDate = new DateTime(2015, 1, 1); clock.EndDate = new DateTime(2015, 12, 31); simulation.Add(clock); simulation.Add(new MockSummary()); ModelWrapper zone = simulation.Add(new Zone()); // Check that it is case sensitive. Assert.IsNull(models.Get("simulation.clock.StartDate")); // Fix case this should work. object d = models.Get("Simulation.Clock.StartDate"); DateTime startDate = (DateTime)d; Assert.AreEqual(startDate.Year, 2015); Assert.AreEqual(startDate.Month, 1); Assert.AreEqual(startDate.Day, 1); }
public Tesbernch_Multiplier() { _m_clk = new Clock(ClockPeriod) { Clk = _clk }; _m_signal = new XilinxMultiplier() { CLK = _clk, A = _A, B = _B, P = _P, }; _m_logger1 = new ConsoleLogger<StdLogicVector>() { DataIn = _A }; _m_logger2 = new ConsoleLogger<StdLogicVector>() { DataIn = _B }; _m_logger3 = new ConsoleLogger<StdLogicVector>() { DataIn = _P }; }
public void SetupTests() { reservoir = new ExponentiallyDecayingReservoir(); clock = new TimerTestClock(); this.timer = new Timer(reservoir, clock); }
public CashBox(Clock clock) { objects = new ConcurrentQueue<QObject>(); r = new Random(); this.clock = clock; willFree = 0; }
static void Main(string[] args) { NetConfig.LatencySimulation = true; Connector client = new Connector("Sample1.1", false); Clock fastClock = new Clock(0.02f); Clock slowClock = new Clock(1.0f); fastClock.OnFixedUpdate += SendPayload; slowClock.OnFixedUpdate += SendNotification; Program.peer = client.Connect("127.0.0.1:42324"); while (true) { fastClock.Tick(); slowClock.Tick(); client.Update(); if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.F1: client.Stop(); return; default: break; } } } }
/// <summary> /// Initializes a new instance of the <see cref="QuickPulseTelemetryProcessor"/> class. Internal constructor for unit tests only. /// </summary> /// <param name="next">The next TelemetryProcessor in the chain.</param> /// <param name="timeProvider">Time provider.</param> /// <param name="maxTelemetryQuota">Max telemetry quota.</param> /// <param name="initialTelemetryQuota">Initial telemetry quota.</param> /// <exception cref="ArgumentNullException">Thrown if next is null.</exception> internal QuickPulseTelemetryProcessor( ITelemetryProcessor next, Clock timeProvider, int? maxTelemetryQuota = null, int? initialTelemetryQuota = null) { if (next == null) { throw new ArgumentNullException(nameof(next)); } this.Register(); this.Next = next; this.requestQuotaTracker = new QuickPulseQuotaTracker( timeProvider, maxTelemetryQuota ?? MaxTelemetryQuota, initialTelemetryQuota ?? InitialTelemetryQuota); this.dependencyQuotaTracker = new QuickPulseQuotaTracker( timeProvider, maxTelemetryQuota ?? MaxTelemetryQuota, initialTelemetryQuota ?? InitialTelemetryQuota); this.exceptionQuotaTracker = new QuickPulseQuotaTracker( timeProvider, maxTelemetryQuota ?? MaxTelemetryQuota, initialTelemetryQuota ?? InitialTelemetryQuota); }
public Guess() { random = new Random(); clock = new Clock(480); clock.Start(); availableNotes = new List<Pitch>(); availableNotes.Add(Pitch.C3); availableNotes.Add(Pitch.CSharp3); availableNotes.Add(Pitch.D3); availableNotes.Add(Pitch.DSharp3); availableNotes.Add(Pitch.E3); availableNotes.Add(Pitch.F3); availableNotes.Add(Pitch.FSharp3); availableNotes.Add(Pitch.G3); availableNotes.Add(Pitch.GSharp3); availableNotes.Add(Pitch.A3); availableNotes.Add(Pitch.ASharp3); availableNotes.Add(Pitch.B4); availableNotes.Add(Pitch.C4); availableNotes.Add(Pitch.CSharp4); availableNotes.Add(Pitch.D4); availableNotes.Add(Pitch.DSharp4); availableNotes.Add(Pitch.E4); availableNotes.Add(Pitch.F4); availableNotes.Add(Pitch.FSharp4); availableNotes.Add(Pitch.G4); availableNotes.Add(Pitch.GSharp4); availableNotes.Add(Pitch.A4); availableNotes.Add(Pitch.ASharp4); availableNotes.Add(Pitch.B4); }
public void AddDevice(string device = "", string name = "", string fabricator = "") { DatabaseMapping databaseMapping = null; switch (device) { case "clock": Clock clock = new Clock(name); _deviceContext.Clocks.Add(clock); databaseMapping = new DatabaseMapping { DeviceTypeId = 1, Clock = clock }; break; case "microwave": MicrowaveFabricatorInfo mi = microwaveFabricatorInfo[fabricator]; Microwave microwave = new Microwave(name, mi.Volume, mi.Lamp); _deviceContext.Microwaves.Add(microwave); databaseMapping = new DatabaseMapping { DeviceTypeId = 2, Microwave = microwave }; break; case "oven": OvenFabricatorInfo oi = ovenFabricatorInfo[fabricator]; Oven oven = new Oven(name, oi.Volume, oi.Lamp); _deviceContext.Ovens.Add(oven); databaseMapping = new DatabaseMapping { DeviceTypeId = 3, Oven = oven }; break; case "fridge": FridgeFabricatorInfo fi = fridgeFabricatorInfo[fabricator]; Fridge fridge = new Fridge(name, fi.Coldstore, fi.Freezer); _deviceContext.Fridges.Add(fridge); databaseMapping = new DatabaseMapping { DeviceTypeId = 4, Fridge = fridge }; break; default: return; } _deviceContext.DatabaseMappings.Add(databaseMapping); _deviceContext.SaveChanges(); }
public static Color AmbientColor(Clock c) { if (c.Hours() < HourDawn || c.Hours() >= HourDusk) { return Night; } else if (c.Hours() == HourDawn) { return Utils.Mix(c.Minutes() + (c.Seconds() / 60f), Night, Twilight); } else if (c.Hours() == HourSunrise) { return Utils.Mix(c.Minutes() + (c.Seconds() / 60f), Twilight, Day); } else if (c.Hours() == HourDayEnd) { return Utils.Mix(c.Minutes() + (c.Seconds() / 60f), Day, TwilightNight); } else if (c.Hours() == HourSunset) { return Utils.Mix(c.Minutes() + (c.Seconds() / 60f), TwilightNight, Night); } else return Day; }
public void Run() { //initialization window.SetActive(); Clock clock = new Clock(); clock.Restart(); //loop while(window.IsOpen) { //make sure windows events are handled window.DispatchEvents(); //handle logic here Time elapsed = clock.Restart(); //elapsed is the amount of time elapsed since the last loop GameStates.Peek().Update(elapsed); //clear the window window.Clear(); //draw objects here GameStates.Peek().Draw(window); //draw the object we placed on our frame window.Display(); } //clean up GameStates.Clear(); }
public static void Main() { // Create a new clock - the publisher, which will publish the SecondChangeEvent Clock theClock = new Clock(); // Create the display and tell it to // subscribe to the clock just created DisplayTimeOfClock dc = new DisplayTimeOfClock(); dc.Subscribe(theClock); // Create a Log object and tell it // to subscribe to the clock LogTimeOfClock lc = new LogTimeOfClock(); lc.Subscribe(theClock); //Write separator for clearer console Console.WriteLine("====="); // Get the clock started, let it run for 10 secs theClock.Run(1); //Stop DisplayTimeOfClock from observer the Clock dc.Unsubscribe(theClock); //Write separator for clearer console Console.WriteLine("====="); //Let the clock run for another 5 secs theClock.Run(1); }
void OnTick(Clock clock) { if (Input.GetKeyDown(KeyCode.Z)) Played(new Note(clock, NoteNumber.C)); if (Input.GetKeyDown(KeyCode.X)) Played(new Note(clock, NoteNumber.D)); if (Input.GetKeyDown(KeyCode.C)) Played(new Note(clock, NoteNumber.E)); if (Input.GetKeyDown(KeyCode.V)) Played(new Note(clock, NoteNumber.F)); }
public static void Main(string[] args) { Console.WriteLine("Input file: "); var inPath = Console.ReadLine(); inPath = !string.IsNullOrEmpty(inPath) ? inPath : "SampleInput.txt"; var lines = File.ReadAllLines(inPath); var n = Convert.ToInt32(lines[0]); var output = new List<string> { n + "" }; for (var i = 1; i < lines.Length; i++) { var clock = new Clock(lines[i]); var hourMinute = AngleUtility.Difference(clock.HourHandDegrees, clock.MinuteHandDegrees); var hourSecond = AngleUtility.Difference(clock.HourHandDegrees, clock.SecondHandDegrees); var minuteSecond = AngleUtility.Difference(clock.MinuteHandDegrees, clock.SecondHandDegrees); output.Add(string.Format("{0}, {1}, {2}", hourMinute, hourSecond, minuteSecond)); } Console.WriteLine("Output file: "); var outPath = Console.ReadLine(); outPath = !string.IsNullOrEmpty(outPath) ? outPath : "Output.txt"; File.WriteAllLines(outPath, output); }
public void Negative_minutes() { var sut = new Clock(1, -40); Assert.Equal("00:20", sut.ToString()); }
public static TimeValue Now(Clock clock) { return(new TimeValue(OffsetTime.now(clock))); }
/// <summary> /// Initializes a new instance of the <see cref="InMemoryStoredEvent"/> class. /// </summary> public InMemoryStoredEvent() { Timestamp = Clock.Now(); metadata = new ExpandoObject(); metadata.AbsoluteSequenceNumber = 0; }
public virtual void Changed() { Clock.MarkDirty(); }
public StatsReporterImpl(PeriodsInfoProvider periodsReader, TimeTablePolicies policies, Clock clock) { this.periodReader = periodsReader; this.policies = policies; this.clock = clock; }
public QueryCacheEventData() { CreationTime = Clock.CurrentTimeMillis(); }
public static TimeValue Now(Clock clock, System.Func <ZoneId> defaultZone) { return(Now(clock.withZone(defaultZone()))); }
public static TimeValue Now(Clock clock, string timezone) { return(Now(clock.withZone(parseZoneName(timezone)))); }
public void TestPlainSaveAndLoadState() { RuntimeState state = new RuntimeState(5); state.IP = 1; state.LSLState = 2; state.Operands = new Stack <object>(); state.Operands.Push(new Vector3(1.0f, 2.0f, 3.0f)); state.Globals[0] = 1; state.Globals[1] = 2.0f; state.Globals[2] = new Vector3(3.0f, 3.0f, 3.0f); state.Globals[3] = new LSLList(new object[] { "4.0", new Vector3(5.1f, 6.1f, 7.1f), new Quaternion(8.1f, 9.1f, 10.1f) }); state.Globals[4] = new Quaternion(5.0f, 5.0f, 5.0f, 5.0f); state.Calls = new Stack <StackFrame>(); state.Calls.Push(new StackFrame(new FunctionInfo { Address = 5, Name = "funk", NumberOfArguments = 0, NumberOfLocals = 0 }, 0)); state.TopFrame = state.Calls.Peek(); state.MemInfo = new MemoryInfo { MemoryUsed = 1000 }; state.EventQueue = new C5.LinkedList <PostedEvent>(); state.EventQueue.Push(new PostedEvent { Args = new object[] { 4 }, DetectVars = new DetectVariables[0], EventType = SupportedEventList.Events.ATTACH, TransitionToState = -1 }); state.RunState = RuntimeState.Status.Running; state.GeneralEnable = true; state.NextWakeup = Clock.GetLongTickCount(); state.TimerInterval = 1000; state.ActiveListens = new Dictionary <int, ActiveListen>(); state.ActiveListens.Add(2, new ActiveListen { Channel = 1, Handle = 2, Key = "", Message = "msg", Name = "blah" }); SerializedRuntimeState serRunState = SerializedRuntimeState.FromRuntimeState(state); MemoryStream memStream = new MemoryStream(); ProtoBuf.Serializer.Serialize(memStream, serRunState); memStream.Seek(0, SeekOrigin.Begin); SerializedRuntimeState deser = ProtoBuf.Serializer.Deserialize <SerializedRuntimeState>(memStream); RuntimeState deserRunState = deser.ToRuntimeState(); Assert.AreEqual(deserRunState.IP, state.IP); Assert.AreEqual(deserRunState.LSLState, state.LSLState); Assert.AreEqual(deserRunState.Operands.Pop(), state.Operands.Pop()); Assert.AreEqual(deserRunState.Globals, state.Globals); StackFrame origTopFrame = state.Calls.Pop(); StackFrame deserFrame = deserRunState.Calls.Pop(); Assert.AreEqual(origTopFrame.Locals, deserFrame.Locals); Assert.AreEqual(origTopFrame.ReturnAddress, deserFrame.ReturnAddress); Assert.AreEqual(origTopFrame.FunctionInfo.Address, deserFrame.FunctionInfo.Address); Assert.AreEqual(origTopFrame.FunctionInfo.Name, deserFrame.FunctionInfo.Name); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfArguments, deserFrame.FunctionInfo.NumberOfArguments); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfLocals, deserFrame.FunctionInfo.NumberOfLocals); Assert.AreEqual(state.MemInfo.MemoryUsed, deserRunState.MemInfo.MemoryUsed); PostedEvent origEvent = state.EventQueue.Pop(); PostedEvent deserEvent = deserRunState.EventQueue.Pop(); Assert.AreEqual(origEvent.Args, deserEvent.Args); Assert.AreEqual(origEvent.EventType, deserEvent.EventType); Assert.AreEqual(origEvent.TransitionToState, deserEvent.TransitionToState); Assert.AreEqual(state.RunState, deserRunState.RunState); Assert.AreEqual(state.GeneralEnable, deserRunState.GeneralEnable); //Assert.AreEqual(state.NextWakeup, deserRunState.NextWakeup); Assert.AreEqual(state.TimerInterval, deserRunState.TimerInterval); origTopFrame = state.TopFrame; deserFrame = deserRunState.TopFrame; Assert.AreEqual(origTopFrame.Locals, deserFrame.Locals); Assert.AreEqual(origTopFrame.ReturnAddress, deserFrame.ReturnAddress); Assert.AreEqual(origTopFrame.FunctionInfo.Address, deserFrame.FunctionInfo.Address); Assert.AreEqual(origTopFrame.FunctionInfo.Name, deserFrame.FunctionInfo.Name); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfArguments, deserFrame.FunctionInfo.NumberOfArguments); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfLocals, deserFrame.FunctionInfo.NumberOfLocals); Assert.AreEqual(state.ActiveListens.ToArray(), deserRunState.ActiveListens.ToArray()); }
/// <summary> /// Runs the poller on the caller's thread. Only returns when <see cref="Stop"/> or <see cref="StopAsync"/> are called from another thread. /// </summary> private void RunPoller() { try { // Recalculate all timers now foreach (var timer in m_timers) { if (timer.Enable) { timer.When = Clock.NowMs() + timer.Interval; } } // Run until stop is requested while (!m_stopSignaler.IsStopRequested) { if (m_isPollSetDirty) { RebuildPollset(); } var pollStart = Clock.NowMs(); // Set tickless to "infinity" long tickless = pollStart + int.MaxValue; // Find the When-value of the earliest timer.. foreach (var timer in m_timers) { // If it is enabled but no When is set yet, if (timer.When == -1 && timer.Enable) { // Set this timer's When to now plus it's Interval. timer.When = pollStart + timer.Interval; } // If it has a When and that is earlier than the earliest found thus far, if (timer.When != -1 && tickless > timer.When) { // save that value. tickless = timer.When; } } // Compute a timeout value - how many milliseconds from now that the earliest-timer will expire. var timeout = tickless - pollStart; // Use zero to indicate it has already expired. if (timeout < 0) { timeout = 0; } var isItemAvailable = false; Assumes.NotNull(m_pollSet); if (m_pollSet.Length != 0) { isItemAvailable = m_netMqSelector.Select(m_pollSet, m_pollSet.Length, timeout); } else if (timeout > 0) { //TODO: Do we really want to simply sleep and return, doing nothing during this interval? //TODO: Should a large value be passed it will sleep for a month literally. // Solution should be different, but sleep is more natural here than in selector (timers are not selector concern). Debug.Assert(timeout <= int.MaxValue); Thread.Sleep((int)timeout); } // Get the expected end time in case we time out. This looks redundant but, unfortunately, // it happens that Poll takes slightly less than the requested time and 'Clock.NowMs() >= timer.When' // may not true, even if it is supposed to be. In other words, even when Poll times out, it happens // that 'Clock.NowMs() < pollStart + timeout' var expectedPollEnd = !isItemAvailable ? pollStart + timeout : -1L; // that way we make sure we can continue the loop if new timers are added. // timers cannot be removed foreach (var timer in m_timers) { if ((Clock.NowMs() >= timer.When || expectedPollEnd >= timer.When) && timer.When != -1) { timer.InvokeElapsed(this); if (timer.Enable) { timer.When = Clock.NowMs() + timer.Interval; } } } for (var i = 0; i < m_pollSet.Length; i++) { NetMQSelector.Item item = m_pollSet[i]; if (item.Socket != null) { Assumes.NotNull(m_pollact); NetMQSocket socket = m_pollact[i]; if (item.ResultEvent.HasError()) { if (++socket.Errors > 1) { Remove(socket); item.ResultEvent = PollEvents.None; } } else { socket.Errors = 0; } if (item.ResultEvent != PollEvents.None) { socket.InvokeEvents(this, item.ResultEvent); } } else if (item.ResultEvent.HasError() || item.ResultEvent.HasIn()) { Assumes.NotNull(item.FileDescriptor); if (m_pollinSockets.TryGetValue(item.FileDescriptor, out Action <Socket> action)) { action(item.FileDescriptor); } } } } #if !NET35 // Try to dequeue and execute all pending tasks before stopping poller while (m_tasksQueue.TryDequeue(out Task? task, TimeSpan.Zero)) { TryExecuteTask(task); } #endif } finally { foreach (var socket in m_sockets.ToList()) { Remove(socket); } } }
/// <summary> /// Runs the poller on the caller's thread. Only returns when <see cref="Stop"/> or <see cref="StopAsync"/> are called from another thread. /// </summary> public void Run() { CheckDisposed(); if (IsRunning) { throw new InvalidOperationException("NetMQPoller is already running"); } #if NET35 m_pollerThread = Thread.CurrentThread; #else var oldSynchronisationContext = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(new NetMQSynchronizationContext(this)); m_isSchedulerThread.Value = true; #endif m_stopSignaler.Reset(); m_switch.SwitchOn(); try { // the sockets may have been created in another thread, to make sure we can fully use them we do full memory barrier // at the beginning of the loop Thread.MemoryBarrier(); // Recalculate all timers now foreach (var timer in m_timers) { if (timer.Enable) { timer.When = Clock.NowMs() + timer.Interval; } } // Run until stop is requested while (!m_stopSignaler.IsStopRequested) { if (m_isPollSetDirty) { RebuildPollset(); } var pollStart = Clock.NowMs(); // Set tickless to "infinity" long tickless = pollStart + int.MaxValue; // Find the When-value of the earliest timer.. foreach (var timer in m_timers) { // If it is enabled but no When is set yet, if (timer.When == -1 && timer.Enable) { // Set this timer's When to now plus it's Interval. timer.When = pollStart + timer.Interval; } // If it has a When and that is earlier than the earliest found thus far, if (timer.When != -1 && tickless > timer.When) { // save that value. tickless = timer.When; } } // Compute a timeout value - how many milliseconds from now that that earliest-timer will expire. var timeout = tickless - pollStart; // Use zero to indicate it has already expired. if (timeout < 0) { timeout = 0; } var isItemAvailable = false; if (m_pollSet.Length != 0) { isItemAvailable = m_selector.Select(m_pollSet, m_pollSet.Length, timeout); } else if (timeout > 0) { //TODO: Do we really want to simply sleep and return, doing nothing during this interval? //TODO: Should a large value be passed it will sleep for a month literally. // Solution should be different, but sleep is more natural here than in selector (timers are not selector concern). Debug.Assert(timeout <= int.MaxValue); Thread.Sleep((int)timeout); } // Get the expected end time in case we time out. This looks redundant but, unfortunately, // it happens that Poll takes slightly less than the requested time and 'Clock.NowMs() >= timer.When' // may not true, even if it is supposed to be. In other words, even when Poll times out, it happens // that 'Clock.NowMs() < pollStart + timeout' var expectedPollEnd = !isItemAvailable ? pollStart + timeout : -1L; // that way we make sure we can continue the loop if new timers are added. // timers cannot be removed foreach (var timer in m_timers) { if ((Clock.NowMs() >= timer.When || expectedPollEnd >= timer.When) && timer.When != -1) { timer.InvokeElapsed(this); if (timer.Enable) { timer.When = Clock.NowMs() + timer.Interval; } } } for (var i = 0; i < m_pollSet.Length; i++) { SelectItem item = m_pollSet[i]; if (item.Socket != null) { NetMQSocket socket = m_pollact[i]; if (item.ResultEvent.HasError()) { if (++socket.Errors > 1) { Remove(socket); item.ResultEvent = PollEvents.None; } } else { socket.Errors = 0; } if (item.ResultEvent != PollEvents.None) { socket.InvokeEvents(this, item.ResultEvent); } } else if (item.ResultEvent.HasError() || item.ResultEvent.HasIn()) { Action <Socket> action; if (m_pollinSockets.TryGetValue(item.FileDescriptor, out action)) { action(item.FileDescriptor); } } } } } finally { try { foreach (var socket in m_sockets.ToList()) { Remove(socket); } } finally { #if NET35 m_pollerThread = null; #else m_isSchedulerThread.Value = false; SynchronizationContext.SetSynchronizationContext(oldSynchronisationContext); #endif m_switch.SwitchOff(); } } }
/// <summary> /// /// </summary> /// <param name="model"></param> /// <param name="useFullDescription">Use full verbose description</param> /// <param name="htmlString"></param> /// <returns></returns> public string GetFullSummary(object model, bool useFullDescription, string htmlString) { string html = ""; html += "\n<div class=\"holdermain\" style=\"opacity: " + ((!this.Enabled) ? "0.4" : "1") + "\">"; // get clock IModel parentSim = Apsim.Parent(this, typeof(Simulation)); // find random number generator RandomNumberGenerator rnd = Apsim.Children(parentSim, typeof(RandomNumberGenerator)).FirstOrDefault() as RandomNumberGenerator; if (rnd != null) { html += "\n<div class=\"clearfix defaultbanner\">"; html += "<div class=\"namediv\">" + rnd.Name + "</div>"; html += "<div class=\"typediv\">RandomNumberGenerator</div>"; html += "</div>"; html += "\n<div class=\"defaultcontent\">"; html += "\n<div class=\"activityentry\">Random numbers are provided for this simultion.<br />"; if (rnd.Seed == 0) { html += "Every run of this simulation will be different."; } else { html += "Each run of this simulation will be identical using the seed <span class=\"setvalue\">" + rnd.Seed.ToString() + "</span>"; } html += "\n</div>"; html += "\n</div>"; } Clock clk = Apsim.Children(parentSim, typeof(Clock)).FirstOrDefault() as Clock; if (clk != null) { html += "\n<div class=\"clearfix defaultbanner\">"; html += "<div class=\"namediv\">" + clk.Name + "</div>"; html += "<div class=\"typediv\">Clock</div>"; html += "</div>"; html += "\n<div class=\"defaultcontent\">"; html += "\n<div class=\"activityentry\">This simulation runs from "; if (clk.StartDate == null) { html += "<span class=\"errorlink\">[START DATE NOT SET]</span>"; } else { html += "<span class=\"setvalue\">" + clk.StartDate.ToShortDateString() + "</span>"; } html += " to "; if (clk.EndDate == null) { html += "<span class=\"errorlink\">[END DATE NOT SET]</span>"; } else { html += "<span class=\"setvalue\">" + clk.EndDate.ToShortDateString() + "</span>"; } html += "\n</div>"; html += "\n</div>"; html += "\n</div>"; } foreach (CLEMModel cm in Apsim.Children(this, typeof(CLEMModel)).Cast <CLEMModel>()) { html += cm.GetFullSummary(cm, true, ""); } return(html); }
public void TestEditing() { string configFile = Path.GetTempFileName(); File.WriteAllLines(configFile, new[] { // Modify an array "[Report].VariableNames = x,y,z", // Modify a date - try a few different formats. "[Clock].StartDate = 2000-01-01", "[Clock].EndDate = 2000-01-10T00:00:00", // Modify a string "[Weather].FileName = fdsa.met", @"[Weather2].FullFileName = jkl.met", // Replace a model with a model from another file. $"[Weather3] = {extFile}", $"[Weather4] = {extFile};[w2]", // Change a property of a resource model. "[Wheat].Leaf.Photosynthesis.RUE.FixedValue = 0.4", // Change a property of a manager script. "[Manager].Script.Amount = 1234", // Set an entire array. "[Physical].BD = 1, 2, 3, 4, 5", // Modify a single element of an array. "[Physical].AirDry[2] = 6", // Modify multiple elements of an array. "[Physical].LL15[3:4] = 7", }); string models = typeof(IModel).Assembly.Location; string args = $"{fileName} /Edit {configFile}"; var proc = new ProcessUtilities.ProcessWithRedirectedOutput(); proc.Start(models, args, Path.GetTempPath(), true, writeToConsole: true); proc.WaitForExit(); // Children of simulation are, in order: // Clock, summary, zone, Weather, Weather2, w1, w2 Assert.AreEqual(null, proc.StdOut); Assert.AreEqual(null, proc.StdErr); Simulations file = FileFormat.ReadFromFile <Simulations>(fileName, out List <Exception> errors); if (errors != null && errors.Count > 0) { throw errors[0]; } var report = file.FindInScope <Models.Report>(); string[] variableNames = new[] { "x", "y", "z" }; Assert.AreEqual(variableNames, report.VariableNames); IModel sim = file.FindChild <Simulation>(); // Use an index-based lookup to locate child models. // When we replace an entire model, we want to ensure // that the replacement is inserted at the correct index. Clock clock = sim.Children[0] as Clock; Assert.AreEqual(new DateTime(2000, 1, 1), clock.StartDate); Assert.AreEqual(new DateTime(2000, 1, 10), clock.EndDate); var weather = sim.Children[3] as Models.Climate.Weather; Assert.NotNull(weather); Assert.AreEqual("Weather", weather.Name); Assert.AreEqual("fdsa.met", weather.FileName); var weather2 = sim.Children[4] as Models.Climate.Weather; Assert.NotNull(weather2); Assert.AreEqual("Weather2", weather2.Name); Assert.AreEqual(@"jkl.met", weather2.FileName); // Weather3 and Weather4 should have been // renamed to w1 and w2, respectively. var weather3 = sim.Children[5] as Models.Climate.Weather; Assert.NotNull(weather3); Assert.AreEqual("w1", weather3.Name); Assert.AreEqual("w1.met", weather3.FileName); var weather4 = sim.Children[6] as Models.Climate.Weather; Assert.NotNull(weather4); Assert.AreEqual("w2", weather4.Name); Assert.AreEqual("w2.met", weather4.FileName); // The edit file operation should have changed RUE value to 0.4. var wheat = sim.Children[2].Children[2] as Plant; var rue = wheat.Children[6].Children[4].Children[0] as Constant; Assert.AreEqual(0.4, rue.FixedValue); double amount = (double)sim.FindByPath("[Manager].Script.Amount")?.Value; Assert.AreEqual(1234, amount); Physical physical = sim.Children[2].Children[4] as Physical; Assert.AreEqual(new double[5] { 1, 2, 3, 4, 5 }, physical.BD); Assert.AreEqual(new double[5] { 0, 6, 0, 0, 0 }, physical.AirDry); Assert.AreEqual(new double[5] { 0, 0, 7, 7, 0 }, physical.LL15); }
public CommunityLockManger(Config config, Clock clock) { _manager = new LockManagerImpl(new RagManager(), config, clock); }
public JsonResponse onStatus(Dictionary <string, object> parameters) { JsonError error = null; Dictionary <string, object> networkArray = new Dictionary <string, object>(); networkArray.Add("Core Version", CoreConfig.version); networkArray.Add("Node Version", CoreConfig.productVersion); string netType = "mainnet"; if (CoreConfig.isTestNet) { netType = "testnet"; } networkArray.Add("Network type", netType); networkArray.Add("My time", Clock.getTimestamp()); networkArray.Add("Network time difference", Clock.networkTimeDifference); networkArray.Add("Real network time difference", Clock.realNetworkTimeDifference); networkArray.Add("My External IP", IxianHandler.publicIP); networkArray.Add("My Listening Port", IxianHandler.publicPort); //networkArray.Add("Listening interface", context.Request.RemoteEndPoint.Address.ToString()); networkArray.Add("Queues", "Rcv: " + NetworkQueue.getQueuedMessageCount() + ", RcvTx: " + NetworkQueue.getTxQueuedMessageCount() + ", SendClients: " + NetworkServer.getQueuedMessageCount() + ", SendServers: " + NetworkClientManager.getQueuedMessageCount() + ", Storage: " + Node.storage.getQueuedQueryCount() + ", Logging: " + Logging.getRemainingStatementsCount() + ", Pending Transactions: " + PendingTransactions.pendingTransactionCount()); networkArray.Add("Node Deprecation Block Limit", Config.nodeDeprecationBlock); string dltStatus = "Active"; if (Node.blockSync.synchronizing) { dltStatus = "Synchronizing"; } if (Node.blockChain.getTimeSinceLastBLock() > 1800) // if no block for over 1800 seconds { dltStatus = "ErrorLongTimeNoBlock"; } if (Node.blockProcessor.networkUpgraded) { dltStatus = "ErrorForkedViaUpgrade"; } networkArray.Add("Update", checkUpdate()); networkArray.Add("DLT Status", dltStatus); networkArray.Add("Core Status", IxianHandler.status); string bpStatus = "Stopped"; if (Node.blockProcessor.operating) { bpStatus = "Running"; } networkArray.Add("Block Processor Status", bpStatus); networkArray.Add("Block Height", Node.blockChain.getLastBlockNum()); networkArray.Add("Block Version", Node.blockChain.getLastBlockVersion()); networkArray.Add("Network Block Height", IxianHandler.getHighestKnownNetworkBlockHeight()); networkArray.Add("Node Type", PresenceList.myPresenceType); networkArray.Add("Connectable", NetworkServer.isConnectable()); if (parameters.ContainsKey("verbose")) { networkArray.Add("Required Consensus", Node.blockChain.getRequiredConsensus()); networkArray.Add("Wallets", Node.walletState.numWallets); networkArray.Add("Presences", PresenceList.getTotalPresences()); networkArray.Add("Supply", Node.walletState.calculateTotalSupply().ToString()); networkArray.Add("Applied TX Count", TransactionPool.getTransactionCount() - TransactionPool.getUnappliedTransactions().Count()); networkArray.Add("Unapplied TX Count", TransactionPool.getUnappliedTransactions().Count()); networkArray.Add("WS Checksum", Crypto.hashToString(Node.walletState.calculateWalletStateChecksum())); } networkArray.Add("Network Clients", NetworkServer.getConnectedClients()); networkArray.Add("Network Servers", NetworkClientManager.getConnectedClients(true)); networkArray.Add("Masters", PresenceList.countPresences('M')); networkArray.Add("Relays", PresenceList.countPresences('R')); networkArray.Add("Clients", PresenceList.countPresences('C')); return(new JsonResponse { result = networkArray, error = error }); }
static void Main(string[] args) { //------------------------------------------------Bound Code------------------------------------------------// window = new RenderWindow(new VideoMode(1280, 800), "Battle City"); window.SetVerticalSyncEnabled(true); window.Closed += WinClosed; Image icon = new Image("..\\Source\\Textures\\panzer.png"); window.SetIcon(64, 64, icon.Pixels); musicThemes = new [] { new Music("..\\Source\\Sounds\\theme1.ogg"), new Music("..\\Source\\Sounds\\theme2.ogg") }; Thread musicThread = new Thread(new ThreadStart(SwitchMusic)); musicThread.Start(); GameHistory history = new GameHistory(); //------------------------------------------------Game Code------------------------------------------------// FieldMap map = new FieldMap("map.png"); Player1 player1 = new Player1("players1.png", "Vitaliy", true, Color.Green, 544, 732); Player2 player2 = new Player2("players1.png", "Davidiy", true, Color.Red, 672, 38); Clock clock = new Clock(); Debug f = new Debug(); while (window.IsOpen) { window.DispatchEvents(); float time = clock.ElapsedTime.AsMicroseconds(); clock.Restart(); time = time / 800; player1.update(time, map.tileMap, ref window, ref map, player1, player2, history); player2.update(time, map.tileMap, ref window, ref map, player1, player2, history); if (player1.isShoot) { player1.bullet.update(time, map.tileMap, ref window, player1, player2); } f.FConsole("P1 \n X - " + player1.X + " Y - " + player1.Y + "\n\nP2 \n X - " + player2.X + " Y - " + player2.Y); //window.Clear(Color.Black); //------------------------------------------------Draw Code------------------------------------------------// map.Draw(ref window); window.Draw(player1.Sprite); window.Draw(player2.Sprite); if (player1.isShoot) { window.Draw(player1.bullet.Sprite); } f.Print(); //------------------------------------------------Show Code------------------------------------------------// window.Display(); } }
public Clock Add(int minutesToAdd) { Clock res = new Clock(this.Hours, this.Minutes + minutesToAdd); return(res); }
public Clock Subtract(int minutesToSubtract) { Clock res = new Clock(this.Hours, this.Minutes - minutesToSubtract); return(res); }
private void ClockStartup() { ClockInit(); Clock.Start(); ClockCon.UpdateTimeControls(); }
public override void Run() { // Create a clock running at the specified beats per minute. int beatsPerMinute = 180; Clock clock = new Clock(beatsPerMinute); // Prompt user to choose an output device (or if there is only one, use that one. OutputDevice outputDevice = ExampleUtil.ChooseOutputDeviceFromConsole(); if (outputDevice == null) { Console.WriteLine("No output devices, so can't run this example."); ExampleUtil.PressAnyKeyToContinue(); return; } outputDevice.Open(); // Prompt user to choose an input device (or if there is only one, use that one). InputDevice inputDevice = ExampleUtil.ChooseInputDeviceFromConsole(); if (inputDevice != null) { inputDevice.Open(); } Arpeggiator arpeggiator = new Arpeggiator(inputDevice, outputDevice, clock); Drummer drummer = new Drummer(clock, outputDevice, 4); clock.Start(); if (inputDevice != null) { inputDevice.StartReceiving(clock); } bool done = false; while (!done) { Console.Clear(); Console.WriteLine("BPM = {0}, Playing = {1}, Arpeggiator Mode = {2}", clock.BeatsPerMinute, clock.IsRunning, arpeggiator.Status); Console.WriteLine("Escape : Quit"); Console.WriteLine("Down : Slower"); Console.WriteLine("Up: Faster"); Console.WriteLine("Left: Previous Chord or Scale"); Console.WriteLine("Right: Next Chord or Scale"); Console.WriteLine("Space = Toggle Play"); Console.WriteLine("Enter = Toggle Scales/Chords"); ConsoleKey key = Console.ReadKey(true).Key; Pitch pitch; if (key == ConsoleKey.Escape) { done = true; } else if (key == ConsoleKey.DownArrow) { clock.BeatsPerMinute -= 2; } else if (key == ConsoleKey.UpArrow) { clock.BeatsPerMinute += 2; } else if (key == ConsoleKey.RightArrow) { arpeggiator.Change(1); } else if (key == ConsoleKey.LeftArrow) { arpeggiator.Change(-1); } else if (key == ConsoleKey.Spacebar) { if (clock.IsRunning) { clock.Stop(); if (inputDevice != null) { inputDevice.StopReceiving(); } outputDevice.SilenceAllNotes(); } else { clock.Start(); if (inputDevice != null) { inputDevice.StartReceiving(clock); } } } else if (key == ConsoleKey.Enter) { arpeggiator.ToggleMode(); } else if (ExampleUtil.IsMockPitch(key, out pitch)) { // We've hit a QUERTY key which is meant to simulate a MIDI note, so // send the Note On to the output device and tell the arpeggiator. NoteOnMessage noteOn = new NoteOnMessage(outputDevice, 0, pitch, 100, clock.Time); clock.Schedule(noteOn); arpeggiator.NoteOn(noteOn); // We don't get key release events for the console, so schedule a // simulated Note Off one beat from now. NoteOffMessage noteOff = new NoteOffMessage(outputDevice, 0, pitch, 100, clock.Time + 1); CallbackMessage.CallbackType noteOffCallback = beatTime => { arpeggiator.NoteOff(noteOff); }; clock.Schedule(new CallbackMessage(beatTime => arpeggiator.NoteOff(noteOff), noteOff.Time)); } } if (clock.IsRunning) { clock.Stop(); if (inputDevice != null) { inputDevice.StopReceiving(); } outputDevice.SilenceAllNotes(); } outputDevice.Close(); if (inputDevice != null) { inputDevice.Close(); inputDevice.RemoveAllEventHandlers(); } // All done. }
// The very start of the program public IEnumerator InitApplication() { // basic initialization Screen.fullScreen = false; appState = AppState.Initializing; Application.targetFrameRate = targetFrameRate; userManager = GetComponentInChildren <UserManager>(); playbackManager = GetComponentInChildren <PlaybackManager>(); scenarioEvents = GetComponentInChildren <ScenarioEvents>(); networkManager = (NetworkManager)FindObjectOfType(typeof(NetworkManager)); osc = networkManager.osc; uiHandler = (UIHandler)FindObjectOfType(typeof(UIHandler)); canvasHandler = uiHandler.GetComponentInChildren <CanvasHandler>(); fileInOut = (FileInOut)FindObjectOfType(typeof(FileInOut)); soundHandler = (SoundHandler)FindObjectOfType(typeof(SoundHandler)); clock = (Clock)FindObjectOfType(typeof(Clock)); canvasHandler.ChangeCanvas("initCanvas"); //_userRole = UserRole.Server; // base setting int t = 0; switch (_userRole) { case UserRole.Server: { t = 0; break; } case UserRole.Player: { t = 1;; break; } case UserRole.Viewer: { t = 2;; break; } case UserRole.Tracker: { t = 3;; break; } case UserRole.Playback: { t = 4; break; } } // load jsons fileInOut.LoadPreferencesFiles(this); if (gameData.runInLocal == 1) { gameData.OSC_LocalIP = "127.0.0.1"; } else { gameData.OSC_LocalIP = CheckIp(); } // change UI's server IP field uiHandler.FillServerIPField(gameData.runInLocal, gameData.OSC_ServerIP); userManager.keepNamesVisibleForPlayers = (gameData.showNamesAboveHead == 1); // adjust user's parameters // build is always for non vr use if (!Application.isEditor) { useVRHeadset = false; StartCoroutine(EnableDisableVRMode(false)); } else { useVRHeadset = (gameData.useVr == 1); StartCoroutine(EnableDisableVRMode(false)); } if (useVRHeadset) { uiHandler.SetPlayerNetworkType(1); } else { uiHandler.SetPlayerNetworkType(t); } // do we print sent and received messages if (gameData.DebugMode == 1) { Instantiate(debugPrefab); debugMode = true; } yield return(new WaitForSeconds(1)); InvokeRepeating("TimedUpdate", 0.5f, 1f / targetFrameRate); }
private void ClockShutdown() => Clock.Stop();
public void TestLoadOldProtobuf1State() { RuntimeState deserRunState; using (var file = System.IO.File.OpenRead(Path.Combine(TestContext.CurrentContext.TestDirectory, "StateTests", "phloxstate.plxs"))) { SerializedRuntimeState deser = ProtoBuf.Serializer.Deserialize <SerializedRuntimeState>(file); deserRunState = deser.ToRuntimeState(); } RuntimeState state = new RuntimeState(5); state.IP = 1; state.LSLState = 2; state.Operands = new Stack <object>(); state.Operands.Push(new Vector3(1.0f, 2.0f, 3.0f)); state.Globals[0] = 1; state.Globals[1] = 2.0f; state.Globals[2] = new Vector3(3.0f, 3.0f, 3.0f); state.Globals[3] = new LSLList(new object[] { "4.0", new Vector3(5.1f, 6.1f, 7.1f), new Quaternion(8.1f, 9.1f, 10.1f) }); state.Globals[4] = new Quaternion(5.0f, 5.0f, 5.0f, 5.0f); state.Calls = new Stack <StackFrame>(); state.Calls.Push(new StackFrame(new FunctionInfo { Address = 5, Name = "funk", NumberOfArguments = 0, NumberOfLocals = 0 }, 0)); state.TopFrame = new StackFrame(new FunctionInfo { Address = 8, Name = "funk2", NumberOfArguments = 1, NumberOfLocals = 1 }, 0); state.TopFrame.Locals = new object[] { 2, 1.1f, new Vector3(1.0f, 2.0f, 3.0f) }; state.Calls.Push(state.TopFrame); state.MemInfo = new MemoryInfo { MemoryUsed = 1000 }; state.EventQueue = new C5.LinkedList <PostedEvent>(); state.EventQueue.Push(new PostedEvent { Args = new object[] { 4 }, DetectVars = new DetectVariables[1] { new DetectVariables { Grab = new Vector3(1, 2, 3), Group = "Group", Key = UUID.Zero.ToString(), LinkNumber = 1, Name = "Name", Owner = "f1d932c0-7236-11e2-bcfd-0800200c9a66", Pos = new Vector3(4.5f, 5.6f, 6.7f), Rot = new Quaternion(7.6f, 6.5f, 5.4f, 4.3f), TouchBinormal = new Vector3(3.2f, 2.1f, 1.0f), TouchFace = 8, TouchNormal = new Vector3(9, 4, 3), TouchPos = new Vector3(7, 6, 5), TouchST = new Vector3(10.9f, 9.8f, 8.7f), TouchUV = new Vector3(7.6f, 6.5f, 5.4f), Type = 0, Vel = new Vector3(999.8f, 888.7f, 777.6f) } }, EventType = SupportedEventList.Events.ATTACH, TransitionToState = -1 }); state.RunState = RuntimeState.Status.Running; state.GeneralEnable = true; state.NextWakeup = Clock.GetLongTickCount(); state.TimerInterval = 1000; state.ActiveListens = new Dictionary <int, ActiveListen>(); state.ActiveListens.Add(2, new ActiveListen { Channel = 1, Handle = 2, Key = "", Message = "msg", Name = "blah" }); Assert.AreEqual(deserRunState.IP, state.IP); Assert.AreEqual(deserRunState.LSLState, state.LSLState); Assert.AreEqual(deserRunState.Operands.Pop(), state.Operands.Pop()); Assert.AreEqual(deserRunState.Globals, state.Globals); StackFrame origTopFrame = state.Calls.Pop(); StackFrame deserFrame = deserRunState.Calls.Pop(); Assert.AreEqual(origTopFrame.Locals, deserFrame.Locals); Assert.AreEqual(origTopFrame.ReturnAddress, deserFrame.ReturnAddress); Assert.AreEqual(origTopFrame.FunctionInfo.Address, deserFrame.FunctionInfo.Address); Assert.AreEqual(origTopFrame.FunctionInfo.Name, deserFrame.FunctionInfo.Name); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfArguments, deserFrame.FunctionInfo.NumberOfArguments); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfLocals, deserFrame.FunctionInfo.NumberOfLocals); Assert.AreEqual(state.MemInfo.MemoryUsed, deserRunState.MemInfo.MemoryUsed); PostedEvent origEvent = state.EventQueue.Pop(); PostedEvent deserEvent = deserRunState.EventQueue.Pop(); Assert.AreEqual(origEvent.Args, deserEvent.Args); Assert.AreEqual(origEvent.EventType, deserEvent.EventType); Assert.AreEqual(origEvent.TransitionToState, deserEvent.TransitionToState); CompareDetectVariables(origEvent.DetectVars, deserEvent.DetectVars); Assert.AreEqual(state.RunState, deserRunState.RunState); Assert.AreEqual(state.GeneralEnable, deserRunState.GeneralEnable); //Assert.AreEqual(state.NextWakeup, deserRunState.NextWakeup); Assert.AreEqual(state.TimerInterval, deserRunState.TimerInterval); origTopFrame = state.TopFrame; deserFrame = deserRunState.TopFrame; Assert.AreEqual(origTopFrame.Locals, deserFrame.Locals); Assert.AreEqual(origTopFrame.ReturnAddress, deserFrame.ReturnAddress); Assert.AreEqual(origTopFrame.FunctionInfo.Address, deserFrame.FunctionInfo.Address); Assert.AreEqual(origTopFrame.FunctionInfo.Name, deserFrame.FunctionInfo.Name); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfArguments, deserFrame.FunctionInfo.NumberOfArguments); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfLocals, deserFrame.FunctionInfo.NumberOfLocals); Assert.AreEqual(state.ActiveListens.ToArray(), deserRunState.ActiveListens.ToArray()); }
static void Main(string[] args) { app = new RenderWindow(new VideoMode(w, h), "Bricks"); app.Closed += new EventHandler(OnClose); app.MouseMoved += App_MouseMoved; CreateColor(); for (int j = 7; j < lengthy; j++) { int r = 0; for (int i = 0; i < lengthx; i++) { var rand = new Random(DateTime.Now.Millisecond); shape[i, j] = new RectangleShape(new Vector2f(32, 32)); shape[i, j].Position = new Vector2f(i * 32, j * 32); if (r == 0) { STEP: for (int sear = 0; sear < 5; sear++) { randoms[sear] = rand.Next(0, 5); } for (int sear = 0; sear < 5; sear++) { for (int searx = 0; searx < 5; searx++) { if (sear != searx) { if (randoms[sear] == randoms[searx]) { goto STEP; } } } } } Thread.Sleep(1); shape[i, j].FillColor = clr[randoms[r]]; if (ScoreFill == 0) { ScoreFill = rand.Next(5, 11); } if (r < 4) { r++; } else { r = 0; } } } Color windowColor = new Color(0, 0, 0); View views = new View(); views.Size = new Vector2f(w, h); Clock clock = new Clock(); var rands = new Random(DateTime.Now.Millisecond); game.Create(lengthx, 192, clr[rands.Next(0, 5)]); Font f = new Font("arial.ttf"); Text text = new Text("0", f, 16); while (app.IsOpen) { app.DispatchEvents(); if (!stop) { views.Center = new Vector2f(w / 2, downy); app.SetView(views); float time = clock.ElapsedTime.AsMicroseconds(); clock.Restart(); time = time / 800; Vector2i pixelPos = Mouse.GetPosition(app); Mpos = app.MapPixelToCoords(pixelPos); app.Clear(windowColor); app.Draw(game.player); for (int j = 7; j < lengthy; j++) { for (int i = 0; i < lengthx; i++) { app.Draw(shape[i, j]); } } if (shape[(int)(game.player.Position.X / 32), 7].FillColor == game.player.FillColor && game.player.Position.X >= shape[(int)(game.player.Position.X / 32), 7].Position.X && game.player.Position.X <= shape[(int)(game.player.Position.X / 32), 7].Position.X + 16 && game.player.Position.Y >= 192) { ScoreFills++; Score++; if (downy > 90) { downy -= 7 * ScoreFills; } game.player.Position = new Vector2f(game.player.Position.X, game.player.Position.Y - 14); game.isGround = false; for (int j = 7; j < lengthy - 1; j++) { int r = 0; for (int i = 0; i < lengthx; i++) { shape[i, j].FillColor = shape[i, j + 1].FillColor; var rand = new Random(DateTime.Now.Millisecond); if (r == 0) { STEP: for (int sear = 0; sear < 5; sear++) { randoms[sear] = rand.Next(0, 5); } for (int sear = 0; sear < 5; sear++) { for (int searx = 0; searx < 5; searx++) { if (sear != searx) { if (randoms[sear] == randoms[searx]) { goto STEP; } } } } } shape[i, lengthy - 1].FillColor = clr[randoms[r]]; if (r < 4) { r++; } else { r = 0; } } } if (ScoreFill == ScoreFills) { level++; STEP: var rand = new Random(DateTime.Now.Millisecond); ScoreFill = rand.Next(5, 11); ScoreFills = 0; var x = rand.Next(0, 5); if (game.player.FillColor == clr[x]) { goto STEP; } game.player.FillColor = clr[x]; } } if (game.isMove) { distance = (float)Math.Sqrt((tempX - game.player.Position.X) * (tempX - game.player.Position.X) + (tempY - game.player.Position.Y) * (tempY - game.player.Position.Y)); if (distance > 2) { float x = game.player.Position.X, y = game.player.Position.Y; x += (float)0.32 * time * (tempX - x) / distance; game.player.Position = new Vector2f(x, y); } else { game.isMove = false; } } text.Position = new Vector2f(game.player.Position.X + 9, game.player.Position.Y); text.FillColor = new Color(0, 0, 0); text.DisplayedString = Score.ToString(); app.Draw(text); if (!game.isGround) { game.player.Position = new Vector2f(game.player.Position.X, game.player.Position.Y + 0.08f); } if (game.player.Position.Y >= 192) { game.isGround = true; } if (timey < 0.6f) { timey += time / 150; } downy += 0.07f * 1.5f * timey; if (downy >= h / 2 + 224) { if (!File.Exists("records.txt")) { File.Create("records.txt"); } FileStream file = new FileStream("records.txt", FileMode.Open, FileAccess.ReadWrite); StreamReader reader = new StreamReader(file); int Best = Convert.ToInt16(reader.ReadLine()); reader.Close(); file.Close(); if (Best < Score) { File.WriteAllText("records.txt", Score.ToString()); Console.WriteLine("GameOver!"); Console.WriteLine("NewScore:" + Score); Console.WriteLine("OldScore:" + Best); } else { Console.WriteLine("GameOver!"); Console.WriteLine("BestScore:" + Best); Console.WriteLine("Score:" + Score); } stop = true; } } app.Display(); } }
static void Main(string[] args) { Trace.Listeners.Clear(); TextWriterTraceListener logger = new TextWriterTraceListener(@".\logs\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"); logger.Name = "TextLogger"; logger.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime; ConsoleTraceListener console = new ConsoleTraceListener(false); console.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime; Trace.Listeners.Add(logger); Trace.Listeners.Add(console); Trace.AutoFlush = true; //Console.WriteLine("Is Clock HighResolution? : {0}", Clock.IsHighResolution); Trace.WriteLine("Is Clock HighResolution? : " + Clock.IsHighResolution); //Console.WriteLine("Clock Frequency in ticks per second : {0}", Clock.Frequency); Trace.WriteLine("Clock Frequency in ticks per second : " + Clock.Frequency); //Console.WriteLine("Timer is {0} nano sec per tick", (1000L * 1000L * 1000L) / Clock.Frequency); Trace.WriteLine("Timer is " + (1000L * 1000L * 1000L) / Clock.Frequency + " nano sec per tick"); int loop = 0; long delay = 0; while (true) { //Console.Write("Please input loop times : "); Trace.Write("Please input loop times : "); if (!int.TryParse(Console.ReadLine(), out loop)) { break; } //Console.Write("Please input delay time in us : "); Trace.Write("Please input delay time in us : "); if (!long.TryParse(Console.ReadLine(), out delay)) { break; } Clock.UsDelay = delay; //Console.WriteLine("{0} US delay in 100 times loop test.", delay); Trace.WriteLine(delay + " US delay in " + loop + " times loop test."); double[] results = new double[loop]; for (int x = 0; x < loop; x++) { long first, last = 0; Clock.QueryPerformanceCounter(out first); Clock.DelayStart(); Clock.QueryPerformanceCounter(out last); results[x] = ((last - first) / (double)Stopwatch.Frequency) * 1000 * 1000; //Console.WriteLine("Loop {0} time is : {1} us", x, results[x]); Trace.WriteLine("Loop " + x + " time is : " + results[x] + " us"); } double total = 0; foreach (var result in results) { total += (result - delay); } //Console.WriteLine("Average in {0} times loop is : {1} us", loop, total / loop); Trace.WriteLine("Average in " + loop + " times loop is : " + total / loop + " us"); } }
public void TestPlainSaveAndLoadStateExtremes() { RuntimeState state = new RuntimeState(5); state.IP = 1; state.LSLState = 2; state.Operands = new Stack <object>(); state.Operands.Push(new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity)); state.Operands.Push(new Vector3(float.MaxValue, float.MinValue, float.PositiveInfinity)); state.Globals[0] = Int32.MaxValue; state.Globals[1] = 2.0f; state.Globals[2] = new Vector3(3.0f, 3.0f, 3.0f); state.Globals[3] = new LSLList(new object[] { "4.0", 2.5f, 5.5f }); state.Globals[4] = new Quaternion(float.NegativeInfinity, 5.0f, 5.0f, 5.0f); state.Calls = new Stack <StackFrame>(); state.Calls.Push(new StackFrame(new FunctionInfo { Address = 5, Name = "funk", NumberOfArguments = 0, NumberOfLocals = 0 }, 0)); state.TopFrame = new StackFrame(new FunctionInfo { Address = 8, Name = "funk2", NumberOfArguments = 1, NumberOfLocals = 1 }, 0); state.TopFrame.Locals = new object[] { 2, 1.1f, new Vector3(1.0f, 2.0f, 3.0f) }; state.Calls.Push(state.TopFrame); state.MiscAttributes[(int)RuntimeState.MiscAttr.Control] = new object[] { 500, 1, 0 }; state.MemInfo = new MemoryInfo { MemoryUsed = 1000 }; state.EventQueue = new C5.LinkedList <PostedEvent>(); state.EventQueue.Push(new PostedEvent { Args = new object[] { 4 }, DetectVars = new DetectVariables[0], EventType = SupportedEventList.Events.ATTACH, TransitionToState = -1 }); state.RunState = RuntimeState.Status.Running; state.GeneralEnable = true; state.NextWakeup = Clock.GetLongTickCount(); state.TimerInterval = 1000; state.ActiveListens = new Dictionary <int, ActiveListen>(); state.ActiveListens.Add(2, new ActiveListen { Channel = 1, Handle = 2, Key = "", Message = "msg", Name = "blah" }); SerializedRuntimeState serRunState = SerializedRuntimeState.FromRuntimeState(state); MemoryStream memStream = new MemoryStream(); ProtoBuf.Serializer.Serialize(memStream, serRunState); memStream.Seek(0, SeekOrigin.Begin); SerializedRuntimeState deser = ProtoBuf.Serializer.Deserialize <SerializedRuntimeState>(memStream); RuntimeState deserRunState = deser.ToRuntimeState(); Assert.AreEqual(deserRunState.IP, state.IP); Assert.AreEqual(deserRunState.LSLState, state.LSLState); Vector3 deserOp1 = (Vector3)deserRunState.Operands.Pop(); Vector3 stateOp1 = (Vector3)state.Operands.Pop(); Assert.AreEqual(deserOp1.X, stateOp1.X); Assert.AreEqual(deserOp1.Y, stateOp1.Y); Assert.That(float.IsInfinity(deserOp1.Z)); Assert.That(float.IsInfinity(stateOp1.Z)); Assert.AreEqual(deserRunState.Globals, state.Globals); StackFrame origTopFrame; StackFrame deserFrame; TestNextFrame(state, deserRunState, out origTopFrame, out deserFrame); TestNextFrame(state, deserRunState, out origTopFrame, out deserFrame); origTopFrame = state.TopFrame; deserFrame = deserRunState.TopFrame; Assert.AreEqual(origTopFrame.Locals, deserFrame.Locals); Assert.AreEqual(origTopFrame.ReturnAddress, deserFrame.ReturnAddress); Assert.AreEqual(origTopFrame.FunctionInfo.Address, deserFrame.FunctionInfo.Address); Assert.AreEqual(origTopFrame.FunctionInfo.Name, deserFrame.FunctionInfo.Name); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfArguments, deserFrame.FunctionInfo.NumberOfArguments); Assert.AreEqual(origTopFrame.FunctionInfo.NumberOfLocals, deserFrame.FunctionInfo.NumberOfLocals); Assert.AreEqual(state.ActiveListens.ToArray(), deserRunState.ActiveListens.ToArray()); Assert.AreEqual(state.MiscAttributes, deserRunState.MiscAttributes); }
internal CypherAdapterStreamV3(QueryResult @delegate, Clock clock) : base(@delegate, clock) { }
public void Negative_hour_rolls_over_continuously() { var sut = new Clock(-91, 0); Assert.Equal("05:00", sut.ToString()); }
public void Negative_hour_rolls_over() { var sut = new Clock(-25, 0); Assert.Equal("23:00", sut.ToString()); }
public BTService() { clock = new Clock(); }