Beispiel #1
0
		private void SortCollection()
		{
			this.orderedEventRooms = 
				from t in this.events.Take(40)
				orderby t.Value descending
				select t;
		}
 static void Print(IOrderedEnumerable<List<int>> sortedResults)
 {
     foreach (var item in sortedResults)
     {
         Console.WriteLine("{0} = {1}", string.Join(" + ", item), endResult);
     }
 }
 public void GatherCollections(ISearchCmdletBaseDataObject searchCriteria, List<ITestSuite> suitesForSearch)
 {
     var testResultsSearcher = new TestResultsSearcher();
     TestSuites = testResultsSearcher.SearchForSuites(searchCriteria, suitesForSearch);
     TestScenarios = testResultsSearcher.SearchForScenarios(searchCriteria, suitesForSearch);
     TestResults = testResultsSearcher.SearchForTestResults(searchCriteria, suitesForSearch);
 }
 public XElement CreateSuitesXElementWithParameters(
         IOrderedEnumerable<ITestSuite> suites,
         IOrderedEnumerable<ITestScenario> scenarios,
         IOrderedEnumerable<ITestResult> testResults,
         IXMLElementsStruct xmlStruct)
 {
     var suitesElement = 
         new XElement(xmlStruct.SuitesNode,
                      from suite in suites
                      select new XElement(xmlStruct.SuiteNode,
                                          new XAttribute("uniqueId", suite.UniqueId),
                                          new XAttribute("id", suite.Id),
                                          new XAttribute("name", suite.Name),
                                          new XAttribute("status", suite.Status),
                                          createXattribute(xmlStruct.TimeSpentAttribute, Convert.ToInt32(suite.Statistics.TimeSpent)),
                                          new XAttribute("all", suite.Statistics.All.ToString()),
                                          new XAttribute("passed", suite.Statistics.Passed.ToString()),
                                          createXattribute(xmlStruct.FailedAttribute, suite.Statistics.Failed.ToString()),
                                          new XAttribute("notTested", suite.Statistics.NotTested.ToString()),
                                          new XAttribute("knownIssue", suite.Statistics.PassedButWithBadSmell.ToString()),
                                          createXattribute("description", suite.Description),
                                          createXattribute("platformId", suite.PlatformId),
                                          createXattribute("platformUniqueId", suite.PlatformUniqueId),
                                          CreateScenariosXElementCommon(
                                              suite,
                                              // 20141122
                                              // scenarios.Where(scenario => scenario.SuiteId == suite.Id).OrderBy(scenario => scenario.Id),
                                              // testResults.Where(testResult => testResult.SuiteId == suite.Id).OrderBy(testResult => testResult.Id),
                                              scenarios.Where(scenario => scenario.SuiteId == suite.Id && scenario.SuiteUniqueId == suite.UniqueId).OrderBy(scenario => scenario.Id),
                                              testResults.Where(testResult => testResult.SuiteId == suite.Id && testResult.SuiteUniqueId == suite.UniqueId).OrderBy(testResult => testResult.Id),
                                              xmlStruct)
                                          )
                     );
     return suitesElement;
 }
Beispiel #5
0
        public ZapperProcessor(FileZapperSettings settings = null, IList<IZapperPhase> phases = null)
        {
            _log.Info("Initializing");

            ZapperFiles = new ConcurrentDictionary<string, ZapperFile>();
            ZapperFilesDeleted = new ConcurrentDictionary<string, ZapperFileDeleted>();

            if (settings == null)
            {
                settings = new FileZapperSettings();
                settings.Load();
            }
            Settings = settings;

            if (phases != null)
            {
                foreach (var phase in phases) { phase.ZapperProcessor = this; }
                _phases = phases.OrderBy(x => x.PhaseOrder);
            }
            else
            {
                List<IZapperPhase> allphases = new List<IZapperPhase>();
                allphases.Add(new PhaseCleanup { PhaseOrder = 1, ZapperProcessor = this, IsInitialPhase = true });
                allphases.Add(new PhaseParseFilesystem { PhaseOrder = 2, ZapperProcessor = this });
                allphases.Add(new PhaseCalculateSamples { PhaseOrder = 3, ZapperProcessor = this });
                allphases.Add(new PhaseCalculateHashes { PhaseOrder = 4, ZapperProcessor = this });
                allphases.Add(new PhaseRemoveDuplicates { PhaseOrder = 5, ZapperProcessor = this });
                _phases = allphases.OrderBy(x => x.PhaseOrder);
            }
        }
        public DisplayPackageViewModel(Package package, IOrderedEnumerable<Package> packageHistory, bool isVersionHistory)
            : base(package)
        {
            Copyright = package.Copyright;

            if (!isVersionHistory)
            {
                Dependencies = new DependencySetsViewModel(package.Dependencies);
                PackageVersions = packageHistory.Select(p => new DisplayPackageViewModel(p, packageHistory, isVersionHistory: true));
            }

            DownloadCount = package.DownloadCount;
            LastEdited = package.LastEdited;

            if (!isVersionHistory && packageHistory.Any())
            {
                // calculate the number of days since the package registration was created
                // round to the nearest integer, with a min value of 1
                // divide the total download count by this number
                TotalDaysSinceCreated = Convert.ToInt32(Math.Max(1, Math.Round((DateTime.UtcNow - packageHistory.Last().Created).TotalDays)));
                DownloadsPerDay = TotalDownloadCount / TotalDaysSinceCreated; // for the package
            }
            else
            {
                TotalDaysSinceCreated = 0;
                DownloadsPerDay = 0;
            }
        }
Beispiel #7
0
        protected virtual bool GetMatchedRecords(
            IOrderedEnumerable<IRecord> recordsFilteredByDate, 
            IModelInput modelInput,
            out IDictionary<string, IList<IRecord>> matchedRecords
        )
        {
            matchedRecords = new Dictionary<string, IList<IRecord>>();
            if (!recordsFilteredByDate.AnySave())
            {
                return false;
            }

            foreach (var record in recordsFilteredByDate)
            {
                foreach (var term in modelInput.FilterTerms)
                {
                    var distinctMatchedDescription = GetMatchedDistinctDescription(record.Description, term);
                    record.DistinctDescription = distinctMatchedDescription;
                    if (string.IsNullOrEmpty(distinctMatchedDescription))
                    {
                        continue;
                    }
                    if (matchedRecords.ContainsKey(distinctMatchedDescription))
                    {
                        matchedRecords[distinctMatchedDescription].Add(record);
                    }
                    else
                    {
                        matchedRecords.Add(distinctMatchedDescription, new List<IRecord>() { record });
                    }
                    break;
                }
            }
            return matchedRecords.Any();
        }
 public ProtocolReport(ReportModel model)
     : base(model, "ProtocolTemplate.docx")
 {
     this.modelItems = ReportModel.ReportParameters["ProtocolResults"] as IOrderedEnumerable<ProtocolResult>;
     this.hasMKB = this.modelItems.Any(pr => pr.ProductTest.Test.TestType.ShortName == TestTypes.MKB);
     this.hasFZH = this.modelItems.Any(pr => pr.ProductTest.Test.TestType.ShortName == TestTypes.FZH);
 }
Beispiel #9
0
        public static StringBuilder ReplaceForbbidenWords(string text, IOrderedEnumerable<KeyValuePair<string, List<int>>> sortedLocations)
        {
            const char STAR_SYMBOL = '*';

            StringBuilder result = new StringBuilder();
            int index = 0;

            foreach (var forbiddenWord in sortedLocations)
            {
                foreach (var location in forbiddenWord.Value)
                {
                    for (; index < text.Length; index++)
                    {
                        if (index >= location && index < location + forbiddenWord.Key.Length)
                        {
                            result.Append(STAR_SYMBOL);
                        }
                        else
                        {
                            result.Append(text[index]);
                        }
                        if (index == location + forbiddenWord.Key.Length)
                        {
                            break;
                        }
                    }
                }
            }

            return result;
        }
        private double Percentile(IOrderedEnumerable<double> sortedData, double p)
        {
            int count = sortedData.Count();
            if (count == 0) return 0;
            if (count == 1) return sortedData.Last();
            if (p >= 100.0d) return sortedData.Last();

            double position = (count + 1) * p / 100d;
            double leftNumber, rightNumber;

            double n = p / 100d * (count - 1) + 1d;

            if (position >= 1)
            {
                leftNumber = sortedData.ElementAt((int)Math.Floor(n) - 1);
                rightNumber = sortedData.ElementAt((int)Math.Floor(n));
            }
            else
            {
                leftNumber = sortedData.First();
                rightNumber = sortedData.ElementAt(1);
            }

            if (Math.Abs(leftNumber - rightNumber) < Double.Epsilon)
                return leftNumber;
            else
            {
                double part = n - Math.Floor(n);
                return leftNumber + part*(rightNumber - leftNumber);
            }
        }
        /// <summary>
        /// Colors the graph and returns the number of colors needed
        /// </summary>
        private static int ColorGraphAndGetColorCount(IOrderedEnumerable<Node> sortedRepeaters )
        {
            int maxColor = 0;

            foreach(Node node in sortedRepeaters)
            {
                int minColorNotUsed = 0;
                List<int> colorsUsed = new List<int>();
                foreach (Node adjacentNode in node.AdjacentNodes)
                {
                    if (adjacentNode.Color != -1)
                        colorsUsed.Add(adjacentNode.Color);
                }

                //its a planar graph so no more than 4 colors needed
                for (int i = 0; i <=3; i ++)
                {
                    if (!colorsUsed.Contains(i))
                    {
                        minColorNotUsed = i;
                        break;
                    }
                }

                //now we have the minimum color not used by adjacent nodes, color the node
                node.Color = minColorNotUsed;
                if (minColorNotUsed > maxColor)
                    maxColor = minColorNotUsed;
            }

            return maxColor+1;
        }
Beispiel #12
0
        public string[] FindArbiters(int arbiterCount, string[] excludedArbiterIds)
        {
            if (arbiterCount > dbContext.Users.Count())
            {
                logger.LogLine("Not enough arbiters available! " + arbiterCount+" wanted. ", Logger.log_types.ERROR_LOG);
                throw new responseTip.Exceptions.NotEnoughArbitersAvailable();
            }
            string[] arbiterIds;
            //arbiterIds=dbContext.Users.Where(model => model.GetPercentageOfPuzzlesSuccesfull() > 0.5f).OrderByDescending(model => model.GetPercentageOfPuzzlesSuccesfull()).Select(model => model.Id).Take(task.ArbiterCount).ToArray();
            orderedArbiters = dbContext.Users.ToList().OrderByDescending(model => model.GetProbabilityOfBeingPicked());

            //TODO check if order is not changed by takewhile
            orderedArbitersAvailable = orderedArbiters.TakeWhile(model => model.GetNumOfPuzzlesWaiting() < model.GetNumOfPuzzlesLimit());
            if (excludedArbiterIds != null)
            {
                orderedArbitersAvailable = orderedArbitersAvailable.Where(model => !excludedArbiterIds.ToList().Contains(model.Id));
            }
            arbiterIds=orderedArbitersAvailable.Select(model => model.Id).Take(arbiterCount).ToArray();

            //            arbiterIds = dbContext.Users.OrderByDescending(model => model.GetProbabilityOfBeingPicked()).Select(model => model.Id).Take(arbiterCount).ToArray();
            if(arbiterIds.Count()<arbiterCount)
            {
                logger.LogLine("Not enough arbiters available! " + arbiterCount + " wanted. ", Logger.log_types.ERROR_LOG);
                throw new responseTip.Exceptions.NotEnoughArbitersAvailable();
            }
            return arbiterIds;
        }
        /// <summary>
        /// Get Total list of items in the inventory
        /// </summary>
        /// <param name="lstTotalInventoryMl"></param>
        /// <param name="lstInventoryMl"></param>
        private List<InventoryModel> GetTotalInventory(IOrderedEnumerable<InventoryModel> lstTotalInventoryMl, string logicalDeviceId, string searchText)
        {
            List<InventoryModel> lstInventoryMl = new List<InventoryModel>();
            var lstInventoryInMl =
                lstTotalInventoryMl.Where(x => x.CurrentState.Equals(Enums.CurrentState.Add.ToString())).ToList();
            var lstInventoryOutMl =
                lstTotalInventoryMl.Where(x => x.CurrentState.Equals(Enums.CurrentState.Remove.ToString())).ToList();

            foreach (var inventoryInMl in lstInventoryInMl)
            {
                var inventoryOutMl =
                    lstInventoryOutMl.Where(
                        x => x.LogicalDeviceId == inventoryInMl.LogicalDeviceId && x.TagEPC == inventoryInMl.TagEPC)
                        .ToList();
                if (inventoryOutMl.Count == 0)
                {
                    lstInventoryMl.Add(inventoryInMl);
                }
                else
                {
                    lstInventoryOutMl.Remove(inventoryOutMl.FirstOrDefault());
                }
            }
            lstInventoryMl.ToList().ForEach(x =>
            {

                x.Batch = (from u in ObjTersoDataContext.items
                           where u.EPC == x.TagEPC
                           select u.Batch).FirstOrDefault();
                x.ItemId = (from u in ObjTersoDataContext.items
                            where u.EPC == x.TagEPC
                            select u.ItemId).FirstOrDefault();
                x.Material = (from u in ObjTersoDataContext.items
                              where u.EPC == x.TagEPC
                              select u.Material).FirstOrDefault();
                x.ExpirationDate = (from u in ObjTersoDataContext.items
                                    where u.EPC == x.TagEPC
                                    select u.ExpirationDate).FirstOrDefault();
                x.ExpirationDateString = x.ExpirationDate != null ? String.Format("{0:MM/dd/yyyy}", x.ExpirationDate.Value) : string.Empty;
                x.DeviceId = (from u in ObjTersoDataContext.devices
                              where u.LogicalDeviceId == x.LogicalDeviceId
                              select u.DeviceId).FirstOrDefault();

            });


            lstInventoryMl = lstInventoryMl.Where(x => (string.IsNullOrEmpty(logicalDeviceId) || x.LogicalDeviceId.Equals(logicalDeviceId))
                                             && (string.IsNullOrEmpty(searchText) ||
                                               (!string.IsNullOrEmpty(x.Material) && x.Material.Contains(searchText)) ||
                                               (!string.IsNullOrEmpty(x.Batch) && x.Batch.Contains(searchText)) ||
                                                 x.TagEPC.Contains(searchText) || x.LogicalDeviceId.Equals(searchText)
                                                 )).ToList();
            lstInventoryMl.ToList().ForEach(x =>
         {
             x.TotalRows = lstInventoryMl.Count;
         });

            return lstInventoryMl.ToList();
        }
 internal BurrowsWheelerTransform(IOrderedEnumerable<int[]> transform)
 {
     var y = transform.Select(v => new { F = v[0], L = v[2], S = v[1] }).ToArray();
     sorted = y.Select(v => v.F).ToArray();
     bwt = y.Select(v => v.L).ToArray();
     suffix = y.Select(v => v.S).ToArray();
     index = suffix.Select((s, i) => new { S = s, I = i }).OrderBy(v => v.S).Select(v => v.I).ToArray();
 }
 public UnitTestsPresenter(IUnitTestsView view)
 {
     _view = view;
     _tests = GetType().Assembly.GetTypes().Where(type => (from customAttribute in type.GetCustomAttributes(true) where customAttribute.GetType() == typeof(NUnit.Framework.TestFixtureAttribute) select customAttribute).Count() > 0).OrderBy(t => t.Name);
     _suites = new List<TestSuite>();
     PerformTests();
     _view.Display(_suites);
 }
Beispiel #16
0
 private void ShowProcesses(IOrderedEnumerable<Process> lstOfProcesses)
 {
     foreach (var proc in lstOfProcesses)
     {
         lv_Processes.Items.Add(String.Format("{0}.exe", proc.ProcessName)).SubItems.AddRange(new string[]
         {proc.Id.ToString(),(proc.PagedMemorySize64/(1024*1024)).ToString()+"M", 
          proc.Threads.Count.ToString()});
     }
 }
 public virtual void GatherCollections(ISearchCmdletBaseDataObject searchCriteria, List<ITestSuite> suitesForSearch)
 {
     // 20150925
     // var testResultsSearcher = new TestResultsSearcher();
     var testResultsSearcher = ProxyFactory.Get<TestResultsSearcher>();
     TestSuites = testResultsSearcher.SearchForSuites(searchCriteria, suitesForSearch);
     TestScenarios = testResultsSearcher.SearchForScenarios(searchCriteria, suitesForSearch);
     TestResults = testResultsSearcher.SearchForTestResults(searchCriteria, suitesForSearch);
 }
Beispiel #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventCategory"/> class.
 /// </summary>
 /// <param name="categoryId">The category identifier.</param>
 internal EventCategory(int categoryId)
 {
     _categoryId = categoryId;
     _events = new Dictionary<RoomData, uint>();
     _orderedEventRooms = from t in _events orderby t.Value descending select t;
     _addQueue = new Queue();
     _removeQueue = new Queue();
     _updateQueue = new Queue();
 }
Beispiel #19
0
        private static void Print(IOrderedEnumerable<A> result)
        {
            var output = result.Select(a =>
                                           {
                                               Console.WriteLine(a.S);
                                               return a.S;
                                           });

        }
        private static void PrintList(IOrderedEnumerable<Human> sortedPeople)
        {
            foreach (var human in sortedPeople)
            {
                Console.WriteLine(human);
            }

            Console.WriteLine();
        }
        public string MeansOfTransportAsString(IOrderedEnumerable<TransportMethod> meansOfTransport)
        {
            if (meansOfTransport == null || !meansOfTransport.Any())
            {
                return string.Empty;
            }

            return string.Join("-", meansOfTransport.Select(m => EnumHelper.GetShortName(m)));
        }
        private void AdicionarTodasAsDespesasOrdenadasPorMesEmConta(ContaDTO contaDTO, IOrderedEnumerable<DespesaDeViagem> despesasOrdenadasPorMes)
        {
            foreach (var despesa in despesasOrdenadasPorMes)
            {
                var despesaDTO = TransformarDespesaEmDespesaDTO(despesa);

                contaDTO.Despesas.Add(despesaDTO);
            }
        }
Beispiel #23
0
        private static void PrintList(IOrderedEnumerable<Worker> list)
        {
            foreach (var human in list)
            {
                Console.WriteLine(human);
            }

            Console.WriteLine();
        }
 public SampleConsecutiveDataPointObservationsCollection(
     IOrderedEnumerable<DataPointObservation> observations,
     Action<IEnumerable<AggregatedDataPoint>> aggregationReceiver,
     bool isPartial)
     : base(observations)
 {
     this.aggregationReceiver = aggregationReceiver;
     this.isPartial = isPartial;
 }
        private static void PrintList(IOrderedEnumerable<Worker> sortedWorkers)
        {
            foreach (var worker in sortedWorkers)
            {
                Console.WriteLine(worker);
            }

            Console.WriteLine();
        }
Beispiel #26
0
            public FromComprenoModel AddSimpleSentence(IOrderedEnumerable<Compreno.SentenceElement> words)
            {
                var simpleSentece = new SimpleSentence();

                simpleSentece.Words.AddRange(words.Select(_toSentenceWord));

                _comparisonSentence.SimpleSentences.Add(simpleSentece);

                return this;
            }
        private static void PrintList(IOrderedEnumerable<Student> sortedStudents)
        {

            foreach (var student in sortedStudents)
            {
                Console.WriteLine(student);
            }

            Console.WriteLine();
        }
        public CacheKeyGenerationService(ICacheKeyRegistrationService cacheKeyRegistrationService)
        {

            _cacheKeyProviders = new List<ICacheKeyProvider>
                                        { new NullCacheKeyProvider(),
                                          new EumCacheKeyProvider(),
                                          new PrimitiveTypeCacheKeyProvider(),
                                          new UserRegisteredCacheKeyProvider(cacheKeyRegistrationService) 
                                        }.OrderBy(x => (int)x.ExecutionOrder);
        }
Beispiel #29
0
            public FromComprenoModel AddLinkedChain(Compreno.SentenceElement master, IOrderedEnumerable<Compreno.SentenceElement> dependantWords)
            {
                var linkedChain = new LinkedChain();
                linkedChain.Master.Words.Add(_toSentenceWord(master));
                linkedChain.Dependent.Words.AddRange(dependantWords.Select(_toSentenceWord));

                _comparisonSentence.LinkedChains.Add(linkedChain);

                return this;
            }
Beispiel #30
0
 public VotingSystem(ICollection<Tag> tags)
 {
     int c = 0;
     this.tags = tags.OrderBy (x => x);
     foreach (Tag tag in this.tags) {
         dict.Add (tag, c);
         c++;
     }
     NumberOfTags = c;
 }
 internal static IOrderedEnumerable <TSource> _ThenBy <TSource, TKey>(
     IOrderedEnumerable <TSource> source, Func <TSource, TKey> expression, OrderingDirection orderingDirection)
 => orderingDirection == OrderingDirection.Asc
         ? source.ThenBy(expression)
         : source.ThenByDescending(expression);
Beispiel #32
0
        static void OrderByName()
        {
            IOrderedEnumerable <ConVar> orderedList = conVarList.OrderBy(cvar => cvar.name);

            conVarList = orderedList.ToList();
        }
Beispiel #33
0
 public void SetPokemons(IOrderedEnumerable <PokemonData> poks)
 {
     pokemons = poks;
 }
Beispiel #34
0
 internal void DrawSprites(IOrderedEnumerable <Sprite> orderedEnumerable)
 {
     orderedEnumerable.ToList().ForEach(x => DrawSprite(x));
 }
Beispiel #35
0
 public static IOrderedEnumerable <TSource> ThenByOrdinal <TSource>(this IOrderedEnumerable <TSource> source, Func <TSource, string> keySelector)
 {
     return(source.ThenBy(keySelector, StringComparer.Ordinal));
 }
Beispiel #36
0
        private async void Execute()
        {
            EnabledButton(false, "Reloading Pokemon list.");


            await check();

            try
            {
                client = Logic.Logic._client;
                if (client.readyToUse != false)
                {
                    profile = await client.Player.GetPlayer();

                    inventory = await client.Inventory.GetInventory();

                    pokemons =
                        inventory.InventoryDelta.InventoryItems
                        .Select(i => i.InventoryItemData?.PokemonData)
                        .Where(p => p != null && p?.PokemonId > 0)
                        .OrderByDescending(key => key.Cp);
                    var families = inventory.InventoryDelta.InventoryItems
                                   .Select(i => i.InventoryItemData?.Candy)
                                   .Where(p => p != null && (int)p?.FamilyId > 0)
                                   .OrderByDescending(p => (int)p.FamilyId);

                    var imageSize = 50;

                    var imageList = new ImageList {
                        ImageSize = new Size(imageSize, imageSize)
                    };
                    PokemonListView.ShowItemToolTips = true;
                    PokemonListView.SmallImageList   = imageList;

                    var templates = await client.Download.GetItemTemplates();

                    var myPokemonSettings = templates.ItemTemplates.Select(i => i.PokemonSettings).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                    var pokemonSettings   = myPokemonSettings.ToList();

                    var myPokemonFamilies = inventory.InventoryDelta.InventoryItems.Select(i => i.InventoryItemData?.Candy).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                    var pokemonFamilies   = myPokemonFamilies.ToArray();

                    PokemonListView.DoubleBuffered(true);
                    PokemonListView.View = View.Details;

                    ColumnHeader columnheader;
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Name";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "CP";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "IV A-D-S";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "LVL";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Evolvable?";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Height";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Weight";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "HP";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Attack";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "SpecialAttack (DPS)";
                    PokemonListView.Columns.Add(columnheader);

                    PokemonListView.BeginUpdate();
                    foreach (var pokemon in pokemons)
                    {
                        Bitmap pokemonImage = null;
                        await Task.Run(() =>
                        {
                            pokemonImage = GetPokemonImage((int)pokemon.PokemonId);
                        });

                        imageList.Images.Add(pokemon.PokemonId.ToString(), pokemonImage);

                        PokemonListView.LargeImageList = imageList;
                        var listViewItem = new ListViewItem();
                        listViewItem.Tag = pokemon;



                        var currentCandy = families
                                           .Where(i => (int)i.FamilyId <= (int)pokemon.PokemonId)
                                           .Select(f => f.Candy_)
                                           .First();
                        listViewItem.SubItems.Add(string.Format("{0}", pokemon.Cp));
                        listViewItem.SubItems.Add(string.Format("{0}% {1}-{2}-{3}", PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00"), pokemon.IndividualAttack, pokemon.IndividualDefense, pokemon.IndividualStamina));
                        listViewItem.SubItems.Add(string.Format("{0}", PokemonInfo.GetLevel(pokemon)));
                        listViewItem.ImageKey = pokemon.PokemonId.ToString();

                        listViewItem.Text = string.Format((pokemon.Favorite == 1) ? "{0} ★" : "{0}", StringUtils.getPokemonNameByLanguage(ClientSettings, (PokemonId)pokemon.PokemonId));

                        listViewItem.ToolTipText = new DateTime((long)pokemon.CreationTimeMs * 10000).AddYears(1769).ToString("dd/MM/yyyy HH:mm:ss");
                        if (pokemon.Nickname != "")
                        {
                            listViewItem.ToolTipText += "\nNickname: " + pokemon.Nickname;
                        }

                        var settings    = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                        var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                        if (settings.EvolutionIds.Count > 0 && familyCandy.Candy_ >= settings.CandyToEvolve)
                        {
                            listViewItem.SubItems.Add("Y (" + familyCandy.Candy_ + "/" + settings.CandyToEvolve + ")");
                            listViewItem.Checked = true;
                        }
                        else
                        {
                            if (settings.EvolutionIds.Count > 0)
                            {
                                listViewItem.SubItems.Add("N (" + familyCandy.Candy_ + "/" + settings.CandyToEvolve + ")");
                            }
                            else
                            {
                                listViewItem.SubItems.Add("N (" + familyCandy.Candy_ + "/Max)");
                            }
                        }
                        listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.HeightM, 2)));
                        listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.WeightKg, 2)));
                        listViewItem.SubItems.Add(string.Format("{0}/{1}", pokemon.Stamina, pokemon.StaminaMax));
                        listViewItem.SubItems.Add(string.Format("{0}", pokemon.Move1));
                        listViewItem.SubItems.Add(string.Format("{0} ({1})", pokemon.Move2, PokemonInfo.GetAttack(pokemon.Move2)));

                        PokemonListView.Items.Add(listViewItem);
                    }
                    PokemonListView.EndUpdate();
                    PokemonListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                    Text = "Pokemon List | User: "******" | Pokemons: " + pokemons.Count() + "/" + profile.PlayerData.MaxPokemonStorage;
                    EnabledButton(true);

                    statusTexbox.Text = string.Empty;
                }
            }
            catch (Exception e)
            {
                Logger.Error("[PokemonList-Error] " + e.StackTrace);
                await Task.Delay(1000); // Lets the API make a little pause, so we dont get blocked

                Execute();
            }
        }
        public void NullSourceComparer()
        {
            IOrderedEnumerable <int> source = null;

            Assert.Throws <ArgumentNullException>("source", () => source.ThenByDescending(i => i, null));
        }
        /// <summary>
        /// 把<see cref="IOrderedEnumerable{T}"/>集合继续指定字段排序方式进行排序
        /// </summary>
        /// <typeparam name="T">动态类型</typeparam>
        /// <param name="source">要排序的数据集</param>
        /// <param name="sortCondition">列表字段排序条件</param>
        /// <returns></returns>
        public static IOrderedEnumerable <T> ThenBy <T>(this IOrderedEnumerable <T> source, SortCondition sortCondition)
        {
            sortCondition.CheckNotNull("sortCondition");

            return(source.ThenBy(sortCondition.SortField, sortCondition.ListSortDirection));
        }
Beispiel #39
0
        public OptionsMenu(IDictionary <Type, object> managers)
            : base(managers)
        {
            _background = ResourceManager.GetSprite("mainbg");
            //  _background.Smoothing = Smoothing.Smooth;

            _lblFullscreen = new Label("Fullscreen", "CALIBRI", ResourceManager);

            _chkFullscreen               = new Checkbox(ResourceManager);
            _chkFullscreen.Value         = ConfigurationManager.GetFullscreen();
            _chkFullscreen.ValueChanged += _chkfullscreen_ValueChanged;

            _lblVsync = new Label("Vsync", "CALIBRI", ResourceManager);

            _chkVsync               = new Checkbox(ResourceManager);
            _chkVsync.Value         = ConfigurationManager.GetVsync();
            _chkVsync.ValueChanged += _chkvsync_ValueChanged;

            _lstResolution = new Listbox(250, 150, ResourceManager);
            _lstResolution.ItemSelected += _reslistbox_ItemSelected;

            IOrderedEnumerable <VideoMode> modes = from v in SFML.Window.VideoMode.FullscreenModes where
                                                   (v.Height > 748 && v.Width > 1024) //GOSH I HOPE NOONES USING 16 BIT COLORS. OR RUNNING AT LESS THAN 59 hz
                                                   orderby v.Height * v.Width ascending
                                                   select v;

            if (!modes.Any())
            {
                //No compatible videomodes at all. It is likely the game is being run on a calculator. TODO handle this.
                Application.Exit();
            }

            foreach (VideoMode vm in modes)
            {
                if (!vmList.ContainsKey(GetVmString(vm)))
                {
                    vmList.Add(GetVmString(vm), vm);
                    _lstResolution.AddItem(GetVmString(vm));
                }
            }

            if (
                vmList.Any(
                    x =>
                    x.Value.Width == CluwneLib.Screen.Size.X && x.Value.Height == CluwneLib.Screen.Size.Y))

            {
                KeyValuePair <string, VideoMode> curr =
                    vmList.FirstOrDefault(
                        x =>
                        x.Value.Width == CluwneLib.Screen.Size.X &&
                        x.Value.Height == CluwneLib.Screen.Size.Y);

                _lstResolution.SelectItem(curr.Key, false);
            }
            else
            {
                //No match due to different refresh rate in windowed mode. Just pick first resolution based on size only.
                KeyValuePair <string, VideoMode> curr =
                    vmList.FirstOrDefault(
                        x =>
                        x.Value.Width == CluwneLib.Screen.Size.X &&
                        x.Value.Height == CluwneLib.Screen.Size.Y);
                _lstResolution.SelectItem(curr.Key, false);
            }

            _ticketBg = ResourceManager.GetSprite("ticketoverlay");

            _btnMainMenu            = new Label("Main Menu", "CALIBRI", ResourceManager);
            _btnMainMenu.DrawBorder = true;
            _btnMainMenu.Clicked   += _mainmenubtt_Clicked;

            _btnApply            = new Label("Apply", "CALIBRI", ResourceManager);
            _btnApply.DrawBorder = true;
            _btnApply.Clicked   += _applybtt_Clicked;


            _lstResolution.Position = new Point(45, (int)(CluwneLib.Screen.Size.Y / 2.5f));
            _lstResolution.Update(0);
            _chkFullscreen.Position = new Point(_lstResolution.Position.X,
                                                _lstResolution.Position.Y + _lstResolution.ClientArea.Height + 10);
            _chkFullscreen.Update(0);
            _chkVsync.Position = new Point(_chkFullscreen.Position.X,
                                           _chkFullscreen.Position.Y + _chkFullscreen.ClientArea.Height + 10);
            _chkVsync.Update(0);
            _lblFullscreen.Position = new Point(_chkFullscreen.Position.X + _chkFullscreen.ClientArea.Width + 3,
                                                _chkFullscreen.Position.Y + (int)(_chkFullscreen.ClientArea.Height / 2f) -
                                                (int)(_lblFullscreen.ClientArea.Height / 2f));
            _lblFullscreen.Update(0);
            _lblVsync.Position = new Point(_chkVsync.Position.X + _chkVsync.ClientArea.Width + 3,
                                           _chkVsync.Position.Y + (int)(_chkVsync.ClientArea.Height / 2f) -
                                           (int)(_chkVsync.ClientArea.Height / 2f));
            _lblVsync.Update(0);
            _btnMainMenu.Position = new Point(_lstResolution.Position.X + 650, _lstResolution.Position.Y);
            _btnMainMenu.Update(0);
            _btnApply.Position = new Point(_btnMainMenu.Position.X,
                                           _btnMainMenu.Position.Y + _btnMainMenu.ClientArea.Height + 5);
            _btnApply.Update(0);
        }
Beispiel #40
0
        internal static string OutputGlobalSchema()
        {
            if (GlobalSchemas == null ||
                !GlobalSchemas.Any())
            {
                return(null);
            }

            string output = "";

            foreach (KeyValuePair <string, Dictionary <string, object> > schema in GlobalSchemas)
            {
                output += string.Format("internal sealed class {0}\r\n{{",
                                        schema.Key);
                IOrderedEnumerable <KeyValuePair <string, object> > schemaValue = schema.Value.OrderBy(o => o.Value.ToString()
                                                                                                       .StartsWith("Collection"))
                                                                                  .ThenBy(t => t.Value.ToString())
                                                                                  .ThenBy(t => t.Key);

                foreach (KeyValuePair <string, object> field in schemaValue)
                {
                    string fieldName  = field.Key;
                    string fieldValue = field.Value.ToString();

                    switch (fieldValue)
                    {
                    case "String":
                        fieldValue = "string";
                        break;

                    case "Integer":
                        fieldValue = "int?";
                        break;

                    case "Decimal":
                        fieldValue = "decimal?";
                        break;

                    case "Float":
                        fieldValue = "float?";
                        break;

                    case "Date":
                        fieldValue = "DateTime?";
                        break;

                    case "TimeSpan":
                        fieldValue = "TimeSpan?";
                        break;

                    case "Boolean":
                        fieldValue = "bool?";
                        break;

                    case "Bytes":
                        fieldValue = "byte[]";
                        break;
                    }

                    if (fieldName.EndsWith("Array") ||
                        fieldValue.StartsWith("Collection"))
                    {
                        fieldName = fieldName.Replace("Array",
                                                      "");
                        string modelName = fieldValue.Replace("Collection",
                                                              "")
                                           .Trim('<',
                                                 '>');

                        bool isValueArray = !GlobalSchemas.ContainsKey(modelName);

                        if (fieldValue.StartsWith("Collection") && isValueArray)
                        {
                            output += string.Format("\r\n\t[JsonProperty(PropertyName=\"{0}\")]",
                                                    fieldName);
                            output += string.Format("\r\n\tpublic string V_{0} {{ get; set; }}",
                                                    fieldName);
                            output += string.Format("\r\n\r\n\t[NotMapped]\r\n\tpublic string[] V_{0}Values {{ get {{ return V_{0}.Split(','); }} set{{ V_{0} = string.Join(\", \", value); }} }}\r\n",
                                                    fieldName);
                        }
                        else
                        {
                            output += string.Format("\r\n\t[JsonProperty(PropertyName=\"{0}\")]",
                                                    fieldName);
                            output += string.Format("\r\n\tpublic {0} V_{1} {{ get; set; }}\r\n",
                                                    fieldValue,
                                                    field.Key);
                        }
                    }
                    else
                    {
                        output += string.Format("\r\n\t[JsonProperty(PropertyName=\"{0}\")]",
                                                fieldName);
                        output += string.Format("\r\n\tpublic {0} V_{1} {{ get; set; }}\r\n",
                                                fieldValue,
                                                field.Key);
                    }
                }

                output += "}\r\n";
            }

            return(output);
        }
Beispiel #41
0
 public ConsoleOutput(SearchOptions options, IOrderedEnumerable <IGrouping <string, FoundLine> > foundlines, CommandStats stats) : base(options, foundlines, stats)
 {
 }
Beispiel #42
0
 public static IOrderedEnumerable <TSource> ThenBy <TSource, TKey>(this IOrderedEnumerable <TSource> source, Func <TSource, TKey> keySelector, SortOrder sortOrder)
 {
     return(sortOrder == SortOrder.Ascending ? source.ThenBy(keySelector) : source.ThenByDescending(keySelector));
 }
        public JsonResult GetProcessMetricsData([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
        {
            IQueryable <Process> query = null;
            int totalCount             = 0;
            int filteredCount          = 0;

            SeniorityLevel seniority       = SeniorityLevel.Entry;
            bool           seniorityExists = false;

            if (Request.Form["seniority"] != string.Empty)
            {
                seniority       = (SeniorityLevel)int.Parse(Request.Form["seniority"]);
                seniorityExists = true;
            }

            string technology = Request.Form["technology"];
            int    month      = int.Parse(Request.Form["month"]);
            int    year       = int.Parse(Request.Form["year"]);

            DateTime start = new DateTime(year, month, 1);
            DateTime end   = new DateTime(year, month, DateTime.DaysInMonth(year, month));

            using (HFContext hfdb = new HFContext())
            {
                query = from proc in hfdb.Processes
                        where ((start <proc.StartDate && end> proc.StartDate) ||
                               (start > proc.StartDate && start < proc.EndDate)) &&
                        ((seniorityExists && proc.Seniority == seniority) || proc.Technologies.Contains(technology))
                        select proc;

                totalCount = query.Count();

                if (requestModel.Search.Value != string.Empty)
                {
                    string value = requestModel.Search.Value.Trim();
                    query = query.Where(p => p.Name.Contains(value) ||
                                        p.Technologies.Contains(value)
                                        );
                }

                filteredCount = query.Count();

                IOrderedEnumerable <Column> sortedColumns = requestModel.Columns.GetSortedColumns();
                string orderByString = string.Empty;

                foreach (Column column in sortedColumns)
                {
                    orderByString += orderByString != string.Empty ? "," : "";
                    orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc");
                }

                query = query.OrderBy(orderByString == string.Empty ? "StartDate asc" : orderByString);
                query = query.Skip(requestModel.Start).Take(requestModel.Length);

                ICollection <Process> processData = query.ToList();

                var data = processData.Select(process =>
                                              new {
                    Id           = process.Id,
                    Name         = process.Name,
                    Technologies = process.Technologies,
                    Seniority    = process.Seniority.ToString(),
                    Duration     = (process.EndDate ?? DateTime.Now).Subtract(process.StartDate).TotalDays.ToString("F")
                }).ToList();

                return(Json(new DataTablesResponse(requestModel.Draw, data, filteredCount, totalCount)));
            }
        }
Beispiel #44
0
 public static BrokerageFeeRate BrokerageFeeRate(IOrderedEnumerable <BrokeragePercentageRate> percentageRates,
                                                 Percent onlineTradingRebate,
                                                 decimal minimumFee,
                                                 Percent intraDayFee) =>
 new BrokerageFeeRate(percentageRates, onlineTradingRebate, minimumFee, intraDayFee);
Beispiel #45
0
        private static void OnUpdate()
        {
            bestAllies = GameObjects.AllyHeroes
                         .Where(t =>
                                t.Distance(ObjectManager.GetLocalPlayer()) < Bases.Champion.W.Range)
                         .OrderBy(x => x.Health);

            foreach (var ally in bestAllies)
            {
                if (ally != null)
                {
                    if (ObjectManager.GetLocalPlayer().IsDead)
                    {
                        return;
                    }
                    if (ally != null)
                    {
                        if (ally.HasBuff("karthusfallenonetarget"))
                        {
                            if ((ally.GetBuff("karthusfallenonetarget").EndTime -
                                 Game.ClockTime) * 1000 <= 300)
                            {
                                if (EvadeTargetManager.Menu["whitelist"][
                                        ally.ChampionName.ToLower()]
                                    .As <MenuBool>().Enabled)
                                {
                                    Bases.Champion.W.CastOnUnit(ally);
                                }
                            }
                        }

                        if (ally.HasBuff("vladimirhemoplaguedebuff"))
                        {
                            if ((ally.GetBuff("vladimirhemoplaguedebuff").EndTime -
                                 Game.ClockTime) *
                                1000 <= 300)
                            {
                                if (EvadeTargetManager.Menu["whitelist"][
                                        ally.ChampionName.ToLower()]
                                    .As <MenuBool>().Enabled)
                                {
                                    Bases.Champion.W.CastOnUnit(ally);
                                }
                            }
                        }
                        if (ally.HasBuff("nautilusgrandlinetarget"))
                        {
                            if ((ally.GetBuff("nautilusgrandlinetarget").EndTime -
                                 Game.ClockTime) *
                                1000 <= 300)
                            {
                                if (EvadeTargetManager.Menu["whitelist"][
                                        ally.ChampionName.ToLower()]
                                    .As <MenuBool>().Enabled)
                                {
                                    Bases.Champion.W.CastOnUnit(ally);
                                }
                            }
                        }
                        if (ally.HasBuff("nocturneparanoiadash"))
                        {
                            if (GameObjects.EnemyHeroes.FirstOrDefault(
                                    x =>
                                    !x.IsDead && x.ChampionName.ToLower() == "nocturne" &&
                                    x.Distance(ObjectManager.GetLocalPlayer()) < 500) != null)
                            {
                                if (EvadeTargetManager.Menu["whitelist"][
                                        ally.ChampionName.ToLower()]
                                    .As <MenuBool>().Enabled)
                                {
                                    Bases.Champion.W.CastOnUnit(ally);
                                }
                            }
                        }

                        if (ally.HasBuff("soulshackles"))
                        {
                            if ((ally.GetBuff("soulshackles").EndTime - Game.ClockTime) *
                                1000 <=
                                300)
                            {
                                if (EvadeTargetManager.Menu["whitelist"][
                                        ally.ChampionName.ToLower()]
                                    .As <MenuBool>().Enabled)
                                {
                                    Bases.Champion.W.CastOnUnit(ally);
                                }
                            }
                        }

                        if (ally.HasBuff("zedrdeathmark"))
                        {
                            if ((ally.GetBuff("zedrdeathmark").EndTime - Game.ClockTime) *
                                1000 <=
                                300)
                            {
                                if (EvadeTargetManager.Menu["whitelist"][
                                        ally.ChampionName.ToLower()]
                                    .As <MenuBool>().Enabled)
                                {
                                    Bases.Champion.W.CastOnUnit(ally);
                                }
                            }
                        }
                    }


                    foreach (var target in GameObjects.EnemyHeroes.Where(x => !x.IsDead && x.IsValidTarget()))
                    {
                        switch (target.ChampionName)
                        {
                        case "Jax":

                            if (target.HasBuff("jaxcounterstrike"))
                            {
                                var buff = target.GetBuff("JaxCounterStrike");

                                if ((buff.EndTime - Game.ClockTime) * 1000 <= 650 &&
                                    ally.Distance(target) <= 350f)
                                {
                                    if (EvadeTargetManager.Menu["whitelist"][
                                            ally.ChampionName.ToLower()]
                                        .As <MenuBool>().Enabled)
                                    {
                                        Bases.Champion.W.CastOnUnit(ally);
                                    }
                                }
                            }



                            break;

                        case "Riven":

                            if (Utils.GameTimeTickCount - RivenQTime <= 100 && RivenDashPos.IsValid() &&
                                ally.Distance(target) <= RivenQRange)
                            {
                                if (EvadeTargetManager.Menu["whitelist"][
                                        ally.ChampionName.ToLower()]
                                    .As <MenuBool>().Enabled)
                                {
                                    Bases.Champion.W.CastOnUnit(ally);
                                }
                            }


                            break;
                        }
                    }
                }
            }
        }
 public static IOrderedEnumerable <T> ThenBy <T>(this IOrderedEnumerable <T> source) where T : IComparable <T>
 {
     return(source.ThenBy(Comparisons <T> .Comparer));
 }
 public IOrderedEnumerable <TEntity> InvokeSort(IOrderedEnumerable <TEntity> collection)
 {
     return(_sort == Sort.Descending
         ? collection.ThenByDescending(AsFunc())
         : collection.ThenBy(AsFunc()));
 }
 public static IOrderedEnumerable <T> ThenBy <T>(this IOrderedEnumerable <T> source, Comparison <T> compare)
 {
     return(source.ThenBy(new ComparisonComparer <T>(compare)));
 }
Beispiel #49
0
 public static ISet <TSource> ToISet <TSource>(this IOrderedEnumerable <TSource> source)
 {
     return(new HashSet <TSource>(source));
 }
 public static IOrderedEnumerable <T> ThenBy <T>(this IOrderedEnumerable <T> source, IComparer <T> comparer)
 {
     return(source.ThenBy(Functions <T> .Identity, comparer));
 }
Beispiel #51
0
        public void UpdateGrid()
        {
            TrinityGrid.Instance.IsUpdatingNodes = true;

            using (new PerformanceLogger("UpdateGrid"))
            {
                HighestNodeWeight = 0;

                if (TrinityGrid.Instance.NearestNode == null ||
                    TrinityGrid.Instance.NearestNode.DynamicWorldId != ZetaDia.Globals.WorldId)
                {
                    s_logger.Debug($"[{nameof(UpdateGrid)}] No Player Nearest Node or WorldId Mismatch");
                    Core.Scenes.Reset();
                    Core.Scenes.Update();
                    return;
                }

                var safeNodes             = new AvoidanceLayer();
                var kiteNodes             = new AvoidanceLayer();
                var avoidanceNodes        = new AvoidanceLayer();
                var monsterNodes          = new AvoidanceLayer();
                var obstacleNodes         = new AvoidanceLayer();
                var activeAvoidanceSnoIds = new HashSet <SNOActor>();
                var kiteFromNodes         = new AvoidanceLayer();

                var nodePool = TrinityGrid.Instance
                               .GetNodesInRadius(Core.Player.Position, node => node.IsWalkable, MaxDistance)
                               .Select(n => n.Reset()).ToList();

                //var allNodes = Grid.GetNodesInRadius(Core.Player.Position, node => node != null, MaxDistance).ToList();
                var nearestNodes = TrinityGrid.Instance
                                   .GetNodesInRadius(Core.Player.Position, node => node != null &&
                                                     node.NodeFlags.HasFlag(NodeFlags.AllowWalk), Settings.AvoiderLocalRadius)
                                   .ToList();

                var weightSettings = Settings.WeightingOptions;

                try
                {
                    if (!ZetaDia.IsInGame || ZetaDia.Globals.IsLoadingWorld)
                    {
                        return;
                    }

                    if (!nodePool.Any())
                    {
                        return;
                    }

                    foreach (var obj in Core.Targets)
                    {
                        if (obj.IsMe)
                        {
                            continue;
                        }

                        UpdateGizmoFlags(obj);
                        UpdateGlobeFlags(obj);
                        UpdateMonsterFlags(obj, monsterNodes);
                        UpdateKiteFromFlags(obj, kiteFromNodes);
                        UpdateProjectileBlockers(obj);
                    }

                    foreach (var door in Core.Actors.Actors.Where(a => a.Type == TrinityObjectType.Door))
                    {
                        UpdateDoorFlags(door);
                    }

                    //foreach (var obstacle in CacheData.NavigationObstacles)
                    //{
                    //    UpdateObstacleFlags(obstacle, obstacleNodes);
                    //}

                    //UpdateBacktrackFlags();

                    foreach (var avoidance in Core.Avoidance.CurrentAvoidances)
                    {
                        try
                        {
                            if (!avoidance.Settings.IsEnabled || avoidance.IsImmune)
                            {
                                continue;
                            }

                            var handler = avoidance.Definition.Handler;
                            if (handler == null)
                            {
                                s_logger.Error($"[{nameof(UpdateGrid)}] Avoidance: {avoidance.Definition.Name} has no handler");
                                continue;
                            }

                            if (avoidance.IsAllowed && !avoidance.IsExpired)
                            {
                                if (handler.UpdateNodes(TrinityGrid.Instance, avoidance))
                                {
                                    var actor = Core.Actors.RactorByRactorId <TrinityActor>(avoidance.RActorId);
                                    if (actor != null && actor.IsValid)
                                    {
                                        activeAvoidanceSnoIds.Add(avoidance.ActorSno);
                                    }
                                }
                            }
                            else
                            {
                                //Core.Logger.Warn(LogCategory.Avoidance, $"Avoidance {avoidance.Definition.Name} is not allowed. Enabled={avoidance.Settings.IsEnabled} IsAllowed={avoidance.IsAllowed} PlayerHealth={Core.Player.CurrentHealthPct * 100} SettingsHealth={avoidance.Settings.HealthPct} ");
                            }
                        }
                        catch (Exception ex)
                        {
                            s_logger.Error($"[{nameof(UpdateGrid)}] Exception in AvoidanceHandler updating nodes. Name={avoidance.Definition?.Name} Handler={avoidance.Definition?.Handler?.GetType()}", ex);
                        }
                    }

                    AvoidanceCentroid = avoidanceNodes.GetCentroid();
                    MonsterCentroid   = monsterNodes.GetCentroid();

                    foreach (var node in nodePool)
                    {
                        if (weightSettings.HasFlag(WeightingOptions.Backtrack) && node.AvoidanceFlags.HasFlag(AvoidanceFlags.Backtrack))
                        {
                            node.Weight--;
                        }

                        if (weightSettings.HasFlag(WeightingOptions.AvoidanceCentroid) && node.NavigableCenter.Distance(AvoidanceCentroid) < 15f)
                        {
                            node.Weight += 2;
                        }

                        if (weightSettings.HasFlag(WeightingOptions.MonsterCentroid) && node.NavigableCenter.Distance(MonsterCentroid) > 15f)
                        {
                            node.Weight--;
                        }

                        // Disabled for performance - 12ms @80yd
                        //if (Grid.IsInKiteDirection(node.NavigableCenter, 70))
                        //{
                        //    node.AddNodeFlags(AvoidanceFlags.Kite);
                        //    node.Weight--;
                        //    kiteNodes.Add(node);
                        //}
                        //else
                        //{
                        //    node.Weight++;
                        //}

                        var anyAdjacentUnsafe = node.AdjacentNodes.Any(n =>
                                                                       !n.NodeFlags.HasFlag(NodeFlags.AllowWalk) ||
                                                                       n.AvoidanceFlags.HasFlag(AvoidanceFlags.Avoidance) ||
                                                                       n.AvoidanceFlags.HasFlag(AvoidanceFlags.Monster) ||
                                                                       n.AvoidanceFlags.HasFlag(AvoidanceFlags.KiteFrom));

                        if (!anyAdjacentUnsafe)
                        {
                            if (weightSettings.HasFlag(WeightingOptions.AdjacentSafe))
                            {
                                node.Weight--;
                            }

                            node.AddNodeFlags(AvoidanceFlags.AdjacentSafe);
                            safeNodes.Add(node);
                        }

                        if (node.Weight > HighestNodeWeight)
                        {
                            HighestNodeWeight = node.Weight;
                            HighestNode       = node;
                        }
                    }
                }
                catch (Exception ex)
                {
                    s_logger.Error($"[{nameof(UpdateGrid)}] Exception in UpdateGrid", ex);

                    if (ex is CoroutineStoppedException)
                    {
                        throw;
                    }
                }

                //AllNodes = allNodes;
                CurrentNodes          = nodePool; //.OrderBy(n => n.Weight).ThenByDescending(n => n.Distance).ToList();
                SafeNodesByWeight     = safeNodes.Nodes.OrderBy(n => n.Weight).ThenByDescending(n => n.Distance);
                SafeNodesByDistance   = safeNodes.Nodes.OrderBy(n => n.Distance);
                SafeNodeLayer         = safeNodes;
                KiteNodeLayer         = kiteNodes;
                KiteFromLayer         = kiteFromNodes;
                AvoidanceNodeLayer    = avoidanceNodes;
                MonsterNodeLayer      = monsterNodes;
                NearbyNodes           = nearestNodes;
                ObstacleNodeLayer     = obstacleNodes;
                ActiveAvoidanceSnoIds = activeAvoidanceSnoIds;
            }

            TrinityGrid.Instance.IsUpdatingNodes = true;
        }
Beispiel #52
0
        private void btn逆向过程_Click(object sender, EventArgs e)
        {
            this.btn逆向过程.Enabled = false;

            if (_t_o == null)
            {
                _t_o = new Thread(new ThreadStart(delegate
                {
                    try
                    {
                        this.Invoke(new MethodInvoker(delegate
                        {
                            this.btn逆向过程.Enabled = true;
                            this.btn逆向过程.Text    = "停止";
                        }));

                        double[] fp1 = rows["TOP1概率"];
                        double[] fp3 = rows["TOP3概率"];
                        double[] s1  = rows["TOP1 SP"];
                        double[] s3  = rows["TOP3 SP"];

                        double[] ee = new double[CNT];
                        double[] dd = new double[CNT];

                        double rr1 = 1 / s1.Sum(x => 1 / x);

                        // 计算WIN投注比率
                        double[] ph1 = new double[CNT];
                        for (int i = 0; i < CNT; i++)
                        {
                            ph1[i] = rr1 / s1[i];
                        }

                        // 计算PLC赔付率
                        IOrderedEnumerable <double> sorted_s3 = s3.OrderBy(x => x);
                        double o3  = sorted_s3.Skip(2).First();
                        double a   = 3 * (o3 - 1) / (3 * (o3 - 1) + 1) * sorted_s3.Take(2).Sum(x => 1 / (3 * (x - 1)));
                        double b   = sorted_s3.Skip(2).Sum(x => 1 / (3 * (x - 1) + 1));
                        double rr3 = (a + 1) / (a + b);

                        // 计算投注比例
                        double po3   = (1 - rr3) / ((sorted_s3.Skip(2).Sum(x => 1 / (3 * x - 2)) - 1) * (3 * o3 - 2));
                        double[] ph3 = new double[CNT];
                        for (int i = 0; i < CNT; i++)
                        {
                            if (s3[i] <= o3)
                            {
                                ph3[i] = po3 * (o3 - 1) / (s3[i] - 1);
                            }
                            else
                            {
                                ph3[i] = po3 * (3 * o3 - 2) / (3 * s3[i] - 2);
                            }
                        }

                        // 设定top1第3的项期望=0,方差=1
                        double trd_s1 = s1.OrderBy(x => x).Skip(2).First();
                        int trd_inx   = -1;
                        for (int i = 0; i < CNT; i++)
                        {
                            if (s1[i] == trd_s1)
                            {
                                trd_inx = i;
                                break;
                            }
                        }

                        if (trd_inx == -1)
                        {
                            MessageBox.Show("没想到找不到排行第3的项");
                            return;
                        }

                        ee[trd_inx] = 0;
                        dd[trd_inx] = 1;

                        // 初始化其他项
                        // 目前全部设为期望=0,方差=1
                        // 后面考虑根据s1设置
                        for (int i = 0; i < CNT; i++)
                        {
                            if (i == trd_inx)
                            {
                                continue;
                            }
                            ee[i] = 0;
                            dd[i] = 1;
                        }

                        double lastE      = double.MaxValue;
                        int[] dir_d_rr_ee = new int[CNT], dir_d_rr_dd = new int[CNT];
                        for (int t = 0; ; t++)
                        {
                            double[] p1, p3, p3detail;
                            this.calc(ee, dd, out p1, out p3, out p3detail);
                            double E = 0;

                            // 交叉熵损失以及交叉熵损失对与各个概率的梯度
                            double[] grad_p1 = new double[CNT], grad_p3 = new double[CNT];
                            for (int i = 0; i < CNT; i++)
                            {
                                E         += -(ph1[i] * Math.Log(p1[i]) + (1 - ph1[i]) * Math.Log(1 - p1[i]));
                                E         += -(ph3[i] * Math.Log(p3[i]) + (1 - ph3[i]) * Math.Log(1 - p3[i]));
                                grad_p1[i] = -(ph1[i] / p1[i] - (1 - ph1[i]) / (1 - p1[i]));
                                grad_p3[i] = -(ph3[i] / p3[i] - (1 - ph3[i]) / (1 - p3[i]));
                            }

                            //double rr = this.calc_rr(s1, p1, s3, p3);
                            double maxr1 = double.MinValue, minr1 = double.MaxValue, maxr3 = double.MinValue, minr3 = double.MaxValue;
                            int maxr1_i  = -1, minr1_i = -1, maxr3_i = -1, minr3_i = -1;
                            double[] r1  = new double[CNT], r3 = new double[CNT]; // 这个是每个马的回报率,非赔付率
                            common.Math.Combination comb = new common.Math.Combination(CNT, PLC_CNT);
                            int[][] combs = comb.GetCombinations();
                            for (int i = 0; i < CNT; i++)
                            {
                                r1[i] = s1[i] * p1[i];
                                r3[i] = this.calc_plc_r(rr3, i, ph3, p3detail, combs);
                                if (r1[i] > maxr1)
                                {
                                    maxr1   = r1[i];
                                    maxr1_i = i;
                                }
                                if (r1[i] < minr1)
                                {
                                    minr1   = r1[i];
                                    minr1_i = i;
                                }
                                if (r3[i] > maxr3)
                                {
                                    maxr3   = r3[i];
                                    maxr3_i = i;
                                }
                                if (r3[i] < minr3)
                                {
                                    minr3   = r3[i];
                                    minr3_i = i;
                                }
                            }


                            // 求对各个参数的梯度
                            double[] d_rr_ee = new double[CNT];
                            double[] d_rr_dd = new double[CNT];
                            for (int i = 0; i < CNT; i++)
                            {
                                // if (i == trd_inx) continue;
                                double[] tp1, tp3, tp3detail;

                                ee[i] += EE_D_INC;
                                this.calc(ee, dd, out tp1, out tp3, out tp3detail);
                                for (int j = 0; j < CNT; j++)
                                {
                                    // 第j匹马的WIN概率对第i匹马的均值的梯度 = (tp1[j] - p1[j]) / EE_D_INC
                                    d_rr_ee[i] += (tp1[j] - p1[j]) / EE_D_INC * grad_p1[j];
                                    // 第j匹马的PLC概率对第i匹马的均值的梯度 = (tp3[j] - p3[j]) / EE_D_INC
                                    d_rr_ee[i] += (tp3[j] - p3[j]) / EE_D_INC * grad_p3[j];
                                }
                                ee[i] -= EE_D_INC;

                                dd[i] += DD_D_INC;
                                this.calc(ee, dd, out tp1, out tp3, out tp3detail);
                                for (int j = 0; j < CNT; j++)
                                {
                                    // 第j匹马的WIN概率对第i匹马的方差的梯度 = (tp1[j] - p1[j]) / DD_D_INC
                                    d_rr_dd[i] += (tp1[j] - p1[j]) / DD_D_INC * grad_p1[j];
                                    // 第j匹马的PLC概率对第i匹马的方差的梯度 = (tp3[j] - p3[j]) / DD_D_INC
                                    d_rr_dd[i] += (tp3[j] - p3[j]) / DD_D_INC * grad_p3[j];
                                }
                                dd[i] -= DD_D_INC;
                            }

                            // 调整各参数
                            for (int i = 0; i < CNT; i++)
                            {
                                // if (i == trd_inx) continue;
                                if (d_rr_ee[i] > 0 && dir_d_rr_ee[i] >= 0)
                                {
                                    dir_d_rr_ee[i]++;
                                }
                                else if (d_rr_ee[i] < 0 && dir_d_rr_ee[i] <= 0)
                                {
                                    dir_d_rr_ee[i]--;
                                }
                                else
                                {
                                    dir_d_rr_ee[i] = 0;
                                }

                                if (d_rr_dd[i] > 0 && dir_d_rr_dd[i] >= 0)
                                {
                                    dir_d_rr_dd[i]++;
                                }
                                else if (d_rr_dd[i] < 0 && dir_d_rr_dd[i] <= 0)
                                {
                                    dir_d_rr_dd[i]--;
                                }
                                else
                                {
                                    dir_d_rr_dd[i] = 0;
                                }

                                // 向负梯度方向调整
                                ee[i] += -d_rr_ee[i] * EE_STEP / (1 + t * STEP_DECAY) * (1 + Math.Abs(dir_d_rr_ee[i]) * STEP_DECAY);
                                dd[i] += -d_rr_dd[i] * DD_STEP / (1 + t * STEP_DECAY) * (1 + Math.Abs(dir_d_rr_dd[i]) * STEP_DECAY);

                                if (dd[i] < 0.0001)
                                {
                                    dd[i] = 0.0001;
                                }
                            }

                            // 调整之后再进行归一化
                            for (int i = 0; i < CNT; i++)
                            {
                                if (i == trd_inx)
                                {
                                    continue;
                                }
                                ee[i] = (ee[i] - ee[trd_inx]) / dd[trd_inx];
                                dd[i] = dd[i] / dd[trd_inx];
                            }
                            ee[trd_inx] = 0;
                            dd[trd_inx] = 1;

                            //E = r1.Sum(x => (x - rr1) * (x - rr1)) + r3.Sum(x => (x - rr3) * (x - rr3));
                            this.Invoke(new MethodInvoker(delegate
                            {
                                for (int i = 0; i < CNT; i++)
                                {
                                    lves[i].Text  = string.Format("{0:0.0000}", ee[i]);
                                    lvds[i].Text  = string.Format("{0:0.0000}", dd[i]);
                                    lres[i].Text  = string.Format("{0:0.0000}", d_rr_ee[i]);
                                    lrds[i].Text  = string.Format("{0:0.0000}", d_rr_dd[i]);
                                    lpws[i].Text  = string.Format("{0:0.0000}", p1[i] * 100);
                                    lpps[i].Text  = string.Format("{0:0.0000}", p3[i] * 100);
                                    lrcws[i].Text = string.Format("{0:0.0000}", p1[i] * s1[i]);
                                    lrcps[i].Text = string.Format("{0:0.0000}", p3[i] * s3[i]);
                                    lrfws[i].Text = string.Format("{0:0.0000}", fp1[i] * s1[i]);
                                    lrfps[i].Text = string.Format("{0:0.0000}", fp3[i] * s3[i]);
                                }

                                for (int i = 0; i < CNT; i++)
                                {
                                    if (i != maxr1_i && i != minr1_i)
                                    {
                                        lpws[i].BackColor = Color.White;
                                    }
                                    if (i != maxr3_i && i != minr3_i)
                                    {
                                        lpps[i].BackColor = Color.White;
                                    }
                                }
                                lpws[maxr1_i].BackColor = Color.Yellow;
                                lpws[minr1_i].BackColor = Color.Red;
                                lpps[maxr3_i].BackColor = Color.Yellow;
                                lpps[minr3_i].BackColor = Color.Red;

                                for (int i = lEs.Length - 1; i > 0; i--)
                                {
                                    lEs[i].Text = lEs[i - 1].Text;
                                }
                                lEs[0].Text = string.Format("{2}: {0:0.0000} | {1:0.0000000}", E, 1 / (1 + t * STEP_DECAY), t);
                                lpwSum.Text = string.Format("{0:0.0000}", p1.Sum() * 100);
                                lppSum.Text = string.Format("{0:0.0000}", p3.Sum() * 100);
                            }));

                            if (E > lastE)
                            {
                                break;
                            }
                        }
                    }
                    finally
                    {
                        _t_o = null;

                        try
                        {
                            this.Invoke(new MethodInvoker(delegate
                            {
                                this.btn逆向过程.Enabled = true;
                                this.btn逆向过程.Text    = "逆向过程";
                            }));
                        }
                        catch
                        {
                        }
                    }
                }));
                _t_o.IsBackground = true;
                _t_o.Start();
            }
            else
            {
                _t_o.Abort();
            }
        }
Beispiel #53
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            try
            {
                IList <Reference> refColumn = uidoc.Selection.PickObjects(ObjectType.Element, "Select columns");

                int count = 0;

                foreach (Reference reference in refColumn)
                {
                    Element selectedColumn = doc.GetElement(reference);

                    //top and bottom elevation
                    ElementId columnTopLevel = selectedColumn.LookupParameter("Top Level").AsElementId();

                    double columnTopElevation = doc.GetElement(columnTopLevel).LookupParameter("Elevation").AsDouble();

                    ElementId columnBottomLevel = selectedColumn.LookupParameter("Base Level").AsElementId();

                    double columnBottomElevation = doc.GetElement(columnBottomLevel).LookupParameter("Elevation").AsDouble();

                    string markValue = selectedColumn.LookupParameter("Mark").AsString();

                    List <ElementId> allLevelsList = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElementIds().ToList();

                    IOrderedEnumerable <ElementId> levelByZ = from ElementId l in allLevelsList orderby doc.GetElement(l).LookupParameter("Elevation").AsDouble() ascending select l;

                    IEnumerable <ElementId> topConstraintList = levelByZ.Where(eid => doc.GetElement(eid).LookupParameter("Elevation").AsDouble() <= columnTopElevation &&

                                                                               doc.GetElement(eid).LookupParameter("Elevation").AsDouble() > columnBottomElevation

                                                                               ).ToList();

                    IEnumerable <ElementId> bottomConstraintList = levelByZ.Where(eid => doc.GetElement(eid).LookupParameter("Elevation").AsDouble() >= columnBottomElevation &&

                                                                                  doc.GetElement(eid).LookupParameter("Elevation").AsDouble() < columnTopElevation

                                                                                  ).ToList();

                    using (var t = new Transaction(doc, "Split Column"))
                    {
                        t.Start();

                        // Set failure handler
                        var failureOptions = t.GetFailureHandlingOptions();
                        failureOptions.SetFailuresPreprocessor(new DuplicateMarkSwallower());
                        t.SetFailureHandlingOptions(failureOptions);

                        for (int i = 0; i < topConstraintList.Count(); i++)
                        {
                            ICollection <ElementId> newWallId = ElementTransformUtils.CopyElement(doc, selectedColumn.Id, new XYZ(0, 0, 0));

                            Element newColumn = doc.GetElement(newWallId.First());

                            ElementId topLevelId    = topConstraintList.ElementAt(i);
                            ElementId bottomLevelId = bottomConstraintList.ElementAt(i);

                            newColumn.LookupParameter("Top Level").Set(topLevelId);

                            newColumn.LookupParameter("Base Level").Set(bottomLevelId);

                            newColumn.LookupParameter("Mark").Set(markValue);
                        }



                        doc.Delete(selectedColumn.Id);

                        t.Commit();
                    }


                    string splittingLevels = "";

                    foreach (ElementId eid in topConstraintList)
                    {
                        splittingLevels += doc.GetElement(eid).Name + "\n";
                    }

                    count += 1;
                }

                TaskDialog.Show("Result", String.Format("{0} columns have been splitted", count));

                return(Result.Succeeded);
            }
            catch
            {
                return(Result.Failed);
            }
        }
        static void Main()
        {
            Sample sample = new Sample();

            sample.Foo();
            //Nullable types
            Nullable <int> x = null;
            int?           y = null;

            x = 10;
            if (x.HasValue)
            {
                Console.WriteLine(x.Value);
            }

            //SimpleDel simpleDel = new SimpleDel(Print);
            //Method group conversions (delegates)
            SimpleDel simpleDel = Print;

            simpleDel(12);

            //anonymous method
            simpleDel = delegate(object obj)
            {
                Console.WriteLine($"Value: {obj}");
            };
            simpleDel("siemens");

            //a --> implicitly typed local variable
            //type inference: technique where compiler understands (interprets) data type of implicitly typed local variable by looking at the assigned value
            var a    = 10;
            var arr  = new[] { 1, 2, 3, 4 };
            var list = new List <int>();

            foreach (var item in list)
            {
            }
            //Student student = new Student("siemens");
            //student.Name = "anil";

            //object initializer
            Student student = new Student {
                Name = "anil", SchoolName = "siemens"
            };
            //collection initlaizer
            List <int> numbers = new List <int> {
                1, 2, 3, 4
            };
            List <Student> students = new List <Student>
            {
                new Student {
                    Name = "anil", SchoolName = "siemens"
                }
            };

            //anonymous type
            var person = new { FirstName = "anil", LastName = "gupta" };

            Console.WriteLine(person.GetType().Name);
            //person.FirstName = "";

            //query expression
            IEnumerable <string> query = from s in students
                                         where s.Name.Contains('a')
                                         orderby s.Name
                                         select s.Name;

            //method expression
            IEnumerable <Student> filteredCollection =
                students.Where(s => s.Name.Contains('a'));

            IOrderedEnumerable <Student> sortedCollection = filteredCollection.OrderBy(s => s.Name);

            IEnumerable <string> finalCollection =
                sortedCollection.Select(s => s.Name);

            //Func<int, bool> del = (num) => num % 2 == 0;

            bool IsEven(int num) => num % 2 == 0;

            Console.WriteLine(IsEven(5));

            void Test(out int m) => m = 12;

            Test(out int z);
            Console.WriteLine($"value of {nameof(z)} is {z}");
        }
 public void ExpandHalfSuffix(string source, ref List <ExtractResult> result, IOrderedEnumerable <ExtractResult> numbers)
 {
 }
Beispiel #56
0
 private void PopulateCombos()
 {
     this.StatutsVerification = this._repoStatutsVerification.GetAll().OrderBy(s => s.EstDefaut).ThenBy(s => s.Libelle);
 }
        public async ValueTask <bool> MoveNextAsync(ITrace trace)
        {
            this.cancellationToken.ThrowIfCancellationRequested();

            if (trace == null)
            {
                throw new ArgumentNullException(nameof(trace));
            }

            if (!await this.crossPartitionRangePageAsyncEnumerator.MoveNextAsync(trace))
            {
                this.Current = default;
                return(false);
            }

            TryCatch <CrossFeedRangePage <QueryPage, QueryState> > currentCrossPartitionPage = this.crossPartitionRangePageAsyncEnumerator.Current;

            if (currentCrossPartitionPage.Failed)
            {
                this.Current = TryCatch <QueryPage> .FromException(currentCrossPartitionPage.Exception);

                return(true);
            }

            CrossFeedRangePage <QueryPage, QueryState> crossPartitionPageResult = currentCrossPartitionPage.Result;
            QueryPage backendQueryPage = crossPartitionPageResult.Page;
            CrossFeedRangeState <QueryState> crossPartitionState = crossPartitionPageResult.State;

            QueryState queryState;

            if (crossPartitionState == null)
            {
                queryState = null;
            }
            else
            {
                // left most and any non null continuations
                IOrderedEnumerable <FeedRangeState <QueryState> > feedRangeStates = crossPartitionState
                                                                                    .Value
                                                                                    .ToArray()
                                                                                    .OrderBy(tuple => ((FeedRangeEpk)tuple.FeedRange).Range.Min);

                List <ParallelContinuationToken> activeParallelContinuationTokens = new List <ParallelContinuationToken>();
                {
                    FeedRangeState <QueryState> firstState = feedRangeStates.First();
                    ParallelContinuationToken   firstParallelContinuationToken = new ParallelContinuationToken(
                        token: firstState.State != null ? ((CosmosString)firstState.State.Value).Value : null,
                        range: ((FeedRangeEpk)firstState.FeedRange).Range);

                    activeParallelContinuationTokens.Add(firstParallelContinuationToken);
                }

                foreach (FeedRangeState <QueryState> feedRangeState in feedRangeStates.Skip(1))
                {
                    this.cancellationToken.ThrowIfCancellationRequested();

                    if (feedRangeState.State != null)
                    {
                        ParallelContinuationToken parallelContinuationToken = new ParallelContinuationToken(
                            token: feedRangeState.State != null ? ((CosmosString)feedRangeState.State.Value).Value : null,
                            range: ((FeedRangeEpk)feedRangeState.FeedRange).Range);

                        activeParallelContinuationTokens.Add(parallelContinuationToken);
                    }
                }

                IEnumerable <CosmosElement> cosmosElementContinuationTokens = activeParallelContinuationTokens
                                                                              .Select(token => ParallelContinuationToken.ToCosmosElement(token));
                CosmosArray cosmosElementParallelContinuationTokens = CosmosArray.Create(cosmosElementContinuationTokens);

                queryState = new QueryState(cosmosElementParallelContinuationTokens);
            }

            QueryPage crossPartitionQueryPage = new QueryPage(
                backendQueryPage.Documents,
                backendQueryPage.RequestCharge,
                backendQueryPage.ActivityId,
                backendQueryPage.ResponseLengthInBytes,
                backendQueryPage.CosmosQueryExecutionInfo,
                backendQueryPage.DisallowContinuationTokenMessage,
                queryState);

            this.Current = TryCatch <QueryPage> .FromResult(crossPartitionQueryPage);

            return(true);
        }
Beispiel #58
0
 public virtual IOrderedEnumerable <object> ThenBy(IOrderedEnumerable <object> seq)
 {
     return(seq.ThenBy(o => o, Comparer));
 }
Beispiel #59
0
        private static void GenerateCategory(Assembly assembly, string category,
                                             IEnumerable <Commands> categoryCommands, List <Type> seeAlsoTypes, string locale)
        {
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);

            string markDown =
                $"# {Resources.ClassicAssist_Macro_Commands}  \n{Resources.Generated_on} {DateTime.UtcNow}  \n{Resources.Version}: {fvi.ProductVersion}  \n  \n";

            if (!string.IsNullOrEmpty(Resources.TRANSLATE_CREDIT))
            {
                markDown =
                    $"# {Resources.ClassicAssist_Macro_Commands}  \n{Resources.Generated_on} {DateTime.UtcNow}  \n{Resources.Version}: {fvi.ProductVersion}  \n{Resources.TRANSLATE_CREDIT}  \n  \n";
            }

            markDown += $"## {category}  \n";

            List <string> seeAlsoNames = new List <string>();

            foreach (Commands command in categoryCommands)
            {
                string example = command.InsertText;

                if (!string.IsNullOrEmpty(command.Example))
                {
                    example = command.Example;
                }

                markDown += $"### {command.Name}  \n  \n";
                markDown += $"{Resources.Method_Signature}:  \n  \n**{command.Signature}**  \n  \n";

                if (command.Parameters.Any())
                {
                    markDown += $"#### {Resources.Parameters}  \n";

                    foreach (Parameter parameter in command.Parameters)
                    {
                        markDown +=
                            $"* {parameter.Name}: {parameter.Description}.{( parameter.Optional ? $" ({Resources.Optional})" : "" )}";

                        if (parameter.SeeAlso != null)
                        {
                            if (!seeAlsoNames.Contains(parameter.SeeAlso.Name))
                            {
                                seeAlsoNames.Add(parameter.SeeAlso.Name);
                            }

                            markDown += string.Format($" {Resources.See_Also___0_}  \n",
                                                      $"[{parameter.SeeAlso.Name}](#{parameter.SeeAlso.Name})");
                        }
                        else
                        {
                            markDown += "  \n";
                        }
                    }

                    markDown += "  \n";
                }

                markDown += $"{Resources.Description}:  \n  \n**{command.Description}**  \n  \n";
                markDown += $"{Resources.Example}:  \n  \n```python  \n{example}  \n```  \n  \n";
            }

            markDown += "\n\n\n";

            IOrderedEnumerable <Type> includedSeeAlso =
                seeAlsoTypes.Where(i => seeAlsoNames.Contains(i.Name)).OrderBy(i => i.Name);

            if (includedSeeAlso.Any())
            {
                markDown += $"## {Resources.Types}  \n";

                foreach (Type seeAlsoType in includedSeeAlso)
                {
                    markDown += $"### {seeAlsoType.Name}  \n";

                    string[] enumNames = seeAlsoType.GetEnumNames();

                    if (enumNames == null)
                    {
                        continue;
                    }

                    markDown = enumNames.Aggregate(markDown, (current, enumName) => current + $"* {enumName}  \n");

                    markDown += "  \n";
                }
            }

            string fileName = $"{RemoveAccents(category)}-{locale}.md".Replace(' ', '-');

            if (locale.Equals("en-US"))
            {
                fileName = $"{category}.md";
            }

            File.WriteAllText(Path.Combine(Environment.CurrentDirectory, "Docs", fileName), markDown);
        }
Beispiel #60
0
        /// <summary>
        /// Dieser Event Handler wird aufgerufen, wenn die Weboberfläche angefordert wird.<para>
        /// Er konfiguriert gegebenenfalls die Tabelle gemäß der Suchanfrage.</para>
        /// </summary>
        /// <param name="search">
        /// Der zu suchende Ausdruck
        /// </param>
        /// <param name="sortOrder">
        /// Das Sortierverhalten
        /// </param>
        public void OnGet(string sortOrder, string search)
        {
            Orders        = _context.HistoricOrders.ToArray();
            SearchKeyWord = search ?? string.Empty;
            if (!string.IsNullOrEmpty(SearchKeyWord))
            {
                Orders = Orders.Search(search, order => order.Product.Name, order => order.User.GetName()).ToArray();
            }

            CollectionTimeSort  = string.IsNullOrEmpty(sortOrder) ? "!ct" : "";
            UserNameSort        = sortOrder == "un" ? "!un" : "un";
            ProductNameSort     = sortOrder == "p" ? "!p" : "p";
            CollectionPlaceSort = sortOrder == "cp" ? "!cp" : "cp";
            TotalPriceSort      = sortOrder == "tp" ? "!tp" : "tp";
            NumberSort          = sortOrder == "n" ? "!n" : "n";
            PreparationTimeSort = sortOrder == "pt" ? "!pt" : "pt";
            NoteSort            = sortOrder == "no" ? "!no" : "no";
            OrderTimeSort       = sortOrder == "ot" ? "!ot" : "ot";

            IOrderedEnumerable <Order> orders = Orders.OrderBy(order => 0);

            switch (sortOrder)
            {
            case "un":
                orders = orders.OrderBy(order => order.User.GetName());
                break;

            case "!un":
                orders = orders.OrderByDescending(order => order.User.GetName());
                break;

            case "p":
                orders = orders.OrderBy(order => order.Product.Name);
                break;

            case "!p":
                orders = orders.OrderByDescending(order => order.Product.Name);
                break;

            case "tp":
                orders = orders.OrderBy(order => order.Product.Price * order.Number);
                break;

            case "!tp":
                orders = orders.OrderByDescending(order => order.Product.Price * order.Number);
                break;

            case "n":
                orders = orders.OrderBy(order => order.Number);
                break;

            case "!n":
                orders = orders.OrderByDescending(order => order.Number);
                break;

            case "pt":
                orders = orders.OrderBy(order => order.PreparationTime);
                break;

            case "!pt":
                orders = orders.OrderByDescending(order => order.PreparationTime);
                break;

            case "ot":
                orders = orders.OrderBy(order => order.OrderTime);
                break;

            case "!ot":
                orders = orders.OrderByDescending(order => order.OrderTime);
                break;

            case "no":
                orders = orders.OrderBy(order => order.Notes);
                break;

            case "!no":
                orders = orders.OrderByDescending(order => order.Notes);
                break;

            case "cp":
                orders = orders.OrderBy(order => order.CollectionPlace);
                break;

            case "!cp":
                orders = orders.OrderByDescending(order => order.CollectionPlace);
                break;

            case "!ct":
                orders = orders.OrderBy(order => order.CollectionTime);
                break;

            default:
                orders = orders.OrderByDescending(order => order.CollectionTime);
                break;
            }

            Orders = orders.ThenByDescending(order => order.CollectionTime).ToArray();
        }