Exemplo n.º 1
0
        public void TestConstructor()
        {
            AgentList agentList = new();

            // Make sure there are the right number of agents in each list
            Assert.AreEqual(GameService.AGENT_TYPES_ORDERED.Length, agentList.Count);
            Assert.AreEqual(agentList.Count, agentList.OrderedList.Count);
            Assert.AreEqual(agentList.Count, agentList.ShuffledList.Count);
            int numAllies = GameService.AGENT_TYPES_ORDERED.Select(a => a.Instantiate <Agent>()).Where(a => a.Allegiance == Allegiance.Ally).Count();

            Assert.AreEqual(numAllies, agentList.PlayerAgents.Count);

            // Make sure all of the agent types are in each list exactly once
            foreach (Type type in GameService.AGENT_TYPES_ORDERED)
            {
                Assert.DoesNotThrow(() => _ = agentList[type.Name]);
                Assert.DoesNotThrow(() => agentList.OrderedList.Single(a => a.GetType() == type));
                Assert.DoesNotThrow(() => agentList.ShuffledList.Single(a => a.GetType() == type));

                if (type.Instantiate <Agent>().Allegiance == Allegiance.Ally)
                {
                    Assert.DoesNotThrow(() => agentList.PlayerAgents.Single(a => a.GetType() == type));
                }
            }

            // Make sure the shuffled list is actually shuffled
            Assert.IsFalse(agentList.OrderedList.SequenceEqual(agentList.ShuffledList));

            // Make sure the shuffling produces a different list each time
            AgentList agentList2 = new AgentList();

            Assert.IsFalse(agentList.ShuffledList.SequenceEqual(agentList2.ShuffledList));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Executes agent initializing. It's the first initializing step.
        /// </summary>
        protected override void InitializeAgents()
        {
            agentList = new AgentList();
            agentList.Initialize(configuration);

            numberOfAgentsAfterInitialize = agentList.Agents.Count;
        }
Exemplo n.º 3
0
        public override void SelectTarget(AgentList agents)
        {
            List <Agent> validTargets = agents.ShuffledList.Where(a => a != this && a.IsActive).ToList();

            if (validTargets.Any())
            {
                Target   = validTargets[GameService.Random.Next(validTargets.Count)];
                IsActing = true;
            }
        }
 private void SetDefaults(UserSettings settings)
 {
     SelectedEnvironment   = EnvironmentList?.FirstOrDefault(env => env == settings.Environment);
     SelectedAgentLocation =
         AgentLocationList.FirstOrDefault(loc => loc.AgentStateCode == settings.AgentLocation) ??
         AgentLocationList.First();
     SelectedAgent = AgentList.FirstOrDefault(agent => agent.AgentId == settings.AgentId) ??
                     AgentList.First();
     SelectedAgentPos = AgentPosList.FirstOrDefault(agentPos => agentPos.AgentSequence == settings.AgentPosId) ??
                        AgentPosList.First();
 }
 private void AgentManagementChange(AgentManagementChangedEvent obj)
 {
     LoadAgents();
     RaisePropertyChanged(nameof(EnvironmentList));
     RaisePropertyChanged(nameof(AgentLocationList));
     SelectedAgentLocation = AgentLocationList.First();
     RaisePropertyChanged(nameof(SelectedAgentLocation));
     RaisePropertyChanged(nameof(AgentList));
     SelectedAgent = AgentList.First();
     RaisePropertyChanged(nameof(SelectedAgent));
     RaisePropertyChanged(nameof(AgentPosList));
 }
Exemplo n.º 6
0
        public override void SelectTarget(AgentList agents)
        {
            List <Agent> validTargets = agents.ShuffledList.Where(a => a != this && a.Allegiance == Allegiance.Ally && a.IsActive).ToList();

            if (validTargets.Any())
            {
                Target = validTargets[GameService.Random.Next(validTargets.Count)];
            }

            // The sleeper is special - they pick a target but do nothing unless executed
            IsActing = false;
        }
Exemplo n.º 7
0
        public override void SelectTarget(AgentList agents)
        {
            if (GameService.Random.NextDouble() <= CHANCE_TO_ATTACK)
            {
                List <Agent> validTargets = agents.ShuffledList.Where(a => a != this && a.IsActive && a is not Mastermind).ToList();

                if (validTargets.Any())
                {
                    Target   = validTargets[GameService.Random.Next(validTargets.Count)];
                    IsActing = true;
                }
            }
        }
Exemplo n.º 8
0
        /// <inheritdoc />
        protected override void InitializeAgents()
        {
            var agents = new List <IAgent>();

            Dictionary <string, AgentPrototype> agentPrototypes = _configuration.AgentConfiguration;

            if (agentPrototypes.Count == 0)
            {
                throw new SosielAlgorithmException("Agent prototypes were not defined. See configuration file");
            }

            InitialStateConfiguration initialState = _configuration.InitialState;

            var networks = new Dictionary <string, List <SOSIEL.Entities.Agent> >();


            //create agents, groupby is used for saving agents numeration, e.g. CEA1, FE1, HM1. HM2 etc
            initialState.AgentsState.GroupBy(state => state.PrototypeOfAgent).ForEach((agentStateGroup) =>
            {
                prototype = agentPrototypes[agentStateGroup.Key];

                var mentalProto = prototype.MentalProto;

                agentStateGroup.ForEach((agentState) =>
                {
                    for (int i = 0; i < agentState.NumberOfAgents; i++)
                    {
                        Agent agent = Agent.CreateAgent(agentState, prototype);
                        agent.SetId(generalAgentIndex);
                        agent.IsActive = true;

                        agentState.PrivateVariables.ForEach((privateVariable) => {
                            if (privateVariable.Value == "Sharer")
                            {
                                agent.Contrib = true;
                            }
                            else
                            {
                                agent.Contrib = false;
                            }
                        });
                        agents.Add(agent);

                        generalAgentIndex++;
                    }
                });
            });

            agentList = new AgentList(agents, agentPrototypes.Select(kvp => kvp.Value).ToList());
            Console.WriteLine("---Agents are initialized");
        }
        public void AgentList_CheckProperties()
        {
            AgentInfo info1 = new AgentInfo(10, AgentInfo.PossibleAgentType.ExcuseGenerator);
            AgentInfo info2 = new AgentInfo(11, AgentInfo.PossibleAgentType.WhiningSpinner);
            AgentInfo info3 = new AgentInfo(12, AgentInfo.PossibleAgentType.BrilliantStudent);

            AgentList list = new AgentList();
            list.Add(info1);
            list.Add(info2);
            list.Add(info3);
            Assert.AreSame(info1, list[0]);
            Assert.AreSame(info2, list[1]);
            Assert.AreSame(info3, list[2]);
        }
Exemplo n.º 10
0
        public void CreateInitialPopulation()
        {
            // initial population
            this.Population = new List <Gen>();

            for (int i = 0; i < this.GenerationsNumber; i++)
            {
                // ingresa uin nuevo gen a la poblacion
                List <Agent> AgentListAux = AgentList.Select(agent => new Agent(agent)).ToList();
                Gen          gen          = new Gen(AgentListAux);
                gen.CreateGen(RequestedServiceList);
                this.Population.Add(gen);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Executes agent initializing. It's the first initializing step.
        /// </summary>
        protected override void InitializeAgents()
        {
            // Debugger.Launch();
            _log.WriteLine("  SosielHarvestAlgorithm: Initializing agents...");
            var agents          = new List <IAgent>();
            var agentArchetypes = _configuration.AgentArchetypeConfiguration;

            if (agentArchetypes.Count == 0)
            {
                throw new SosielAlgorithmException("Agent archetypes are not defined. Please check configuration files");
            }

            // Create agents, groupby is used for saving agents numeration, e.g. FE1, HM1, HM2, etc.
            _configuration.InitialState.AgentStates.Where(s => s.Mode == _sheMode)
            .GroupBy(state => state.Archetype)
            .ForEach((agentStateGroup) =>
            {
                int index       = 1;
                var archetype   = agentArchetypes[agentStateGroup.Key];
                var mentalProto = archetype.MentalProto; //do not remove
                agentStateGroup.ForEach((agentState) =>
                {
                    for (var i = 0; i < agentState.NumberOfAgents; i++)
                    {
                        var name = agentState.Name;
                        if (string.IsNullOrEmpty(name) || agentState.NumberOfAgents > 1)
                        {
                            name = $"{agentState.Archetype}{index}";
                        }
                        var agent = SosielHarvestAgent.Create(agentState, archetype, name);
                        agents.Add(agent);
                        index++;
                    }
                });

                agents.ForEach(agent =>
                {
                    if (agent.ContainsVariable(AlgorithmVariables.Group))
                    {
                        agent.ConnectedAgents.AddRange(agents.Where(
                                                           a => a != agent && a.ContainsVariable(AlgorithmVariables.Group) &&
                                                           a[AlgorithmVariables.Group] == agent[AlgorithmVariables.Group]));
                    }
                });
            });

            agentList = new AgentList(agents, agentArchetypes.Select(kvp => kvp.Value).ToList());
            numberOfAgentsAfterInitialize = agentList.Agents.Count;
        }
        public void AgentList_CheckProperties()
        {
            AgentInfo info1 = new AgentInfo(10, AgentInfo.PossibleAgentType.ExcuseGenerator);
            AgentInfo info2 = new AgentInfo(11, AgentInfo.PossibleAgentType.WhiningSpinner);
            AgentInfo info3 = new AgentInfo(12, AgentInfo.PossibleAgentType.BrilliantStudent);

            AgentList list = new AgentList();

            list.Add(info1);
            list.Add(info2);
            list.Add(info3);
            Assert.AreSame(info1, list[0]);
            Assert.AreSame(info2, list[1]);
            Assert.AreSame(info3, list[2]);
        }
Exemplo n.º 13
0
        /*Creara el nuevo gen en a sus padres(Cruce)*/
        public Gen CreateChildGen(Gen pParent1, Gen pParent2)
        {
            List <Agent> AgentListAux = AgentList.Select(agent => new Agent(agent)).ToList();

            List <Agent> crossedGen = Crossing(pParent1, pParent2);
            //Gen nuevo vacio
            Gen child = new Gen(AgentListAux);

            //Crea los objetos nuevos para no referenciar a objetos anteriores
            child.CreateChildGen(crossedGen, RequestedServiceList);

            child.Mutation(RequestedServiceList);
            child.ManipulatedMutation(RequestedServiceList);

            return(child);
        }
        public void AgentList_CheckEncodeAndDecode()
        {
            AgentInfo info1 = new AgentInfo(10, AgentInfo.PossibleAgentType.ExcuseGenerator);
            AgentInfo info2 = new AgentInfo(11, AgentInfo.PossibleAgentType.WhiningSpinner);
            AgentInfo info3 = new AgentInfo(12, AgentInfo.PossibleAgentType.BrilliantStudent);

            AgentList list1 = new AgentList();

            list1.Add(info1);
            list1.Add(info2);
            list1.Add(info3);

            ByteList bytes = new ByteList();

            list1.Encode(bytes);
            AgentList list2 = AgentList.Create(bytes);

            Assert.AreEqual(3, list2.Count);
            Assert.AreEqual(10, list2[0].Id);
            Assert.AreEqual(11, list2[1].Id);
            Assert.AreEqual(12, list2[2].Id);

            bytes.Clear();
            list1.Encode(bytes);
            bytes.GetByte();            // Read one byte, which will throw the length off
            try
            {
                list2 = AgentList.Create(bytes);
                Assert.Fail("Expected an exception to be thrown");
            }
            catch (ApplicationException)
            {
            }

            bytes.Clear();
            list1.Encode(bytes);
            bytes.Add((byte)100);       // Add a byte
            bytes.GetByte();            // Read one byte, which will make the ID wrong
            try
            {
                list2 = AgentList.Create(bytes);
                Assert.Fail("Expected an exception to be thrown");
            }
            catch (ApplicationException)
            {
            }
        }
Exemplo n.º 15
0
        //// The Win32 API methods
        //[DllImport("kernel32", SetLastError = true)]
        //static extern int WritePrivateProfileString(string section, string key, string value, string fileName);
        //[DllImport("kernel32", SetLastError = true)]
        //static extern int WritePrivateProfileString(string section, string key, int value, string fileName);
        //[DllImport("kernel32", SetLastError = true)]
        //static extern int WritePrivateProfileString(string section, int key, string value, string fileName);
        //[DllImport("kernel32")]
        //static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder result, int size, string fileName);
        //[DllImport("kernel32")]
        //static extern int GetPrivateProfileString(string section, int key, string defaultValue, [MarshalAs(UnmanagedType.LPArray)] byte[] result, int size, string fileName);
        //[DllImport("kernel32")]
        //static extern int GetPrivateProfileString(int section, string key, string defaultValue, [MarshalAs(UnmanagedType.LPArray)] byte[] result, int size, string fileName);
        #endregion


        private void AKcomSettings_Load(object sender, EventArgs e)
        {
            //if (File.Exists("c:\\Program Files\\AKcom\\AKcom.ini"))
            //{
            //    // Loop until the buffer has grown enough to fit the value
            //    for (int maxSize = 250; true; maxSize *= 2)
            //    {
            //        StringBuilder result = new StringBuilder(maxSize);

            //        int size = GetPrivateProfileString("CurrentAgent", "Name", "", result, maxSize, "c:\\Program Files\\AKcom\\AKcom.ini");

            //        if (size < maxSize - 1)
            //        {
            //            if (size == 0)
            //            {
            //                savedAgent = "";
            //            }
            //            else
            //            {
            //                savedAgent = result.ToString();
            //                break;
            //            }
            //        }
            //    }
            //}

            _serverPath = TaskTrayApplication.Properties.Settings.Default.LDAPserver;
            _searchPath = TaskTrayApplication.Properties.Settings.Default.SearchPath;
            _userAttr   = TaskTrayApplication.Properties.Settings.Default.UserAttr;
            _savedAgent = TaskTrayApplication.Properties.Settings.Default.AgentID;

            CSRs = null;
            CSRs = _objCPCC.GetAgents();

            foreach (Agent agnt in CSRs)
            {
                lstBxAgents.Items.Add(agnt.ID.ToString() + " -- " + agnt.FirstName + " " + agnt.LastName);
            }

            int fnd = lstBxAgents.FindString(_savedAgent);

            lstBxAgents.SelectedIndex = fnd;
            txtBxServerPath.Text      = _serverPath;
            txtBxSearchPath.Text      = _searchPath;
            txtBxUserAttr.Text        = _userAttr;
        }
Exemplo n.º 16
0
        public async Task <AgentList> GetAgentwithID([FromBody] int id)
        {
            string request = await _agentRepository.GetRequestID(id);

            var response = await _agentRepository.GetAgentwithID(request);

            AgentList agentList = new AgentList();

            agentList.Agent         = response.Item1;
            agentList.Bank          = response.Item2;
            agentList.Contact       = response.Item3;
            agentList.AgentBranches = response.Item4;
            agentList.Terminal      = response.Item5;
            agentList.BankFees      = response.Item6;
            agentList.Moa           = response.Item7;

            return(agentList);
        }
        public void AgentList_CheckEncodeAndDecode()
        {
            AgentInfo info1 = new AgentInfo(10, AgentInfo.PossibleAgentType.ExcuseGenerator);
            AgentInfo info2 = new AgentInfo(11, AgentInfo.PossibleAgentType.WhiningSpinner);
            AgentInfo info3 = new AgentInfo(12, AgentInfo.PossibleAgentType.BrilliantStudent);

            AgentList list1 = new AgentList();
            list1.Add(info1);
            list1.Add(info2);
            list1.Add(info3);

            ByteList bytes = new ByteList();
            list1.Encode(bytes);
            AgentList list2 = AgentList.Create(bytes);
            Assert.AreEqual(3, list2.Count);
            Assert.AreEqual(10, list2[0].Id);
            Assert.AreEqual(11, list2[1].Id);
            Assert.AreEqual(12, list2[2].Id);

            bytes.Clear();
            list1.Encode(bytes);
            bytes.GetByte();            // Read one byte, which will throw the length off
            try
            {
                list2 = AgentList.Create(bytes);
                Assert.Fail("Expected an exception to be thrown");
            }
            catch (ApplicationException)
            {
            }

            bytes.Clear();
            list1.Encode(bytes);
            bytes.Add((byte)100);       // Add a byte
            bytes.GetByte();            // Read one byte, which will make the ID wrong
            try
            {
                list2 = AgentList.Create(bytes);
                Assert.Fail("Expected an exception to be thrown");
            }
            catch (ApplicationException)
            {
            }
        }
Exemplo n.º 18
0
        public List <ClientModel> clientListToModelViewList(List <Client> clientList)
        {
            object             objectLock = new object();
            List <ClientModel> output     = new List <ClientModel>();

            lock (objectLock)
                foreach (Client client in clientList)
                {
                    ClientModel cvm = (ClientModel)_main.ModelCreator.createModel(QOBDModels.Enums.EModel.CLIENT);
                    if (AgentList.Count() > 0)
                    {
                        var result = AgentList.Where(x => x.ID.Equals(client.AgentId)).ToList();
                        cvm.Agent.Agent = (result.Count > 0) ? result[0] : new Agent();
                    }
                    cvm.Client = client;
                    output.Add(cvm);
                }
            return(output);
        }
 public ActionResult Save(AgentList list)
 {
     if (list.Id == 0)
     {
         _context.Agent_List.Add(list);
     }
     else
     {
         var agentListInDb = _context.Agent_List.Single(c => c.Id == list.Id);
         agentListInDb.CODE        = list.CODE;
         agentListInDb.NAME        = list.NAME;
         agentListInDb.MARKUP_PLAN = list.MARKUP_PLAN;
         agentListInDb.MOBILE      = list.MOBILE;
         agentListInDb.EMAIL       = list.EMAIL;
     }
     _context.Agent_List.Add(list);
     _context.SaveChanges();
     return(RedirectToAction("Index", "Agent"));
 }
        /// 查询有权限的坐席
        /// <summary>
        /// 查询有权限的坐席
        /// </summary>
        private void BindAgentData()
        {
            DataTable dt = BLL.EmployeeAgent.Instance.GetEmployeeAgentByLoginUser();

            rowCount             = "可分配坐席数:" + dt.Rows.Count;
            AgentList.DataSource = dt;
            AgentList.DataBind();

            string[] arrCount = BLL.OtherTaskInfo.Instance.GetNotDistrictCountAndTaskCount(ProjectID).Split(',');
            if (arrCount.Length == 2)
            {
                int notdistrictcount, taskcount;
                if (int.TryParse(arrCount[0], out notdistrictcount))
                {
                    NotDistrictTaskCount = notdistrictcount;
                }
                if (int.TryParse(arrCount[1], out taskcount))
                {
                    TaskCount = taskcount;
                }
            }
        }
Exemplo n.º 21
0
        public override void SelectTarget(AgentList agents)
        {
            Agent drudge = agents[nameof(Drudge)];

            if (!drudge.IsActive && GameService.Random.NextDouble() <= CHANCE_TO_ATTACK)
            {
                if (drudge.Target?.IsActive == true)
                {
                    Target   = drudge.Target;
                    IsActing = true;
                }
                else
                {
                    List <Agent> validTargets = agents.ShuffledList.Where(a => a != this && a.Allegiance == Allegiance.Ally && a.IsActive).ToList();

                    if (validTargets.Any())
                    {
                        Target   = validTargets[GameService.Random.Next(validTargets.Count)];
                        IsActing = true;
                    }
                }
            }
        }
Exemplo n.º 22
0
        public override void SelectTarget(AgentList agents)
        {
            List <Agent> validTargets = agents.ShuffledList.Where(a =>
                                                                  a != this &&
                                                                  a.Allegiance != Allegiance.Enemy &&
                                                                  a.IsActive &&
                                                                  a != agents[nameof(Mastermind)].Target &&
                                                                  a != agents[nameof(Drudge)].Target &&
                                                                  a is not Sleeper // Sleeper is a valid target but it's treated differently
                                                                  ).ToList();

            // Give the Sleeper a higher chance of being selected than the others
            if (agents[nameof(Sleeper)].IsActive && GameService.Random.NextDouble() <= CHANCE_TO_TARGET_SLEEPER)
            {
                Target   = agents[nameof(Sleeper)];
                IsActing = true;
            }
            else if (validTargets.Any())
            {
                Target   = validTargets[GameService.Random.Next(validTargets.Count)];
                IsActing = true;
            }
        }
Exemplo n.º 23
0
        GameInfo(int day, int agent, Judge mediumResult, Judge divineResult, int executedAgent,
                 int latestExecutedAgent, int cursedFox, int attackedAgent, int guardedAgent,
                 List <Vote> voteList, List <Vote> latestVoteList,
                 List <Vote> attackVoteList, List <Vote> latestAttackVoteList,
                 List <Talk> talkList, List <Whisper> whisperList,
                 List <int> lastDeadAgentList, List <Role> existingRoleList,
                 Dictionary <int, string> statusMap, Dictionary <int, string> roleMap,
                 Dictionary <int, int> remainTalkMap, Dictionary <int, int> remainWhisperMap)
        {
            // 引数からプロパティへ
            Day                  = day;
            Agent                = Agent.GetAgent(agent);
            MediumResult         = mediumResult;
            DivineResult         = divineResult;
            ExecutedAgent        = Agent.GetAgent(executedAgent);
            LatestExecutedAgent  = Agent.GetAgent(latestExecutedAgent);
            CursedFox            = Agent.GetAgent(cursedFox);
            AttackedAgent        = Agent.GetAgent(attackedAgent);
            GuardedAgent         = Agent.GetAgent(guardedAgent);
            VoteList             = voteList;
            LatestVoteList       = latestVoteList;
            AttackVoteList       = attackVoteList;
            LatestAttackVoteList = latestAttackVoteList;
            TalkList             = talkList;
            WhisperList          = whisperList;
            LastDeadAgentList    = lastDeadAgentList.Select(i => Agent.GetAgent(i)).ToList();
            ExistingRoleList     = existingRoleList;
            StatusMap            = statusMap.ToDictionary(p => Agent.GetAgent(p.Key), p => (Status)Enum.Parse(typeof(Status), p.Value));
            RoleMap              = roleMap.ToDictionary(p => Agent.GetAgent(p.Key), p => (Role)Enum.Parse(typeof(Role), p.Value));
            RemainTalkMap        = remainTalkMap.ToDictionary(p => Agent.GetAgent(p.Key), p => p.Value);
            RemainWhisperMap     = remainWhisperMap.ToDictionary(p => Agent.GetAgent(p.Key), p => p.Value);

            // その他のプロパティ
            Role           = RoleMap[Agent];
            AgentList      = StatusMap.Keys.ToList();
            AliveAgentList = AgentList.Where(a => StatusMap[a] == Status.ALIVE).ToList();
        }
Exemplo n.º 24
0
        public WebModule() : base()
        {
            Get["/"] = parameters =>
            {
                ApplicationModel appModel = new ApplicationModel(Application.APPLICATION_NAME);
                return(Render("index.pt", context: appModel, view: new ApplicationView(appModel)));
            };

            Get["/objs"] = parameters =>             // Это страница сайта с квартирами.
            {
                ObjectList objList = new ObjectList();
                // Надо отлаживать в монодевелоп...
                ObjectListView objView = new ObjectListView(objList);
                return(Render("objlist.pt", context: objList, view: objView));
            };

            Get["/offers"] = parameters =>
            {
                OfferList     model = new OfferList();
                OfferListView view  = new OfferListView(model);
                return(Render("offerlist.pt", context: model, view: view));
            };

            Get["/agents"] = parameters =>
            {
                AgentList     model = new AgentList();
                AgentListView view  = new AgentListView(model);
                return(Render("agentlist.pt", context: model, view: view));
            };             // Why it is emplty???

            Get["/hello/{Name}"] = parameters =>
            {
                IAgent testModel = Application.Context.Agents.Create();
                testModel.Name = parameters.Name;
                return(View["hello.html", testModel]);
            };
        }
Exemplo n.º 25
0
        public AgentList GetAgentList(int pageIndex)
        {
            AgentList agentModel = new AgentList();

            int bgNumber = ((pageIndex - 1) * 15) + 1;
            int edNumber = (pageIndex) * 15;

            StringBuilder strSql = new StringBuilder();

            strSql.Append("select * from (select row_number() over (order by ID desc) rowNumber,* from Sys_agent_mess) t where t.rowNumber between @bgNumber and @edNumber; ");

            agentModel.list =
                DapperHelper.Query <AgentModel>(strSql.ToString(), new { bgNumber = bgNumber, edNumber = edNumber })
                .ToList();

            strSql.Clear();

            strSql.Append("select count(*) from Sys_agent_mess;");
            agentModel.rowCount = DapperHelper.ExecuteScalar <int>(strSql.ToString());

            agentModel.maxPage = (agentModel.rowCount % 15 == 0) ? agentModel.rowCount / 15 : (agentModel.rowCount / 15 + 1);

            return(agentModel);
        }
 public void AgentList_CheckConstructors()
 {
     AgentList list = new AgentList();
     Assert.AreEqual(0, list.Count);
 }
Exemplo n.º 27
0
        public WebModule() : base()
        {
            Get["/"] = parameters =>
            {
                RestoreSession();
                ApplicationModel appModel = new ApplicationModel(Application.APPLICATION_NAME);
                return(Render("index.pt", context: appModel,
                              view: new ApplicationView(appModel, CurrentSession)));
            };

            Get["/objs"] = parameters =>             // Это страница сайта с квартирами.
            {
                RestoreSession();

                ObjectList objList = new ObjectList();
                // Надо отлаживать в монодевелоп...
                ObjectListView objView = new ObjectListView(objList);
                return(Render("objlist.pt", context: objList, view: objView));
            };

            Get["/offers"] = parameters =>
            {
                RestoreSession();
                OfferList     model = new OfferList(null);
                OfferListView view  = new OfferListView(model);
                return(Render("offerlist.pt", context: model, view: view));
            };

            Get["/offers/{clid}"] = parameters =>
            {
                int clid = int.Parse(parameters.clid);
                RestoreSession();
                OfferList     model = new OfferList(clid: clid);
                OfferListView view  = new OfferListView(model);
                return(Render("offerlist.pt", context: model, view: view));
            };

            Get["/offer/{GUID}"] = parameters =>             // Эта страница с индивидуальной квартирой
            {
                RestoreSession();
                string GUID  = parameters.GUID;
                IOffer model = Application.Context.Offers.Where(x => x.GUID == GUID).FirstOrDefault();

                // По идее в BrightStarDB есть у каждого объекта свой ID и наш
                // GUID можно к нему привязать. FIXME: Привязать!

                string msg = "Объект (Offer) не найден!: " + GUID;
                if (model == null)
                {
                    Console.WriteLine(msg);
                    // и я НЕ понял почему....
                    return("msg");
                }
                else
                {
                    Console.WriteLine(model);
                }
                // Надо нудно искать ошибку в основном шаблоне....
                // Завтра. Вырубает....

                OfferView view = new OfferView(model);
                return(Render("offer.pt", context: model, view: view));
            };

            Get["/agents"] = parameters =>
            {
                RestoreSession();
                AgentList     model = new AgentList();
                AgentListView view  = new AgentListView(model);
                return(Render("agentlist.pt", context: model, view: view));
            };

            Get["/login"] = parameters =>             // Эта страница уже лет 20 не нужна.
            {
                RestoreSession();
                LoginObject model = new LoginObject();
                LoginView   view  = new LoginView(model, this.Request, CurrentSession);

                // return View["login.pt", testModel]; // Оставим для истории.
                // Это, к стати правильный вариант отрисовки по шаблону.

                return(Render("login.pt", context: model, view: view));
            };

            // Принимаем данные пользователя из формы регистрации
            Post["/login"] = parameters =>
            {
                RestoreSession();

                LoginObject model = new LoginObject();
                LoginView   view  = new LoginView(model, this.Request, CurrentSession);

                Response response = null;
                bool     res      = view.Process();

                CurrentSession = view.Session;                         // Обновление сессии
                if (res)
                {
                    response = Response.AsRedirect("/");
                }
                else                         // Неуданая идентификация
                {
                    response = Response.AsRedirect("/login");
                }
                // Перенаправить браузер на домашнюю страницу.
                return(InSession(response));
            };

            Get["/logout"] = parameters =>             // Эта страница уже лет 20 не нужна.
            {
                RestoreSession();
                LoginObject model = new LoginObject();
                LoginView   view  = new LoginView(model, this.Request, CurrentSession);

                // return View["login.pt", testModel]; // Оставим для истории.
                // Это, к стати правильный вариант отрисовки по шаблону.
                view.Logout();
                CurrentSession = view.Session;

                return(Render("login.pt", context: model, view: view));
            };

            Post["/clustering"] = parameters =>
            {
                RestoreSession();

                Response response = null;

                int num = 0;
                try
                {
                    num = int.Parse(this.Request.Form.max);
                    int clnum             = 5;
                    FlatClusterAnalyzer a = FlatClusterAnalyzer.AnalyzeFlatWithCluster(num);
                    a.Store(clnum);

                    CurrentSession["message"] = info("Обработано для " + num + " квартир, " + clnum + " кластеров",
                                                     msg: "Успешный запуск");
                    CurrentSession["analysis_data"] = a;
                }
                catch (FormatException)
                {
                    CurrentSession["message"] = error("Неправильное число квартир", msg: "Неуспешный запуск");
                }

                response = Response.AsRedirect("/analysis");
                return(InSession(response));
            };

            Get["/analysis"] = parameters =>
            {
                RestoreSession();
                ClusterList     model = new ClusterList();
                ClusterListView view  = new ClusterListView(model);
                return(Render("clusters.pt", context: model, view: view));
            };

            Post["/analysis"] = parameters =>
            {
                RestoreSession();
                ClusterList         model    = new ClusterList();
                ClusterListView     view     = new ClusterListView(model);
                FlatClusterAnalyzer analyzer = null;
                var form = this.Request.Form;
                if (form.reconstruct != null)
                {
                    try
                    {
                        analyzer = (FlatClusterAnalyzer)CurrentSession["analysis_data"];
                        int k = int.Parse(form.numclusters);
                        Console.WriteLine("---> K=" + k);
                        analyzer.Store(k);
                        CurrentSession["message"] = info("Произведена перестройка кластера", msg: "Удачное завершение операции");
                    }
                    catch
                    {
                        // В сессии нет данных по кластеру.
                        CurrentSession["message"] = error("Похоже кластер не рассчитан", msg: "Неудачная операция");
                    }
                }
                return(InSession(Response.AsRedirect("/analysis")));
            };
        }
        private void ProcessBirths(int iteration, Dictionary <IAgent, AgentState <TDataSet> > iterationState, AgentList agentList)
        {
            var iterationAgents = new List <IAgent>();

            var unactiveAgents = _births.Where(kvp => kvp.Key >= iteration - _configuration.YearsBetweenBirths)
                                 .SelectMany(kvp => kvp.Value)
                                 .ToList();

            var activeAgents = agentList.ActiveAgents.Except(unactiveAgents).ToList();

            var pairs = activeAgents.Where(a => a[SosielVariables.PairStatus] == PairStatus.Paired)
                        .GroupBy(a => a[SosielVariables.NuclearFamily])
                        .ToList();

            foreach (var pair in pairs)
            {
                var pairList = pair.ToList();

                if (pairList.Count != 2)
                {
                    continue;
                }

                var averageAge = (int)Math.Ceiling(pair.Average(a => (int)a[SosielVariables.Age]));

                if (_birthProbability.IsVariableSpecificEventOccur(averageAge))
                {
                    //generate random value to determine gender
                    var gender     = LinearUniformRandom.GetInstance.Next(2);
                    var baseParent = LinearUniformRandom.GetInstance.Next(2);

                    var baseAgent      = pairList[baseParent];
                    var baseAgentState = iterationState[baseAgent];

                    var childName = $"{baseAgent.Archetype.NamePrefix}{agentList.GetAgentsWithPrefix(baseAgent.Archetype.NamePrefix).Count() + 1}";
                    var child     = baseAgent.CreateChild(gender == 0 ? Gender.Male : Gender.Female, childName);

                    child[SosielVariables.Household]      = baseAgent[SosielVariables.Household];
                    child[SosielVariables.NuclearFamily]  = baseAgent[SosielVariables.NuclearFamily];
                    child[SosielVariables.ExtendedFamily] = baseAgent[SosielVariables.ExtendedFamily];

                    var extendedFamilies = baseAgent[SosielVariables.ExtendedFamily] as List <string>;

                    child.ConnectedAgents.AddRange(pairList);

                    foreach (var extendedFamily in extendedFamilies)
                    {
                        child.ConnectedAgents.AddRange(baseAgent.ConnectedAgents.Where(a => a[SosielVariables.NuclearFamily] == extendedFamily).Except(child.ConnectedAgents));
                    }

                    foreach (var agent in child.ConnectedAgents)
                    {
                        agent.ConnectedAgents.Add(child);
                    }

                    var childState = baseAgentState.CreateChildCopy(child);

                    agentList.Agents.Add(child);
                    iterationState[child] = childState;

                    iterationAgents.AddRange(pairList);
                }
            }

            _births[iteration] = iterationAgents;
        }
        public void ChangeDemographic(int iteration, Dictionary <IAgent, AgentState <TDataSet> > iterationState, AgentList agents)
        {
            ProcessBirths(iteration, iterationState, agents);

            ProcessPairing(agents.ActiveAgents);

            ProcessDeaths(agents.ActiveAgents);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Selects an agent and sets them as this agent's <see cref="Agent.Target"/>.
 /// </summary>
 /// <param name="agents">The list of agents in the current game from which the target will be selected.</param>
 public abstract void SelectTarget(AgentList agents);
Exemplo n.º 31
0
        /// <summary>
        /// List the external agent monitors
        /// </summary>
        private static void ListExternalAgents(AgentList agentList)
        {
            // Add a dummy agent
            Agent dummy = new Agent();
            dummy.Id = "9999";
            dummy.Name = "EXTERNAL";
            agentList.Add(dummy);

            dummy.GetExternalMonitors(apiKey, client, argMonitors);
        }
        public void AgentList_CheckConstructors()
        {
            AgentList list = new AgentList();

            Assert.AreEqual(0, list.Count);
        }
Exemplo n.º 33
0
        /// <summary>
        /// List agents and collect monitor information
        /// </summary>
        private static void ListInternalAgents(AgentList agentList)
        {
            // Retrieve all the agents defined
            agentList.GetAgents(apiKey, client);

            // Process each Agent
            foreach (Agent agent in agentList)
            {
                if (useMonitors)
                    agent.GetGlobalMonitors(apiKey, client, argMonitors);

                if (useProcesses)
                    agent.GetProcessMonitors(apiKey, client, argProcesses);
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Process the commands
        /// </summary>
        private static void ProcessCommands()
        {
            // process the command
            switch (argCommand)
            {
                case "listagents":
                    // create the Agent list
                    AgentList agentList = new AgentList();

                    if (argAgentTypes.Contains("int"))
                        ListInternalAgents(agentList);

                    if (argAgentTypes.Contains("ext"))
                        ListExternalAgents(agentList);

                    if (argAgentTypes.Contains("full"))
                        ListFullpageAgents(agentList);

                    // Display the results
                    agentList.DisplayAgents();
                    break;

                case "setkeys":
                    SetKeys(argApiKey, argSecretKey);
                    break;

                case "getkeys":
                    Console.WriteLine("APIKey: {0}", GetAPIKey());
                    Console.WriteLine("SecretKey: {0}", GetSecretKey());
                    break;
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// List the fullpage monitors
        /// </summary>
        private static void ListFullpageAgents(AgentList agentList)
        {
            // Add a dummy agent
            Agent dummy = new Agent();
            dummy.Id = "9999";
            dummy.Name = "FULLPAGE";
            agentList.Add(dummy);

            dummy.GetFullpageMonitors(apiKey, client, argMonitors);
        }
Exemplo n.º 36
0
        /// <inheritdoc />
        protected override void InitializeAgents()
        {
            var agents = new List <IAgent>();

            Dictionary <string, AgentArchetype> agentArchetypes = _configuration.AgentConfiguration;

            if (agentArchetypes.Count == 0)
            {
                throw new SosielAlgorithmException("Agent archetypes were not defined. See configuration file");
            }

            InitialStateConfiguration initialState = _configuration.InitialState;

            var networks = new Dictionary <string, List <SOSIEL.Entities.Agent> >();

            //create agents, groupby is used for saving agents numeration, e.g. FE1, HM1. HM2 etc
            initialState.AgentsState.GroupBy(state => state.ArchetypeOfAgent).ForEach((agentStateGroup) =>
            {
                AgentArchetype archetype = agentArchetypes[agentStateGroup.Key];
                var mentalProto          = archetype.MentalProto;
                int index = 1;

                agentStateGroup.ForEach((agentState) =>
                {
                    for (int i = 0; i < agentState.NumberOfAgents; i++)
                    {
                        SOSIEL.Entities.Agent agent = Agent.CreateAgent(agentState, archetype);
                        agent.SetId(index);

                        agents.Add(agent);

                        networks.AddToDictionary((string)agent[AlgorithmVariables.Household], agent);
                        networks.AddToDictionary((string)agent[AlgorithmVariables.NuclearFamily], agent);

                        if (agent.ContainsVariable(AlgorithmVariables.ExternalRelations))
                        {
                            var externals = (string)agent[AlgorithmVariables.ExternalRelations];

                            foreach (var en in externals.Split(';'))
                            {
                                networks.AddToDictionary(en, agent);
                            }
                        }

                        //household and extended family are the same at the beginning
                        agent[AlgorithmVariables.ExtendedFamily] = new List <string>()
                        {
                            (string)agent[AlgorithmVariables.Household]
                        };

                        index++;
                    }
                });
            });

            //convert temp networks to list of connetcted agents
            networks.ForEach(kvp =>
            {
                var connectedAgents = kvp.Value;

                connectedAgents.ForEach(agent =>
                {
                    agent.ConnectedAgents.AddRange(connectedAgents.Where(a => a != agent).Except(agent.ConnectedAgents));
                });
            });


            agentList = new AgentList(agents, agentArchetypes.Select(kvp => kvp.Value).ToList());
        }
Exemplo n.º 37
0
 /// <summary>
 /// Constructor used by all specializations, which in turn are used by
 /// senders of a message
 /// </summary>
 /// <param name="conversationId">conversation id</param>
 /// <param name="status">Status of the ack/nak</status>
 /// <param name="note">error message or note</note>
 public AgentListReply(PossibleStatus status, AgentList agents, string note = null) :
     base(Reply.PossibleTypes.AgentListReply, status, note)
 {
     Agents = agents;
 }
 /// <summary>
 /// Constructor used by all specializations, which in turn are used by
 /// senders of a message 
 /// </summary>
 /// <param name="conversationId">conversation id</param>
 /// <param name="status">Status of the ack/nak</status>
 /// <param name="note">error message or note</note>
 public AgentListReply(PossibleStatus status, AgentList agents, string note = null)
     : base(Reply.PossibleTypes.AgentListReply, status, note)
 {
     Agents = agents;
 }