Example #1
0
    private void SetParticleActive(List<ParticleSystem> particles, int newActive)
    {
        //Find out how many are active, and determine if we need to add an active or not
        int currentActiveCount = particles.Count(pSys => {
            return pSys.enableEmission;
        });

        int diff = newActive - currentActiveCount;
        //Debug.Log ("Setting NumParticles Active: " + currentActiveCount + " NewActive: " + newActive);
        //If we have a net increase in particle requests, and we have enough particle systems to activate, pick one at random and activate it.
        if(diff > 0 && particles.Count > currentActiveCount) {
            List<ParticleSystem> inactiveParticles = particles.FindAll(pSys => {
                return pSys.enableEmission == false;
            });

            SetEmissionCountOnParticlePool(inactiveParticles, Mathf.Abs(diff), true);
        }
        //If we have a net decrease in particle requests, pick a random positive effect and deactivate them
        else if(diff < 0) {
            List<ParticleSystem> activeParticles = particles.FindAll(pSys => {
                return pSys.enableEmission == true;
            });

            SetEmissionCountOnParticlePool(activeParticles, Mathf.Abs(diff), false);
        }
    }
 // recursion function
 private void CreateTreeView(List<CostCenter> source, int? parentID, TreeNode parentNode)
 {
     List<CostCenter> newSource = CostCenter.GetAllCostCenterTree();
     if (parentID == null)
     {
         newSource = source.FindAll(a => a.ParentId == null);
     }
     else
     {
         newSource = source.FindAll(a => a.ParentId == parentID);
     }
     foreach (var i in newSource)
     {
         TreeNode newnode = new TreeNode(i.Name);
         newnode.Name = i.CostCenterId.ToString();
         newnode.Tag = i.CostCenterId;
         if (parentNode == null)
         {
             trvCostCenterTree.Nodes.Add(newnode);
         }
         else
         {
             parentNode.Nodes.Add(newnode);
         }
         CreateTreeView(source, i.CostCenterId, newnode);
     }
 }
        static void Main(string[] args)
        {
            List<int> firstArr = new List<int>();
            int num = 1;
            int l1 = 0;
            
            Console.Write("Element {0} of the array(write some bad input to finish):", l1);
            l1++;
            while (int.TryParse(Console.ReadLine(), out num))
            {
                Console.Write("Element {0} of the array(write some bad input to finish):", l1);
                firstArr.Add(num);
                l1++;
            }

            firstArr.TrimExcess();
            Console.WriteLine();
            Console.WriteLine();

            int element=firstArr[0];
            int occurenceCount=firstArr.FindAll(x=> x==element).Count;

            for (int i = 1; i < firstArr.Count; i++)
            {
                int temp = firstArr[i];
                int count=firstArr.FindAll(x => x == temp).Count;
                if (count > occurenceCount)
                {
                    occurenceCount = count;
                    element = firstArr[i];
                }
            }

            Console.WriteLine("{0}({1} times)",element,occurenceCount);
        }
Example #4
0
 private void pbColor_MouseDown(object sender, MouseEventArgs e)
 {
     if (e.Button == MouseButtons.Left)
     {
         double            xPos   = e.Location.X;
         List <SlideBlock> sbList = blockList?.FindAll((p) => p.IsMouseOn(xPos));
         if (sbList.Count == 1)
         {
             curSlideBlock = sbList.First();
         }
         else if (sbList.Count >= 2)
         {
             if (sbList.FindAll(p => p.Value == min).Count > 0)
             {
                 curSlideBlock = sbList.Last();
             }
             else if (sbList.FindAll(p => p.Value == max).Count > 0)
             {
                 curSlideBlock = sbList.First();
             }
             else
             {
                 curSlideBlock = sbList.First();
             }
         }
         mouseDownCalculateLoc = e.Location.X;
     }
 }
        private void RunGA(){
            _teams = LoadTeams();
            _winners = _teams.FindAll(l => l.Winner == true);
            _losers = _teams.FindAll(l => l.Winner == false);

            const double crossoverProbability = 0.85;
            const double mutationProbability = 0.15;
            const int elitismPercentage = 5;

            var population = new Population(1000, 72, true, false, ParentSelectionMethod.TournamentSelection);

            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.DoublePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            ga.Run(TerminateAlgorithm);

        }
        /// <summary>
        /// 查找市、县代码表
        /// </summary>
        /// <param name="lstTmp">所有行政列表</param>
        /// <param name="code">当前行政代码</param>
        static void Init(List<AdministrativeCode> lstTmp, AdministrativeCode code)
        {
            if (code == null) { return; }
            var id = code.ID.ToString().Substring(0, (code.Level + 1) * 2);
            code.SubAdministrativeCode = new List<AdministrativeCode>();
            var lst = new List<AdministrativeCode>();

            switch (code.Level + 1)
            {
                //  查找市级规则  
                //  前2位省代码 + 后4位**00(固定)
                case 1:
                    {
                        lst = lstTmp.FindAll(o => o.ID.ToString().StartsWith(id) && !o.ID.ToString().EndsWith("0000") && o.ID.ToString().EndsWith("00"));
                        break;
                    }

                //  查找县级规则  
                //  前4位市代码 + 后2位00(固定)
                case 2:
                    {
                        lst = lstTmp.FindAll(o => o.ID.ToString().StartsWith(id) && !o.ID.ToString().EndsWith("00"));
                        break;
                    }
            }
            lst.ForEach(o => { code.SubAdministrativeCode.Add(o); o.Level = code.Level + 1; Init(lstTmp, o); });
            if (code.SubAdministrativeCode.Count == 0) { code.SubAdministrativeCode = null; }
        }
        public static void AddRegionAndFKForCountryLanguage(List<CountryLanguageDto> listOfCountryLanguages, DataTable countries, DataTable languages)
        {
            for (int i = 0; i < countries.Rows.Count; i++ )
            {
                String region = countries.Rows[i]["webpage_in_region"].ToString();
                String countryFK = countries.Rows[i]["country"].ToString();
                String country = countries.Rows[i]["country_name"].ToString();

                List<CountryLanguageDto> clDto = listOfCountryLanguages.FindAll(cl => cl.CountryName.Equals(country));
                if (clDto != null)
                {
                    foreach (CountryLanguageDto countryLanguage in clDto)
                    {
                        countryLanguage.WebPageInRegion = region;
                        countryLanguage.CountryFK = countryFK;
                    }
                }
            }

            for (int i = 0; i < languages.Rows.Count; i++)
            {
                String languageFK = languages.Rows[i]["language"].ToString();
                String language = languages.Rows[i]["language_name"].ToString();

                List<CountryLanguageDto> clDto = listOfCountryLanguages.FindAll(cl => cl.LanguageName.Equals(language));
                if (clDto != null)
                {
                    foreach(CountryLanguageDto countryLanguage in clDto)
                        countryLanguage.LanguageFK = languageFK;
                }
            }
        }
 // recursion function
 private void CreateTreeView(List<AssetCatogry> source, int? parentID, TreeNode parentNode)
 {
     List<AssetCatogry> newSource = AssetCatogry.GetAllAssetCatogryTree();
     if (parentID == null)
     {
         newSource = source.FindAll(a => a.ParentId == null);
     }
     else
     {
         newSource = source.FindAll(a => a.ParentId == parentID);
     }
     foreach (var i in newSource)
     {
         TreeNode newnode = new TreeNode(i.Name);
         newnode.Tag = i.AstCatId.ToString();
         if (parentNode == null)
         {
             trvAssetCatogryTree.Nodes.Add(newnode);
         }
         else
         {
             parentNode.Nodes.Add(newnode);
         }
         CreateTreeView(source, i.AstCatId, newnode);
     }
 }
Example #9
0
        public static void Main()
        {
            var myNumbers = new List<int>();
            myNumbers.AddRange(new int [] { 0, 4, 5, 11, 12, 15, 16, 1412, 1413 });

            var wn = new IsWeirdNumber<int>(MyIsEvenNumber);
            Console.WriteLine("test(10) : {0}", wn(10));
            Console.WriteLine("test(11) : {0}", wn(11));

            // �븮�� ��ü�� ����ϴ� ���
            var pi = new Predicate<int>(wn);
            foreach (var number in myNumbers.FindAll(pi))
            {
            Console.WriteLine("even number : {0}", number);
            }

            // ���� �޼ҵ带 ����ϴ� ���
            foreach (var number in myNumbers.FindAll(delegate (int v) {
                    return (v % 2 != 0);
                }))
            {
            Console.WriteLine("custom delegate number : {0}", number);
            }

            // ���� ǥ������ ����ϴ� ���
            foreach (var number in myNumbers.FindAll(i => ( i > 100 )))
            {
            Console.WriteLine("> 100 numbers: {0}", number);
            }
        }
 // recursion function
 private void CreateTreeView(List<Account> source, string parentID, TreeNode parentNode)
 {
     List<Account> newSource = new List<Account>();
     if (parentID == "")
     {
         newSource = source.FindAll(a => a.ParentId == null);
     }
     else
     {
         newSource = source.FindAll(a => a.ParentId == parentID);
     }
     foreach (var i in newSource)
     {
         TreeNode newnode = new TreeNode(i.NameAndNo);
         newnode.Name = i.AccountID;
         newnode.Tag = i.AccountID;
         if (parentNode == null)
         {
             trvAccountTree.Nodes.Add(newnode);
         }
         else
         {
             parentNode.Nodes.Add(newnode);
         }
         CreateTreeView(source, i.AccountID, newnode);
     }
 }
Example #11
0
        private static void writeAssortedStats(List<eclipse.EclipsePlay> plays, String fileName)
        {
            Dictionary<int, int> playerCounts = new Dictionary<int, int>();
            Dictionary<int, Dictionary<eclipse.EclipseRace, int>> winCounts = new Dictionary<int, Dictionary<eclipse.EclipseRace, int>>();
            Dictionary<int, Dictionary<eclipse.EclipseRace, int>> participationCounts = new Dictionary<int, Dictionary<eclipse.EclipseRace, int>>();
            System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName);
            writer.WriteLine("Total Plays: " + plays.Count);
            plays = plays.FindAll(play => play.hasOneWinner);
            writer.WriteLine("Plays With Winner: " + plays.Count);
            plays = plays.FindAll(play => play.hasColors);
            writer.WriteLine("Plays With Parsed Races: " + plays.Count);

            for (int playerCount = 1; playerCount < 10; playerCount++)
            {
                playerCounts[playerCount] = 0;
                winCounts[playerCount] = new Dictionary<eclipse.EclipseRace, int>();
                participationCounts[playerCount] = new Dictionary<eclipse.EclipseRace, int>();
                foreach (eclipse.EclipseRace race in Enum.GetValues(typeof(eclipse.EclipseRace)))
                {
                    winCounts[playerCount][race] = 0;
                    participationCounts[playerCount][race] = 0;
                }
            }

            foreach (eclipse.EclipsePlay play in plays)
            {
                int playerCount = play.players.Count;
                playerCounts[playerCount] += 1;
                foreach (eclipse.EclipsePlayer player in play.players)
                {
                    participationCounts[playerCount][player.race] += 1;
                    if (player.win)
                    {
                        winCounts[playerCount][player.race] += 1;
                    }
                }
            }

            for (int playerCount = 1; playerCount < 10; playerCount++)
            {
                String header = "Statsfor " + playerCount + " player games";
                String participation = "Participates in: " + playerCounts[playerCount] + " games";
                String weightedWins = "%Wins out of " + playerCounts[playerCount] * playerCount +  " participations" ;
                String overallWins = "%Wins out of " + playerCounts[playerCount] + " games";
                foreach (eclipse.EclipseRace race in Enum.GetValues(typeof(eclipse.EclipseRace)))
                {
                    header += ", " + race;
                    participation += ", " + Math.Round(100 * participationCounts[playerCount][race] / (double)playerCounts[playerCount], 2);
                    weightedWins += ", " + Math.Round(100 * winCounts[playerCount][race] / (double)participationCounts[playerCount][race], 2);
                    overallWins += ", " + Math.Round(100 * winCounts[playerCount][race] / (double)playerCounts[playerCount], 2);
                }

                writer.WriteLine(header);
                writer.WriteLine(participation);
                writer.WriteLine(weightedWins);
                writer.WriteLine(overallWins);
            }
            writer.Close();
        }
Example #12
0
 protected void ChangeDatesFontSize(double newValue, double oldValue)
 {
     if (Math.Abs(newValue - oldValue) < 0.01)
     {
         return;
     }
     buttons?.FindAll(b => !b.IsSelected && b.IsEnabled).ForEach(b => b.FontSize = newValue);
 }
Example #13
0
 public static RDAFolder GenerateFrom(List<RDAFile> file, FileHeader.Version version)
 {
     RDAFolder root = new RDAFolder(version);
     root.Files.AddRange(file.FindAll(f => !f.FileName.Contains("/")));
     foreach (RDAFile rdaFile in file.FindAll(f => f.FileName.Contains("/")))
         NavigateTo(root, Path.GetDirectoryName(rdaFile.FileName), "").Files.Add(rdaFile);
     return root;
 }
Example #14
0
    public static void Main (string[] args) {
        var l = new List<string> {
            "A", "A", "B", "C", "D"
        };

        PrintItems(l);
        PrintItems(l.FindAll((s) => s == "A"));
        PrintItems(l.FindAll((s) => s == "Q"));
    }
 public double valueFromPersona(List<Persona> personas)
 {
     double retorno = (double)Valores.INVALIDO;
     if (personas.FindAll(persona => persona.Vehicle.Equals(Vehicle.Moto) && persona.Nationality.Equals(Nationality.Turco))
         .Count > 0 && personas.FindAll(persona => persona.Vehicle.Equals(Vehicle.Moto)).Count==1)
     {
         retorno = (double)Valores.VALIDO;
     }
     return retorno;
 }
Example #16
0
 public List<string> Parse(List<string> files)
 {
     List<string> filesWithSearchPattern = files.FindAll(x => x.Contains(XlsSearchPattern) || x.Contains(XlsxSearchPattern));
     List<string> completeListOfFiles = files.FindAll(x => !x.Contains(XlsSearchPattern) && !x.Contains(XlsxSearchPattern));
     foreach (string file in filesWithSearchPattern)
     {
         completeListOfFiles.AddRange(GetFiles(file));
     }
     return completeListOfFiles;
 }
Example #17
0
 public void UpdateMinions()
 {
     AllMinions = ObjectManager.Get<Obj_AI_Minion>().ToList();
     AllyMinions =
         AllMinions.FindAll(
             minion => minion.IsValid && !minion.IsDead && minion.IsAlly && MinionManager.IsMinion(minion));
     EnemyMinions =
         AllMinions.FindAll(
             minion => minion.IsValid && !minion.IsDead && minion.IsEnemy && MinionManager.IsMinion(minion));
 }
 public double valueFromPersona(List<Persona> personas)
 {
     double retorno = (double)Valores.INVALIDO;
     if (personas.FindAll(persona => persona.Vehicle.Equals(Vehicle.Moto) && !vehiculos.Contains((Int32)persona.MouthAction))
         .Count > 0 && personas.FindAll(persona => persona.Vehicle.Equals(Vehicle.Moto)).Count == 1)
     {
         retorno = (double)Valores.VALIDO;
     }
     return retorno;
 }
 public double valueFromPersona(List<Persona> personas)
 {
     double retorno = (double)Valores.INVALIDO;
     if (personas.FindAll(persona => persona.Nationality.Equals(Nationality.Finlandes) && !persona.Name.Equals(Name.Saverio))
                 .Count > 0 && personas.FindAll(persona => persona.Nationality.Equals(Nationality.Finlandes)).Count==1)
     {
         retorno = (double)Valores.VALIDO;
     }
     return retorno;
 }
 public double valueFromPersona(List<Persona> personas)
 {
     double retorno = (double)Valores.INVALIDO;
     if (personas.FindAll(persona => persona.Nationality.Equals(Nationality.Turco) && !persona.MouthAction.Equals(MouthAction.Recita))
         .Count > 0 && personas.FindAll(persona => persona.Nationality.Equals(Nationality.Turco)).Count == 1)
     {
         retorno = (double)Valores.VALIDO;
     }
     return retorno;
 }
        public static string AvarageAgeOfAnimals(List<IAnimal> animals)
        {
            StringBuilder output = new StringBuilder();
            output.AppendFormat("Dogs avarage age = {0:F2}\n", AvarageAge(animals.FindAll( x => x.GetType().Name == "Dog")));
            output.AppendFormat("Kittens avarage age = {0:F2}\n", AvarageAge(animals.FindAll(x => x.GetType().Name == "Kitten")));
            output.AppendFormat("Tomcats avarage age = {0:F2}\n", AvarageAge(animals.FindAll(x => x.GetType().Name == "Tomcat")));
            output.AppendFormat("Frogs avarage age = {0:F2}", AvarageAge(animals.FindAll(x => x.GetType().Name == "Frog")));

            return output.ToString();
        }
Example #22
0
 public static void LoadObjects()
 {
     AutoSharpporting.SRShopAI.Main.Init();   //SRShopAI
     //Heroes
     AllHeroes = ObjectManager.Get<Obj_AI_Hero>().ToList();
     AllyHeroes = (Utility.Map.GetMap().Type != Utility.Map.MapType.HowlingAbyss)
         ? AllHeroes.FindAll(hero => hero.IsAlly && !IsSupport(hero) && !hero.IsMe && !HasSmite(hero)).ToList()
         : AllHeroes.FindAll(hero => hero.IsAlly && !hero.IsMe).ToList();
     EnemyHeroes = AllHeroes.FindAll(hero => !hero.IsAlly).ToList();
     UpdateObjects();
 }
Example #23
0
        public OverrideInstance(List<OverrideItem> items)
        {
            var i = items.FindAll(o => o.Type == OverrideType.FEEDRATE_OVERRIDE).Select(o => o.Value);
            if (i.Any()) FeedrateAverage = i.Average();

            i = items.FindAll(o => o.Type == OverrideType.SPINDLE_OVERRIDE).Select(o => o.Value);
            if (i.Any()) SpindleAverage = i.Average();

            i = items.FindAll(o => o.Type == OverrideType.RAPID_OVERRIDE).Select(o => o.Value);
            if (i.Any()) RapidAverage = i.Average();
        }
Example #24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        List<string> list = new List<string>();
        list.Add("liu12");
        list.Add("liu123");
        list.Add("li12");
        list.Add("u12");

        var varLam = list.FindAll(s => s.IndexOf("liu") >= 0 && 1==1);
        var varDele = list.FindAll(delegate(string s) { return s.IndexOf("liu") >= 0; });
    }
Example #25
0
 public static Weights GetActualWeights(List<Move> moves)
 {
     var Weights = new Weights()
     {
         RockWeight = moves.FindAll(m => m.Equals(Moves.Rock)).Count,
         PaperWeight = moves.FindAll(m => m.Equals(Moves.Paper)).Count,
         ScissorsWeight = moves.FindAll(m => m.Equals(Moves.Scissors)).Count,
         DynamiteWeight = moves.FindAll(m => m.Equals(Moves.Dynamite)).Count,
         WaterWeight = moves.FindAll(m => m.Equals(Moves.WaterBalloon)).Count,
     };
     return Weights;
 }
 public override void OnNewTurn(StateObject s)
 {
     List<Unit> targets = new List<Unit>();
     targets = PathFinder.BreadthFirstSearch(s.MainHex, GameControl.gameControl.GridControl.Map, 2, s.MainHex.Unit.Team).ConvertAll<Unit>(h => h.Unit);
     targets = targets.FindAll(u => u != null);
     targets = targets.FindAll(u => u.Team != s.MainHex.Unit.Team);
     if(targets.Count > 0) {
         Unit target = targets.RandomElement();
         s.MainHex.Unit.attacking = target;
         s.MainHex.Unit.AttackTarget(target, 0);
     }
 }
        public List<Modelo_Entidades.Chofer> ObtenerChoferes(string nombre, string apellido, string tipo_documento, int nro_documento, Modelo_Entidades.Cliente oClienteRecibido)
        {
            List<Modelo_Entidades.Chofer> oListaChoferes = new List<Modelo_Entidades.Chofer>();
            oListaChoferes = Modelo_Entidades.Acopio_FertilizantesEntities.ObtenerInstancia().CatChoferes.ToList<Modelo_Entidades.Chofer>();
            if (!(string.IsNullOrWhiteSpace(nombre)))
            {
                //oListaChoferes = oListaChoferes.FindAll(delegate(Modelo_Entidades.Chofer oChoferBuscado) { return oChoferBuscado.nombre == nombre; });
                oListaChoferes = oListaChoferes.FindAll(delegate(Modelo_Entidades.Chofer oChoferBuscado) { return oChoferBuscado.nombre.StartsWith(Convert.ToString(nombre)); });
            }
            if (!(string.IsNullOrWhiteSpace(apellido)))
            {
                oListaChoferes = oListaChoferes.FindAll(delegate(Modelo_Entidades.Chofer oChoferBuscado) { return oChoferBuscado.apellido.StartsWith(apellido.ToString()); });
            }
            if (!(string.IsNullOrWhiteSpace(tipo_documento)))
            {
                oListaChoferes = oListaChoferes.FindAll(delegate(Modelo_Entidades.Chofer oChoferBuscado) { return oChoferBuscado.tipo_documento.StartsWith(tipo_documento.ToString()); });
            }
            if (oClienteRecibido != null)
            {
                //copiar la lista actual en una lista temporal, ya que no es posible modificar una lista que se está recorriendo
                //List<Modelo_Entidades.Chofer> oListaTemporal = oListaChoferes;
                List<Modelo_Entidades.Chofer> oListaTemporal = new List<Modelo_Entidades.Chofer>();
                /* si el chofer trabaja para al menos uno de los clientes que tienen este nombre no se lo quita de la lista
                //obtener la lista de los clientes para los que trabaja cada chofer
                foreach (Modelo_Entidades.Chofer oChoferActual in oListaTemporal)
                {
                    List<Modelo_Entidades.Cliente> oListaClientes = oChoferActual.Clientes.ToList<Modelo_Entidades.Cliente>().FindAll(delegate(Modelo_Entidades.Cliente oClienteBuscado) { return oClienteBuscado.nombre.StartsWith(nombre_cliente.ToString()); });
                    //si la lista está vacía quitar el chofer de la lista de choferes
                    if (oListaClientes.Count == 0)
                    {
                        oListaChoferes.Remove(oChoferActual);
                    }
                }
                */

                // si el chofer trabaja para el cliente especificado no se lo borra de la lista no temporal
                foreach (Modelo_Entidades.Chofer oChoferActual in oListaChoferes)
                {
                    Modelo_Entidades.Cliente oCliente = oChoferActual.Clientes.ToList<Modelo_Entidades.Cliente>().Find(delegate(Modelo_Entidades.Cliente oClienteBuscado) { return oClienteBuscado == oClienteRecibido; });
                    //si la lista está vacía quitar el chofer de la lista de choferes
                    if (oCliente != null)
                    {
                        oListaTemporal.Add(oChoferActual);
                    }
                }
                oListaChoferes = oListaTemporal;
            }
            if (nro_documento != 0)
            {
                oListaChoferes = oListaChoferes.FindAll(delegate(Modelo_Entidades.Chofer oChoferBuscado) { return Convert.ToString(oChoferBuscado.num_documento).StartsWith(Convert.ToString(nro_documento)); });
            }
            return oListaChoferes;
        }
Example #28
0
        private static void ListAndPredicates()
        {
            List<int> numbers = new List<int>(new int[] { 1, 2, 5, 4, 1, 7, 8, 9, 1, 11, -1, -2, -1, 0 });

            Predicate<int> oddFinder = (n) => (n % 2 != 0);
            Predicate<int> evenFinder = (n) => (n % 2 == 0);

            List<int> odds = numbers.FindAll(oddFinder);
            System.Console.WriteLine("ListAndPredicates: odds = " + string.Join(", ", odds));

            List<int> evens = numbers.FindAll(evenFinder);
            System.Console.WriteLine("ListAndPredicates: evens = " + string.Join(", ", evens));
        }
Example #29
0
        Dictionary<Suit, int> GetSuitCount(IEnumerable<Card> input)
        {
            var ls = new List<Card>(input);

            var lsCnt = new Dictionary<Suit, int>();
            lsCnt.Add(Suit.Hearts, ls.FindAll((card) => card.Suit == Suit.Hearts).Count);
            lsCnt.Add(Suit.Diamonds, ls.FindAll((card) => card.Suit == Suit.Diamonds).Count);
            lsCnt.Add(Suit.Clubs, ls.FindAll((card) => card.Suit == Suit.Clubs).Count);
            lsCnt.Add(Suit.Spades, ls.FindAll((card) => card.Suit == Suit.Spades).Count);

            lsCnt.Add(Suit.NOT_RECOGNIZED, ls.FindAll((card) => card.Suit == Suit.NOT_RECOGNIZED).Count);

            return lsCnt;
        }
        public static void Add(DataTable table, List<DataItem> dataItems)
        {
            DeviceConfiguration.EditTable(table, "/GeneratedData/SnapShotData/Generated||00", null, "id||00;name||Device Status;link||device_status;");
            DeviceConfiguration.EditTable(table, "/GeneratedData/SnapShotData/Generated||01", null, "id||01;name||Production Status;link||production_status;");
            DeviceConfiguration.EditTable(table, "/GeneratedData/SnapShotData/Generated||02", null, "id||02;name||Program Execution;link||program_execution;");

            int id = 3;

            // Feedrate Overrides
            var items = dataItems.FindAll(x => x.Category == DataItemCategory.EVENT && x.Type == "PATH_FEEDRATE_OVERRIDE" && x.SubType == "PROGRAMMED" && x.FullAddress.ToLower().Contains("controller"));
            if (items != null)
            {
                int i = 1;

                foreach (var item in items)
                {
                    DeviceConfiguration.EditTable(table, "/GeneratedData/SnapShotData/Collected||" + id.ToString("00"), null, "id||" + id.ToString("00") + ";name||Feedrate Override " + i.ToString("00") + ";link||" + item.Id + ";");
                    i++;
                    id++;
                }
            }

            // Rapidrate Overrides
            items = dataItems.FindAll(x => x.Category == DataItemCategory.EVENT && x.Type == "PATH_FEEDRATE_OVERRIDE" && x.SubType == "RAPID" && x.FullAddress.ToLower().Contains("controller"));
            if (items != null)
            {
                int i = 1;

                foreach (var item in items)
                {
                    DeviceConfiguration.EditTable(table, "/GeneratedData/SnapShotData/Collected||" + id.ToString("00"), null, "id||" + id.ToString("00") + ";name||Rapid Override " + i.ToString("00") + ";link||" + item.Id + ";");
                    i++;
                    id++;
                }
            }

            // Spindle Overrides
            items = dataItems.FindAll(x => x.Category == DataItemCategory.EVENT && x.Type == "ROTARY_VELOCITY_OVERRIDE" && x.FullAddress.ToLower().Contains("rotary"));
            if (items != null)
            {
                int i = 1;

                foreach (var item in items)
                {
                    DeviceConfiguration.EditTable(table, "/GeneratedData/SnapShotData/Collected||" + id.ToString("00"), null, "id||" + id.ToString("00") + ";name||Spindle Override " + i.ToString("00") + ";link||" + item.Id + ";");
                    i++;
                    id++;
                }
            }
        }
        private void RemoveWatchFolders(CellEditEventArgs e)
        {
            foldersListView.RemoveObject(e.RowObject);

            var folderObject = e.RowObject as ProjectRequest;

            var requestToRemove = _folderPathList?.FindAll(p => p.Path == folderObject.Path);

            if (requestToRemove != null)
            {
                foreach (var request in requestToRemove)
                {
                    _folderPathList.Remove(request);
                    var notification = GetUINotification(request);
                    _controller.ClearNotification(notification);
                }
            }

            var watchFolderToRemove = _watchFolders?.FirstOrDefault(w => w.Path == folderObject.Path);

            if (watchFolderToRemove != null)
            {
                _watchFolders.Remove(watchFolderToRemove);
            }

            _persistence.SaveProjectRequestList(_folderPathList);
            LoadProjectRequests();
        }
Example #32
0
 public static List <Meeple> GetOpenMeeples(List <Meeple> myMeeples)
 {
     return(myMeeples?.FindAll(
                meeple =>
                Validation.IsValidStartField(meeple.CurrentPosition) ||
                meeple.CurrentPosition.FieldType.Contains("StandardField")));
 }
Example #33
0
    static void Main()
    {
        List<int> list = new List<int>();
        for (int i = 1; i < 71; i++)
        {
            list.Add(i);
        }

        List<int> newList = list.FindAll(num => (num % 5 == 0 && num % 7 == 0));

        foreach (var item in newList)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine();

        // LINQ operation
        var divisable =
            from num in list
            where num % 5 == 0 && num % 7 == 0
            select num;

        foreach (var num in divisable)
        {
            Console.WriteLine(num);
        }
    }
Example #34
0
        public bool HasQuestInteract(Player plr, Creature crea)
        {
            if (Entry == 0)
            {
                return(false);
            }

            List <Quest> starter    = crea.Spawn.Proto.StartingQuests;
            List <Quest> finisher   = crea.Spawn.Proto.FinishingQuests;
            List <Quest> inProgress = starter?.FindAll(info => plr.QtsInterface.HasQuest(info.Entry) && !plr.QtsInterface.HasDoneQuest(info.Entry));

            if (starter != null && starter.FindAll(q => plr.QtsInterface.CanStartQuest(q)).Count > 0)
            {
                return(true);
            }

            if (finisher != null && finisher.FindAll(q => plr.QtsInterface.CanEndQuest(q)).Count > 0)
            {
                return(true);
            }

            if (inProgress != null && inProgress.Count > 0)
            {
                return(true);
            }

            return(false);
        }
Example #35
0
        static void Main(string[] args)
        {

            List<int>testArray = new List<int> { 1, 2, 3, 7, 11, 14, 12, 21};

            var findNumbersByPaternLambda = 
                testArray.FindAll((i) =>
            {
                return i % 3 == 0 || i % 7 == 0;
            });
            Console.WriteLine();
            Console.WriteLine("By Lambda");
            foreach (var item in findNumbersByPaternLambda)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            Console.WriteLine("By LINQ");
            var findNumberNyPaternLINQ =
                from num in testArray
                where num % 3 == 0 || num % 7 == 0
                select num;

            foreach (var item in findNumberNyPaternLINQ)
            {
                Console.WriteLine(item);
            }
        }
        /// <summary>
        /// 查询子级菜单
        /// </summary>
        /// <param name="model"></param>
        /// <param name="allmenus"></param>
        private void FindSubMenus(MenuModel model, List <MenuModel> allmenus)
        {
            //尝试查询子级菜单
            var submenus = allmenus?.FindAll(p => p.pid == model.id);

            submenus?.ForEach(item =>
            {
                //循环查询子级并添加
                if (model.children == null)
                {
                    //并集合初始化一次
                    model.children = new List <MenuModel>();
                }
                MenuModel submenusModel = new MenuModel
                {
                    //创建当前级别菜单
                    id            = item.id,
                    pid           = item.pid,
                    name          = item.name,
                    code          = item.code,
                    icon          = item.icon,
                    path          = item.path,
                    is_first_page = item.is_first_page
                };
                //再次检查当前子菜单是否还有子级菜单,如果有则添加到subMenusModel
                FindSubMenus(submenusModel, allmenus);
                //添加到子级菜单的集合中
                model.children.Add(submenusModel);
            });
        }
        private void OnAccomodationClick(object sender, EventArgs e)
        {
            listHostInfo.IsVisible          = true;
            placeOfInterest_group.IsVisible = false;

            if (lastFilter == filterAccomodation)
            {
                lastFilter = null;

                SeparatorAcc.BackgroundColor = (Color)Application.Current.Resources["Color_Background"];
                //filterAccomodation.BorderColor = (Color)Application.Current.Resources["Color_Background"];
                //filterTitleAccomodation.BackgroundColor = (Color)Application.Current.Resources["Color_Background"];

                listHostInfo.ItemsSource = null;
                listHostInfo.ItemsSource = listHostOriginal?.OrderBy(h => h.name).ToList();
            }
            else
            {
                lastFilter = filterAccomodation;

                SeparatorAcc.BackgroundColor = (Color)Application.Current.Resources["Color_SeparatorButton"];
                SeparatorAdv.BackgroundColor = (Color)Application.Current.Resources["Color_Background"];
                //SeparatorTr.BackgroundColor = (Color)Application.Current.Resources["Color_Background"];
                //filterAccomodation.BorderColor = (Color)Application.Current.Resources["Color_Background"];
                //filterAdventures.BorderColor = (Color)Application.Current.Resources["Color_Background"];
                //filterTravel.BorderColor = (Color)Application.Current.Resources["Color_Background"];

                //filterTitleAccomodation.BackgroundColor = (Color)Application.Current.Resources["Color_Background"];
                //filterTitleAdventures.BackgroundColor = (Color)Application.Current.Resources["Color_Background"];
                //filterTitleTravel.BackgroundColor = (Color)Application.Current.Resources["Color_Background"];

                listHostInfo.ItemsSource = null;
                listHostInfo.ItemsSource = listHost1?.FindAll(h => h.is_accommodation).OrderBy(h => h.name).ToList();
            }
        }
Example #38
0
        /// <summary>
        /// Créer la carte avec les lignes extraites du fichier d'entrée
        /// </summary>
        /// <param name="dataLines">Lignes extraites du fichier d'entrée</param>
        /// <returns></returns>
        public static Map CreateMapWithInitialData(List <string> dataLines)
        {
            Map    map             = new Map();
            string mapSizeDataLine = dataLines?.FirstOrDefault(l => l.StartsWith("C"));

            map.InitializeCells(mapSizeDataLine);
            List <string> mountainDataLines = dataLines?.FindAll(l => l.StartsWith("M"));

            map?.InitializeMountains(mountainDataLines);
            List <string> treasureDataLines = dataLines?.FindAll(l => l.StartsWith("T"));

            map?.InitializeTreasures(treasureDataLines);
            List <string> adventurerDataLines = dataLines?.FindAll(l => l.StartsWith("A"));

            map?.InitializeAdventurers(adventurerDataLines);
            return(map);
        }
Example #39
0
        public async Task <List <Events> > GetEventByUserName(string username)
        {
            var user = await _userService.GetUserByUsername(username);

            var events = eventsList?.FindAll(x => x.User_id == user.Id);

            return(events);
        }
Example #40
0
    public override void OnFocusUpdate()
    {
        if (Tank.Local == null && Input.GetKeyDown(KeyCode.Mouse0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hitInfo, 100) == true)
            {
                Entity ent = hitInfo.transform.GetComponent <Entity>();
                if (ent != null)
                {
                    ToggleFollow(ent);
                }
            }
        }

        Scroll();

        List <Entity> targets = m_Targets?.FindAll(x => !x.Is <Tank>() || x.GetComponent <Tank>().IsAlive);

        if (targets?.Count == 0)
        {
            return;
        }

        Vector3 middle;
        float   targetCameraDistance = 0;

        if (targets.Count == 1)
        {
            middle = targets[0].transform.position;
        }
        else
        {
            Vector3 min = Vector3.positiveInfinity;
            Vector3 max = Vector3.negativeInfinity;

            foreach (Entity ent in targets)
            {
                min = Vector3.Min(min, ent.transform.position);
                max = Vector3.Max(max, ent.transform.position);
            }

            middle = Vector3.Lerp(min, max, 0.5f);

            float maxDistance = Vector3.Magnitude(min - max);

            targetCameraDistance = (maxDistance / 2 / Camera.main.aspect) / Mathf.Tan(Camera.main.fieldOfView * Mathf.Deg2Rad / 2);
        }

        if (follow)
        {
            Position = middle + offset + offset.normalized * targetCameraDistance;
        }
        if (look)
        {
            Rotation = Quaternion.LookRotation(middle - Position);
        }
    }
Example #41
0
 private void UpdateTotalInfo()
 {
     Invoke(new Action(() => {
         int totalBoxNum     = (int)currentBoxList?.Count(i => i.PACKRESULT == "S" && i.RESULT == "S").CastTo <int>(0);
         int totalNum        = (int)currentBoxList?.FindAll(i => i.PACKRESULT == "S" && i.RESULT == "S").Sum(j => j.Details?.Count);
         lblTotalBoxNum.Text = totalBoxNum.ToString();
         lblTotalNum.Text    = totalNum.ToString();
     }));
 }
Example #42
0
        private void CreateStaticTextData()
        {
            if (Pat == null)
            {
                return;
            }
            //Procedure CodeNums-------------------------------------------------------------------------------------------------------------
            List <long> listProcCodeNums = new List <long>();
            //ListIntraoralAndBiteWings consists of the following proccodes: D0210, D0270, D0272, D0274, D0277, D0273
            List <long> listIntraoralAndBiteWings = new List <long>();
            //listOralEvals consists of the following proccodes: D0120, D0140, D0150, D0160
            List <long> listOralEvals = new List <long>();
            //listProphy consists of the following proccodes: D1110, D1120, D1201, D1205
            List <long> listProphy                     = new List <long>();
            List <long> listIntraoralComplete          = new List <long>();
            List <long> listBiteWingSingle             = new List <long>();
            List <long> listBiteWingsTwo               = new List <long>();
            List <long> listBiteWingsFour              = new List <long>();
            List <long> listVertBiteWings7to8          = new List <long>();
            List <long> listBiteWingsThree             = new List <long>();
            List <long> listPerioOralEval              = new List <long>();
            List <long> listLimitedOralEval            = new List <long>();
            List <long> listCompOralEval               = new List <long>();
            List <long> listDetailedExtensiveOralEval  = new List <long>();
            List <long> listPerioMaintenance           = new List <long>();
            List <long> listPanoramicFilm              = new List <long>();
            List <long> listProphylaxisAdult           = new List <long>();
            List <long> listProphylaxisChild           = new List <long>();
            List <long> listTopicalFluorideProphyChild = new List <long>();
            List <long> listTopicalFluorideProphyAdult = new List <long>();

            listProcCodeNums = SheetFiller.GetListProcCodeNumsForStaticText(listIntraoralAndBiteWings, listOralEvals, listProphy, ref listIntraoralComplete
                                                                            , ref listBiteWingSingle, ref listBiteWingsTwo, ref listBiteWingsThree, ref listBiteWingsFour, ref listVertBiteWings7to8, ref listPerioOralEval
                                                                            , ref listLimitedOralEval, ref listCompOralEval, ref listDetailedExtensiveOralEval, ref listPerioMaintenance, ref listPanoramicFilm
                                                                            , ref listProphylaxisAdult, ref listProphylaxisChild, ref listTopicalFluorideProphyChild, ref listTopicalFluorideProphyAdult);
            //Create a new StaticTextData object, using data we already have, supplementing with queried data where necessary.
            StaticTextData                       = new StaticTextData();
            StaticTextData.PatNote               = PatNote;
            StaticTextData.ListRefAttaches       = ListRefAttaches;
            StaticTextData.ListInsSubs           = ListInsSubs;
            StaticTextData.ListInsPlans          = ListInsPlans;
            StaticTextData.ListPatPlans          = ListPatPlans;
            StaticTextData.ListBenefits          = ListBenefits;
            StaticTextData.HistList              = HistList;
            StaticTextData.ListTreatPlans        = ListTreatPlans;
            StaticTextData.ListRecallsForFam     = ListRecalls;
            StaticTextData.ListAppts             = ListAppts;
            StaticTextData.ListFutureApptsForFam = ListAppts?.FindAll(x => x.AptDateTime > DateTime.Now && x.AptStatus == ApptStatus.Scheduled);
            StaticTextData.ListDiseases          = ListDiseases;
            StaticTextData.ListAllergies         = ListAllergies;
            StaticTextData.ListMedicationPats    = ListMedPats;
            //StaticTextData.ListFamPopups=Popups.GetForFamily(Pat);//Will be handled by StaticTextData.GetStaticTextData() if necessary.
            StaticTextData.ListProceduresSome = ListProcedures?.FindAll(x => x.CodeNum.In(listProcCodeNums));
            StaticTextData.ListDocuments      = ListDocuments;
            StaticTextData.ListProceduresPat  = ListProcedures;
            StaticTextData.ListPlannedAppts   = ListPlannedAppts;
        }
Example #43
0
        /// <summary>
        /// 为输出参数赋值
        /// </summary>
        /// <param name="DBParameters">传入的输出参数</param>
        /// <param name="result">生成的输出参数</param>
        void SETDBOutParameters(List <DBParameters> DBParameters, List <DbParameter> result)
        {
            var left  = DBParameters?.FindAll(m => m.Direction == ParameterDirection.Output);
            var right = result?.FindAll(m => m.Direction == ParameterDirection.Output);

            if (left?.Count > 0 && right?.Count > 0)
            {
                left.ForEach(m => m.Value = right?.Find(k => k.ParameterName.TrimStart('@') == m.ParameterName.TrimStart('@'))?.Value);
            }
        }
Example #44
0
        public List <Order> findByAgentEmail(string email)
        {
            List <Order> orders = getAll();

            orders?.ForEach(o => {
                o.tour = tourRepository.findById((long)o.tour.tourId);
            });
            orders?.FindAll(o => o.tour.user.email.Equals(email));
            return(orders);
        }
Example #45
0
        public BoundingBox2D GetBoundingBox(double offset = 0)
        {
            List <BoundingBox2D> boundingBox2Ds = face2Ds?.FindAll(x => x != null).ConvertAll(x => x.GetBoundingBox(offset));

            if (boundingBox2Ds == null || boundingBox2Ds.Count == 0)
            {
                return(null);
            }

            return(new BoundingBox2D(boundingBox2Ds));
        }
 public List <ApplicationViewModel> Get(string id)
 {
     if (string.IsNullOrEmpty(id))
     {
         return(_applications);
     }
     else
     {
         return(_applications?.FindAll(a => a.ApplicationId.ToString() == id));
     }
 }
Example #47
0
        public static float GetCumVolume(this Pawn pawn, List <Hediff> hediffs)
        {
            CompHediffBodyPart part = hediffs?.FindAll((Hediff hed) => hed.def.defName.ToLower().Contains("penis")).InRandomOrder().FirstOrDefault()?.TryGetComp <CompHediffBodyPart>();

            if (part == null)
            {
                part = hediffs?.FindAll((Hediff hed) => hed.def.defName.ToLower().Contains("ovipositorf")).InRandomOrder().FirstOrDefault()?.TryGetComp <CompHediffBodyPart>();
            }
            if (part == null)
            {
                part = hediffs?.FindAll((Hediff hed) => hed.def.defName.ToLower().Contains("ovipositorm")).InRandomOrder().FirstOrDefault()?.TryGetComp <CompHediffBodyPart>();
            }
            if (part == null)
            {
                part = hediffs?.FindAll((Hediff hed) => hed.def.defName.ToLower().Contains("tentacle")).InRandomOrder().FirstOrDefault()?.TryGetComp <CompHediffBodyPart>();
            }


            return(pawn.GetCumVolume(part));
        }
Example #48
0
        private void BaseButton4_Click(object sender, EventArgs e)
        {
            //找出勾选的款项
            List <CheckStoreDetail> list        = dataGridView1.DataSource as List <CheckStoreDetail>;
            List <CheckStoreDetail> uncheckList = list?.FindAll(t => t.Selected);

            if (uncheckList != null && uncheckList.Count > 0)
            {
                SameWithStoreClick?.Invoke(uncheckList, null);
                Reload();
            }
        }
Example #49
0
        private static List <EnvDTE.Window> FindAllLinkedWindows(EnvDTE.Window window, List <EnvDTE.Window> linkedParentWindows)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var top  = window.Top;
            var left = window.Left;

            return(linkedParentWindows?.FindAll((eachWindow) =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                return eachWindow.Top == top && eachWindow.Left == left;
            }));
        }
Example #50
0
 public static async Task <List <Item> > FindItemsAsync(string searchText)
 {
     return(await Task.Run(() =>
     {
         try
         {
             return Items?.FindAll(s => (s.LocalizedName().ToLower().Contains(searchText.ToLower())));
         }
         catch (Exception ex)
         {
             Debug.Print(ex.Message);
             return null;
         }
     }));
 }
        private void CalculateWordFrequency(string [] wordsList)
        {
            List <WordStats> stats = new List <WordStats>();

            foreach (var word in wordsList)
            {
                if (stats?.FindAll(x => x.Word.Equals(word)).Count == 0)
                {
                    int count = wordsList.ToList().FindAll(x => x.Equals(word)).Count;
                    stats.Add(new WordStats {
                        Word = word, Count = count
                    });
                }
            }
            WordStats = stats;
        }
Example #52
0
 //for system/mobile notification
 public void BeforeSaveValidation4SysMobNotification(Dictionary <int, EbControlWrapper> _dict,
                                                     EbFnSys_NotifyBy NotifyBy, List <Int32> Roles, int UserGroup, EbScript Users,
                                                     Dictionary <string, string> QryParams, string type)
 {
     if (NotifyBy == EbFnSys_NotifyBy.Roles)
     {
         if (!(Roles?.FindAll(e => e > 0).Count() > 0))
         {
             throw new FormException($"Invalid roles found for {type} notification");
         }
     }
     else if (NotifyBy == EbFnSys_NotifyBy.UserGroup)
     {
         if (UserGroup <= 0)
         {
             throw new FormException($"Invalid user group found for {type} notification");
         }
     }
     else if (NotifyBy == EbFnSys_NotifyBy.Users)
     {
         QryParams = new Dictionary <string, string>();//<param, table>
         if (string.IsNullOrWhiteSpace(Users?.Code))
         {
             throw new FormException($"Required SQL query for {type} notification");
         }
         MatchCollection matchColl = Regex.Matches(Users.Code, @"(?<=@)(\w+)|(?<=:)(\w+)");
         foreach (Match match in matchColl)
         {
             KeyValuePair <int, EbControlWrapper> item = _dict.FirstOrDefault(e => e.Value.Control.Name == match.Value);
             if (item.Value == null)
             {
                 throw new FormException($"Can't resolve {match.Value} in SQL query of {type} notification");
             }
             if (!QryParams.ContainsKey(item.Value.Control.Name))
             {
                 QryParams.Add(item.Value.Control.Name, item.Value.TableName);
             }
         }
     }
     else
     {
         throw new FormException($"Invalid NotifyBy found for {type} notification");
     }
 }
Example #53
0
        public void Initialize(bool hideAll, bool isEnableList, int customerTypeValue = -1)
        {
            this.hideAll      = hideAll;
            this.isEnableList = isEnableList;
            CustomerTypeValue = customerTypeValue;
            List <PfCustomer> list = new List <PfCustomer>();

            if (!hideAll)
            {
                list.Add(new PfCustomer()
                {
                    Name           = CommonGlobalUtil.COMBOBOX_ALL,
                    FirstCharSpell = DisplayUtil.GetPYString(CommonGlobalUtil.COMBOBOX_ALL),
                    ID             = null
                });
            }
            List <PfCustomer> pfCustomerList = PfCustomerCache.PfCustomerList;

            if (pfCustomerList != null && CustomerTypeValue != -1)
            {
                pfCustomerList = pfCustomerList.FindAll(t => t.CustomerType == CustomerTypeValue);
            }

            if (isEnableList)
            {
                List <PfCustomer> pfs = pfCustomerList?.FindAll(t => t.Enabled);
                if (pfs != null)
                {
                    list.AddRange(pfs);
                }
            }
            else
            {
                List <PfCustomer> pfs = pfCustomerList;
                if (pfs != null)
                {
                    list.AddRange(pfs);
                }
            }
            DisplayMember = "Name";
            ValueMember   = "ID";
            DataSource    = list;
        }
Example #54
0
        /// <summary>
        /// Resolves all the matching <see cref="IEngineService"/> objects from the services list.
        /// </summary>
        public static List <TService> GetAllServices <TService> (Predicate <TService> predicate = null, bool assertResult = true)
            where TService : class, IEngineService
        {
            var result        = new List <TService>();
            var resolvingType = typeof(TService);

            var servicesOfType = services?.FindAll(s => resolvingType.IsAssignableFrom(s.GetType()));

            if (servicesOfType != null && servicesOfType.Count > 0)
            {
                result = servicesOfType.FindAll(s => predicate is null || predicate(s as TService)).Cast <TService>().ToList();
            }

            if (result is null && assertResult)
            {
                Debug.LogError($"Failed to resolve service of type '{resolvingType}': service not found.");
            }

            return(result);
        }
Example #55
0
        public SintesiRichiesta GetSintesi(string codiceRichiesta)
        {
            var richiesta = GetByCodice(codiceRichiesta);
            var sintesi   = new SintesiRichiesta();

            var rubrica = new List <EnteDTO>();

            if (richiesta.CodEntiIntervenuti != null)
            {
                rubrica = _getRubrica.GetBylstCodici(richiesta.CodEntiIntervenuti.Select(c => int.Parse(c)).ToArray());
            }

            if (richiesta.CodUOCompetenza != null)
            {
                sintesi = _mapperSintesi.Map(richiesta);
                sintesi.ListaEntiIntervenuti = rubrica.Count > 0 ? rubrica?.FindAll(c => richiesta.CodEntiIntervenuti?.Contains(c.Codice.ToString()) ?? false) : null;
                sintesi.Competenze           = MapCompetenze(richiesta.CodUOCompetenza);
                sintesi.SediAllertate        = richiesta.CodSOAllertate != null?MapCompetenze(richiesta.CodSOAllertate.ToArray()) : null;
            }

            return(sintesi);
        }
Example #56
0
        public async Task <bool> HasUserRequestedTooMany(string username, int songRequestLimit)
        {
            try
            {
                if (_songRequestPlaylistVideoIds == null && !_initialLoadYoutubePlaylist)
                {
                    _songRequestPlaylistVideoIds = await _youTubeClientInstance.GetPlaylistItems(_botConfig.YouTubeBroadcasterPlaylistId);
                }

                await WaitForInitialPlaylistLoad();

                if (_songRequestPlaylistVideoIds?.FindAll(p => p.ContentDetails.Note.Contains(username))?.Count >= songRequestLimit)
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                await _errHndlrInstance.LogError(ex, "LibVLCSharpPlayer", "HasUserRequestedTooMany(string, int)", false);
            }

            return(false);
        }
Example #57
0
        private void baseButton1_Click(object sender, EventArgs e)
        {
            List <CheckStoreDetail> list        = dataGridView1.DataSource as List <CheckStoreDetail>;
            List <CheckStoreDetail> uncheckList = list?.FindAll(t => t.Selected);

            try
            {
                if (uncheckList != null && uncheckList.Count > 0)
                {
                    ZeroClick?.Invoke(uncheckList, null);
                    Reload();
                }
            }
            catch (Exception ex)
            {
                CommonGlobalUtil.ShowError(ex);
            }
            finally
            {
                CompleteProgressForm();
                UnLockPage();
            }
        }
    public override object?ToEditor(IProperty property, string?culture = null, string?segment = null)
    {
        var value = property.GetValue(culture, segment)?.ToString();

        if (string.IsNullOrEmpty(value))
        {
            return(Enumerable.Empty <object>());
        }

        try
        {
            List <LinkDto>?links = JsonConvert.DeserializeObject <List <LinkDto> >(value);

            List <LinkDto>?documentLinks = links?.FindAll(link =>
                                                          link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Document);
            List <LinkDto>?mediaLinks = links?.FindAll(link =>
                                                       link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Media);

            var entities = new List <IEntitySlim>();
            if (documentLinks?.Count > 0)
            {
                entities.AddRange(
                    _entityService.GetAll(
                        UmbracoObjectTypes.Document,
                        documentLinks.Select(link => link.Udi !.Guid).ToArray()));
            }

            if (mediaLinks?.Count > 0)
            {
                entities.AddRange(
                    _entityService.GetAll(UmbracoObjectTypes.Media, mediaLinks.Select(link => link.Udi !.Guid).ToArray()));
            }

            var result = new List <LinkDisplay>();
            if (links is null)
            {
                return(result);
            }

            foreach (LinkDto dto in links)
            {
                GuidUdi?udi       = null;
                var     icon      = "icon-link";
                var     published = true;
                var     trashed   = false;
                var     url       = dto.Url;

                if (dto.Udi != null)
                {
                    IUmbracoEntity?entity = entities.Find(e => e.Key == dto.Udi.Guid);
                    if (entity == null)
                    {
                        continue;
                    }

                    IPublishedSnapshot publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
                    if (entity is IDocumentEntitySlim documentEntity)
                    {
                        icon      = documentEntity.ContentTypeIcon;
                        published = culture == null
                            ? documentEntity.Published
                            : documentEntity.PublishedCultures.Contains(culture);
                        udi     = new GuidUdi(Constants.UdiEntityType.Document, documentEntity.Key);
                        url     = publishedSnapshot.Content?.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
                        trashed = documentEntity.Trashed;
                    }
                    else if (entity is IContentEntitySlim contentEntity)
                    {
                        icon      = contentEntity.ContentTypeIcon;
                        published = !contentEntity.Trashed;
                        udi       = new GuidUdi(Constants.UdiEntityType.Media, contentEntity.Key);
                        url       = publishedSnapshot.Media?.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
                        trashed   = contentEntity.Trashed;
                    }
                    else
                    {
                        // Not supported
                        continue;
                    }
                }

                result.Add(new LinkDisplay
                {
                    Icon        = icon,
                    Name        = dto.Name,
                    Target      = dto.Target,
                    Trashed     = trashed,
                    Published   = published,
                    QueryString = dto.QueryString,
                    Udi         = udi,
                    Url         = url ?? string.Empty,
                });
            }

            return(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting links");
        }

        return(base.ToEditor(property, culture, segment));
    }
Example #59
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="dataAccess">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess dataAccess)
        {
            int index;

            bool run = false;

            index = Params.IndexOfInputParam("_run");
            if (index == -1 || !dataAccess.GetData(index, ref run))
            {
                run = false;
            }

            if (!run)
            {
                return;
            }

            index = Params.IndexOfInputParam("_pathTasTSD");
            if (index == -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            string path_TSD = null;

            if (!dataAccess.GetData(index, ref path_TSD) || string.IsNullOrWhiteSpace(path_TSD))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            index = Params.IndexOfInputParam("_pathTasTBD");
            if (index == -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            string path_TBD = null;

            if (!dataAccess.GetData(index, ref path_TBD) || string.IsNullOrWhiteSpace(path_TBD))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            index = Params.IndexOfInputParam("_analyticalObject");
            if (index == -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Core.SAMObject sAMObject = null;
            if (!dataAccess.GetData(index, ref sAMObject) || sAMObject == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            bool unmetHours = false;

            index = Params.IndexOfInputParam("_runUnmetHours_");
            if (index != -1)
            {
                if (!dataAccess.GetData(index, ref unmetHours))
                {
                    unmetHours = true;
                }
            }

            double unmetHoursMargin = 0.5;

            index = Params.IndexOfInputParam("_unmetHoursMargin_");
            if (index != -1)
            {
                if (!dataAccess.GetData(index, ref unmetHoursMargin))
                {
                    unmetHoursMargin = 0.5;
                }
            }

            AdjacencyCluster adjacencyCluster = null;

            if (sAMObject is AdjacencyCluster)
            {
                adjacencyCluster = new AdjacencyCluster((AdjacencyCluster)sAMObject);
            }
            else if (sAMObject is AnalyticalModel)
            {
                adjacencyCluster = ((AnalyticalModel)sAMObject).AdjacencyCluster;
            }

            List <Core.Result> results = null;

            if (adjacencyCluster != null)
            {
                results = Analytical.Tas.Modify.AddResults(path_TSD, adjacencyCluster);

                if (unmetHours)
                {
                    List <Core.Result> results_UnmetHours = Analytical.Tas.Query.UnmetHours(path_TSD, path_TBD, unmetHoursMargin);
                    if (results_UnmetHours != null && results_UnmetHours.Count > 0)
                    {
                        foreach (Core.Result result in results_UnmetHours)
                        {
                            if (result is AdjacencyClusterSimulationResult)
                            {
                                adjacencyCluster.AddObject(result);
                                results.Add(result);
                            }
                            else if (result is SpaceSimulationResult)
                            {
                                SpaceSimulationResult spaceSimulationResult = (SpaceSimulationResult)result;

                                List <SpaceSimulationResult> spaceSimulationResults = Analytical.Tas.Query.Results(results, spaceSimulationResult);
                                if (spaceSimulationResults == null)
                                {
                                    results.Add(spaceSimulationResult);
                                }
                                else
                                {
                                    spaceSimulationResults.ForEach(x => Core.Modify.Copy(spaceSimulationResult, x, SpaceSimulationResultParameter.UnmetHourFirstIndex, SpaceSimulationResultParameter.UnmetHours, SpaceSimulationResultParameter.OccupiedUnmetHours));
                                }
                            }
                        }
                    }
                }

                adjacencyCluster = Analytical.Tas.Modify.UpdateDesignLoads(path_TBD, adjacencyCluster);

                if (sAMObject is AdjacencyCluster)
                {
                    sAMObject = adjacencyCluster;
                }
                else if (sAMObject is AnalyticalModel)
                {
                    sAMObject = new AnalyticalModel((AnalyticalModel)sAMObject, adjacencyCluster);
                }
            }

            index = Params.IndexOfOutputParam("analyticalObject");
            if (index != -1)
            {
                dataAccess.SetData(index, sAMObject);
            }

            index = Params.IndexOfOutputParam("zoneSimulationResultsHeating");
            if (index != -1)
            {
                dataAccess.SetDataList(index, results?.FindAll(x => x is ZoneSimulationResult && ((ZoneSimulationResult)x).LoadType() == LoadType.Heating));
            }

            index = Params.IndexOfOutputParam("spaceSimulationResultsHeating");
            if (index != -1)
            {
                dataAccess.SetDataList(index, results?.FindAll(x => x is SpaceSimulationResult && ((SpaceSimulationResult)x).LoadType() == LoadType.Heating));
            }

            index = Params.IndexOfOutputParam("zoneSimulationResultsCooling");
            if (index != -1)
            {
                dataAccess.SetDataList(index, results?.FindAll(x => x is ZoneSimulationResult && ((ZoneSimulationResult)x).LoadType() == LoadType.Cooling));
            }

            index = Params.IndexOfOutputParam("spaceSimulationResultsCooling");
            if (index != -1)
            {
                dataAccess.SetDataList(index, results?.FindAll(x => x is SpaceSimulationResult && ((SpaceSimulationResult)x).LoadType() == LoadType.Cooling));
            }

            index = Params.IndexOfOutputParam("panelSimulationResultsCooling");
            if (index != -1)
            {
                dataAccess.SetDataList(index, results?.FindAll(x => x is PanelSimulationResult && Analytical.Query.LoadType(((PanelSimulationResult)x)) == LoadType.Cooling));
            }

            index = Params.IndexOfOutputParam("panelSimulationResultsHeating");
            if (index != -1)
            {
                dataAccess.SetDataList(index, results?.FindAll(x => x is PanelSimulationResult && Analytical.Query.LoadType(((PanelSimulationResult)x)) == LoadType.Heating));
            }

            index = Params.IndexOfOutputParam("_adjacencyClusterSimulationResultCooling");
            if (index != -1)
            {
                dataAccess.SetData(index, results?.Find(x => x is AdjacencyClusterSimulationResult && Analytical.Query.LoadType(((AdjacencyClusterSimulationResult)x)) == LoadType.Cooling));
            }

            index = Params.IndexOfOutputParam("adjacencyClusterSimulationResultHeating");
            if (index != -1)
            {
                dataAccess.SetData(index, results?.Find(x => x is AdjacencyClusterSimulationResult && Analytical.Query.LoadType(((AdjacencyClusterSimulationResult)x)) == LoadType.Heating));
            }
        }
Example #60
0
        private void skinComboBox_TextUpdate(object sender, EventArgs e)
        {
            try
            {
                List <PfCustomer> listNew = new List <PfCustomer>();
                //  skinComboBox_Brand.Items.Clear();
                SkinComboBox      box  = (SkinComboBox)sender;
                List <PfCustomer> temp = (List <PfCustomer>)box.DataSource;
                if (temp != null && temp.Count == 0)
                {
                    List <PfCustomer> tempList = new List <PfCustomer>();
                    tempList[0].ID    = null;
                    tempList[0].Name  = null;
                    box.DisplayMember = "Name";
                    box.ValueMember   = "ID";
                    box.DataSource    = tempList;
                    return;
                }

                String str = box.Text;
                curSelectStr = str;

                List <PfCustomer> pfCustomerList = PfCustomerCache.PfCustomerList;
                if (pfCustomerList != null && CustomerTypeValue != -1)
                {
                    pfCustomerList = pfCustomerList.FindAll(t => t.CustomerType == CustomerTypeValue);
                }

                if (String.IsNullOrEmpty(str))
                {
                    if (!hideAll)
                    {
                        listNew.Add(new PfCustomer()
                        {
                            Name           = CommonGlobalUtil.COMBOBOX_ALL,
                            FirstCharSpell = DisplayUtil.GetPYString(CommonGlobalUtil.COMBOBOX_ALL),
                            ID             = null
                        });
                    }
                    if (isEnableList)
                    {
                        listNew.AddRange(pfCustomerList?.FindAll(t => t.Enabled));
                    }
                    else
                    {
                        listNew.AddRange(pfCustomerList);
                    }
                }
                else
                {
                    if (!hideAll)
                    {
                        listNew.Add(new PfCustomer()
                        {
                            Name           = CommonGlobalUtil.COMBOBOX_ALL,
                            FirstCharSpell = DisplayUtil.GetPYString(CommonGlobalUtil.COMBOBOX_ALL),
                            ID             = null
                        });
                    }
                    List <PfCustomer> list = new List <PfCustomer>();
                    if (isEnableList)
                    {
                        list.AddRange(pfCustomerList?.FindAll(t => t.Enabled));
                    }
                    else
                    {
                        list.AddRange(pfCustomerList);
                    }

                    foreach (var item in list)
                    {
                        if ((item.FirstCharSpell).ToUpper().Contains(str.ToUpper()) || (item.ID).ToUpper().Contains(str.ToUpper()) || (item.Name).ToUpper().Contains(str.ToUpper()))
                        {
                            listNew.Add(item);
                        }
                    }
                }

                if (listNew.Count == 0)
                {
                    if (!HideEmpty)
                    {
                        listNew.Add(new PfCustomer()
                        {
                            ID             = null,
                            Name           = "(无)",
                            FirstCharSpell = DisplayUtil.GetPYString("(无)")
                        });
                    }
                }

                //box.DataSource = null;
                if (isEnableList)
                {
                    listNew = listNew.FindAll(t => t.Enabled);
                }

                if (listNew == null || listNew.Count == 0)
                {
                    List <PfCustomer> tempList = new List <PfCustomer>();
                    PfCustomer        firstPC  = new PfCustomer();
                    firstPC.ID   = null;
                    firstPC.Name = null;
                    tempList.Add(firstPC);
                    box.DisplayMember = "Name";
                    box.ValueMember   = "ID";
                    box.DataSource    = tempList;
                }
                else
                {
                    List <PfCustomer> PfList = new List <PfCustomer>();

                    if (!hideAll && this.Text == "")
                    {
                        PfList.Add(new PfCustomer()
                        {
                            Name           = CommonGlobalUtil.COMBOBOX_ALL,
                            FirstCharSpell = DisplayUtil.GetPYString(CommonGlobalUtil.COMBOBOX_ALL),
                            ID             = null
                        });
                    }
                    PfList.AddRange(listNew);
                    box.DisplayMember = "Name";
                    box.ValueMember   = "ID";
                    box.DataSource    = PfList;
                }
                box.DroppedDown = true;//自动展开下拉框
                box.Text        = str;
                curSelectStr    = str;
                //box.sele = str;
                box.Select(box.Text.Length, 0);
                //滚动到控件光标处
                // box.ScrollToCaret();
                //box.SelectionStart = str.Length;
                // box.Cursor = Cursors.Default;

                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                box.Cursor = System.Windows.Forms.Cursors.Default;
            }
            catch (Exception ex)
            {
                //  CommonGlobalUtil.ShowError(ex);
            }
        }