Exemple #1
0
        public BasePlayer(IPlayerSettings playerSettings, IPhysicsComponent physicsComponent, IBoundaryCollider boundaryCollider, IWeapons weapons, ITimer timer)
        {
            this.PlayerSettings = playerSettings;
            this.PlayerScore = new PlayerScore();

            if (physicsComponent == null)
                this.PhysicsComponent = new DummyPhysicsComponent();
            else
                this.PhysicsComponent = physicsComponent;

            this.PhysicsComponent.CollidedWithWorld += () => InContactWithLevel = true;
            this.PhysicsComponent.WasShot += Damage;

            this.Weapons = weapons;
            this.Weapons.DamagedAPlayer += (damage, physicsComp) => physicsComp.OnWasShot(this, damage);

            this.Timer = timer;
            this.BoundaryCollider = boundaryCollider;

            this.Health = BasePlayer.StartHealth;
            this.Status = PlayerStatus.Alive;
            this.Position = new Vector2(400, 100);

            this.PhysicsComponent.CollisionGroup = BasePlayer.CollisionGroup;
        }
 public hide_the_splash_screen(ITimer timer, ISplashScreenView view, ISplashScreenPresenter presenter)
 {
     this.timer = timer;
     this.view = view;
     this.presenter = presenter;
     timer.start_notifying(presenter, new TimeSpan(50));
 }
        public WorkingDaysLeftController(
            WorkingDaysLeftViewModel leftViewModel,
            WorkingDaysLeftSettingsViewModel settingsViewModel,
            IAsyncRepository<ProjectInfoServer> projectInforepository,
            IAsyncRepository<Holiday> holidayRepository,
            ITimer refreshNotifier,
            ILog logger,
            IProgressbar loadingNotifier,
            Configuration config)
        {
            this.leftViewModel = leftViewModel;
            this.settingsViewModel = settingsViewModel;
            this.holidayRepository = holidayRepository;
            this.projectInforepository = projectInforepository;
            this.logger = logger;
            this.loadingNotifier = loadingNotifier;
            this.refreshNotifier = refreshNotifier;

            this.Rand = new Random((int)DateTime.Now.Ticks).Next();

            projectInforepository.GetCompleted += GotProjectInfo;
            holidayRepository.GetCompleted += GotHolidays;

            this.settingsViewModel.RefreshAvailableServers.ExecuteDelegate = OnRefreshAvailableServers;
            this.settingsViewModel.ReloadSettings.ExecuteDelegate = settingsViewModel.Reset;

            refreshNotifier.Elapsed += refreshNotifier_Elapsed;
            settingsViewModel.PropertyChanged += RefreshAvailableProjectsWhenSelectedServerChanges;
            refreshNotifier.Start(10000);

            OnRefreshAvailableServers();
            SetConfigAndUpdate(config);
        }
 public PeriodicTask(Action action, ITimer timer) {
   if (action == null) throw new ArgumentNullException("action");
   if (timer == null) throw new ArgumentNullException("timer");
   _action = action;
   _timer = timer;
   _isDisposed = false;
 }
        public TeamPictureViewModel(
            IRepository<DomainModel.TeamPicture.TeamPicture> teamPictureRepository, 
            IPersistDomainModelsAsync<DomainModel.TeamPicture.TeamPicture> teamPicturePersister, 
            ITimer refreshTimer, 
            IInvokeBackgroundWorker<IEnumerable<DomainModel.TeamPicture.TeamPicture>> backgroundWorker, 
            ILog log, 
            IWebcamService webcam, 
            IProgressbar progressbarService)
            : this()
        {
            _teamPictureRepository = teamPictureRepository;
            _teamPicturePersister = teamPicturePersister;
            _refreshTimer = refreshTimer;
            _backgroundWorker = backgroundWorker;
            _log = log;
        	_webcamService = webcam;
        	_webcamService.CaptureImageCompleted += ImageCapturedFromWebCam;
            _refreshTimer.Start(REFRESH_INTERVAL);
            _progressbarService = progressbarService;

            _refreshTimer.Elapsed += _refreshTimer_Elapsed;
            _teamPicturePersister.SaveCompleted += ConfigPersisterSaveCompleted;

            LoadDataFromDatabaseIntoViewModel();
        }
        public SipInviteServerDialog(
             ISipTransaction transaction, 
             SipDialogTable dialogTable,
             ITimerFactory timerFactory,
             SipHeaderFactory headerFactory,
             SipMessageFactory messageFactory,
             SipAddressFactory addressFactory,
             ISipMessageSender messageSender,
             ISipListener listener,
            IPEndPoint listeningPoint)
            : base(headerFactory, messageFactory, addressFactory, messageSender, listener, listeningPoint, transaction)
        {
            Check.Require(transaction, "transaction");
            Check.Require(dialogTable, "dialogTable");
            Check.Require(timerFactory, "timerFactory");

            _logger = NLog.LogManager.GetCurrentClassLogger();

            _dialogTable = dialogTable;
            _state = DialogState.Null;
            _timerFactory = timerFactory;

            //(only ?) localtag is set on firstresponse
            //localtarget is not defined, because is has no use, (every user agent knows it local address)

            _retransmitOkTimer = _timerFactory.CreateInviteCtxRetransmitTimer(OnOkReTransmit);
            //_endWaitForAckTimer = _timerFactory.CreateInviteCtxTimeOutTimer(OnWaitForAckTimeOut);

            if (_logger.IsInfoEnabled) _logger.Info("ServerDialog[Id={0}] created.", GetId());
        }
 public void RaiseFakeTimerEvents(int numEvents, ITimer fakeTimer)
 {
     for (int eventCount = 1; eventCount <= numEvents; eventCount++)
     {
         fakeTimer.Raise(x => x.Elapsed += null, fakeTimer, new EventArgs() as ElapsedEventArgs);
     }
 }
Exemple #8
0
 public RssPlugin(IBitTorrentEngine torrentEngine, IDataRepository dataRepository, ITimerFactory timerFactory, IWebClient webClient)
 {
     _torrentEngine = torrentEngine;
     _dataRepository = dataRepository;
     _timer = timerFactory.CreateTimer();
     _webClient = webClient;
 }
 public SolutionBuild(ITimer timer, string configuration, ISolution solution)
     : base(timer)
 {
     Solution = solution;
     this.configuration = configuration;
     projects = new List<IProjectBuild>();
 }
Exemple #10
0
	    public GraphController(Graph viewModel, 
            IDownloadStringService downloadStringService,
            ITimer timer,
            Configuration configuration,
            IProgressbar progressbarService)
		{
	        Guard.Requires<ArgumentNullException>(viewModel != null);
            Guard.Requires<ArgumentNullException>(downloadStringService != null);
            Guard.Requires<ArgumentNullException>(timer != null);
            Guard.Requires<ArgumentNullException>(progressbarService != null);
            Guard.Requires<ArgumentNullException>(configuration != null);

            graphConfig = new GraphConfig(configuration);

            Guard.Requires<ArgumentException>(graphConfig.IsValid, graphConfig.ErrorMsg);

			this.ViewModel = viewModel;
            ViewModel.Refresh.AfterExecute += new EventHandler(Refresh_AfterExecute);
            this.downloadStringService = downloadStringService;
            this.timer = timer;
            this.timer.Elapsed += new EventHandler(timer_Elapsed);
            this.progressbarService = progressbarService;

	        StartFetchingDataInBackground();

	        DownloadDataAndAddToViewModel();
		}
 internal static TimerCommandFactory CreateTimerCommandFactory(IGeneralRegisters generalRegisters = null,
     ITimer delayTimer = null, ITimer soundTimer = null)
 {
     return new TimerCommandFactory(generalRegisters ?? Substitute.For<IGeneralRegisters>(),
                                    delayTimer ?? Substitute.For<ITimer>(),
                                    soundTimer ?? Substitute.For<ITimer>());
 }
Exemple #12
0
        public CorkboardController(CorkboardViewModel viewModel,
                                   CorkboardSettingsViewModel settingsViewModel, 
                                   IRepository<RetrospectiveNote> retrospectiveNoteRepository,
                                   IPersistDomainModelsAsync<RetrospectiveNote> persistRetrospectiveNoteRepository, 
                                   IDeleteDomainModelsAsync<RetrospectiveNote> deleteRetrospectiveNoteRepository,
                                   ITimer timer, 
                                   IUIInvoker uiInvoker, 
                                   IInvokeBackgroundWorker asyncClient, 
                                   ILog logger, 
                                   IProgressbar progressbar,
                                   Configuration config 
            )
        {
            _viewModel = viewModel;
            _settingsViewModel = settingsViewModel;
            _asyncClient = asyncClient;
            _repository = retrospectiveNoteRepository;
            _persistRepository = persistRetrospectiveNoteRepository;
            _uiInvoker = uiInvoker;
            _refreshNotifier = timer;
            _logger = logger;
            _progressBar = progressbar;
            _currentConfig = config;
            _deleteRepository = deleteRetrospectiveNoteRepository;
            
            _persistRepository.SaveCompleted += PersisterSaveCompleted;

            _refreshNotifier.Elapsed += (o, e) => UpdateViewModels();
            
            _settingsViewModel.Save.ExecuteDelegate = Save;
            _settingsViewModel.ReloadSettings.ExecuteDelegate = ReloadSettings;
            
            UpdateViewModels();
        }
        public Aktivitetsdetektor(ITimer timer, IAnvändaraktivitet användaraktivitet, IStrömspararkontroll strömspararkontroll)
        {
            timer.Tick += (s, e) =>
                               {
                                   if (användaraktivitet.ÄrAktiv())
                                   {
                                       if (!_aktivEventKastat)
                                       {
                                           AktivitetUpptäckt(this, new EventArgs());
                                           _aktivEventKastat = true;
                                           _inaktivEventKastat = false;
                                       }
                                   }
                                   else
                                   {
                                       if (!_inaktivEventKastat)
                                       {
                                           InaktivitetUpptäckt(this, new EventArgs());
                                           _inaktivEventKastat = true;
                                           _aktivEventKastat = false;
                                       }
                                   }
                               };

            strömspararkontroll.GårNerIStrömsparläge += (s, e) => InaktivitetUpptäckt(this, new EventArgs());
        }
Exemple #14
0
 public static void Initialize(         
  IConsole console,
  ISurface surface,
  IStyle style,
  IDrawings drawing,
  IShapes shapes,
  IImages images,
  IControls controls,
  ISounds sounds,         
  IKeyboard keyboard,
  IMouse mouse,
  ITimer timer,
  IFlickr flickr,
  ISpeech speech,
  CancellationToken token)
 {
     TextWindow.Init(console);
      Desktop.Init(surface);
      GraphicsWindow.Init(style, surface, drawing, keyboard, mouse);
      Shapes.Init(shapes);
      ImageList.Init(images);
      Turtle.Init(surface, drawing, shapes);
      Controls.Init(controls);
      Sound.Init(sounds);
      Timer.Init(timer);
      Stack.Init();
      Flickr.Init(flickr);
      Speech.Init(speech);
      Program.Init(token);
 }
Exemple #15
0
        /// <summary>
        /// Starts this state.
        /// </summary>
        public override void Start()
        {
            base.Start();

            // start the watchdog timer
            watchDog = Server.Scheduler.SetTimeout(ElectionTimedOut, Server.Configuration.ElectionTimeout);
        }
        public SimpleTimerLiftEngine(ITimer timer)
        {
            _myTimer = timer;

            MakeTimerKeepFiringForTheLifeOfThisObject();

            _moving = false;
        }
Exemple #17
0
        protected override void SetUp()
        {
            timer = NewMock<ITimer>();
            clock = NewMock<IClock>();
            eventFactory = NewMock<IScheduledEventFactory>();

            scheduler = new Scheduler(clock, timer, eventFactory);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SendHeartBeatDecorator" /> class.
 /// </summary>
 /// <param name="metrics">The metrics factory.</param>
 /// <param name="handler">The handler.</param>
 /// <param name="connectionInformation">The connection information.</param>
 public SendHeartBeatDecorator(IMetrics metrics,
     ISendHeartBeat handler,
     IConnectionInformation connectionInformation)
 {
     var name = handler.GetType().Name;
     _timer = metrics.Timer($"{connectionInformation.QueueName}.{name}.SendTimer", Units.Calls);
     _handler = handler;
 }
 public static void OddSecondHandler(ITimer toHandle)
 {
     if (toHandle.ElapsedSeconds % 2 == 0)
     {
         var msg = string.Format("{0} seconds have passed, which is even.", toHandle.ElapsedSeconds);
         Console.WriteLine(msg);
     }
 }
        public void Setup()
        {
            connectionFactory = Substitute.For<IConnectionFactory>();
            timer = Substitute.For<ITimer>();
            waiter = Substitute.For<IWaiter>();

            sut = new ReliableConnection(connectionFactory, timer, waiter, new Aggregator());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PinsBehavior"/> class.
        /// </summary>
        /// <param name="configurations">The configurations.</param>
        protected PinsBehavior(IEnumerable<PinConfiguration> configurations)
        {
            Configurations = configurations.ToArray();

            timer = Timer.Create();
            timer.Interval = TimeSpan.FromMilliseconds(250);
            timer.Action = OnTimer;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PinsBehavior"/> class.
        /// </summary>
        /// <param name="configurations">The configurations.</param>
        protected PinsBehavior(IEnumerable<PinConfiguration> configurations)
        {
            Configurations = configurations.ToArray();

            timer = Timer.Create();
            timer.Interval = 250;
            timer.Action = OnTimer;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="QueueCreationDecorator" /> class.
 /// </summary>
 /// <param name="metrics">The metrics factory.</param>
 /// <param name="handler">The handler.</param>
 /// <param name="connectionInformation">The connection information.</param>
 public MessageHandlerDecorator(IMetrics metrics,
     IMessageHandler handler,
     IConnectionInformation connectionInformation)
 {
     var name = handler.GetType().Name;
     _runCodeTimer = metrics.Timer($"{connectionInformation.QueueName}.{name}.HandleTimer", Units.Calls);
     _handler = handler;
 }
        public TaskScheduler(ITimer timer, ITaskRunner taskRunner)
        {
            _timer = timer;
            _taskRunner = taskRunner;

            ProcessTimeout = 1000 * 60 * 10;
            Granularity = 1000 * 5;
        }
Exemple #25
0
        public ProcessPerformer(IMessenger messenger, ITimer timer, IProcessLoader processLoader)
        {
            _messenger = messenger;
            _timer = timer;
            _processLoader = processLoader;

            _processes = new List<IProcess>();
        }
        public TimerBasedScheduler(ITimer timer, ITimeProvider timeProvider)
        {
            Ensure.NotNull(timer, "timer");
            Ensure.NotNull(timeProvider, "timeProvider");

            _timer = timer;
            _timeProvider = timeProvider;
        }
Exemple #27
0
 public TimerIdle(ITimer i_session_timer)
 {
     m_idle_dispatcher = new DispatcherTimer
     {
         Interval = TimeSpan.FromSeconds(1)
     };
     m_idle_dispatcher.Tick += TimerTick;
     m_session_timer = i_session_timer as TimerSession;
 }
		public void RemoveTimer(ITimer timer)
		{
			timer.ActiveChanged -= OnActiveTimerChanged;

			lock (timers)
			{
				timers.Remove(timer);
			}
		}
		public void AddTimer(ITimer timer)
		{
			lock (timers)
			{
				timers.Add(timer);
			}

			timer.ActiveChanged += OnActiveTimerChanged;
		}
 protected BaseGameEngine(IMessageBus bus, IGraphicsEngine graphics, ILevel level, ITimer timer, IGameObjectFactory gameObjectFactory)
 {
     _graphics = graphics;
     _timer = timer;
     _gameObjectFactory = gameObjectFactory;
     Bus = bus;
     Level = level;
     _timer.Ticks.Subscribe(Update);
 }
        public DeviceActor(
            ILogger logger,
            Connect connectLogic,
            DeviceBootstrap deviceBootstrapLogic,
            UpdateDeviceState updateDeviceStateLogic,
            UpdateReportedProperties updateReportedPropertiesLogic,
            SendTelemetry sendTelemetryLogic,
            IRateLimiting rateLimiting,
            ITimer cancellationCheckTimer)
        {
            this.log          = logger;
            this.rateLimiting = rateLimiting;

            this.connectLogic                  = connectLogic;
            this.deviceBootstrapLogic          = deviceBootstrapLogic;
            this.updateDeviceStateLogic        = updateDeviceStateLogic;
            this.updateReportedPropertiesLogic = updateReportedPropertiesLogic;
            this.sendTelemetryLogic            = sendTelemetryLogic;

            this.cancellationCheckTimer = cancellationCheckTimer;
            this.cancellationCheckTimer.Setup(CancellationCheck, this);

            this.ActorStatus = Status.None;
        }
Exemple #32
0
        private void Start()
        {
            _logger.Debug("Starting NAT discovery");
            NatUtility.EnabledProtocols = new List <NatProtocol>
            {
                NatProtocol.Pmp
            };
            NatUtility.DeviceFound += NatUtility_DeviceFound;

            // Mono.Nat does never rise this event. The event is there however it is useless.
            // You could remove it with no risk.
            NatUtility.DeviceLost += NatUtility_DeviceLost;


            NatUtility.StartDiscovery();

            _timer = _timerFactory.Create(ClearCreatedRules, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));

            _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;

            _lastConfigIdentifier = GetConfigIdentifier();

            _isStarted = true;
        }
Exemple #33
0
        public void RestartTimer()
        {
            if (_disposed)
            {
                return;
            }

            lock (_timerLock)
            {
                if (_disposed)
                {
                    return;
                }

                if (_timer == null)
                {
                    _timer = _timerFactory.Create(OnTimerCallback, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
                }
                else
                {
                    _timer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
                }
            }
        }
Exemple #34
0
        public Game(IGameBoard gameBoard,
                    IEnumerable <ILayerRenderer> boardRenderers,
                    IPixelMapper pixelMapper,
                    IImageFactory imageFactory,
                    ITimer renderLoop,
                    IEnumerable <IScreen> screens,
                    IImageCache imageCache)
        {
            _gameBoard      = gameBoard;
            _boardRenderers = boardRenderers;
            _pixelMapper    = pixelMapper;
            _imageFactory   = imageFactory;
            _renderLoop     = renderLoop;
            _screens        = screens;
            _imageCache     = imageCache;

            foreach (IScreen screen in _screens)
            {
                screen.Changed += (s, e) => _imageCache.SetDirty(screen);
            }
            foreach (ICachableLayerRenderer renderer in _boardRenderers.OfType <ICachableLayerRenderer>())
            {
                renderer.Changed += (s, e) => _imageCache.SetDirty(renderer);
            }

            _renderLayerDrawTimes         = _boardRenderers.ToDictionary(x => x, x => InstrumentationBag.Add <ElapsedMillisecondsTimedStat>(GetLayerDiagnosticsName(x)));
            _screenDrawTimes              = _screens.ToDictionary(x => x, x => InstrumentationBag.Add <ElapsedMillisecondsTimedStat>(GetLayerDiagnosticsName(x)));
            _renderCacheDrawTimes         = _boardRenderers.Where(x => x is ICachableLayerRenderer).ToDictionary(x => x, x => InstrumentationBag.Add <ElapsedMillisecondsTimedStat>("Draw-Cache-" + x.Name.Replace(" ", "")));
            _pixelMapper.ViewPortChanged += (s, e) => _imageCache.SetDirtyAll(_boardRenderers);

            _renderLoop.Elapsed += (s, e) => DrawFrame();
            _renderLoop.Interval = RenderInterval;
            _renderLoop.Start();

            _gameBoard.Initialize(_pixelMapper.Columns, _pixelMapper.Rows);
        }
Exemple #35
0
        public void Onstart()
        {
            _logger.Log("Agent Service Starting ...");
            _logger.Log("Agent Version: " + Assembly.GetExecutingAssembly().GetName().Version);

            const int TIMER_INTERVAL_IS_SIX_SECONDS = 6000;

            RestartManager.RestartNeeded       = false;
            CommandsController.ProcessCommands = true;
            _timer = new ProdTimer {
                Interval = TIMER_INTERVAL_IS_SIX_SECONDS
            };
            _timer.Elapsed(TimerElapsed);


            StructureMapConfiguration.UseDefaultStructureMapConfigFile = false;
            StructureMapConfiguration.BuildInstancesOf <ITimer>().TheDefaultIs(Registry.Object(_timer));
            IoC.Register();

            RunCloudAutomation();
            CheckAgentUpdater();

            _timer.Enabled = true;
        }
Exemple #36
0
        private static void DoPWM(IWrapI2C i2cWrapper, ILogger logger, ITimer timer, int address)
        {
            var driverHandler = new ServoDriver(i2cWrapper, address, logger, timer);

            driverHandler.Configure();
            driverHandler.Reset();
            Console.WriteLine($"Obtained hanlder: {driverHandler}");
            Console.ReadKey();

            string readedValue;

            while (true)
            {
                Console.WriteLine("Give me value:");
                readedValue = Console.ReadLine();

                if (string.IsNullOrEmpty(readedValue))
                {
                    break;
                }

                driverHandler.SetPWM(1, int.Parse(readedValue));
            }
        }
        public PersistenceEnabler([NotNull] PersistenceManager persistenceManager, [NotNull] ITimerFactory timerFactory,
                                  [NotNull] IKernelConfig kernelConfig)
        {
            if (persistenceManager == null)
            {
                throw new ArgumentNullException(nameof(persistenceManager));
            }
            if (timerFactory == null)
            {
                throw new ArgumentNullException(nameof(timerFactory));
            }
            if (kernelConfig == null)
            {
                throw new ArgumentNullException(nameof(kernelConfig));
            }
            this.updateTimer          = timerFactory.CreateUiThreadTimer();
            this.updateTimer.Interval = TimeSpan.FromMilliseconds(500);
            this.updateTimer.Tick    += UpdateLoopOnUpdated;

            this.persistenceManager = persistenceManager;
            this.kernelConfig       = kernelConfig;

            this.updateTimer.Start();
        }
Exemple #38
0
 public Table(IChessBoard chessBoard, ITimer timer, INotes notes)
 {
     ChessBoard = chessBoard;
     Timer      = timer;
     Notes      = notes;
 }
Exemple #39
0
 public void Update(ITimer timer)
 {
     this.totalSeconds = timer?.TotalSeconds ?? 0.0;
 }
Exemple #40
0
 public TrainLookaheadRenderer(IGameBoard gameBoard, IPixelMapper pixelMapper, ITrackParameters parameters, ITrainPainter painter, ITimer gameTimer)
 {
     _gameBoard   = gameBoard;
     _pixelMapper = pixelMapper;
     _parameters  = parameters;
     _painter     = painter;
     _gameTimer   = gameTimer;
 }
Exemple #41
0
 private void Start()
 {
     ITimer externalTimer = externTimer.GetComponent <ITimer>();
 }
        public TriggersFeature(
            [NotNull] ISoundManager soundManager,
            [NotNull] IWurmAssistantDataDirectory wurmAssistantDataDirectory,
            [NotNull] ITimerFactory timerFactory,
            [NotNull] IWurmApi wurmApi,
            [NotNull] ITrayPopups trayPopups,
            [NotNull] ILogger logger,
            [NotNull] TriggersDataContext triggersDataContext,
            [NotNull] ITriggerManagerFactory triggerManagerFactory)
        {
            if (soundManager == null)
            {
                throw new ArgumentNullException(nameof(soundManager));
            }
            if (wurmAssistantDataDirectory == null)
            {
                throw new ArgumentNullException(nameof(wurmAssistantDataDirectory));
            }
            if (timerFactory == null)
            {
                throw new ArgumentNullException(nameof(timerFactory));
            }
            if (wurmApi == null)
            {
                throw new ArgumentNullException(nameof(wurmApi));
            }
            if (trayPopups == null)
            {
                throw new ArgumentNullException(nameof(trayPopups));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (triggersDataContext == null)
            {
                throw new ArgumentNullException(nameof(triggersDataContext));
            }
            if (triggerManagerFactory == null)
            {
                throw new ArgumentNullException(nameof(triggerManagerFactory));
            }
            this.soundManager = soundManager;
            this.wurmAssistantDataDirectory = wurmAssistantDataDirectory;
            this.wurmApi               = wurmApi;
            this.trayPopups            = trayPopups;
            this.logger                = logger;
            this.triggersDataContext   = triggersDataContext;
            this.triggerManagerFactory = triggerManagerFactory;

            updateTimer          = timerFactory.CreateUiThreadTimer();
            updateTimer.Interval = TimeSpan.FromMilliseconds(500);
            updateTimer.Tick    += (sender, args) => Update();

            mainUi = new FormTriggersMain(this, soundManager);
            foreach (var name in GetAllActiveCharacters())
            {
                AddManager(name);
            }
            updateTimer.Start();
        }
 public PingPongMonitor(ITimer timer, IDateTimeKeeper dateTimeKeeper)
 {
     this._timer          = timer;
     this._dateTimeKeeper = dateTimeKeeper;
 }
 public DoubleTapPrevention(ITimer model)
 {
     InternalModel = model;
     LastEvent     = TimeStamp.Now - LongDelay;
 }
 internal static FileStub GetFile_0_0_2(ITimer timer)
 {
     return(new FileStub(timer, FileHelper.GetMockFileSystem(), FileHelper.HostDirectory + FileHelper.MockCSXFile3Path));
 }
Exemple #46
0
 public NodeRunner(Node node, ITimer timer, StrategySelector strategySelector)
 {
     Node = node;
     _strategySelector = strategySelector;
     _timer            = timer;
 }
        private int _rs = 0b00000001; // # Register select bit

        #endregion commands

        //TODO: address should be hidden above some abstraction
        public LcdDisplay(ITimer timer, ILogger logger, int address = 0x3f) : base(address, logger, timer)
        {
            Initialize();
        }
Exemple #48
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Name">定时器名称</param>
        /// <param name="StartTime">开始时间,null表示网站启动的自动开始</param>
        /// <param name="EndTime">结束时间,null表示不会结束</param>
        /// <param name="GSeconds">执行间隔时间(秒)</param>
        /// <param name="_ITimer">对象</param>
        public NewTimer(string Name, DateTime?StartTime, DateTime?EndTime, int GSeconds, ITimer _ITimer)
        {
            try
            {
                this.Name      = Name;
                this.StartTime = StartTime;
                this.EndTime   = EndTime;
                this.GSeconds  = GSeconds;
                this._ITimer   = _ITimer;

                _T          = new System.Timers.Timer();
                _T.Interval = this.GSeconds * 1000;
                _T.Elapsed += new System.Timers.ElapsedEventHandler(_T_Elapsed);
                _T.Start();
            }
            catch { }
        }
Exemple #49
0
        public GrangerFeature(
            [NotNull] ILogger logger,
            [NotNull] IWurmAssistantDataDirectory dataDirectory,
            [NotNull] ISoundManager soundManager,
            [NotNull] ITrayPopups trayPopups,
            [NotNull] IWurmApi wurmApi,
            [NotNull] GrangerSettings grangerSettings,
            [NotNull] DefaultBreedingEvaluatorOptions defaultBreedingEvaluatorOptions,
            [NotNull] IWurmAssistantConfig wurmAssistantConfig,
            [NotNull] ITimerFactory timerFactory,
            [NotNull] CreatureColorDefinitions creatureColorDefinitions,
            [NotNull] GrangerContext grangerContext,
            [NotNull] IFormEditCreatureColorsFactory formEditCreatureColorsFactory,
            [NotNull] ITelemetry telemetry)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (dataDirectory == null)
            {
                throw new ArgumentNullException(nameof(dataDirectory));
            }
            if (soundManager == null)
            {
                throw new ArgumentNullException(nameof(soundManager));
            }
            if (trayPopups == null)
            {
                throw new ArgumentNullException(nameof(trayPopups));
            }
            if (wurmApi == null)
            {
                throw new ArgumentNullException(nameof(wurmApi));
            }
            if (grangerSettings == null)
            {
                throw new ArgumentNullException(nameof(grangerSettings));
            }
            if (defaultBreedingEvaluatorOptions == null)
            {
                throw new ArgumentNullException(nameof(defaultBreedingEvaluatorOptions));
            }
            if (wurmAssistantConfig == null)
            {
                throw new ArgumentNullException(nameof(wurmAssistantConfig));
            }
            if (timerFactory == null)
            {
                throw new ArgumentNullException(nameof(timerFactory));
            }
            if (creatureColorDefinitions == null)
            {
                throw new ArgumentNullException(nameof(creatureColorDefinitions));
            }
            if (grangerContext == null)
            {
                throw new ArgumentNullException(nameof(grangerContext));
            }
            if (formEditCreatureColorsFactory == null)
            {
                throw new ArgumentNullException(nameof(formEditCreatureColorsFactory));
            }

            this.logger        = logger;
            this.dataDirectory = dataDirectory;
            this.soundManager  = soundManager;
            this.trayPopups    = trayPopups;

            settings = grangerSettings;
            this.defaultBreedingEvaluatorOptions = defaultBreedingEvaluatorOptions;
            this.creatureColorDefinitions        = creatureColorDefinitions;

            context = grangerContext;
            this.formEditCreatureColorsFactory = formEditCreatureColorsFactory;
            this.telemetry = telemetry ?? throw new ArgumentNullException(nameof(telemetry));

            grangerUi = new FormGrangerMain(this,
                                            settings,
                                            context,
                                            logger,
                                            wurmApi,
                                            defaultBreedingEvaluatorOptions,
                                            creatureColorDefinitions,
                                            formEditCreatureColorsFactory,
                                            telemetry);

            logsFeedMan = new LogsFeedManager(this, context, wurmApi, logger, trayPopups, wurmAssistantConfig, creatureColorDefinitions, grangerSettings, telemetry);
            logsFeedMan.UpdatePlayers(settings.CaptureForPlayers);
            grangerUi.GrangerPlayerListChanged += GrangerUI_Granger_PlayerListChanged;

            updateLoop          = timerFactory.CreateUiThreadTimer();
            updateLoop.Interval = TimeSpan.FromMilliseconds(500);
            updateLoop.Tick    += (sender, args) => Update();
            updateLoop.Start();
        }
Exemple #50
0
        /// <summary>
        /// Note that Explore can silently fail (exits with 1), if a second chance AV happens
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="planManager"></param>
        /// <param name="methodWeigthing"></param>
        /// <param name="forbidNull"></param>
        /// <param name="mutateFields"></param>
        public void Explore(ITimer timer, PlanManager planManager, MethodWeighing methodWeigthing,
                            bool forbidNull, bool mutateFields, bool fairOpt)
        {
            int currentPlans         = planManager.Plans;
            int currentRedundantAdds = planManager.RedundantAdds;

            // Start timing test generation.
            Timer.QueryPerformanceCounter(ref TimeTracking.generationStartTime);


            //exercise the fair option
            if (fairOpt)
            {
                Console.WriteLine("Using the fair option ....");

                //fairOptLog = new StreamWriter("Randoop.fairopt.log");

                //compute the initial working set and the active methods for each class
                InitializeActiveMemberAndDependency(planManager);

                for (; ;)
                {
                    //field setting
                    if (mutateFields && this.actions.fieldList.Count > 0 && Common.Enviroment.Random.Next(2) == 0)
                    {
                        NewFieldSettingPlan(this.actions.RandomField(), planManager, forbidNull);
                    }

                    //If the active set is recomputed from scratch
                    //InitializeActiveMemberAndDependency(planManager);


                    //copy the keys
                    Dictionary <Type, bool> .KeyCollection keys = new Dictionary <Type, bool> .KeyCollection(activeTypes);

                    List <Type> activeList = new List <Type>();
                    foreach (Type t in keys)
                    {
                        activeList.Add(t);
                    }

                    RandoopPrintFairStats("Randoop.RandomExplore::Explore", "Starting a round of the fair workset algorithm with " + activeTypes.Count + "activeTypes");

                    foreach (Type t in activeList)
                    {
                        //pick up an active method of the type

                        MemberInfo m;

                        try
                        {
                            m = this.actions.RandomActiveMethodorConstructor(activeMembers, t);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Exception raised from RandomActiveMethodorConstructor is {0}", e.ToString());
                            continue;
                        }

                        //Console.WriteLine("Picked up method {0}::{1}", m.DeclaringType,m.Name );
                        int prevBuilderPlanCnt = planManager.builderPlans.NumPlans;

                        //Randoop step
                        ExploreMemberInternal(timer, planManager, forbidNull, m);

                        //need to know if the object creation was succesful, since we know the type
                        //we do it indirectly by looking at the builder plans
                        if (planManager.builderPlans.NumPlans > prevBuilderPlanCnt)
                        {
                            Type retType;
                            if (m is MethodInfo)
                            {
                                retType = (m as MethodInfo).ReturnType;
                            }
                            else if (m is ConstructorInfo)
                            {
                                retType = (m as ConstructorInfo).DeclaringType;
                            }
                            else
                            {
                                throw new RandoopBug("Constructor or Method expected");
                            }

                            //use the return type of the method/constructor to incrementally activate more methods/classes
                            try
                            {
                                UpdateActiveMethodsAndClasses(retType);
                            }
                            catch (Exception e) // had a nasty bug in the updateActiveMethodsAndClasses, so using try-catch
                            {
                                Console.WriteLine("Exception raised from UpdateActiveMethodsAndClasses is {0}", e.ToString());
                            }
                        }

                        if (timer.TimeToStop())
                        {
                            //get the size of # of active members
                            int size = 0;
                            foreach (KeyValuePair <Type, List <MemberInfo> > kv in activeMembers)
                            {
                                List <MemberInfo> l = kv.Value;
                                size = size + l.Count;
                            }

                            //stats printing
                            Console.WriteLine("Finishing the fair exploration...printing activity stats");
                            Console.WriteLine("Stats: <#ActiveTypes, #ActiveMembers, #BuilderPlans, #typesWithObjs> = <{0},{1},{2},{3}>",
                                              activeTypes.Count, size, planManager.builderPlans.NumPlans, typesWithObjects.Count);
                            //fairOptLog.Close();

                            return;
                        }
                    }
                }
            }
            else
            {
                #region Old code for the Randoop exploration
                for (; ;)
                {
                    //field setting
                    if (mutateFields && this.actions.fieldList.Count > 0 && Common.Enviroment.Random.Next(2) == 0)
                    {
                        NewFieldSettingPlan(this.actions.RandomField(), planManager, forbidNull);
                    }

                    MemberInfo m;
                    if (methodWeigthing == MethodWeighing.RoundRobin)
                    {
                        m = this.actions.RandomMethodOrConstructorRoundRobin();
                    }
                    else if (methodWeigthing == MethodWeighing.Uniform)
                    {
                        m = this.actions.RandomMethodOrConstructorUniform();
                    }
                    else
                    {
                        throw new RandoopBug("Unrecognized method weighting option.");
                    }


                    ExploreMemberInternal(timer, planManager, forbidNull, m);

                    if (timer.TimeToStop())
                    {
                        // this computation gives us the activity stats for the non-fair option
                        InitializeActiveMemberAndDependency(planManager);
                        //get the size of # of active members
                        int size = 0;
                        foreach (KeyValuePair <Type, List <MemberInfo> > kv in activeMembers)
                        {
                            List <MemberInfo> l = kv.Value;
                            size = size + l.Count;
                        }

                        //stats printing
                        Console.WriteLine("Finishing the non-fair exploration...printing activity stats");
                        Console.WriteLine("Stats: <#ActiveTypes, #ActiveMembers, #BuilderPlans, #typesWithObjs> = <{0},{1},{2},{3}>",
                                          activeTypes.Count, size, planManager.builderPlans.NumPlans, typesWithObjects.Count);
                        //fairOptLog.Close();

                        return;
                    }
                }
                #endregion
            }
        }
Exemple #51
0
        void IKeyboardListener.keyDown(Keys key)
        {
            if (disabled)
            {
                return;
            }

            lastBlink = 0;
            cursorOn  = false;

            var isCtrlDown = InputUtils.isControlDown();
            var jump       = isCtrlDown && !passwordMode;
            var repeat     = false;

            if (isCtrlDown)
            {
                if (key == Keys.V)
                {
                    paste(Clipboard.getContents(), true);
                }
                else if (key == Keys.C || key == Keys.Insert)
                {
                    copy();
                    return;
                }
                else if (key == Keys.X)
                {
                    cut(true);
                    return;
                }
                else if (key == Keys.A)
                {
                    selectAll();
                    return;
                }
            }

            if (InputUtils.isShiftDown())
            {
                if (key == Keys.Insert)
                {
                    paste(Clipboard.getContents(), true);
                }
                else if (key == Keys.Delete)
                {
                    cut(true);
                }

                // jumping around shortcuts
                var temp         = cursor;
                var foundJumpKey = true;

                if (key == Keys.Left)
                {
                    moveCursor(false, jump);
                    repeat = true;
                }
                else if (key == Keys.Right)
                {
                    moveCursor(true, jump);
                    repeat = true;
                }
                else if (key == Keys.Home)
                {
                    goHome();
                }
                else if (key == Keys.End)
                {
                    goEnd();
                }
                else
                {
                    foundJumpKey = false;
                }

                if (foundJumpKey && !hasSelection)
                {
                    selectionStart = temp;
                    hasSelection   = true;
                }
            }
            else
            {
                // Cursor movement or other keys (kills selection)
                if (key == Keys.Left)
                {
                    moveCursor(false, jump);
                    clearSelection();
                    repeat = true;
                }
                else if (key == Keys.Right)
                {
                    moveCursor(true, jump);
                    clearSelection();
                    repeat = true;
                }
                else if (key == Keys.Home)
                {
                    goHome();
                }
                else if (key == Keys.End)
                {
                    goEnd();
                }
            }

            cursor = Mathf.clamp(cursor, 0, text.Length);

            if (repeat)
            {
                if (_keyRepeatTimer != null)
                {
                    _keyRepeatTimer.stop();
                }
                _keyRepeatTimer = Core.schedule(_keyRepeatTime, true, this, t => (t.context as IKeyboardListener).keyDown(key));
            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="HitRatioGauge" /> class.
 /// </summary>
 /// <param name="hitMeter">The numerator meter to use for the ratio.</param>
 /// <param name="totalTimer">The denominator meter to use for the ratio.</param>
 /// <remarks>
 ///     Creates a new HitRatioGauge with externally tracked Meter and Timer, and uses the OneMinuteRate from the MeterValue
 ///     of the meters.
 /// </remarks>
 public HitRatioGauge(IMeter hitMeter, ITimer totalTimer)
     : this(hitMeter, totalTimer, value => value.OneMinuteRate)
 {
 }
Exemple #53
0
 public void Start()
 {
     _logger.LogDebug("Dlna Device.Start");
     _timer = _timerFactory.Create(TimerCallback, null, 1000, Timeout.Infinite);
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="HitRatioGauge" /> class.
 /// </summary>
 /// <param name="hitMeter">The numerator meter to use for the ratio.</param>
 /// <param name="totalTimer">The denominator timer to use for the ratio.</param>
 /// <param name="meterRateFunc">
 ///     The function to extract a value from the MeterValue. Will be applied to both the numerator
 ///     and denominator meters.
 /// </param>
 /// <remarks>
 ///     Creates a new HitRatioGauge with externally tracked Meter and Timer, and uses the provided meter rate function to
 ///     extract the value for the ratio.
 /// </remarks>
 public HitRatioGauge(IMeter hitMeter, ITimer totalTimer, Func <MeterValue, double> meterRateFunc)
     : base(() => meterRateFunc(hitMeter.GetValueOrDefault()), () => meterRateFunc(totalTimer.GetValueOrDefault().Rate))
 {
 }
Exemple #55
0
 public static void ProvideTimer(ITimer _tickerInstance)
 {
     _factoryFunc = () => _tickerInstance;
 }
Exemple #56
0
 public TaskWaitForSeconds(float seconds)
 {
     timer = new Timer <T>(seconds);
 }
Exemple #57
0
 private void onTurnTimeout()
 {
     logger.log("Debug", currentPlayer + "回合超时");
     turnTimer = null;
     answers.cancel(answers.getRequests(currentPlayer.id));
 }
Exemple #58
0
 public void Start()
 {
     _timer = _timerFactory.New(DeleteTempFiles, null, 1000, GlobalConstants.NetworkComputerNameQueryFreq);
 }
Exemple #59
0
        internal SystemMetricsExecutor(IList <SystemMetric> metrics, IVeStatsDClient client, ITimer timer)
        {
            _metrics = metrics;
            _client  = client;
            _timer   = timer;

            _timer.Elapsed += Invoke;
            _timer.Start();
        }
Exemple #60
0
 public OcvVideoProvider(ITimer timer)
 {
     this.timer = timer;
 }