当前位置: 首页>>代码示例>>C#>>正文


C# SortedList.First方法代码示例

本文整理汇总了C#中SortedList.First方法的典型用法代码示例。如果您正苦于以下问题:C# SortedList.First方法的具体用法?C# SortedList.First怎么用?C# SortedList.First使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SortedList的用法示例。


在下文中一共展示了SortedList.First方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TestMethod

 public void TestMethod(int operationCount)
 {
     var stack = new Stack<int>();
     var heap = new SortedList<int, int>();
     var minStack = new MinStack();
     Repeat(operationCount, () =>
     {
         var operation = stack.Count == 0 ? 0 : Random.Next(4);
         var x = Random.Next(int.MaxValue);
         switch (operation)
         {
             case 0: // Push
                 stack.Push(x);
                 heap.Add(x, x);
                 minStack.Push(x);
                 break;
             case 1: // Pop
                 heap.Remove(stack.Peek());
                 stack.Pop();
                 minStack.Pop();
                 break;
             case 2: // Top
                 Assert.AreEqual(stack.Peek(), minStack.Top());
                 break;
             case 3: // GetMin
                 Assert.AreEqual(heap.First().Key, minStack.GetMin());
                 break;
         }
     });
 }
开发者ID:alexguo88,项目名称:LeetCode,代码行数:30,代码来源:155.MinStack.Test.cs

示例2: ToRelativeDateString

		/// <summary>
		/// Liefert aus einem Datum einen relativen String wie: 10 days ago.
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
        public static string ToRelativeDateString(this DateTime input)
        {
            TimeSpan oSpan = DateTime.Now.Subtract(input);
            double TotalMinutes = oSpan.TotalMinutes;
            string Suffix = " ago";

            if (TotalMinutes < 0.0) {
                TotalMinutes = Math.Abs(TotalMinutes);
                Suffix = " from now";
            }

            var aValue = new SortedList<double, Func<string>>();
            aValue.Add(0.75, () => "less than a minute");
            aValue.Add(1.5, () => "about a minute");
            aValue.Add(45, () => string.Format("{0} minutes", Math.Round(TotalMinutes)));
            aValue.Add(90, () => "about an hour");
            aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24
            aValue.Add(2880, () => "a day"); // 60 * 48
            aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30
            aValue.Add(86400, () => "about a month"); // 60 * 24 * 60
            aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 
            aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2
            aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));

            return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;
        }
开发者ID:atitsbest,项目名称:llprk.net,代码行数:31,代码来源:DateTime+RelativeDate.cs

示例3: Aggregate

        public static List<Point> Aggregate(SortedList<long, int>[] hists, int repeats, int sums, out long minTime)
        {
            SortedList<long, int> sumHist = new SortedList<long, int>();

            foreach (var hist in hists)
                foreach (var pair in hist)
                {
                    int ex;
                    if (sumHist.TryGetValue(pair.Key, out ex))
                        sumHist[pair.Key] = ex + pair.Value;
                    else
                        sumHist.Add(pair.Key, pair.Value);
                }

            minTime = sumHist.First().Key;

            return Normalize(sumHist, repeats * hists.Length, sums);
        }
开发者ID:ExM,项目名称:LogBenchmark,代码行数:18,代码来源:Toolkit.cs

示例4: CreateNavigationLinks

    private void CreateNavigationLinks(Collective.Offer.SortType sortBy, bool isAsc, int currPage, int numOfRows, int totalPageCount)
    {
        string basicUrl = Request.Url.ToString();
        basicUrl = basicUrl.Substring(0, basicUrl.IndexOf(".aspx") + ".aspx".Count());

        // sort linkovi
        HyperLink hlOfferNameSort = (HyperLink)this.grdOffers.HeaderRow.FindControl("hlOfferNameSort");
        if (sortBy == Collective.Offer.SortType.OfferName)
        {
            hlOfferNameSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.OfferName.ToString() + "&asc=" + (!isAsc).ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlOfferNameSort.Text = isAsc ? "Offer Name ↑" : "Offer Name ↓";
        }
        else
        {
            hlOfferNameSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.OfferName.ToString() + "&asc=" + true.ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlOfferNameSort.Text = "Offer Name ↑";
        }

        HyperLink hlOfferIdSort = (HyperLink)this.grdOffers.HeaderRow.FindControl("hlOfferIdSort");
        if (sortBy == Collective.Offer.SortType.OfferId)
        {
            hlOfferIdSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.OfferId.ToString() + "&asc=" + (!isAsc).ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlOfferIdSort.Text = isAsc ? "ID ↑" : "ID ↓";
        }
        else
        {
            hlOfferIdSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.OfferId.ToString() + "&asc=" + true.ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlOfferIdSort.Text = "ID ↑";
        }

        HyperLink hlCategoryNameSort = (HyperLink)this.grdOffers.HeaderRow.FindControl("hlCategoryNameSort");
        if (sortBy == Collective.Offer.SortType.CategotyName)
        {
            hlCategoryNameSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.CategotyName.ToString() + "&asc=" + (!isAsc).ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlCategoryNameSort.Text = isAsc ? "Category Name ↑" : "Category Name ↓";
        }
        else
        {
            hlCategoryNameSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.CategotyName.ToString() + "&asc=" + true.ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlCategoryNameSort.Text = "Category Name ↑";
        }

        HyperLink hlBoughtCountSort = (HyperLink)this.grdOffers.HeaderRow.FindControl("hlBoughtCountSort");
        if (sortBy == Collective.Offer.SortType.BoughtCount)
        {
            hlBoughtCountSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.BoughtCount.ToString() + "&asc=" + (!isAsc).ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlBoughtCountSort.Text = isAsc ? "Bought Count ↑" : "Bought Count ↓";
        }
        else
        {
            hlBoughtCountSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.BoughtCount.ToString() + "&asc=" + true.ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlBoughtCountSort.Text = "Bought Count ↑";
        }

        HyperLink hlDateStartSort = (HyperLink)this.grdOffers.HeaderRow.FindControl("hlDateStartSort");
        if (sortBy == Collective.Offer.SortType.DateStart)
        {
            hlDateStartSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.DateStart.ToString() + "&asc=" + (!isAsc).ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlDateStartSort.Text = isAsc ? "Date Start ↑" : "Date Start ↓";
        }
        else
        {
            hlDateStartSort.NavigateUrl = basicUrl + "?sortby=" + Collective.Offer.SortType.DateStart.ToString() + "&asc=" + true.ToString() + "&page=" + currPage.ToString() + "&rows=" + numOfRows.ToString();
            hlDateStartSort.Text = "Date Start ↑";
        }

        // paging linovi
        this.hlFirst.NavigateUrl = basicUrl + "?sortby=" + sortBy.ToString() + "&asc=" + isAsc.ToString() + "&page=" + 1.ToString() + "&rows=" + numOfRows.ToString();
        this.hlLast.NavigateUrl = basicUrl + "?sortby=" + sortBy.ToString() + "&asc=" + isAsc.ToString() + "&page=" + totalPageCount.ToString() + "&rows=" + numOfRows.ToString();
        this.hlPrev.NavigateUrl = basicUrl + "?sortby=" + sortBy.ToString() + "&asc=" + isAsc.ToString() + "&page=" + (currPage - 1).ToString() + "&rows=" + numOfRows.ToString();
        this.hlNext.NavigateUrl = basicUrl + "?sortby=" + sortBy.ToString() + "&asc=" + isAsc.ToString() + "&page=" + (currPage + 1).ToString() + "&rows=" + numOfRows.ToString();
        this.hlPrev.Visible = this.hlFirst.Visible = currPage > 1;
        this.hlNext.Visible = this.hlLast.Visible = currPage < totalPageCount;

        SortedList<int, int> pags = new SortedList<int, int>();
        pags.Add(currPage, currPage);
        int pl = currPage;
        int pr = currPage;

        for (int i = 0; i < 3; ++i)
        {
            if (--pl >= 1)
            {
                pags.Add(pl, pl);
            }
            else if (++pr <= totalPageCount)
            {
                pags.Add(pr, pr);
            }

            if (++pr <= totalPageCount)
            {
                pags.Add(pr, pr);
            }
            else if (--pl >= 1)
            {
                pags.Add(pl, pl);
            }
        }

//.........这里部分代码省略.........
开发者ID:bneuhold,项目名称:pb-dev,代码行数:101,代码来源:OfferList.aspx.cs

示例5: pathTo

        public PathData pathTo(Pos target, Pos currentLocation, Tile[][] board, int spikeCost = 10)
        {
            spikePrice = spikeCost;
            //int resultCost = 0;
            PathData pathData = new PathData();
            int size = board.GetLength(0);
            int[][] pointValues = new int[size][];
            for (int x = 0; x < size; x++) 
            {
               pointValues[x] = new int[size];
            }
            pointValues[currentLocation.x][currentLocation.y] = 1;
            SortedList<int, Pos> newMarkedPoints = new SortedList<int, Pos>(new DuplicateKeyComparer<int>());
            newMarkedPoints.Add(1, currentLocation);
            size--;
            while (newMarkedPoints.Count() != 0) {
                Pos pos = newMarkedPoints.First().Value;
                newMarkedPoints.RemoveAt(0);
                int basecost = pointValues[pos.x][pos.y];
                int x;
                int y;
                x = pos.x;
                y = pos.y + 1;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
                x = pos.x + 1;
                y = pos.y;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
                x = pos.x - 1;
                y = pos.y;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
                x = pos.x;
                y = pos.y - 1;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
            }
            //Console.Out.WriteLine(resultCost);

            //backtrace
            Pos currentPos = target;
            while (true) {
                //Console.Out.WriteLine(currentPos.x + "," + currentPos.y);
                int x, y, a=99999,b=99999,c=99999,d=99999;
                
                x = currentPos.x - 1;
                y = currentPos.y;
                if (x <= size && x >= 0 && y <= size && y >= 0) {
                    if (currentLocation.x == x && currentLocation.y == y) {
                        pathData.nextDirection = Direction.South;
                        break;
                    }
                    a = pointValues[x][y];

                }
                    x = currentPos.x;
                    y = currentPos.y - 1;
                if (x <= size && x >= 0 && y <= size && y >= 0) {
                    if (currentLocation.x == x && currentLocation.y == y) {
                        pathData.nextDirection = Direction.East;
                        break;
                    }
                    b = pointValues[x][y];
                }

                x = currentPos.x;
                y = currentPos.y + 1;
//.........这里部分代码省略.........
开发者ID:coveoblitz2016,项目名称:wowblitzawesome,代码行数:101,代码来源:Dijkstra.cs

示例6: printReleventFringeSuffixes

        public void printReleventFringeSuffixes()
        {
            var fringeWordSuffixes = new SortedList<double, List<string>>(new MainControl.ReverseDoubleComparer());
            int trieIndex = 0;

            //print the fringe words suffixes to the listbox
            foreach (var trie in MainControl.MostRelevntTries)
            {
                if (isCurrentWordHasMatcher[trieIndex])
                {
                    //get list of matches
                    var tempList = trie.Matcher.GetPrefixSuggestions(MainControl.numberOfFringe, MainControl.ConsiderSuffixLength, MainControl.GetProbabilityFor,new MainControl.ReverseDoubleComparer());
                    addToMainList(fringeWordSuffixes, tempList);
                }
                trieIndex++;
            }

            //add to listbox only the words with the most highest Weight
            int i = 0;
            while (i < MainControl.numberOfFringe && fringeWordSuffixes.Count > 0)
            {
                List<string> list = fringeWordSuffixes.First().Value;
                while (list.Count > 0 && i < MainControl.numberOfFringe)
                {
                    listBox1.Items.Add(list.First());
                    list.RemoveAt(0);
                    i++;
                }
                fringeWordSuffixes.RemoveAt(0);
            }
        }
开发者ID:roeibux,项目名称:text-predict,代码行数:31,代码来源:MainWindow.cs

示例7: UpdateMaps

        // Content Manager Update Script
        // Currently not a WebMethod as incomplete
        public void UpdateMaps()
        {
            //GET AND PROCESS DATA INTO WaypointData dataSource AND SortedList<int, WaypointData> data

            // FAKE DATA - FAILS DUE TO EMPTY
            WaypointData dataSource = new WaypointData();
            SortedList<int, WaypointData> data = new SortedList<int, WaypointData>();

            // Initialise test variables
            SortedList<int, WaypointData> dataEdges = new SortedList<int, WaypointData>();
            SortedList<int, WaypointData> dataEdgesDis = new SortedList<int, WaypointData>();

            // Set min path dist to 0 for source node
            dataSource.minDist = 0f;
            // Add source node to process que
            dataEdges.Add(dataSource.waypointID, dataSource);

            // Until the path que is empty
            while (dataEdges.Count != 0)
            {
                // Get the waypointID of the current node
                int key = dataEdges.First().Key;
                // Then get the current node
                WaypointData current = dataEdges[key];

                // For every node that current is linked to
                foreach (int i in current.edgeKeys)
                {
                    // Find the edge node
                    WaypointData edge = data[i];
                    // Get dist using Tan(adj/opp)
                    double distX = current.coordX - edge.coordX;
                    double distY = current.coordY - edge.coordY;
                    double dist = Math.Tan(distX / distY);
                    // Get total distance from source to edge node
                    double edgeDist = current.minDist + dist;

                    // If the distance along this path is shorter than the current path for the edge node
                    if (edgeDist < edge.minDist)
                    {
                        // Remove the edge node from the que
                        dataEdges.Remove(i);
                        // Update the local-stored edge node
                        edge.minDist = edgeDist;
                        edge.waypointIDPrev = key;
                        // Update global node
                        data[i] = edge;
                        // Reinsert edge node to que with updated values
                        dataEdges.Add(i, edge);
                    }
                }

                // When all processing for the current node is done remove from the processing que
                dataEdges.Remove(key);
            }

            // Set min disabled path dist to 0 for source node
            dataSource.minDistDis = 0f;
            // Add source node to disabled process que
            dataEdgesDis.Add(dataSource.waypointID, dataSource);

            // Until the disabled path que is empty
            while (dataEdgesDis.Count != 0)
            {
                // Get the waypointID of the current node
                int key = dataEdgesDis.First().Key;
                // Then get the current node
                WaypointData current = dataEdgesDis[key];

                // For every node that current is linked to
                foreach (int i in current.edgeKeys)
                {
                    // Find the edge node
                    WaypointData edge = data[i];
                    // Get dist using Tan(adj/opp)
                    double distX = current.coordX - edge.coordX;
                    double distY = current.coordY - edge.coordY;
                    double dist = Math.Tan(distX / distY);
                    // Get total distance from source to edge node
                    double edgeDist = current.minDistDis + dist;

                    // If the distance along this path is shorter than the current path for the edge node
                    if (edgeDist < edge.minDistDis)
                    {
                        // Remove the edge node from the que
                        dataEdgesDis.Remove(i);
                        // Update the local-stored edge node
                        edge.minDist = edgeDist;
                        edge.waypointIDPrevDis = key;
                        // Update global node
                        data[i] = edge;
                        // Reinsert edge node to que with updated values
                        dataEdgesDis.Add(i, edge);
                    }
                }

                // When all processing for the current node is done remove from the processing que
                dataEdgesDis.Remove(key);
//.........这里部分代码省略.........
开发者ID:KerrN,项目名称:WF_WebService,代码行数:101,代码来源:WF_Service.svc.cs

示例8: calcPrognoz

        public void calcPrognoz()
        {
            if (PArr.Count % 24 != 0) {
                int addCnt=24 - PArr.Count % 24;
                for (int i=0; i < addCnt; i++) {
                    DateTime last=PArr.Last().Key;
                    PArr.Add(last.AddMinutes(30), PArr[last]);
                }
            }

            SortedList<int,double>prevDataRashodArray=new SortedList<int, double>();
            SortedList<int,double>prevDataNBArray=new SortedList<int, double>();
            SortedList<int,double>prevDataVBArray=new SortedList<int, double>();
            prognoz=new SortedList<DateTime, double>();

            int index=0;
            double k=0;
            foreach (DateTime date in FirstData.Keys) {
                prevDataRashodArray.Add(index, FirstData[date].Q);
                prevDataNBArray.Add(index, FirstData[date].NB);
                prevDataVBArray.Add(index, FirstData[date].VB);
                k = FirstData[date].Q / RashodTable.getStationRashod(FirstData[date].P, FirstData[date].VB - FirstData[date].NB, RashodCalcMode.avg);
                index++;
            }

            napors=new SortedList<DateTime, double>();
            rashods = new SortedList<DateTime, double>();

            double napor=prevDataVBArray.Last().Value - prevDataNBArray.Last().Value;
            foreach (KeyValuePair<DateTime,double>de in pArr) {
                napors.Add(de.Key, napor);
            }

            foreach (KeyValuePair<DateTime,double> de in PArr) {
                double rashod=IsQFakt ? de.Value : RashodTable.getStationRashod(de.Value, napors[de.Key], RashodCalcMode.avg) * k;
                rashods.Add(de.Key, rashod);
                prognoz.Add(de.Key, 0);
            }
            //prognoz.Add(rashods.First().Key.AddMinutes(-30), prevDataNBArray[4]);

            double currentNapor=napors.First().Value;
            SortedList<DateTime,double> dataForPrognoz=new SortedList<DateTime, double>();
            SortedList<DateTime,double> naporsForPrognoz=new SortedList<DateTime, double>();
            for (int indexPoint=0; indexPoint < pArr.Keys.Count; indexPoint++) {
                DateTime Key=pArr.Keys[indexPoint];
                dataForPrognoz.Add(Key, pArr[Key]);
                naporsForPrognoz.Add(Key, napors[Key]);
                if (dataForPrognoz.Count == 24) {
                    SortedList<int,double> outputVector=new SortedList<int, double>();
                    for (int step=0; step <= 3; step++) {
                        SortedList<int, double> inputVector=new SortedList<int, double>();
                        inputVector[0] = DatePrognozStart.Year;
                        inputVector[1] = DatePrognozStart.DayOfYear;
                        inputVector[2] = T;

                        inputVector[3] = prevDataVBArray[1];
                        inputVector[4] = prevDataVBArray[2];
                        inputVector[5] = prevDataVBArray[3];
                        inputVector[6] = prevDataVBArray[4];

                        inputVector[7] = prevDataRashodArray[1];
                        inputVector[8] = prevDataRashodArray[2];
                        inputVector[9] = prevDataRashodArray[3];
                        inputVector[10] = prevDataRashodArray[4];

                        for (int i=0; i < 24; i++) {
                            double rashod=0;
                            if (!IsQFakt) {
                                rashod = RashodTable.getStationRashod(pArr[dataForPrognoz.Keys[i]], naporsForPrognoz[dataForPrognoz.Keys[i]], RashodCalcMode.avg)*k;
                            } else {
                                rashod = rashods[dataForPrognoz.Keys[i]];
                            }

                            rashods[dataForPrognoz.Keys[i]] = rashod;
                            inputVector[i + 11] = rashod;
                        }

                        inputVector[35] = prevDataNBArray[1];
                        inputVector[36] = prevDataNBArray[2];
                        inputVector[37] = prevDataNBArray[3];
                        inputVector[38] = prevDataNBArray[4];

                        outputVector = nnet.calc(inputVector);

                        for (int i=0; i < outputVector.Count; i++) {
                            prognoz[dataForPrognoz.Keys[i]] = outputVector[i];
                        }

                        for (int i=0; i < 24; i++) {
                            naporsForPrognoz[dataForPrognoz.Keys[i]] = prevDataVBArray[4] - prognoz[dataForPrognoz.Keys[i]];
                            napors[dataForPrognoz.Keys[i]] = naporsForPrognoz[dataForPrognoz.Keys[i]];
                        }
                    }

                    for (int i=0; i <= 4; i++) {
                        prevDataNBArray[i] = prognoz[dataForPrognoz.Keys[19 + i]];
                        prevDataRashodArray[i] = rashods[dataForPrognoz.Keys[19 + i]];
                    }

                    dataForPrognoz.Clear();
//.........这里部分代码省略.........
开发者ID:rj128x,项目名称:VotGES,代码行数:101,代码来源:PrognozNB.cs

示例9: outputResponse


//.........这里部分代码省略.........
                                else
                                    ranges.Add(rFrom, rTo);
                            }

                            // If one of the ranges spans the complete file, don't bother with ranges
                            if (!ranges.ContainsKey(0) || ranges[0] < contentLength - 1)
                            {
                                // Make a copy of this so that we can modify Ranges while iterating over it
                                var rangeFroms = new List<long>(ranges.Keys);

                                long prevFrom = 0;
                                bool havePrevFrom = false;
                                foreach (long from in rangeFroms)
                                {
                                    if (!havePrevFrom)
                                    {
                                        prevFrom = from;
                                        havePrevFrom = true;
                                    }
                                    else if (ranges[prevFrom] >= from)
                                    {
                                        ranges[prevFrom] = Math.Max(ranges[prevFrom], ranges[from]);
                                        ranges.Remove(from);
                                    }
                                }

                                // Note that "ContentLength" here refers to the total size of the file.
                                // The functions ServeSingleRange() and ServeRanges() will automatically
                                // set a Content-Length header that specifies the size of just the range(s).

                                // Also note that if Ranges.Count is 0, we want to fall through and handle the request without ranges
                                if (ranges.Count == 1)
                                {
                                    var range = ranges.First();
                                    serveSingleRange(headers, contentStream, originalRequest, range.Key, range.Value, contentLength);
                                    return useKeepAlive;
                                }
                                else if (ranges.Count > 1)
                                {
                                    serveRanges(headers, contentStream, originalRequest, ranges, contentLength);
                                    return useKeepAlive;
                                }
                            }
                        }
                    }

                    bool useGzip = useGzipOption != UseGzipOption.DontUseGzip && gzipRequested && !(contentLengthKnown && contentLength <= 1024) && originalRequest.HttpVersion == HttpProtocolVersion.Http11;

                    if (useGzip && useGzipOption == UseGzipOption.AutoDetect && contentLengthKnown && contentLength >= _server.Options.GzipAutodetectThreshold && contentStream.CanSeek)
                    {
                        try
                        {
                            contentStream.Seek((contentLength - _server.Options.GzipAutodetectThreshold) / 2, SeekOrigin.Begin);
                            byte[] buf = new byte[_server.Options.GzipAutodetectThreshold];
                            contentStream.Read(buf, 0, _server.Options.GzipAutodetectThreshold);
                            using (var ms = new MemoryStream())
                            {
                                using (var gzTester = new GZipOutputStream(ms))
                                {
                                    gzTester.SetLevel(1);
                                    gzTester.Write(buf, 0, _server.Options.GzipAutodetectThreshold);
                                }
                                if (ms.ToArray().Length >= 0.99 * _server.Options.GzipAutodetectThreshold)
                                    useGzip = false;
                            }
                            contentStream.Seek(0, SeekOrigin.Begin);
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:67,代码来源:HttpServer.cs

示例10: Optimize

        private void Optimize()
        {
            SortedList<int, int> Result = new SortedList<int, int>();
            lblScanCount.Text = "ScanCount:---";
            lblScanMaxCount.Text = "ScanMaxCount:---";

            for (nudAWin.Value = 500; nudAWin.Value > 0; nudAWin.Value--)
            {

                Simulate(gPairList,20, 30, 100, 0, (double)nudAWin.Value);

                int AWCount = 0;
                int ScanCount = 0;
                int ScanMaxCount = 0;
                Analyze(gPairList,out AWCount, out ScanCount, out ScanMaxCount);
                //lblAWC.Text = "AWCount: " + AWCount.ToString();

                Result.Add((int)nudAWin.Value, AWCount);
            }

            KeyValuePair<int, int> Best = Result.First(x => (x.Value == Result.Values.Min()));
            nudAWin.Value = Best.Key;
            lblAWC.Text = "AWCount: " + Best.Value.ToString();

            Random rand = new Random();
            GA ga = new GA(500, 3,
            individual =>
            {
                List<Pair> PairList = gPairList.ToList(); ;
                Simulate(PairList,Math.Abs(individual.Genotype[0] * 100),
                    Math.Abs(individual.Genotype[1] * 100),
                    Math.Abs(individual.Genotype[2] * 100),
                    0/* Math.Abs(individual.Genotype[3] * 100)*/,
                    (double)nudAWin.Value);

                int AWCount = 0;
                int ScanCount = 0;
                int ScanMaxCount = 0;
                Analyze(PairList,out AWCount, out ScanCount, out ScanMaxCount);

                return ((Math.Pow(AWCount - ScanMaxCount, 2) / 4) + Math.Pow(AWCount - ScanCount, 2) + Math.Abs(individual.Genotype[2]) * 10 + Math.Abs(individual.Genotype[1]) * 100 + Math.Abs(individual.Genotype[0]) * 100 + (Math.Abs(individual.Genotype[1]) < Math.Abs(individual.Genotype[0]) ? 100 : 0));
            },
            individual =>
            {
                individual.Genotype[0] = 2 * rand.NextDouble();
                individual.Genotype[1] = 2 * rand.NextDouble();
                individual.Genotype[2] = 2 * rand.NextDouble();
            });

            backgroundWorker1.RunWorkerAsync(ga);

            /* nudScanTime.Value=(decimal)Math.Abs(ga.BestIndividual.Genotype[0]*100);
             nudMaskTime.Value = (decimal)Math.Abs(ga.BestIndividual.Genotype[1]*100);
             nudThresold.Value = (decimal)Math.Abs(ga.BestIndividual.Genotype[2]*100);
             nudRet.Value = 0;//(decimal)Math.Abs(ga.BestIndividual.Genotype[3] * 100);
             */

            //double ScanTime = (double);
            //double MaskTime = (double)
            //double Thresold = (double)
        }
开发者ID:massimobernava,项目名称:md-drumscope,代码行数:61,代码来源:mainform.cs

示例11: AStarSolver

        /// <summary>
        /// Runs an AStar search through the puzzle, looking for the solution.
        /// </summary>
        /// <returns>Node holding the solved puzzle, or nothing if puzzle not solved.</returns>
        private SliderNode AStarSolver()
        {
            // Initialize the first node for the default state, add it to found state list,
            // then push it to the stack
            var node = CurrentPuzzle.StartingNode;

            var comp = new ClassComparer();
            var heuristicList = new SortedList<int, SliderNode>(comp);

            _history.Add(node.StateS, node);
            heuristicList.Add(node.Heuristic + node.Cost, node);

            while (heuristicList.Count > 0)
            {
                // get first in stack
                var currentNode = heuristicList.First().Value;
                heuristicList.RemoveAt(0);

                // Increment for each node expanded
                NodesExpanded++;

                // Is state the goal state?
                if (currentNode.StateS.Equals(CurrentPuzzle.GoalNode.StateS)) return currentNode;

                // Get all swaps and push them to the queue
                foreach (var swapNode in currentNode.GetSuccessors())
                {
                    var key = swapNode.StateS;

                    // If key is in history and the cost in the history is larger, then reduce the cost in the history
                    //
                    if (_history.ContainsKey(key))
                    {
                        if (_history[key].Cost <= swapNode.Cost) continue;
                        _history[key].Cost = swapNode.Cost;
                        heuristicList.Add(swapNode.Heuristic + swapNode.Cost, swapNode);
                    }
                    else
                    {
                        heuristicList.Add(swapNode.Heuristic + swapNode.Cost, swapNode);
                        _history.Add(swapNode.StateS, swapNode);
                    }
                }
            }
            return null;
        }
开发者ID:WCapelle,项目名称:Slider8Solver,代码行数:50,代码来源:SliderSolver.cs

示例12: FillHourGaps

        internal static SortedList<DateTime, MeasureKwH> FillHourGaps(SortedList<DateTime, MeasureKwH> hourlyKwH
                                                                        , int startHour, int endHour)
        {
            //break if we have no data
              if (hourlyKwH.Count == 0)
              {
            return hourlyKwH;
              }
              int privateInverterID = hourlyKwH.Values.First().PrivateInverterId;
              int publicInverterId = hourlyKwH.Values.First().PublicInverterId;

              DateTime firstMeasureDate = hourlyKwH.First().Value.DateTime;
              DateTime lastMeasureDate = hourlyKwH.Last().Value.DateTime;

              //build startDate and endDate we need
              DateTime startDate = new DateTime(firstMeasureDate.Year
              , firstMeasureDate.Month
              , firstMeasureDate.Day
              , startHour, 0, 0);

              DateTime endDate = new DateTime(lastMeasureDate.Year
              , lastMeasureDate.Month
              , lastMeasureDate.Day
              , endHour, 0, 0);

              //counter
              var countDate = startDate;

              while (countDate <= endDate)
              {
            if (!hourlyKwH.ContainsKey(countDate))
            {
              MeasureKwH dummyMeasure = new MeasureKwH();
              dummyMeasure.DateTime = countDate;
              dummyMeasure.Value = 0;
              dummyMeasure.PrivateInverterId = privateInverterID;
              dummyMeasure.PublicInverterId = publicInverterId;
              hourlyKwH.Add(countDate, dummyMeasure);
            }

            //increase hour until endHour, then jump to the next day
            countDate = countDate.AddHours(1);
            if (countDate.Hour > endHour)
            {
              countDate = countDate.AddHours(24 - countDate.Hour + startHour);
            }
              }
              return hourlyKwH;
        }
开发者ID:Epstone,项目名称:mypvlog,代码行数:49,代码来源:KwhCalculator.cs

示例13: isTooClose

 static bool isTooClose(KeyValuePair<int, DateTime> keyVal, SortedList<int, DateTime> lst)
 {
     if (keyVal.Key == lst.First().Key || keyVal.Key == lst.Last().Key)
         return false;
     foreach (var kv in lst)
     {
         if (kv.Key > keyVal.Key && Math.Abs((kv.Value - keyVal.Value).TotalMinutes) < 2)
             return true;
     }
     return false;
 }
开发者ID:JBetser,项目名称:MiDax,代码行数:11,代码来源:MarketSelector.cs

示例14: SelectFilesToKeep

        static bool SelectFilesToKeep(HashPointers ptr, out List<int> toKeep)
        {
            bool selectionSuccess = false;
            toKeep = new List<int>(Enumerable.Range(1, ptr.FileEntries.Count));
            bool decided = false;
            int choice = 0;

            bool canAutoSelect = false;
            List<int> oldestIDs = new List<int>();
            List<int> newestIDs = new List<int>();
            {
                // Read and register the timestamp when the files were last accessed
                // The oldest file (lowest timestamp) will be on the top of the list
                SortedList<DateTime, List<int>> timeStamps = new SortedList<DateTime, List<int>>(ptr.FileEntries.Count);
                PathEntry entry = new PathEntry();
                int currentID = 1;
                foreach (long offset in ptr.FileEntries)
                {
                    PathsFile.GetRecordAt(offset, out entry);
                    FileInfo fi = new FileInfo(entry.Path);

                    IEnumerable<DateTime> tsRegistered = timeStamps.Select(ts => ts.Key)
                        .Where(ts => ts.Date == fi.LastAccessTime.Date
                            && ts.Hour == fi.LastAccessTime.Hour
                            && ts.Minute == fi.LastAccessTime.Minute
                            && ts.Second == fi.LastAccessTime.Second);
                    if (tsRegistered.Count() == 1)
                        timeStamps[tsRegistered.First()].Add(currentID);
                    else
                    {
                        List<int> idList = new List<int>(1);
                        idList.Add(currentID);
                        timeStamps.Add(fi.LastAccessTime, idList);
                    }
                    ++currentID;
                }

                // If the oldest and newest files are the same, don't select any of them
                if (timeStamps.Count == 1 && (AutoOldest || AutoNewest))
                    Console.WriteLine("The files' age are equal. Unable to select oldest and newest ones.");
                else
                {
                    oldestIDs.AddRange(timeStamps.First().Value);
                    newestIDs.AddRange(timeStamps.Last().Value);
                    canAutoSelect = true;
                }
            }

            while (!selectionSuccess)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine(new String('-', Console.WindowWidth - 1));
                DuplicateFileLog.WriteLine(new String('-', 24));
                Console.WriteLine("The following " + ptr.FileEntries.Count + " files are duplicate of each other");
                DuplicateFileLog.WriteLine("The following " + ptr.FileEntries.Count + " files are duplicate of each other");
                Console.ResetColor();
                if (Verbose)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Hash: " + ptr.Hash);
                    DuplicateFileLog.WriteLine("Hash: " + ptr.Hash);
                    Console.ResetColor();
                }

                if (!DryRun)
                {
                    Console.Write("Files marked ");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("[ KEEP ]");
                    Console.ResetColor();
                    Console.Write(" will be kept. Files marked ");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("[DELETE]");
                    Console.ResetColor();
                    Console.WriteLine(" will be deleted.");

                    if (!AutoNewest && !AutoOldest)
                        Console.WriteLine("Please select the files you wish to keep or delete.");
                    else
                        if (!canAutoSelect)
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Was unable to automatically select " + (AutoOldest ? "oldest" : "newest") + " file to keep");
                            Console.ResetColor();
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Automatically selecting the " + (AutoOldest ? "OLDEST" : "NEWEST") + " file to keep");
                            Console.ResetColor();
                            toKeep.Clear();

                            if (AutoOldest)
                                toKeep.AddRange(oldestIDs);
                            else if (AutoNewest)
                                toKeep.AddRange(newestIDs);
                        }
                }

                // Print the file list with a choice
//.........这里部分代码省略.........
开发者ID:whisperity,项目名称:DuplicateDestroyer,代码行数:101,代码来源:Program.cs

示例15: Subscribe

        public override void Subscribe(string[] epics, IHandyTableListener tableListener)
        {
            Dictionary<string, List<CqlQuote>> priceData = GetReplayData(epics);

            foreach (var epic in epics)
            {
                // for each quote, associate the observed gains in the near future
                var mktData = new MarketData(epic);
                var wmaLow = new IndicatorWMA(mktData, 10);
                var wmaMid = new IndicatorWMA(mktData, 30);
                var wmaHigh = new IndicatorWMA(mktData, 90);
                var wmaDailyAvg = new IndicatorLevelMean(mktData);

                foreach (var quote in priceData[epic])
                    mktData.TimeSeries.Add(quote.t, new Price(quote.MidPrice()));
                foreach (var quote in ExpectedIndicatorData[wmaLow.Id])
                    wmaLow.TimeSeries.Add(quote.t, new Price(quote.ScaleValue(0, 1)));
                foreach (var quote in ExpectedIndicatorData[wmaLow.Id])
                    wmaLow.TimeSeries.Add(quote.t, new Price(quote.ScaleValue(0, 1)));

                var expectations = new Dictionary<DateTime, KeyValuePair<CqlQuote, decimal>>();
                var gainDistribution = new SortedList<int, DateTime>();
                KeyValuePair<int, DateTime> minProfit = new KeyValuePair<int, DateTime>(1000000, DateTime.MinValue);
                KeyValuePair<int, DateTime> maxProfit = new KeyValuePair<int, DateTime>(-1000000, DateTime.MinValue);
                var rnd = new Random(155);
                var openPrice = priceData[epic][0];
                foreach (var quote in priceData[epic])
                {
                    if (quote.t.TimeOfDay < Config.ParseDateTimeLocal(Config.Settings["TRADING_START_TIME"]).TimeOfDay)
                        continue;
                    var futureVal = wmaLow.Average(quote.t.AddMinutes(2));
                    var profit = (int)Math.Round(futureVal.Mid() - quote.MidPrice());
                    expectations.Add(quote.t, new KeyValuePair<CqlQuote, decimal>(quote, profit));
                    if (gainDistribution.ContainsKey(profit))
                    {
                        if ((quote.t - gainDistribution[profit]).Hours > 3 && (rnd.Next(100) == 0))
                            gainDistribution[profit] = quote.t;
                    }
                    else
                        gainDistribution[profit] = quote.t;
                    if (profit < minProfit.Key)
                        minProfit = new KeyValuePair<int, DateTime>(profit, gainDistribution[profit]);
                    if (profit > maxProfit.Key)
                        maxProfit = new KeyValuePair<int, DateTime>(profit, gainDistribution[profit]);
                    quote.b -= openPrice.MidPrice();
                    quote.o -= openPrice.MidPrice();
                }
                int nbPoints = 10;
                int idxProfit = 0;
                KeyValuePair<int, DateTime> nextProfit = minProfit;
                var selection = new SortedList<DateTime, KeyValuePair<int, CqlQuote>>();
                while (idxProfit++ < nbPoints)
                {
                    PublisherConnection.Instance.Insert(nextProfit.Value, epic, new Value(nextProfit.Key));
                    selection.Add(nextProfit.Value, new KeyValuePair<int, CqlQuote>(nextProfit.Key, expectations[nextProfit.Value].Key));
                    nextProfit = gainDistribution.First(keyVal => keyVal.Key >= ((decimal)minProfit.Key + (decimal)idxProfit * (decimal)(maxProfit.Key - minProfit.Key) / (decimal)nbPoints));
                }
                foreach (var profit in selection)
                {
                    PublisherConnection.Instance.Insert(gainDistribution[profit.Value.Key], wmaLow, wmaLow.Average(gainDistribution[profit.Value.Key]).Mid() - openPrice.MidPrice());
                    PublisherConnection.Instance.Insert(gainDistribution[profit.Value.Key], wmaMid, wmaMid.Average(gainDistribution[profit.Value.Key]).Mid() - openPrice.MidPrice());
                    PublisherConnection.Instance.Insert(gainDistribution[profit.Value.Key], wmaHigh, wmaHigh.Average(gainDistribution[profit.Value.Key]).Mid() - openPrice.MidPrice());
                    PublisherConnection.Instance.Insert(gainDistribution[profit.Value.Key], wmaDailyAvg, wmaDailyAvg.Average().Mid() - openPrice.MidPrice());
                }
                priceData[epic] = selection.Values.Select(keyVal => keyVal.Value).ToList();
            }
            replay(priceData, tableListener);
        }
开发者ID:JBetser,项目名称:MiDax,代码行数:68,代码来源:Calibration.cs


注:本文中的SortedList.First方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。