public Main(RemoteHooking.IContext InContext, ProcessDto procDto, SystemState state, string InChannelName)
        {
            try
            {
                _functions = new List<FunctionInjected>();

                switch (state)
                {
                    case SystemState.Scanning:
                        _behaviorWrapper = RemoteHooking.IpcConnectClient<BehaviorsWrapper<FunctionBehaviorForXml>>(InChannelName);
                        break;
                    case SystemState.Locking:
                        _behaviorWrapper = RemoteHooking.IpcConnectClient<BehaviorsWrapper<FunctionBehaviorForNLog>>(InChannelName);
                        break;
                }

                foreach (var functionBehavior in _behaviorWrapper.Functions)
                {
                    _functions.Add(functionBehavior.CreateAttachedTypeOfFunctionInjected(procDto));
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, procDto.ProcName);
            }
        }
Esempio n. 2
0
        public void TemplatedGetProfileUnitTest()
        {
            SystemState state = new SystemState();
            HSFProfile<int> intProf = new HSFProfile<int>(0, 1);
            intProf.Add(1, 2);
            intProf.Add(2, -1);

            StateVarKey<int> intKey = new StateVarKey<int>("testIntVar");
            state.SetProfile(intKey, intProf);

            HSFProfile<double> doubleProf = new HSFProfile<double>(0, 1);
            doubleProf.Add(1, 2);
            doubleProf.Add(2, -1);

            StateVarKey<double> doubleKey = new StateVarKey<double>("testDoubleVar");
            state.SetProfile(doubleKey, doubleProf);

            HSFProfile<Matrix<double>> matrixProf = new HSFProfile<Matrix<double>>(0, new Matrix<double>(1, 2, 1));
            matrixProf.Add(1, new Matrix<double>(1, 2, 2));
            matrixProf.Add(2, new Matrix<double>(1, 2, -1));

            var matrixKey = new StateVarKey<Matrix<double>>("testMatrixVar");
            state.SetProfile(matrixKey, matrixProf);

            HSFProfile<int> newIntProf = state.GetProfile(intKey);
            HSFProfile<double> newDoubleProf = state.GetProfile(doubleKey);
            HSFProfile<Matrix<double>> newMatrixProf = state.GetProfile(matrixKey);

            Console.WriteLine();
        }
        private void Intersept(ProcessDto processDto, SystemState state)
        {
            try
            {
                switch (state)
                {
                    case SystemState.Scanning:
                        RemoteHooking.IpcCreateServer<BehaviorsWrapper<FunctionBehaviorForXml>>(ref ChannelName, WellKnownObjectMode.SingleCall, WellKnownSidType.WorldSid);
                        break;
                    case SystemState.Locking:
                        RemoteHooking.IpcCreateServer<BehaviorsWrapper<FunctionBehaviorForNLog>>(ref ChannelName, WellKnownObjectMode.SingleCall, WellKnownSidType.WorldSid);
                        break;
                }

                var str = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "LibraryInjected.dll");

                RemoteHooking.Inject(processDto.ProcId, str, str, (object)processDto, (object)state, (object)ChannelName);
                Logger.Info($"Injected to process {processDto.ProcId}", processDto.ProcName);

            }
            catch (Exception ex)
            {
                Logger.Error($"There was an error while connecting to target:\r\n{(object) ex.ToString()}", processDto.ProcName);
            }
        }
Esempio n. 4
0
        private SystemState displayOrientation; // Für die Überwachung der Displayorientierung                   // Browser für die Kommunikation

        #endregion Fields

        #region Constructors

        public ModuleScreen()
        {
            displayOrientation = null;
            AddFunctionToModul(new ModuleFunctionPointer(GetInfo), "getinfo");
            AddFunctionToModul(new ModuleFunctionPointer(StartObserveOrientation), "startobserveorientation");
            AddFunctionToModul(new ModuleFunctionPointer(StopObserveOrientation), "stopobserveorientation");
        }
Esempio n. 5
0
    public const string NEW_STATE = "NewState"; // Type: SystemState

    /// <summary>
    /// Sends a <see cref="MessageType.SystemStateChanged"/> message.
    /// </summary>
    /// <param name="newState">The state the system will switch to.</param>
    public static void SendSystemStateChangeMessage(SystemState newState)
    {
      SystemMessage msg = new SystemMessage(MessageType.SystemStateChanged);
      msg.MessageData[NEW_STATE] = newState;
      IMessageBroker messageBroker = ServiceRegistration.Get<IMessageBroker>();
      if (messageBroker != null)
        messageBroker.Send(CHANNEL, msg);
    }
Esempio n. 6
0
        public IncomingsParser(bool useFormThread)
        {
            incomingNumberState = new SystemState(SystemProperty.PhoneIncomingCallerNumber, useFormThread);
            missedCalsState = new SystemState(SystemProperty.PhoneMissedCalls, useFormThread);
            missedCalls = SystemState.PhoneMissedCalls;

            incomingNumberState.Changed += IncomingNumberStateChanged;
            missedCalsState.Changed += new ChangeEventHandler(missedCalsState_Changed);
        }
 public InterseptDll(SystemState state, ProcessDto processDto)
 {
     if (processDto.ProcId == -1)
     {
         Logger.Error("No process exists with that name!", processDto.ProcName);
         return;
     }
     Intersept(processDto, state);
 }
Esempio n. 8
0
 /// <summary>
 ///  Creates an Event, in which the Task was performed by an Asset, and the time history 
 /// of the pertinent State information was saved.
 /// </summary>
 /// <param name="task"></param>
 /// <param name="state"></param>
 public Event(Dictionary<Asset, Task> task, SystemState state)
 {
     Tasks = task;
     State = state; //Should this be a deep copy?
     EventStarts = new Dictionary<Asset, double>();
     EventEnds = new Dictionary<Asset, double>();
     TaskStarts = new Dictionary<Asset, double>();
     TaskEnds = new Dictionary<Asset, double>();
     isEvaluated = 0;
 }
        public static void CreateNewInjectProcess(SystemState state, ProcessDto processDto)
        {
            if (ChildDomains.ContainsKey(processDto.ProcName))
            {
                AppDomain.Unload(ChildDomains[processDto.ProcName]);
                ChildDomains.Remove(processDto.ProcName);
            }
            ChildDomains.Add(processDto.ProcName, AppDomain.CreateDomain(processDto.ProcName));

            ChildDomains[processDto.ProcName].CreateInstanceFromAndUnwrap(AppDomain.CurrentDomain.BaseDirectory + "InterceptedModule.dll", "InterceptedModule.InterseptDll", false, BindingFlags.CreateInstance, null, new[] {(object) state, (object) processDto}, CultureInfo.InvariantCulture, null);
        }
Esempio n. 10
0
        public DetailsGeneralLanscape()
        {
            InitializeComponent();
            _activeCallState = new SystemState(SystemProperty.PhoneActiveCallCount);

            this._alarmPictureBox.Image = Properties.Resources.notify_large;
            this._alarmPictureBox.PushImage = Properties.Resources.notify_large_hover;
            this._commonPhrasesPictureBox.Image = Properties.Resources.commonphrases;
            this._commonPhrasesPictureBox.PushImage = Properties.Resources.commonphrases_hover;

            this.Disposed += new EventHandler(DetailsGeneral_Disposed);
        }
Esempio n. 11
0
        public void when_state_is_set_then_can_query()
        {
            var state = new SystemState();

            var query = state.Of<float>("t", "kids").Where(v => v == 22f);

            Assert.False(query.Any());

            state.Set("t", "kids", 22f);

            Assert.True(query.Any());
        }
Esempio n. 12
0
        public void when_string_impulse_received_then_sets_system_state()
        {
            var stream = new EventStream();
            var state = new SystemState();
            var consumer = new SetSystemState(state);
            consumer.Connect(stream);

            Assert.False(state.Of<string>("t", "kids").Any());

            stream.Push(Mock.Of<IDevice>(x => x.Id == "kids"), Impulse.Create("t", "foo", DateTimeOffset.Now));

            Assert.Equal("foo", state.Of<string>("t", "kids").FirstOrDefault());
        }
Esempio n. 13
0
 public Startup()
 {
     InitializeComponent ();
     InitListViewComponent ();
     InitZoneComponent ();
     lblSetGps.Text = gps.GetDeviceState().
         DeviceState.ToString ();
     //Following two lines handles entry of new Appointment
     calendarNewAppointment = new SystemState
         (SystemProperty.CalendarAppointment);
     calendarNewAppointment.Changed += new
     ChangeEventHandler (calendarApp_Changed);
 }
 private bool TryLoadJsonSystemState(string name, out SystemState systemState)
 {
     var nestHostExecutablePath = Assembly.GetEntryAssembly().Location;
      var nestHostDirectoryInfo = new FileInfo(nestHostExecutablePath).Directory;
      var nestDirectoryInfo = nestHostDirectoryInfo.Parent;
      var jsonTogglesPath = Path.Combine(nestDirectoryInfo.FullName, name);
      if (File.Exists(jsonTogglesPath)) {
     systemState = JsonReadOnlySystemStateImpl.FromFile(jsonTogglesPath);
     return true;
      } else {
     systemState = null;
     return false;
      }
 }
Esempio n. 15
0
        /// <summary>
        /// Startet einen Listener der eine Änderung der Displayausrichtund erfasst.
        /// </summary>
        private string StartObserveOrientation(Dictionary<string, string> parameter)
        {
            // MessageBox.Show("Device.GetInfo [ Starte observer ]");
            if (displayOrientation != null)
            {
                //deviceThread = null;
                return "";
            }

            displayOrientation = new SystemState(SystemProperty.DisplayRotation);
            displayOrientation.Changed += new ChangeEventHandler(displayOrientation_Changed);
            //deviceThread = null;

            return "";
        }
Esempio n. 16
0
        public void Run(RemoteHooking.IContext InContext, ProcessDto procDto, SystemState state, string InChannelName)
        {
            try
            {
                RemoteHooking.WakeUpProcess();

                while (true)
                {

                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, procDto.ProcName);
            }
        }
Esempio n. 17
0
 public static bool CanSyncInventoryCountsToShopify(this SystemState state)
 {
     return(state.ShopifyConnState == StateCode.Ok &&
            state.InventoryRefreshState == StateCode.Ok);
 }
 public void SwitchSystemState(SystemState newState, bool sendMessage)
 {
   _state = newState;
   if (sendMessage)
     SystemMessaging.SendSystemStateChangeMessage(_state);
 }
Esempio n. 19
0
 /*
  * Sets the current system state
  * Generally this is only called from within the UpdateState methods
  */
 public void SetState(SystemState newState)
 {
     SystemFlags.currentState = newState;
 }
Esempio n. 20
0
 /**
  * Creates a new empty schedule with the given initial state.
  * @param initialState the initial state of the system for which the schedule applies
  */
 public AssetSchedule(SystemState state)
 {
     InitialState = state;
 }
Esempio n. 21
0
        /// <summary>
        /// Calculate the solar panel power in over the time of the task
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="state"></param>
        /// <param name="position"></param>
        /// <param name="universe"></param>
        /// <returns></returns>
        protected HSFProfile<double> CalcSolarPanelPowerProfile(double start, double end, SystemState state, DynamicState position, Universe universe)
        {
            // create solar panel profile for this event
            double freq = 5;
            ShadowState lastShadow = universe.Sun.castShadowOnPos(position, start);
            HSFProfile<double> solarPanelPowerProfile = new HSFProfile<double>(start, GetSolarPanelPower(lastShadow));

            for (double time = start + freq; time <= end; time += freq)
            {
                ShadowState shadow = universe.Sun.castShadowOnPos(position, time);
                // if the shadow state changes during this step, save the power data
                if (shadow != lastShadow)
                {
                    solarPanelPowerProfile[time] = GetSolarPanelPower(shadow);
                    lastShadow = shadow;
                }
            }
            state.AddValue(POWIN_KEY, solarPanelPowerProfile);
            return solarPanelPowerProfile;
        }
Esempio n. 22
0
        public virtual List <SystemSchedule> GenerateSchedules(SystemClass system, Stack <MissionElements.Task> tasks, SystemState initialStateList, Evaluator scheduleEvaluator)
        {
            //system.setThreadNum(1);
            //DWORD startTickCount = GetTickCount();
            //accumSchedTimeMs = 0;

            // get the global dependencies object
            //Dependencies dependencies = new Dependencies().Instance();

            Console.WriteLine("SIMULATING... ");
            // Create empty systemSchedule with initial state set
            SystemSchedule        emptySchedule   = new SystemSchedule(initialStateList);
            List <SystemSchedule> systemSchedules = new List <SystemSchedule>();

            systemSchedules.Add(emptySchedule);

            // if all asset position types are not dynamic types, can pregenerate accesses for the simulation
            bool canPregenAccess = true;

            foreach (var asset in system.Assets)
            {
                if (asset.AssetDynamicState != null)
                {
                    canPregenAccess &= asset.AssetDynamicState.Type != HSFUniverse.DynamicStateType.DYNAMIC_ECI && asset.AssetDynamicState.Type != HSFUniverse.DynamicStateType.DYNAMIC_LLA;
                }
                else
                {
                    canPregenAccess = false;
                }
            }

            // if accesses can be pregenerated, do it now
            Stack <Access>          preGeneratedAccesses = new Stack <Access>();
            Stack <Stack <Access> > scheduleCombos       = new Stack <Stack <Access> >();

            if (canPregenAccess)
            {
                Console.Write("Pregenerating Accesses...");
                //DWORD startPregenTickCount = GetTickCount();

                preGeneratedAccesses = Access.pregenerateAccessesByAsset(system, tasks, _startTime, _endTime, _stepLength);
                //DWORD endPregenTickCount = GetTickCount();
                //pregenTimeMs = endPregenTickCount - startPregenTickCount;
                //writeAccessReport(access_pregen, tasks); - TODO:  Finish this code - EAM
                Console.WriteLine(" DONE!");
            }
            // otherwise generate an exhaustive list of possibilities for assetTaskList
            else
            {
                Console.Write("Generating Exhaustive Task Combinations... ");
                Stack <Stack <Access> > exhaustive  = new Stack <Stack <Access> >();
                Stack <Access>          allAccesses = new Stack <Access>(tasks.Count);

                foreach (var asset in system.Assets)
                {
                    foreach (var task in tasks)
                    {
                        allAccesses.Push(new Access(asset, task));
                    }

                    exhaustive.Push(allAccesses);
                    allAccesses.Clear();
                }

                scheduleCombos = (Stack <Stack <Access> >)exhaustive.CartesianProduct();
                Console.WriteLine(" DONE!");
            }

            /// \todo TODO: Delete (or never create in the first place) schedules with inconsistent asset tasks (because of asset dependencies)

            // Find the next timestep for the simulation
            //DWORD startSchedTickCount = GetTickCount();

            for (double currentTime = _startTime; currentTime < _endTime; currentTime += _stepLength)
            {
                Console.WriteLine(currentTime);
                // if accesses are pregenerated, look up the access information and update assetTaskList
                if (canPregenAccess)
                {
                    scheduleCombos = GenerateExhaustiveSystemSchedules(preGeneratedAccesses, system, currentTime);
                }

                // Check if it's necessary to crop the systemSchedule list to a more managable number
                if (systemSchedules.Count > _maxNumSchedules)
                {
                    CropSchedules(systemSchedules, scheduleEvaluator, emptySchedule);
                }

                // Create a new system schedule list by adding each of the new Task commands for the Assets onto each of the old schedules
                // Start timing
                // Generate an exhaustive list of new tasks possible from the combinations of Assets and Tasks
                //TODO: Parallelize this.

                List <SystemSchedule> potentialSystemSchedules = new List <SystemSchedule>();

                foreach (var oldSystemSchedule in systemSchedules)
                {
                    foreach (var newAccessStack in scheduleCombos)
                    {
                        if (oldSystemSchedule.CanAddTasks(newAccessStack, currentTime))
                        {
                            SystemSchedule newSched = new SystemSchedule(oldSystemSchedule, newAccessStack, currentTime);
                            potentialSystemSchedules.Add(newSched);
                        }
                    }
                    potentialSystemSchedules.Add(new SystemSchedule(oldSystemSchedule));
                    //deep copy
                }

                // TODO EAM: Remove this and only add new SystemScedule if canAddTasks and CanPerform are both true.  That way we don't need to delete SystemSchedules after the fact below.
                List <SystemSchedule> systemCanPerformList = new List <SystemSchedule>();
                //for (list<systemSchedule*>::iterator newSchedIt = newSysScheds.begin(); newSchedIt != newSysScheds.end(); newSchedIt++)
                // The parallel version
                // Should we use a Partitioner?
                // Need to test this...

                /*
                 * Stopwatch stopWatch = new Stopwatch();
                 * stopWatch.Start();
                 * // The Scheduler has to call the CanPerform for a SystemClass, SystemSchedule combo.  The SystemClass
                 * Parallel.ForEach(potentialSystemSchedules, (currentSchedule) =>
                 * {
                 *  // dependencies.updateStates(newSchedule.getEndStates());
                 *  if (Checker.CheckSchedule(system, currentSchedule))
                 *      systemCanPerformList.Add(currentSchedule);
                 *  Console.WriteLine("Processing {0} on thread {1}", currentSchedule.ToString(), Thread.CurrentThread.ManagedThreadId);
                 * });
                 * stopWatch.Stop();
                 *
                 * TimeSpan ts = stopWatch.Elapsed;
                 * // Format and display the TimeSpan value.
                 * string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                 *  ts.Hours, ts.Minutes, ts.Seconds,
                 *  ts.Milliseconds / 10);
                 * Console.WriteLine("Parallel Scheduler RunTime: " + elapsedTime);
                 */
                foreach (var potentialSchedule in potentialSystemSchedules)
                {
                    if (Checker.CheckSchedule(system, potentialSchedule))
                    {
                        systemCanPerformList.Add(potentialSchedule);
                    }
                    //dependencies.updateStates(newSchedule.getEndStates());
                    //systemCanPerformList.Push(system.canPerform(potentialSchedule));
                }

                // End timing

                /*
                 * // delete systemSchedules (and corresponding lower level classes) that are not possible
                 * list<systemSchedule*>::iterator eraseIt = newSysScheds.begin();
                 * for (vector<bool>::iterator successIt = systemCanPerformList.begin(); successIt != systemCanPerformList.end(); successIt++)
                 * {
                 *  if (*successIt) { eraseIt++; }
                 *  else {
                 *      delete* eraseIt;
                 *      eraseIt = newSysScheds.erase(eraseIt);
                 *  }
                 * }
                 */

                // Merge old and new systemSchedules
                systemSchedules.InsertRange(0, systemCanPerformList);//<--This was potentialSystemSchedules
                potentialSystemSchedules.Clear();
                // Print completion percentage in command window
                Console.Write("Scheduler Status: {0} done; {1} schedules generated.", 100 * currentTime / _endTime, systemSchedules.Count);
            }


            if (systemSchedules.Count > _maxNumSchedules)
            {
                CropSchedules(systemSchedules, scheduleEvaluator, emptySchedule);
            }

            // THIS GOES AWAY IF CAN EXTEND HAPPENS IN THE SUBSYSTEM - EAM
            // extend all schedules to the end of the simulation

            /*
             * foreach (var schedule in systemSchedules)
             * {
             *  bool canExtendUntilEnd = true;
             *  // Iterate through Subsystem Nodes and set that they havent run
             *  foreach (var subsystem in system.Subsystems)
             *      subsystem.IsEvaluated = false;
             *
             *  int subAssetNum;
             *  foreach (var subsystem in system.Subsystems)
             *      canExtendUntilEnd &= subsystem.canPerform(schedule.getSubsystemNewState(subsystem.Asset), schedule.getSubsytemNewTask(subsystem.Asset), system.Environment, _endTime, true);
             *
             *  // Iterate through constraints
             *  foreach (var constraint in system.Constraints)
             *  {
             *      canExtendUntilEnd &= constraint.Accepts(schedule);
             *  }
             *  //                for (vector <const Constraint*>::const_iterator constraintIt = system.getConstraints().begin(); constraintIt != system.getConstraints().end(); constraintIt++)
             *  //            canExtendUntilEnd &= (*constraintIt)->accepts(*schedIt);
             *  if (!canExtendUntilEnd) {
             *      //delete *schedIt;
             *      Console.WriteLine("Schedule may not be valid");
             *  }
             * }
             */

            //DWORD endSchedTickCount = GetTickCount();
            //schedTimeMs = endSchedTickCount - startSchedTickCount;

            //DWORD endTickCount = GetTickCount();
            //totalTimeMs = endTickCount - startTickCount;

            return(systemSchedules);
        }
Esempio n. 23
0
        static int Main(string[] args)
        {
            // Begin the Logger
            ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            log.Info("STARTING HSF RUN"); //Do not delete

            // Set Defaults
            var simulationInputFilePath = @"..\..\..\SimulationInput.XML";
            var targetDeckFilePath = @"..\..\..\v2.2-300targets.xml";
            var modelInputFilePath = @"..\..\..\DSAC_Static.xml";
            bool simulationSet = false, targetSet = false, modelSet = false;

            // Get the input filenames
            int i = 0;
            foreach(var input in args)
            {
                i++;
                switch (input)
                {
                    case "-s":
                        simulationInputFilePath = args[i];
                        simulationSet = true;
                        break;
                    case "-t":
                        targetDeckFilePath = args[i];
                        targetSet = true;
                        break;
                    case "-m":
                        modelInputFilePath = args[i];
                        modelSet = true;
                        break;
                }
            }
            ///add usage statement

            if (!simulationSet)
            {
                log.Info("Using Default Simulation File");
            }

            if (!targetSet)
            {
                log.Info("Using Default Target File");
            }

            if (!modelSet)
            {
                log.Info("Using Default Model File");
            }


            // Initialize Output File
            var outputFileName = string.Format("output-{0:yyyy-MM-dd}-*", DateTime.Now);
            var outputPath = @"C:\HorizonLog\";
            var txt = ".txt";
            string[] fileNames = System.IO.Directory.GetFiles(outputPath, outputFileName, System.IO.SearchOption.TopDirectoryOnly);
            double number = 0;
            foreach (var fileName in fileNames)
            {
                char version = fileName[fileName.Length - txt.Length-1];
                if(number < Char.GetNumericValue(version))
                    number = Char.GetNumericValue(version);
            }
            number++;
            outputFileName = outputFileName.Remove(outputFileName.Length - 1) + number;
            outputPath += outputFileName + txt;
            // Find the main input node from the XML input files
            XmlNode evaluatorNode = XmlParser.ParseSimulationInput(simulationInputFilePath);

            // Load the target deck into the targets list from the XML target deck input file
            Stack<Task> systemTasks = new Stack<Task>();
            bool targetsLoaded = Task.loadTargetsIntoTaskList(XmlParser.GetTargetNode(targetDeckFilePath), systemTasks);
            if (!targetsLoaded)
            {
                return 1;
            }

            // Find the main model node from the XML model input file
            var modelInputXMLNode = XmlParser.GetModelNode(modelInputFilePath);

            // Load the environment. First check if there is an ENVIRONMENT XMLNode in the input file
            Universe SystemUniverse = null;

            //Create singleton dependency dictionary
            Dependency dependencies = Dependency.Instance;

            // Initialize List to hold assets and subsystem nodes
            List<Asset> assetList = new List<Asset>();
            List<Subsystem> subList = new List<Subsystem>();

            // Maps used to set up preceeding nodes
            Dictionary<ISubsystem, XmlNode> subsystemXMLNodeMap = new Dictionary<ISubsystem, XmlNode>();
            Dictionary<string, Subsystem> subsystemMap = new Dictionary<string, Subsystem>();
            List<KeyValuePair<string, string>> dependencyMap = new List<KeyValuePair<string, string>>();
            List<KeyValuePair<string, string>> dependencyFcnMap = new List<KeyValuePair<string, string>>();
            // Dictionary<string, ScriptedSubsystem> scriptedSubNames = new Dictionary<string, ScriptedSubsystem>();

            // Create Constraint list 
            List<Constraint> constraintsList = new List<Constraint>();

            //Create Lists to hold all the initial condition and dependency nodes to be parsed later
            List<XmlNode> ICNodes = new List<XmlNode>();
            List<XmlNode> DepNodes = new List<XmlNode>();
            SystemState initialSysState = new SystemState();

            // Set up Subsystem Nodes, first loop through the assets in the XML model input file
            foreach (XmlNode modelChildNode in modelInputXMLNode.ChildNodes)
            {
                if (modelChildNode.Name.Equals("ENVIRONMENT"))
                {
                    // Create the Environment based on the XMLNode
                    SystemUniverse = new Universe(modelChildNode);
                }
                if (modelChildNode.Name.Equals("ASSET"))
                {
                    Asset asset = new Asset(modelChildNode);
                    assetList.Add(asset);
                    // Loop through all the of the ChildNodess for this Asset
                    foreach (XmlNode childNode in modelChildNode.ChildNodes)
                    {
                        // Get the current Subsystem XML Node, and create it using the SubsystemFactory
                        if (childNode.Name.Equals("SUBSYSTEM"))
                        {  //is this how we want to do this?
                            // Check if the type of the Subsystem is scripted, networked, or other
                            string subName = SubsystemFactory.GetSubsystem(childNode, dependencies, asset, subsystemMap);
                            foreach (XmlNode ICorDepNode in childNode.ChildNodes)
                            {
                                if(ICorDepNode.Name.Equals("IC"))
                                    ICNodes.Add(ICorDepNode);
                                if (ICorDepNode.Name.Equals("DEPENDENCY"))
                                {
                                    string depSubName = "", depFunc = "";
                                    depSubName = Subsystem.parseNameFromXmlNode(ICorDepNode, asset.Name) ;
                                    dependencyMap.Add(new KeyValuePair<string, string>(subName, depSubName));

                                    if (ICorDepNode.Attributes["fcnName"] != null)
                                    {
                                        depFunc = ICorDepNode.Attributes["fcnName"].Value.ToString();
                                        dependencyFcnMap.Add(new KeyValuePair<string, string>(subName, depFunc));
                                    }
                                }  
                            }
                        }
                        //Create a new Constraint
                        if (childNode.Name.Equals("CONSTRAINT"))
                        {
                            constraintsList.Add(ConstraintFactory.GetConstraint(childNode, subsystemMap, asset));
                        }
                    }
                    if (ICNodes.Count > 0)
                        initialSysState.Add(SystemState.setInitialSystemState(ICNodes, asset));
                    ICNodes.Clear();
                }
            }
            if (SystemUniverse == null)
                SystemUniverse = new Universe();

            foreach (KeyValuePair<string, Subsystem> sub in subsystemMap)
            {
                if(!sub.Value.GetType().Equals(typeof(ScriptedSubsystem)))//let the scripted subsystems add their own dependency collector
                    sub.Value.AddDependencyCollector();
                subList.Add(sub.Value);
            }
            log.Info("Subsystems and Constraints Loaded");

            //Add all the dependent subsystems to the dependent subsystem list of the subsystems
            foreach (KeyValuePair<string, string> depSubPair in dependencyMap)
            {
                Subsystem subToAddDep, depSub;
                subsystemMap.TryGetValue(depSubPair.Key, out subToAddDep);
                subsystemMap.TryGetValue(depSubPair.Value, out depSub);
                subToAddDep.DependentSubsystems.Add(depSub);
            }

            //give the dependency functions to all the subsytems that need them
            foreach (KeyValuePair<string, string> depFunc in dependencyFcnMap)
            {
                Subsystem subToAddDep;
                subsystemMap.TryGetValue(depFunc.Key, out subToAddDep);
                subToAddDep.SubsystemDependencyFunctions.Add(depFunc.Value, dependencies.GetDependencyFunc(depFunc.Value));
            }
            log.Info("Dependencies Loaded");

            SystemClass simSystem = new SystemClass(assetList, subList, constraintsList, SystemUniverse);

            if (simSystem.CheckForCircularDependencies())
                throw new NotFiniteNumberException("System has circular dependencies! Please correct then try again.");

            Evaluator schedEvaluator = EvaluatorFactory.GetEvaluator(evaluatorNode, dependencies);
            Scheduler scheduler = new Scheduler(schedEvaluator);
            List<SystemSchedule> schedules = scheduler.GenerateSchedules(simSystem, systemTasks, initialSysState);
            // Evaluate the schedules and set their values
            foreach (SystemSchedule systemSchedule in schedules)
            {
                systemSchedule.ScheduleValue = schedEvaluator.Evaluate(systemSchedule);
                bool canExtendUntilEnd = true;
                // Extend the subsystem states to the end of the simulation 
                foreach (var subsystem in simSystem.Subsystems)
                {
                    if(systemSchedule.AllStates.Events.Count >0)
                        if (!subsystem.CanExtend(systemSchedule.AllStates.Events.Peek(), simSystem.Environment, SimParameters.SimEndSeconds))
                            log.Error("Cannot Extend " + subsystem.Name + " to end of simulation");
                }
            }

            // Sort the sysScheds by their values
            schedules.Sort((x, y) => x.ScheduleValue.CompareTo(y.ScheduleValue));
            schedules.Reverse();
            double maxSched = schedules[0].ScheduleValue;
            i = 0;
            //Morgan's Way
            using (StreamWriter sw = File.CreateText(outputPath))
            {
                foreach (SystemSchedule sched in schedules)
                {
                    sw.WriteLine("Schedule Number: " + i + "Schedule Value: " + schedules[i].ScheduleValue);
                    foreach (var eit in sched.AllStates.Events)
                    {
                        if (i < 5)//just compare the first 5 schedules for now
                        { 
                            sw.WriteLine(eit.ToString());
                        }
                    }
                    i++;
            }
            log.Info("Max Schedule Value: " + maxSched);
            }

            // Mehiel's way
            string stateDataFilePath = @"C:\HorizonLog\" + string.Format("output-{0:yyyy-MM-dd-hh-mm-ss}", DateTime.Now);
            SystemSchedule.WriteSchedule(schedules[0], stateDataFilePath);

            var csv = new StringBuilder();
            csv.Clear();
            foreach (var asset in simSystem.Assets)
            {
                File.WriteAllText(@"..\..\..\" + asset.Name + "_dynamicStateData.csv", asset.AssetDynamicState.ToString());
            }
            return 0;
            //   Console.ReadKey();
        }
Esempio n. 24
0
 //页面更新部分
 private void RefreshPagesShow()
 {
     SystemState.SetUserControlInfo(SystemStateInfo);//设置系统状态
     FaultPage1.UpdateStateView();
 }
 private void OnMessageReceived(AsynchronousMessageQueue queue, SystemMessage message)
 {
     if (message.ChannelName == SystemMessaging.CHANNEL)
     {
         SystemMessaging.MessageType messageType = (SystemMessaging.MessageType)message.MessageType;
         switch (messageType)
         {
         case SystemMessaging.MessageType.SystemStateChanged:
             SystemState newState = (SystemState)message.MessageData[SystemMessaging.NEW_STATE];
             if (newState == SystemState.Resuming)
             {
                 // Signal the event, callback is executed after timeout, see OnResume
                 _resumeEvent.EnqueueEvent(this, EventArgs.Empty);
             }
             if (newState == SystemState.Suspending)
             {
                 ServiceRegistration.Get <ILogger>().Info("SlimTvClientModel: System suspending, stopping all SlimTV players");
                 IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();
                 for (int index = 0; index < playerContextManager.NumActivePlayerContexts; index++)
                 {
                     IPlayerContext playerContext = playerContextManager.GetPlayerContext(index);
                     if (playerContext != null && playerContext.CurrentMediaItem is LiveTvMediaItem ltvi)
                     {
                         if (ltvi.AdditionalProperties.ContainsKey(LiveTvMediaItem.CHANNEL))
                         {
                             _ = UpdateWatchDuration((IChannel)ltvi.AdditionalProperties[LiveTvMediaItem.CHANNEL]);
                         }
                         playerContext.Stop();
                         _tvWasActive = true;
                     }
                 }
             }
             break;
         }
     }
     else if (message.ChannelName == ServerStateMessaging.CHANNEL)
     {
         //Check if Tv Server state has changed and update if necessary
         ServerStateMessaging.MessageType messageType = (ServerStateMessaging.MessageType)message.MessageType;
         if (messageType == ServerStateMessaging.MessageType.StatesChanged)
         {
             var states = message.MessageData[ServerStateMessaging.STATES] as IDictionary <Guid, object>;
             if (states != null && states.ContainsKey(TvServerState.STATE_ID))
             {
                 ServerState = states[TvServerState.STATE_ID] as TvServerState;
             }
         }
     }
     else if (message.ChannelName == PlayerManagerMessaging.CHANNEL)
     {
         PlayerManagerMessaging.MessageType messageType = (PlayerManagerMessaging.MessageType)message.MessageType;
         switch (messageType)
         {
         case PlayerManagerMessaging.MessageType.PlayerStopped:
         case PlayerManagerMessaging.MessageType.PlayerEnded:
             if (_lastTunedChannel != null)
             {
                 _ = UpdateWatchDuration(_lastTunedChannel);
             }
             break;
         }
     }
 }
Esempio n. 26
0
 private void ProcessPosition(DateTime ts, SystemState systemState, int positionIndex, Func<Position, StockPricesData, int, float> closePriceSelector, StockPricesData pricesData, int pricesDataIndex)
 {
     systemState.Close(positionIndex, ts, closePriceSelector(systemState.PositionsActive[positionIndex], pricesData, pricesDataIndex), _slippage, _commission);
 }
Esempio n. 27
0
 public static bool IsShopifyUrlFinalized(this SystemState state)
 {
     return(state.ShopifyConnState != StateCode.None);
 }
Esempio n. 28
0
 public static bool CanSyncOrdersToAcumatica(this SystemState state)
 {
     return(state.AcumaticaConnState == StateCode.Ok &&
            state.AcumaticaRefDataState == StateCode.Ok &&
            state.WarehouseSyncState == StateCode.Ok);
 }
Esempio n. 29
0
 public static void ResetSystemState()
 {
     sys = SystemState.internalState;
 }
Esempio n. 30
0
        public void select(Dock dock, ScrollBar sBar, AttractorWeight weight, List<Photo> photos, List<Photo> activePhotos, List<Stroke> strokes, SystemState systemState)
        {
            
            weight_ = weight.NonOverlapWeight;
            //List<Stroke> strokes = strokeCol.strokeList;
            for (int i = 0, ilen = strokes.Count; i < ilen; ++i)
            {
                if (strokes[i].IsClosed)
                {
                    foreach (Photo a in photos)
                    {
                        Vector2 v = Vector2.Zero;
                        // 到最近锚点的矢量
                        Vector2 v2n = Vector2.One * float.MaxValue;
                        foreach (Vector2 s in strokes[i].Strokes)
                        {
                            Vector2 dist = s - a.Position;
                            if (dist.LengthSquared() < v2n.LengthSquared())
                            {
                                v2n = dist;
                            }
                        }
                        bool inner = strokes[i].IsInternal(a.Position);
#if STRICT
                            bool inner1 = strokes[i][j].IsInternal(a.BoudingBox.Min);
                            bool inner2 = strokes[i][j].IsInternal(new Vector2(a.BoudingBox.Min.X, a.BoudingBox.Max.Y));
                            bool inner3 = strokes[i][j].IsInternal(a.boudingBox_.Max);
                            bool inner4 = strokes[i][j].IsInternal(new Vector2(a.BoudingBox.Max.X, a.BoudingBox.Min.Y));
                            if(inner || inner1 || inner2 || inner3 || inner4)
                            {
#else
                        if (inner)
                        {
#endif
                            int matchedTagCount = 0;
                            foreach (string t in strokes[i].Tags)
                            {
                                if (a.containTag(t))
                                {
                                    ++matchedTagCount;
                                    break;
                                }
                            }
                            if (matchedTagCount == 0)
                            {
                                v += v2n;
                                v += (a.Position - strokes[i].Center);
                                v *= 0.02f * INTO_DISPLAY * weight_;
                            }
#if STRICT
                            }
                            if (!inner || !inner1 || !inner2 || !inner3 || !inner4)
                            {
#else
                        }
                        else
                        {
#endif
                            int matchedTagCount = 0;
                            foreach (string t in strokes[i].Tags)
                            {
                                if (a.containTag(t))
                                {
                                    ++matchedTagCount;
                                    break;
                                }
                            }
                            if (matchedTagCount > 0)
                            {
                                v += v2n;
                                v += (strokes[i].Center - a.Position);
                                v *= 0.02f * INTO_DISPLAY * weight_;
                            }
                        }
                        // 添加噪音
                        if (false)
                        {
                            if (v != Vector2.Zero)
                            {
                                float variance = weight.NoiseWeight * 0.5f;
                                Vector2 noise = new Vector2((float)randbm.NextDouble(variance), (float)randbm.NextDouble(variance));
                                v += noise;
                            }
                        }
                        a.AddPosition(v);
                    }
                }
                
            }
        }
    }
        internal TopReflectedPackage GetReflectedAssembly(SystemState state, Assembly assem)
        {
            Debug.Assert(assem != null);
            lock (this) {
                TopReflectedPackage reflectedAssembly;
                if (assemblyMap.TryGetValue(assem, out reflectedAssembly))
                    return reflectedAssembly;

                reflectedAssembly = new TopReflectedPackage(true);
                reflectedAssembly.LoadAssembly(state, assem);
                assemblyMap[assem] = reflectedAssembly;

                return reflectedAssembly;
            }
        }
Esempio n. 32
0
    static void Main(string[] args)
    {
        SystemState systemState = new SystemState();

        CommandInterpreter.ExecuteCommands(systemState);
    }
Esempio n. 33
0
        private void SetupSystemStates()
        {
            this.timeState = new SystemState(SystemProperty.Time);
            this.batteryLevelState = new SystemState(SystemProperty.PowerBatteryStrength);
            this.batteryChargeState = new SystemState(SystemProperty.PowerBatteryState);

            this.Invoke(new MethodInvoker(delegate
            {
                this.timeState.Changed += new ChangeEventHandler(timeState_Changed);
                this.batteryLevelState.Changed += new ChangeEventHandler(batteryLevelState_Changed);
                this.batteryChargeState.Changed += new ChangeEventHandler(batteryChargeState_Changed);
            }));
        }
Esempio n. 34
0
 public void OnUpdate(ref SystemState state)
 {
 }
Esempio n. 35
0
 public static bool CanPollDataFromAcumatica(this SystemState state)
 {
     return(state.AcumaticaConnState == StateCode.Ok);
 }
 public ClientSystemStateMob(SystemState systemState)
 {
     this.systemState = systemState;
 }
 public void SetUp()
 {
     _state   = new SystemState();
     _summary = new SystemStateSummary();
 }
 public void OnCreate(ref SystemState state)
 {
     createdFlag = 16;
 }
 public void OnDestroy(ref SystemState state)
 {
     *Ptr |= 1 | createdFlag;
 }
Esempio n. 40
0
 /// <summary>
 /// 启动短信监听
 /// </summary>
 internal void Start()
 {
     systemState=new  SystemState(SystemProperty.PhoneIncomingCall);
     systemState.Changed += new ChangeEventHandler(systemState_Changed);
 }
 public LeagueBuildUtilitiesConfiguration(SystemState systemState) {
    this.systemState = systemState;
    this.isLoggingEnabled = systemState.Get(kEnableBuildLoggingKey, false);
 }
Esempio n. 42
0
 /// <summary>
 ///  Creates a new empty schedule with the given initial state.
 /// </summary>
 /// <param name="initialState"></param>
 public StateHistory(SystemState initialState)
 {
     InitialState = initialState;
     Events = new Stack<Event>();
 }
 public void OnStartRunning(ref SystemState state)
 {
     *Ptr |= 2;
 }
Esempio n. 44
0
 public static bool CanSyncRefundsToAcumatica(this SystemState state)
 {
     return(state.CanSyncOrdersToAcumatica());
 }
Esempio n. 45
0
 public Game()
 {
     CurrentSystemState = SystemState.NAME;
 }
Esempio n. 46
0
 private float GetTotalValue(SystemState systemState) => systemState.Cash;
Esempio n. 47
0
        //public void getInitialStateFromXmlNode(XmlNode ICXmlNode)
        //{
        //    Type keyType = Type.GetType(ICXmlNode.Attributes["type"].Value.ToString());
        //    string key = ICXmlNode.Attributes["key"].Value.ToString();
        //    string value = ICXmlNode.Attributes["value"].ToString();
        //    if(keyType)
        //    StateVarKey <keyType.GetType()> = new StateVarKey<keyType.GetType() > (key);
        //    .ChangeType(value, keyType);
        //}

        /// <summary>
        /// Method to get subsystem state at a given time. Should be used for writing out state data
        /// </summary>
        /// <param name="currentSystemState"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public SystemState getSubStateAtTime(SystemState currentSystemState, double time)
        {
            SystemState state = new SystemState();
            foreach(var key in Ikeys)
            {
                state.Idata.Add(key, new HSFProfile<int>(time, currentSystemState.GetValueAtTime(key, time).Value));
            }
            foreach (var key in Bkeys)
            {
                state.Bdata.Add(key, new HSFProfile<bool>(time, currentSystemState.GetValueAtTime(key, time).Value));
            }
            foreach (var key in Dkeys)
            {
                state.Ddata.Add(key, new HSFProfile<double>(time, currentSystemState.GetValueAtTime(key, time).Value));
            }
            foreach (var key in Mkeys)
            {
                state.Mdata.Add(key, new HSFProfile<Matrix<double>>(time, currentSystemState.GetValueAtTime(key, time).Value));
            }
            return state;
        }
 public void OnUpdate(ref SystemState state)
 {
     ++UpdateCount;
 }
Esempio n. 49
0
        private void Main_Load(object sender, EventArgs e)
        {
            outlook = new OutlookSession();

            gps = new Gps();
            gps.Open();

            #region SMS Interception Setup

            smsInterceptor = new MessageInterceptor(InterceptionAction.NotifyAndDelete);

            smsInterceptor.MessageCondition = new MessageCondition(
                MessageProperty.Sender,
                MessagePropertyComparisonType.Equal,
                "+14254448851");

            smsInterceptor.MessageReceived += new MessageInterceptorEventHandler(smsInterceptor_MessageReceived);

            #endregion

            #region State Notification Setup

            umtsAvailable = new SystemState(SystemProperty.CellularSystemAvailableUmts);
            umtsAvailable.ComparisonType = StatusComparisonType.AnyChange;
            umtsAvailable.Changed += new ChangeEventHandler(umtsAvailable_Changed);

            detailsMenuItem.Enabled =
                ((int)umtsAvailable.CurrentValue & SN_CELLSYSTEMAVAILABLE_UMTS_BITMASK) != 0;

            #endregion
        }
Esempio n. 50
0
 /// <summary>
 ///  Creates a new empty schedule with the given initial state.
 /// </summary>
 /// <param name="initialState"></param>
 public StateHistory(SystemState initialState)
 {
     InitialState = initialState;
     Events       = new Stack <Event>();
 }
Esempio n. 51
0
 /// <summary>
 /// Applies the constraint to the appropriate variables in the given state,
 /// that contains updated state data for all the requested Subsystems.
 /// </summary>
 /// <param name="state"></param>
 /// <returns></returns>
 public virtual bool Accepts(SystemState state)
 {
     return false;
 }
 public void OnCreate(ref SystemState state)
 {
 }
 /// <summary>
 /// Changes the state to.
 /// </summary>
 /// <param name="state">The state.</param>
 public void ChangeStateTo(SystemState state)
 {
     this.CurrentState = state;
     OnSystemStateChanged(state);
 }
 public void OnDestroy(ref SystemState state)
 {
 }
Esempio n. 55
0
 /**
  * Creates an Event, in which the Task was performed by an Asset, and the time history
  * of the pertinent State information was saved.
  * @param task The Task that was performed.
  * @param state The time history of the Asset State during the Event.
  */
 public Event(Task task, SystemState state)
 {
     Task  = task;
     State = state;
 }
Esempio n. 56
0
        /// <summary>
        /// Inicializace okna
        /// </summary>
        private void MainForm_Load(object sender, EventArgs e)
        {
            // GPS inicializace
            updateDataHandler = new EventHandler(UpdateData);
            gps.DeviceStateChanged += new DeviceStateChangedEventHandler(gps_DeviceStateChanged);
            gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged);

            // INI soubor
            ini = new IniFile(path + "\\settings.ini");

            // Sledovani preklopeni displeje
            orientationWatcher = new SystemState(SystemProperty.DisplayRotation);
            orientationWatcher.Changed += new ChangeEventHandler(OrientationWatcher_Changed);

            // Inicializace
            Layout();
            IniLoad();
            DatabaseLoad();
            MapLoad();

            // GPX databazovy soubor
            openFileDialog1.FileName = settings[0];
            openFileDialog1.Filter = "XML file (.xml)|*.xml|GPX file (.gpx)|*.gpx";
            openFileDialog1.FilterIndex = 1;

            // XML mapovy soubor
            openFileDialog2.FileName = settings[1];
            openFileDialog2.Filter = "XML file (.xml)|*.xml";
            openFileDialog2.FilterIndex = 1;
            comboBox1.SelectedIndex = selectedMap;
            Map map = (Map)maps[selectedMap];
            try
            {
                mapImage = new Bitmap(pathMap + map.File);
            }
            catch
            {
                mapImage = null;
            }
        }
 public void OnStopRunning(ref SystemState state)
 {
     *Ptr |= 4;
 }
Esempio n. 58
0
 public static bool CanPollDataFromShopify(this SystemState state)
 {
     return(state.ShopifyConnState == StateCode.Ok);
 }
Esempio n. 59
0
 /// <summary>
 /// Stopt den Listener zur erfassung der Displayausrichtung.
 /// </summary>
 private string StopObserveOrientation(Dictionary<string, string> parameter)
 {
     // MessageBox.Show("Device.GetInfo [ Stope server ]");
     if (displayOrientation == null)
     {
         //deviceThread = null;
         return "";
     }
     displayOrientation.Changed -= new ChangeEventHandler(displayOrientation_Changed);
     displayOrientation = null;
     //deviceThread = null;
     return "";
 }
 public void OnUpdate(ref SystemState state)
 {
     *Ptr |= 8;
 }