/// <summary>
        /// Generates the result of the first N steps of the algorithm for display
        /// </summary>
        /// <param name="step">The amount of steps to work through</param>
        /// <returns>The lines to draw on the graph</returns>
        public List<Line> ComputeToStep(int step)
        {
            if (step >= lines.Count)
            {
                step = lines.Count;
            }

            List<Line> linesAtStep = new List<Line>();

            List<int> greenIndex = new List<int>();

               foreach (Line line in lines)
            {
                if (line.GetColor() == Color.Green)
                {
                    greenIndex.Add(lines.IndexOf(line));
                }
            }

            if (step == 0)
            {
                return linesAtStep;
            }

            linesAtStep = lines.GetRange(0, step);

            int removeRedsBefore = greenIndex.FindLast(a => a < step);

            linesAtStep.RemoveAll(a => a.GetColor() == Color.Red && linesAtStep.IndexOf(a) < removeRedsBefore);

            return linesAtStep;
        }
 internal static CompletionSet Create(List<DesignerNode> nodes, SnapshotPoint point)
 {
     DesignerNode node = nodes.FindLast(n => n.NodeType == NDjango.Interfaces.NodeType.ParsingContext);
     if (node == null)
         return null;
     return new TagCompletionSet(node, point);
 }
        static void Main(string[] args)
        {
            List<int> lista=new List<int>(new int[] {1,2,3,4,5,6,7,8});
            List<int> numeripari=lista.FindAll(delegate(int i){
                return i%2==0;
            });
            numeripari.ForEach(Console.WriteLine);

            //lambda
            CheckIntDelegate del = (x => x % 2 == 0);
            var pari = del(234);

            Predicate<int> pred= (x => x % 2 == 0);
            bool b=pred(234521);

            var dispari = lista.FindLast(i => i % 2 != 0);

            Func<int,int, double> mediaFunc= (x,y) => (x+y)/2.0;
            double average=mediaFunc(3,7);

            Action<string, string> upperAction = (s1, s2) =>
            {
                string s = s1 + " " + s2;
                Console.WriteLine(s.ToUpper());
            };

            upperAction("Hello", "World");

            //variabili catturata
            Func<int, int> func = CreaFunc();
            int res = func(5);

            //modifica variabile catturata
            Func<int> modificaVariabile = () => res = 10;
            modificaVariabile();
            Console.WriteLine(res);

            Expression<Func<int, bool>> exprPari = num => num % 2==0;

            // Compila l'abero di espression in delegate.
            Func<int, bool> isPari = exprPari.Compile();

            // invoca il delegate
            Console.WriteLine(isPari(4));

            // sintassi semplificata
            Console.WriteLine(exprPari.Compile()(5));

            //analizzare l'espressione
            ParameterExpression parNum=exprPari.Parameters[0];
            BinaryExpression opModulo = (BinaryExpression)exprPari.Body;
            BinaryExpression exprLeft = (BinaryExpression)opModulo.Left;
            ParameterExpression exprNum = (ParameterExpression)exprLeft.Left;
            ConstantExpression expr2 = (ConstantExpression)exprLeft.Right;
            ConstantExpression opRight = (ConstantExpression)opModulo.Right;
        }
        public void AddHealthAmount(int health)
        {
            if (_healths != null && _healths.Count > 0 && _healths.TrueForAll(h => h.IsFullHealth()))
            {
                return;
            }

            var damagedHealth = _healths?.FindLast(h => !h.IsFullHealth());

            damagedHealth?.AddHealth(health);
        }
        /// <summary>
        /// Gets the custom pricing for each mailbox plan
        /// </summary>
        /// <param name="product"></param>
        /// <param name="companyCode"></param>
        /// <param name="mailboxPlans"></param>
        public static void GetCustomPricing(string product, string companyCode, string currencySymbol, ref List<MailboxPlan> plans)
        {
            SqlConnection sql = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT PlanID, Product, Price FROM PriceOverride WHERE CompanyCode=@CompanyCode AND Product=@Product", sql);

            try
            {
                // Add parameters
                cmd.Parameters.AddWithValue("Product", product);
                cmd.Parameters.AddWithValue("CompanyCode", companyCode);
                
                // Open connection
                sql.Open();

                // Read data
                SqlDataReader r = cmd.ExecuteReader();
                if (r.HasRows)
                {
                    while (r.Read())
                    {
                        int planId = int.Parse(r["PlanID"].ToString());

                        var findItem = plans.FindLast(x => x.PlanID == planId);
                        if (findItem != null)
                        {
                            plans[plans.IndexOf(findItem)].CustomPrice = String.Format(currencySymbol + r["Price"].ToString());
                        }
                    }
                }

                // Close
                r.Close();
                sql.Close();

                // Dispose
                r.Dispose();
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (cmd != null)
                    cmd.Dispose();

                if (sql != null)
                    sql.Dispose();
            }
        }
    private IMarker FindClosestMarker( List<IMarker> markers, NavDestination destination, int caretLine, int caretColumn )
    {
      IMarker closestMarker = null;
      if ( markers != null && markers.Count > 0 && destination != NavDestination.None )
      {
        IMarker firstMarker = markers[0];
        IMarker lastMarker = markers[markers.Count - 1];
        switch ( destination )
        {
          case NavDestination.First:
            closestMarker = firstMarker;
            break;
          case NavDestination.Prev:
          case NavDestination.Next:
            if ( destination == NavDestination.Prev )
              closestMarker = markers.FindLast( marker =>
                  marker.Line < caretLine || (marker.Line == caretLine && marker.Column < caretColumn) );
            else
              closestMarker = markers.Find( marker =>
                marker.Line > caretLine || (marker.Line == caretLine && marker.Column > caretColumn) );

            // if no target found and we have only a single marker, that's the new target
            if ( closestMarker == null && markers.Count == 1 )
            {
              IMarker marker = firstMarker;
              if ( marker.Line == caretLine && marker.Column == caretColumn )
                closestMarker = marker;
            }
            // if we allow "rolling over" on prev/next, do so
            if ( _settings.RollOverOnPrevNext && closestMarker == null )
            {
              if ( destination == NavDestination.Prev )
                closestMarker = lastMarker;
              else if ( destination == NavDestination.Next )
                closestMarker = firstMarker;
            }
            break;
          case NavDestination.Last:
            closestMarker = lastMarker;
            break;
          case NavDestination.Top:
            closestMarker = CodeRush.Markers.Top;
            break;
        }
      }
      return closestMarker;
    }
Esempio n. 7
0
        static void Main()
        {
            var racers = new List<Racer>();
            racers.Add(new Racer(26, "Jacques", "Villeneuve", "Canada", 11));
            racers.Add(new Racer(18, "Alan", "Jones", "Australia", 12));
            racers.Add(new Racer(11, "Jackie", "Stewart", "United Kingdom", 27));
            racers.Add(new Racer(15, "James", "Hunt", "United Kingdom", 10));
            racers.Add(new Racer(5, "Jack", "Brabham", "Australia", 14));
            racers.Add(new Racer(25, "Adi", "ADDD", "Australia", 28));

            var lookupRacers = racers.ToLookup(r => r.Country);

            foreach (Racer r in lookupRacers["Australia"])
            {
                Console.WriteLine(r);
            }
            // public delegate bool Predicate<T>(T obj);
            int index = racers.FindIndex(new FindCountry("Australia").FindCountryPredicate);
            Console.WriteLine("index:{0}",index);
            //下面是等价的
            int index2 = racers.FindIndex(r => r.Country == "Australia");
            Console.WriteLine("index2:{0}", index2);
            //返回第一个匹配的
            //FindLast 最后一个匹配的
            Console.WriteLine("Find get first match object");
            Racer racerFirst = racers.Find(c => c.Country == "Australia");
            Console.WriteLine(racerFirst.FirstName);
            Console.WriteLine(racerFirst.LastName);

            Console.WriteLine("FindLast get last match object");
            Racer racerLast = racers.FindLast(c => c.Country == "Australia");
            Console.WriteLine(racerLast.FirstName);
            Console.WriteLine(racerLast.LastName);

            Console.WriteLine("FindAll get All match object");
            List<Racer> racerAll = racers.FindAll(r => r.Wins > 20);
            foreach (Racer r in racerAll)
            {
                Console.WriteLine("{0:A}",r);
            }
            Console.ReadKey();
            
        }
 /// <summary>
 /// Handles and updates the player lives
 /// </summary>
 /// <param name="_amount">amount of lives lost</param>
 public void UpdatePlayerLives(int _amount)
 {
     lives -= _amount;
     if (lives < 1)
     {
         lives = MAXLIVES;
         EventManager.OnGameOverHandler();
     }
     for (int attackTimes = 0; attackTimes <= _amount - 1; attackTimes++)
     {
         if (lives > 0)
         {
             Image lastImage = livesImages?.FindLast(i => i.gameObject.activeSelf);
             if (lastImage == null)
             {
                 return;
             }
             else
             {
                 lastImage.gameObject.SetActive(false);
             }
         }
     }
 }
      //@}

      //! \name CashFlow functions
      //@{
      //! the last cashflow paying before or at the given date
      public static CashFlow previousCashFlow(List<CashFlow> leg, bool includeSettlementDateFlows,Date settlementDate = null) 
      {
         if (leg.Count == 0) return null;

         Date d = (settlementDate == null ? Settings.evaluationDate() : settlementDate);
         return  leg.FindLast(x => x.hasOccurred(d, includeSettlementDateFlows));
      }
Esempio n. 10
0
 /// <summary>
 /// Find last element by condition.
 /// </summary>
 /// <param name="match">Condition to find.</param>
 /// <returns>Finded element.</returns>
 public JsonValue FindLast(Predicate <JsonValue> match)
 {
     return(_values.FindLast(match));
 }
Esempio n. 11
0
        private CompletionSet CreateCompletionSet(SnapshotPoint point)
        {
            switch (Context)
            {
            case CompletionContext.Tag:
                return(AbstractCompletionSet.Create <TagCompletionSet>(
                           this, point,
                           nodeProvider.GetNodes(point, n => n.NodeType == NodeType.ParsingContext || n.NodeType == NodeType.CommentContext).FindLast(n => true)
                           ));

            case CompletionContext.Variable:
                return(AbstractCompletionSet.Create <VariableCompletionSet>(
                           this, point,
                           nodeProvider.GetNodes(point, n => n.NodeType == NodeType.ParsingContext).FindLast(n => true)
                           ));

            case CompletionContext.FilterName:
                return(AbstractCompletionSet.Create <FilterName>(
                           this, point,
                           nodeProvider.GetNodes(point, n => n.NodeType == NodeType.ParsingContext).FindLast(n => true)
                           ));

            case CompletionContext.FilterArgument:
                return(AbstractCompletionSet.Create <FilterArgument>(
                           this, point,
                           nodeProvider.GetNodes(point, n => n.NodeType == NodeType.Filter).FindLast(n => true)));

            case CompletionContext.Word:
                // Get the list of all nodes with non-empty value lists
                List <DesignerNode> nodes = nodeProvider.GetNodes(point, n => n.IsCompletionProvider);
                // out of the list get the last node which is not a parsing context
                DesignerNode node = nodes.FindLast(n => n.NodeType != NodeType.ParsingContext);
                if (node == null)
                {
                    return(null);
                }
                switch (node.NodeType)
                {
                case NodeType.Reference:
                    return(AbstractCompletionSet.Create <Member>(this, point, node));

                case NodeType.TagName:
                    return(new TagName(this, node, point));

                case NodeType.TypeName:
                    return(new TypeName(this, node, point));

                default:
                    break;
                }
                return(new ValueCompletionSet(this, node, point));

            case CompletionContext.NewMemberReference:
                return(AbstractCompletionSet.Create <NewMember>(
                           this, point,
                           nodeProvider.GetNodes(point, n => n.NodeType == NodeType.Reference).FindLast(n => true)));

            case CompletionContext.AposString:
            case CompletionContext.QuotedString:
                return(AbstractCompletionSet.Create <TemplateName>(
                           this, point,
                           nodeProvider.GetNodes(point, n => n.NodeType == NodeType.TemplateName).FindLast(n => true)));

            default:
                return(null);
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire EventList&lt;IFeature&gt;.
 /// </summary>
 /// <param name="match">The System.Predicate&lt;IFeature&gt; delegate that defines the conditions of the element to search for.</param>
 /// <returns>The last element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type IFeature.</returns>
 /// <exception cref= "System.ArgumentNullException">match is null."</exception>
 public virtual IFeature FindLast(Predicate <IFeature> match)
 {
     return(_list.FindLast(match));
 }
        /// <summary>
        /// 开始计算
        /// </summary>
        private void Statistics()
        {
            try
            {
                List <ReadingRoomInfo> rooms = seatManageService.GetReadingRooms(null, null, null);
                DateTime sdt = seatManageService.GetLastRoomUsageStatisticsDate();
                if (sdt <= DateTime.Parse("2000-1-1"))
                {
                    return;
                }
                sdt = sdt.AddDays(1);
                while (true)
                {
                    //获取进出记录
                    List <EnterOutLogInfo>         enterOutLogList  = seatManageService.GetEnterOutBakLogsByDate(sdt);
                    List <BespeakLogInfo>          bespeakLogList   = seatManageService.GetBespeakLogs(null, null, sdt, 0, null);
                    List <ViolationRecordsLogInfo> violationLogList = seatManageService.GetViolationRecordsLogs(null, null, sdt.ToShortDateString(), sdt.Date.AddDays(1).AddSeconds(-1).ToString(), LogStatus.None, LogStatus.None);
                    //List<BlackListInfo> blacklistList = T_SM_Blacklist.GetAllBlackListInfo(null, LogStatus.None, sdt.ToShortDateString(), sdt.Date.AddDays(1).AddSeconds(-1).ToString());
                    if (enterOutLogList.Count <= 0 && bespeakLogList.Count <= 0 && violationLogList.Count <= 0 && sdt >= DateTime.Now.Date.AddDays(-1))
                    {
                        break;
                    }
                    Dictionary <string, SeatManage.ClassModel.RoomUsageStatistics> roomDir = rooms.ToDictionary(room => room.No, room => new SeatManage.ClassModel.RoomUsageStatistics());

                    //基本数据及排序处理
                    foreach (ReadingRoomInfo room in rooms)
                    {
                        roomDir[room.No].StatisticsDate  = sdt;
                        roomDir[room.No].ReadingRoomNo   = room.No;
                        roomDir[room.No].SeatAllCount    = room.SeatList.Seats.Count;
                        roomDir[room.No].OpenTime        = DateTime.Parse(room.Setting.GetRoomOpenTimeByDate(sdt).BeginTime);
                        roomDir[room.No].CloseTime       = DateTime.Parse(room.Setting.GetRoomOpenTimeByDate(sdt).EndTime);
                        roomDir[room.No].RoomUsageTime   = (int)(roomDir[room.No].CloseTime - roomDir[room.No].OpenTime).TotalMinutes;
                        roomDir[room.No].SeatUsageCount  = enterOutLogList.FindAll(u => u.ReadingRoomNo == room.No).GroupBy(u => u.SeatNo).Count();
                        roomDir[room.No].UsedReaderCount = enterOutLogList.FindAll(u => u.ReadingRoomNo == room.No).GroupBy(u => u.CardNo).Count();
                        roomDir[room.No].CanBesapeakSeat = room.Setting.SeatBespeak.BespeakArea.BespeakType == BespeakAreaType.Percentage ? (int)room.Setting.SeatBespeak.BespeakArea.Scale * room.SeatList.Seats.Count : room.SeatList.Seats.Count(u => u.Value.CanBeBespeak);
                        roomDir[room.No].BespeakedSeat   = bespeakLogList.FindAll(u => u.ReadingRoomNo == room.No).GroupBy(u => u.SeatNo).Count();
                    }
                    foreach (ViolationRecordsLogInfo vrl in violationLogList)
                    {
                        roomDir[vrl.ReadingRoomID].ViolationRecordCount++;
                        switch (vrl.EnterFlag)
                        {
                        case ViolationRecordsType.BookingTimeOut:
                            roomDir[vrl.ReadingRoomID].VRBookingTimeOut++;
                            break;

                        case ViolationRecordsType.LeaveByAdmin:
                            roomDir[vrl.ReadingRoomID].VRLeaveByAdmin++;
                            break;

                        case ViolationRecordsType.LeaveNotReadCard:
                            roomDir[vrl.ReadingRoomID].VRLeaveNotReadCard++;
                            break;

                        case ViolationRecordsType.SeatOutTime:
                            roomDir[vrl.ReadingRoomID].VRSeatOutTime++;
                            break;

                        case ViolationRecordsType.ShortLeaveByAdminOutTime:
                            roomDir[vrl.ReadingRoomID].VRShortLeaveByAdminOutTime++;
                            break;

                        case ViolationRecordsType.ShortLeaveByReaderOutTime:
                            roomDir[vrl.ReadingRoomID].VRShortLeaveByReaderOutTime++;
                            break;

                        case ViolationRecordsType.ShortLeaveByServiceOutTime:
                            roomDir[vrl.ReadingRoomID].VRShortLeaveByServiceOutTime++;
                            break;

                        case ViolationRecordsType.ShortLeaveOutTime:
                            roomDir[vrl.ReadingRoomID].VRShortLeaveOutTime++;
                            break;
                        }
                    }
                    //预约记录处理
                    foreach (BespeakLogInfo bli in bespeakLogList)
                    {
                        roomDir[bli.ReadingRoomNo].AllBespeakCount++;
                        if (bli.BsepeakTime.Date == bli.SubmitTime.Date)
                        {
                            switch (bli.BsepeakState)
                            {
                            case BookingStatus.Cencaled:
                                switch (bli.CancelPerson)
                                {
                                case Operation.Admin:
                                case Operation.Reader:
                                    roomDir[bli.ReadingRoomNo].NowDayBespeakCancel++;
                                    break;

                                case Operation.Service:
                                    roomDir[bli.ReadingRoomNo].NowDayBespeakOverTime++;
                                    break;
                                }
                                break;

                            case BookingStatus.Confinmed:
                                roomDir[bli.ReadingRoomNo].NowDayBespeakCheck++;
                                break;
                            }
                            roomDir[bli.ReadingRoomNo].NowDayBespeakCount++;
                        }
                        else
                        {
                            switch (bli.BsepeakState)
                            {
                            case BookingStatus.Cencaled:
                                switch (bli.CancelPerson)
                                {
                                case Operation.Admin:
                                case Operation.Reader:
                                    roomDir[bli.ReadingRoomNo].BespeakCancel++;
                                    break;

                                case Operation.Service:
                                    roomDir[bli.ReadingRoomNo].BespeakOverTime++;
                                    break;
                                }
                                break;

                            case BookingStatus.Confinmed:
                                roomDir[bli.ReadingRoomNo].BespeakCheck++;
                                break;
                            }
                            roomDir[bli.ReadingRoomNo].BespeakCount++;
                        }
                    }
                    foreach (EnterOutLogInfo eol in enterOutLogList)
                    {
                        //刷卡次数
                        if (!string.IsNullOrEmpty(eol.TerminalNum) && !(eol.EnterOutState == EnterOutLogType.ContinuedTime && eol.Flag == Operation.Service))
                        {
                            roomDir[eol.ReadingRoomNo].RushCardOperatingCount++;
                        }
                        //记录类型
                        switch (eol.EnterOutState)
                        {
                        case EnterOutLogType.BookingConfirmation:
                            roomDir[eol.ReadingRoomNo].CheckBespeakCount++;
                            if (string.IsNullOrEmpty(eol.TerminalNum))
                            {
                                roomDir[eol.ReadingRoomNo].CkeckBespeakInOtherClient++;
                            }
                            else
                            {
                                roomDir[eol.ReadingRoomNo].CheckBespeakInSeatClient++;
                            }
                            break;

                        case EnterOutLogType.ComeBack:
                            roomDir[eol.ReadingRoomNo].ComeBackCount++;
                            switch (eol.Flag)
                            {
                            case Operation.Admin:
                                roomDir[eol.ReadingRoomNo].ComeBackByAdmin++;
                                break;

                            case Operation.OtherReader:
                                roomDir[eol.ReadingRoomNo].ComeBackByOtherReader++;
                                break;

                            case Operation.Reader:
                                roomDir[eol.ReadingRoomNo].ComeBackByReader++;
                                if (string.IsNullOrEmpty(eol.TerminalNum))
                                {
                                    roomDir[eol.ReadingRoomNo].ComeBackInOtherClient++;
                                }
                                else
                                {
                                    roomDir[eol.ReadingRoomNo].ComeBackInSeatClient++;
                                }
                                break;
                            }
                            EnterOutLogInfo slEOL = enterOutLogList.FindLast(u => u.EnterOutState == EnterOutLogType.ShortLeave && u.EnterOutLogNo == eol.EnterOutLogNo && u.EnterOutTime < eol.EnterOutTime);
                            if (slEOL != null)
                            {
                                roomDir[eol.ReadingRoomNo].ShortLeaveTime += (int)(slEOL.EnterOutTime - eol.EnterOutTime).TotalMinutes;
                            }
                            break;

                        case EnterOutLogType.ContinuedTime:
                            roomDir[eol.ReadingRoomNo].ContinueTimeCount++;
                            switch (eol.Flag)
                            {
                            case Operation.Service:
                                roomDir[eol.ReadingRoomNo].ContinueTimeByService++;
                                break;

                            case Operation.Reader:
                                roomDir[eol.ReadingRoomNo].ContinueTimeByReader++;
                                if (string.IsNullOrEmpty(eol.TerminalNum))
                                {
                                    roomDir[eol.ReadingRoomNo].ContinueTimeInOtherClient++;
                                }
                                else
                                {
                                    roomDir[eol.ReadingRoomNo].ContinueTimeInSeatClient++;
                                }
                                break;
                            }
                            break;

                        case EnterOutLogType.Leave:
                            roomDir[eol.ReadingRoomNo].LeaveCount++;
                            roomDir[eol.ReadingRoomNo].ReaderUsageCount++;
                            switch (eol.Flag)
                            {
                            case Operation.Service:
                                roomDir[eol.ReadingRoomNo].LeaveByService++;
                                break;

                            case Operation.Admin:
                                roomDir[eol.ReadingRoomNo].LeaveByAdmin++;
                                break;

                            case Operation.Reader:
                                roomDir[eol.ReadingRoomNo].LeaveByReader++;
                                if (string.IsNullOrEmpty(eol.TerminalNum))
                                {
                                    roomDir[eol.ReadingRoomNo].LeaveInOtherClient++;
                                }
                                else
                                {
                                    roomDir[eol.ReadingRoomNo].LeaveInSeatClient++;
                                }
                                break;
                            }
                            EnterOutLogInfo enterEOL = enterOutLogList.Find(u => (u.EnterOutState == EnterOutLogType.BookingConfirmation || u.EnterOutState == EnterOutLogType.ReselectSeat || u.EnterOutState == EnterOutLogType.SelectSeat || u.EnterOutState == EnterOutLogType.WaitingSuccess) && u.EnterOutLogNo == eol.EnterOutLogNo);
                            if (enterEOL != null)
                            {
                                roomDir[eol.ReadingRoomNo].SeatUsageTime += (int)(eol.EnterOutTime - enterEOL.EnterOutTime).TotalMinutes;
                            }
                            break;

                        case EnterOutLogType.ReselectSeat:
                            roomDir[eol.ReadingRoomNo].ReselectSeatCount++;
                            if (string.IsNullOrEmpty(eol.TerminalNum))
                            {
                                roomDir[eol.ReadingRoomNo].ReselectSeatInOtherClient++;
                            }
                            else
                            {
                                roomDir[eol.ReadingRoomNo].ReselectSeatInSeatClient++;
                            }
                            break;

                        case EnterOutLogType.SelectSeat:
                            roomDir[eol.ReadingRoomNo].SelectSeatCount++;
                            switch (eol.Flag)
                            {
                            case Operation.Admin:
                                roomDir[eol.ReadingRoomNo].SelectSeatByAdmin++;
                                break;

                            case Operation.Reader:
                                roomDir[eol.ReadingRoomNo].SelectSeatByReader++;
                                if (string.IsNullOrEmpty(eol.TerminalNum))
                                {
                                    roomDir[eol.ReadingRoomNo].SelectSeatInOtherClient++;
                                }
                                else
                                {
                                    roomDir[eol.ReadingRoomNo].SelectSeatInSeatClient++;
                                }
                                break;
                            }
                            break;

                        case EnterOutLogType.ShortLeave:
                            roomDir[eol.ReadingRoomNo].ShortLeaveCount++;
                            switch (eol.Flag)
                            {
                            case Operation.OtherReader:
                                roomDir[eol.ReadingRoomNo].ShortLeaveByOtherReader++;
                                break;

                            case Operation.Service:
                                roomDir[eol.ReadingRoomNo].ShortLeaveByService++;
                                break;

                            case Operation.Admin:
                                roomDir[eol.ReadingRoomNo].ShortLeaveByAdmin++;
                                break;

                            case Operation.Reader:
                                roomDir[eol.ReadingRoomNo].ShortLeaveByReader++;
                                if (string.IsNullOrEmpty(eol.TerminalNum))
                                {
                                    roomDir[eol.ReadingRoomNo].ShortLeaveInOtherClient++;
                                }
                                else
                                {
                                    roomDir[eol.ReadingRoomNo].ShortLeaveInSeatClient++;
                                }
                                break;
                            }
                            break;

                        case EnterOutLogType.WaitingSuccess:
                            roomDir[eol.ReadingRoomNo].WaitSeatCount++;
                            break;
                        }
                    }
                    foreach (SeatManage.ClassModel.RoomUsageStatistics roomUS in roomDir.Values.Where(roomUS => !seatManageService.AddRoomUsageStatistics(roomUS)))
                    {
                        WriteLog.Write(string.Format("数据统计服务:添加阅览室:{0} {1} 数据统计出错", roomUS.ReadingRoomNo, roomUS.StatisticsDate));
                        throw new Exception(string.Format("数据统计服务:添加阅览室:{0} {1} 数据统计出错", roomUS.ReadingRoomNo, roomUS.StatisticsDate));
                    }
                    sdt = sdt.AddDays(1);
                    if (sdt >= DateTime.Now.Date)
                    {
                        break;
                    }
                    roomDir = null;
                }
                WriteLog.Write("数据统计服务:统计阅览室完成使用情况完成");
            }

            catch (Exception ex)
            {
                WriteLog.Write(string.Format("数据统计服务:统计阅览室使用情况失败:{0}", ex.Message));
            }
        }
Esempio n. 14
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            if ((int)Android.OS.Build.VERSION.SdkInt >= 21)
            {
                ActionBar.SetIcon(
                    new ColorDrawable(Resources.GetColor(Android.Resource.Color.Transparent)));
            }

            ServicePointManager.ServerCertificateValidationCallback = validatedCertificate;

            BQ = new BlueQueenCore(@"http://usafeapi.bluequeen.tk", "v1", "token");

            //Portrait
            tx2 = FindViewById <TextView>(Resource.Id.textView2);
            averagepressureTxt    = FindViewById <TextView>(Resource.Id.averagepress);
            pressureTxt           = FindViewById <TextView>(Resource.Id.cisnienie);
            maximaltempTxt        = FindViewById <TextView>(Resource.Id.maximaltemp);
            minimaltempTxt        = FindViewById <TextView>(Resource.Id.minimaltemp);
            averageTemperatureTxt = FindViewById <TextView>(Resource.Id.averagetemp);
            button = FindViewById <Button>(Resource.Id.button1);
            if (button != null)
            {
                button.Click += test;
            }
            if (minimaltempTxt != null)
            {
                minimaltempTxt.Click += delegate
                {
                    double a   = WeatherData.Min(x => x.Value);
                    var    min = WeatherData.First(x => x.Value.ToString() == a.ToString());
                    ShowAlert(min.Date.ToLongDateString() + "\nToday's MIN : " + min.Value.ToString() + "°C\nMeasured on " + min.Date.ToShortTimeString());
                };
            }

            if (maximaltempTxt != null)
            {
                maximaltempTxt.Click += delegate
                {
                    double a   = WeatherData.Max(x => x.Value);
                    var    min = WeatherData.First(x => x.Value.ToString() == a.ToString());
                    ShowAlert(min.Date.ToLongDateString() + "\nToday's MAX : " + min.Value.ToString() + "°C\nMeasured on " + min.Date.ToShortTimeString());
                };
            }

            if (averageTemperatureTxt != null)
            {
                averageTemperatureTxt.Click += delegate
                {
                    var    a    = WeatherData.Average(x => x.Value);
                    string avg  = string.Format("{0:0.00}°C", a);
                    var    min  = WeatherData.FindLast(x => x.ID > 0);
                    string last = string.Format("{0:0.00}°C", min.Value);
                    string diff = string.Format("{0:0.00}°C", Math.Abs(a - min.Value));

                    ShowAlert(min.Date.ToLongDateString() + "\nToday's AVG : " + avg + "\nCurrent : " + last + "\nDiff : " + diff);
                };
            }

            if (averagepressureTxt != null)
            {
                averagepressureTxt.Click += delegate
                {
                    var    a    = PressureData.Average(x => x.Pressure);
                    string avg  = string.Format("{0:0.00} hPa", a);
                    var    min  = PressureData.FindLast(x => x.ID > 0);
                    string last = string.Format("{0:0.00} hPa", min.Pressure);
                    string diff = string.Format("{0:0.00} hPa", Math.Abs(a - min.Pressure));

                    ShowAlert(min.Date.ToLongDateString() + "\nToday's AVG : " + avg + "\nCurrent : " + last + "\nDiff : " + diff);
                };
            }

            if (tx2 != null)
            {
                tx2.Click += delegate
                {
                    var    min  = WeatherData.FindLast(x => x.ID > 0);
                    string last = string.Format("{0:0.00}°C", min.Value);
                    ShowAlert("Measured on:\n" + min.Date.ToLongDateString() + " " + min.Date.ToLongTimeString());
                };
            }
            if (pressureTxt != null)
            {
                pressureTxt.Click += delegate
                {
                    var    min  = PressureData.FindLast(x => x.ID > 0);
                    string last = string.Format("{0:0.00} hPa", min.Pressure);
                    ShowAlert("Measured on:\n" + min.Date.ToLongDateString() + " " + min.Date.ToLongTimeString());
                };
            }

            string text = Intent.GetStringExtra("WeatherData") ?? "[]";

            WeatherData = BQ.deserializeJson <WeatherInfo>(text);
            string text1 = Intent.GetStringExtra("PressureData") ?? "[]";

            PressureData = BQ.deserializeJson <PressureInfo>(text1);
            fillTextboxes();

            chart = FindViewById <PlotView>(Resource.Id.plotview);
            showTempChart();
            tempChartSw = FindViewById <Button>(Resource.Id.tempChart);
            if (tempChartSw != null)
            {
                tempChartSw.Click += delegate
                {
                    showTempChart();
                };
            }
            pressChartSw = FindViewById <Button>(Resource.Id.pressChart);
            if (pressChartSw != null)
            {
                pressChartSw.Click += delegate
                {
                    showPressureChart();
                };
            }
        }
        public string GetLocalIpAddress()
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                List<string> ipAddresses = new List<string>();

                var hostnames = NetworkInformation.GetHostNames();
                foreach (var hn in hostnames)
                {
                    if (hn.IPInformation != null)
                    {
                        if (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6 || // An Ethernet network interface.
                            hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71) // An IEEE 802.11 wireless network interface.
                        {
                            IPAddress validIpAddress;

                            var valid = IPAddress.TryParse(hn.DisplayName, out validIpAddress);
                            if (valid)
                            {
                                string ipAddress = validIpAddress.ToString();
                                ipAddresses.Add(ipAddress);
                            }
                        }
                    }
                }
                //TODO: maybe change how to chose if klas C network 192... then chose that one (in case more NICs which are active
                //TODO: or maybe don't return LastOrDefault but return list and iterate one after another
                //[TW]11/21/2015 - changed to return IP only that starts with 192.
                return ipAddresses.FindLast(ip => ip.StartsWith("192."));
            }

            return "Not Connected";
        }
        public static void Main()
        {
            string        input;
            List <Animal> animals = new List <Animal>();

            while ((input = Console.ReadLine()) != "End")
            {
                var commandArgs = input.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                var animalType  = commandArgs[0];
                if (commandArgs.Length == 5)
                {
                    animalType = commandArgs[0];
                    var name         = commandArgs[1];
                    var weight       = double.Parse(commandArgs[2]);
                    var livingRegion = commandArgs[3];
                    var breed        = commandArgs[4];

                    switch (animalType)
                    {
                    case "Cat":
                        animals.Add(new Cat(name, weight, livingRegion, breed));
                        break;

                    case "Tiger":
                        animals.Add(new Tiger(name, weight, livingRegion, breed));
                        break;
                    }
                }
                else if (commandArgs.Length == 4 && commandArgs[0] == "Mouse" || commandArgs[0] == "Dog")
                {
                    animalType = commandArgs[0];
                    var name         = commandArgs[1];
                    var weight       = double.Parse(commandArgs[2]);
                    var livingRegion = commandArgs[3];
                    switch (animalType)
                    {
                    case "Mouse":
                        animals.Add(new Mouse(name, weight, livingRegion));
                        break;

                    case "Dog":
                        animals.Add(new Dog(name, weight, livingRegion));
                        break;
                    }
                }
                else if (commandArgs.Length == 4)
                {
                    animalType = commandArgs[0];
                    var name     = commandArgs[1];
                    var weight   = double.Parse(commandArgs[2]);
                    var wingSize = double.Parse(commandArgs[3]);

                    switch (animalType)
                    {
                    case "Hen":
                        animals.Add(new Hen(name, weight, wingSize));
                        break;

                    case "Owl":
                        animals.Add(new Owl(name, weight, wingSize));
                        break;
                    }
                }


                var foodInput = Console.ReadLine().Split();

                var foodType     = foodInput[0];
                var foodQuantity = int.Parse(foodInput[1]);

                try
                {
                    Console.WriteLine(animals.FindLast(a => a.GetType().Name == animalType).MakeSound());

                    animals.FindLast(a => a.GetType().Name == animalType).FeedTheAnimal(foodType, foodQuantity);
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            foreach (var animal in animals)
            {
                Console.WriteLine(animal.ToString());
            }
        }
Esempio n. 17
0
        private void objectListViewShows2_SelectionChanged(object sender, EventArgs e)
        {
            //Create view on left when index is changed
            //if single item selected show more informaion

            if (objectListViewShows2.SelectedItems.Count == 1)
            {
                tableLayoutPanelOverview.Visible = true;
                tableLayoutPanelShows2_show_details.Visible = true;
                labelShows2_tvdb_name.Visible = true;
                buttonShows2_details_save.Visible = true;

                using (SABSyncEntities sabSyncEntities = new SABSyncEntities())
                {
                    //Get all information about the show, grab last and next episode information at some point

                    long id = Convert.ToInt64(objectListViewShows2.SelectedItem.Text);

                    var show =
                        (from s in sabSyncEntities.shows.AsEnumerable()
                         where s.id == id
                         select s).FirstOrDefault();

                    labelShows2_name_value.Text = show.show_name;
                    labelShows2_tvdb_id_value.Text = show.tvdb_id.ToString();
                    labelShows2_tvdb_name.Text = show.tvdb_name;
                    comboBoxShows2_quality.SelectedIndex = (int)show.quality;
                    numericUpDownShows2_ignore_seasons.Value = (int)show.ignore_season;
                    textBoxShows2_aliases.Text = show.aliases;

                    labelShows2_air_day_value.Text = show.air_day;
                    labelShows2_air_time_value.Text = show.air_time;
                    labelShows2_status_value.Text = show.status;
                    labelShows2_genre_value.Text = show.genre.Replace('|', '/');
                    textBoxShows2_overview.Text = show.overview;

                    var episodes = from n in sabSyncEntities.episodes
                                where n.shows.id == id select new EpisodeObject
                                {
                                    AirDate = n.air_date,
                                    AirTime = n.shows.air_time,
                                    SeasonNumber = n.season_number,
                                    EpisodeNumber = n.episode_number,
                                    EpisodeName = n.episode_name,
                                    EpisodeId = n.id
                                };

                    List<EpisodeObject> episodeList = new List<EpisodeObject>();
                    episodeList = episodes.ToList();
                    episodeList.Sort();

                    var last = episodeList.FindLast(d => d.Airs != new DateTime(1,1,1) && d.Airs < DateTime.Today);
                    var next = episodeList.Find(d => d.Airs != new DateTime(1, 1, 1) && d.Airs >= DateTime.Today);

                    if (next != null)
                    {
                        labelShows2_airs_next_date_value.Text = GetDateString(next.Airs);
                        labelShows2_airs_next_season_number_value.Text = next.SeasonNumber.ToString();
                        labelShows2_airs_next_episode_number_value.Text = next.EpisodeNumber.ToString();
                        labelShows2_airs_next_title_value.Text = next.EpisodeName;

                        //If SABSync downloaded this episode show a check mark!
                        if (sabSyncEntities.histories.Any(h => h.episode_id == next.EpisodeId))
                            pictureBoxShows2_next_downloaded.Visible = true;

                        else
                            pictureBoxShows2_next_downloaded.Visible = false;
                    }

                    else
                    {
                        labelShows2_airs_next_date_value.Text = "N/A";
                        labelShows2_airs_next_season_number_value.Text = "N/A";
                        labelShows2_airs_next_episode_number_value.Text = "N/A";
                        labelShows2_airs_next_title_value.Text = "N/A";
                    }

                    if (last != null)
                    {
                        labelShows2_airs_last_date_value.Text = GetDateString(last.Airs);
                        labelShows2_airs_last_season_number_value.Text = last.SeasonNumber.ToString();
                        labelShows2_airs_last_episode_number_value.Text = last.EpisodeNumber.ToString();
                        labelShows2_airs_last_title_value.Text = last.EpisodeName;

                        //If SABSync downloaded this episode show a check mark!
                        if (sabSyncEntities.histories.Any(h => h.episode_id == last.EpisodeId))
                            pictureBoxShows2_last_downloaded.Visible = true;

                        else
                            pictureBoxShows2_last_downloaded.Visible = false;
                    }

                    else
                    {
                        labelShows2_airs_last_date_value.Text = "N/A";
                        labelShows2_airs_last_season_number_value.Text = "N/A";
                        labelShows2_airs_last_episode_number_value.Text = "N/A";
                        labelShows2_airs_last_title_value.Text = "N/A";
                    }

                    //Show the Banner!
                    string image = String.Format("Images{0}Banners{1}{2}.jpg", Path.DirectorySeparatorChar,
                                                     Path.DirectorySeparatorChar, objectListViewShows2.SelectedItem.Text);

                    if (File.Exists(image))
                        pictureBoxShows2_banner.Image = Image.FromFile(image);

                    else
                        pictureBoxShows2_banner.Image = global::SABSync.Images.SABSync_Banner;
                }
            }

            if (objectListViewShows2.SelectedItems.Count > 1) //Multiple Selected
            {
                pictureBoxShows2_banner.Image = global::SABSync.Images.SABSync_Banner;

                //Display only Quality (and Ignore seasons options?)
                tableLayoutPanelOverview.Visible = false;
                tableLayoutPanelShows2_show_details.Visible = false;
                labelShows2_tvdb_name.Visible = false;
                buttonShows2_details_save.Visible = true;

                //Create a new Label
                this.labelShows2_quality_multi.Text = "Quality:";
                this.labelShows2_quality_multi.AutoSize = true;
                this.labelShows2_quality_multi.Location = new Point(13, 50);
                this.labelShows2_quality_multi.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                //Create a new Combobox
                this.comboBoxShows2_quality_multi.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
                this.comboBoxShows2_quality_multi.SelectedIndex = -1;
                this.comboBoxShows2_quality_multi.Location = new Point(70, 45);
                this.comboBoxShows2_quality_multi.Size = new System.Drawing.Size(88, 21);
                this.comboBoxShows2_quality_multi.Visible = true;

                //Add the Controls to the Container
                this.groupBoxShows2_details.Controls.Add(labelShows2_quality_multi);
                this.groupBoxShows2_details.Controls.Add(comboBoxShows2_quality_multi);
            }

            else
            {
                //Display some default information
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Constructs the mod list suitable for display to the user.
        /// This manipulates <c>full_list_of_mod_rows</c> as it runs, and by default
        /// will only update entries which have changed or were previously missing.
        /// (Set <c>refreshAll</c> to force update everything.)
        /// </summary>
        /// <returns>The mod list.</returns>
        /// <param name="modules">A list of modules that may require updating</param>
        /// <param name="refreshAll">If set to <c>true</c> then always rebuild the list from scratch</param>
        /// <param name="hideEpochs">If true, remove epochs from the displayed versions</param>
        public IEnumerable <DataGridViewRow> ConstructModList(IEnumerable <GUIMod> modules, List <ModChange> mc = null, bool refreshAll = false, bool hideEpochs = false, bool hideV = false)
        {
            if (refreshAll || full_list_of_mod_rows == null)
            {
                full_list_of_mod_rows = new Dictionary <string, DataGridViewRow>();
            }

            // We're only going to update the status of rows that either don't already exist,
            // or which exist but have changed their latest version
            // or whose installation status has changed
            //
            // TODO: Will this catch a mod where the latest version number remains the same, but
            // another part of the metadata (eg: dependencies or description) has changed?
            IEnumerable <GUIMod> rowsToUpdate = modules.Where(
                mod => !full_list_of_mod_rows.ContainsKey(mod.Identifier) ||
                mod.LatestVersion != (full_list_of_mod_rows[mod.Identifier].Tag as GUIMod)?.LatestVersion ||
                mod.IsInstalled != (full_list_of_mod_rows[mod.Identifier].Tag as GUIMod)?.IsInstalled);

            // Let's update our list!
            foreach (var mod in rowsToUpdate)
            {
                full_list_of_mod_rows.Remove(mod.Identifier);
                var item = new DataGridViewRow {
                    Tag = mod
                };

                ModChange myChange = mc?.FindLast((ModChange ch) => ch.Mod.Identifier == mod.Identifier);

                var selecting = mod.IsInstallable()
                    ? (DataGridViewCell) new DataGridViewCheckBoxCell()
                {
                    Value = myChange == null ? mod.IsInstalled
                            : myChange.ChangeType == GUIModChangeType.Install ? true
                            : myChange.ChangeType == GUIModChangeType.Remove  ? false
                            : mod.IsInstalled
                } : new DataGridViewTextBoxCell()
                {
                    Value = mod.IsAutodetected ? "AD" : "-"
                };

                var updating = mod.IsInstallable() && mod.HasUpdate
                    ? (DataGridViewCell) new DataGridViewCheckBoxCell()
                {
                    Value = myChange == null ? false
                            : myChange.ChangeType == GUIModChangeType.Update ? true
                            : false
                } : new DataGridViewTextBoxCell()
                {
                    Value = "-"
                };

                var name = new DataGridViewTextBoxCell {
                    Value = mod.Name
                };
                var author = new DataGridViewTextBoxCell {
                    Value = mod.Authors
                };

                var installVersion = new DataGridViewTextBoxCell {
                    Value =
                        hideEpochs ?
                        (hideV ? ModuleInstaller.StripEpoch(ModuleInstaller.StripV(mod.InstalledVersion))
                            : ModuleInstaller.StripEpoch(mod.InstalledVersion))
                        :   (hideV ? ModuleInstaller.StripV(mod.InstalledVersion)
                            : mod.InstalledVersion)
                };

                var latestVersion = new DataGridViewTextBoxCell
                {
                    Value =
                        hideEpochs ?
                        (hideV ? ModuleInstaller.StripEpoch(ModuleInstaller.StripV(mod.LatestVersion))
                            : ModuleInstaller.StripEpoch(mod.LatestVersion))
                        : (hideV ? ModuleInstaller.StripV(mod.LatestVersion)
                            : mod.LatestVersion)
                };

                var desc = new DataGridViewTextBoxCell {
                    Value = mod.Abstract
                };
                var compat = new DataGridViewTextBoxCell {
                    Value = mod.KSPCompatibility
                };
                var size = new DataGridViewTextBoxCell {
                    Value = mod.DownloadSize
                };

                item.Cells.AddRange(selecting, updating, name, author, installVersion, latestVersion, compat, size, desc);

                selecting.ReadOnly = selecting is DataGridViewTextBoxCell;
                updating.ReadOnly  = updating is  DataGridViewTextBoxCell;

                full_list_of_mod_rows.Add(mod.Identifier, item);
            }
            return(full_list_of_mod_rows.Values);
        }
        /* Returns the highest card in the straight,
         * or an empty string if there is no straight */
        public static List<Card> HasStraight(List<Card> cards)
        {
            cards.Sort ();
            cards.Reverse ();
            var hand = new List<Card>();
            hand.Add(cards[0]);
            for (int i = 1; i < cards.Count; i++) {
                if (cards [i].value == hand[hand.Count-1].value-1) {
                    hand.Add(cards[i]);
                    if (hand.Count >= 5) {
                        return hand;
                    }
                    if (hand[0].value == Value.Five && hand[hand.Count-1].value == Value.Three) {
                        //Need to handle the ace playing low for straights
                        //the card suit here is unimportant, it just has to be something
                        if (cards.Contains (new Card (Suit.Clubs, Value.Ace)) &&
                            cards.Contains (new Card (Suit.Clubs, Value.Two))) {
                            hand.Add(cards.FindLast(x => x.value == Value.Two));
                            hand.Add(cards.FindLast(x => x.value == Value.Ace));
                            return hand;
                        }
                        return null;
                    }
                    continue;
                }
                if (i == 4) {
                    return null;
                }
                //there might still be a straight
                hand.Clear();
                hand.Add(cards[i]);
            }

            return null;
        }
Esempio n. 20
0
        /*
         * Functions in List.
         * 1. Contains() function: Checks if an item exists in the list.
         *      This method returns true if item exists, else false.
         *
         * 2. Exists() function: Checks if an item exists in the list based on a condition.
         *      This method returns true if item exists else false.
         *
         * 3. Find() function: Searches for an element that matches the conditions defined by the specified lambda expression
         *      and returns the first matching item from the list.
         *
         * 4. FindLast() function: Searches for an element that matches the conditions defined by the specified lambda expression
         *      and returns the Last matching item from the list.
         *
         * 5. FindAll() function: Returns all the items from the list matches the conditions specified by the lambda expression.
         *
         * 6. FindIndex() function: Returns the index of the item, that matches the condition specfied by the lambda expression.
         *      There are 2 other overloads of this method which allows us to specify the range of the elements to search, with in the list.
         *
         * 7. FindLastIndex() function: Returns the index of the items, that matches the condition specified by the lambda expression.
         *      There are 2 other overloads of this method which allows us to specify the range of the elements to search, with in the list.
         *
         * 8. ToList() function: Convert an array to a List.
         *
         * 9. ToArray function: Convert a List to an Array.
         *
         * 10. ToDictionary() function: Convert a List  to a Dictionary.
         */
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 101, Name = "Anand Dev", Salary = 4000 };
            Customer customer2 = new Customer() { ID = 102, Name = "Praveen", Salary = 5000 };
            Customer customer3 = new Customer() { ID = 103, Name = "Uttam", Salary = 8000 };

            List<Customer> listCustomers = new List<Customer>(2);
            listCustomers.Add(customer1);
            listCustomers.Add(customer2);
            listCustomers.Add(customer3);

            Console.WriteLine("Values in the list are:");
            foreach (Customer c in listCustomers)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            Console.WriteLine();

            #region 1. Contains() method.
            if (listCustomers.Contains(customer3))
            {
                Console.WriteLine("List Contains() Customer 3 object.\n");
            }
            else
            {
                Console.WriteLine("List does NOT Contains() Customer 3 object.\n");
            }
            #endregion

            #region 2. Exists() method.
            if (listCustomers.Exists(cust => cust.Name.StartsWith("A")))
            {
                Console.WriteLine("Item Exists(), having Name starting with \"A\".\n");
            }
            else
            {
                Console.WriteLine("Item NOT Exists(), having Name starting with \"A\".\n");
            }
            #endregion

            #region 3. Find() method.
            Customer findCustomer = listCustomers.Find(cust => cust.Salary > 4000);
            Console.WriteLine("Find() method give us first object matching condition from list:\nID = {0}, Name = {1}, Salry = {2}", findCustomer.ID, findCustomer.Name, findCustomer.Salary);

            #endregion

            #region 4. FindLast() method.
            Customer findLastCustomer = listCustomers.FindLast(cust => cust.Salary > 4000);
            Console.WriteLine("\nFindLast() method give us last object matching condition from list:\nID = {0}, Name = {1}, Salry = {2}", findLastCustomer.ID, findLastCustomer.Name, findLastCustomer.Salary);
            #endregion

            #region 5. FindAll() method.
            Console.WriteLine("\nFindAll() method returns all the items from the list matches the conditions specified by the lambda expression.");
            List<Customer> listFindAllCustomers = listCustomers.FindAll(cust => cust.Salary > 4000);
            foreach (Customer c in listFindAllCustomers)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            #region 6. FindIndex() method.
            int index = listCustomers.FindIndex(cust => cust.Salary > 4000);
            Console.WriteLine("\nFindIndex() method, Index = {0}", index);
            #endregion

            #region 7. FindLastIndex() method.
            int lastIndex = listCustomers.FindLastIndex(cust => cust.Salary > 4000);
            Console.WriteLine("\nFindLastIndex() method, Last Index = {0}",lastIndex);
            #endregion

            #region 8. Array to List conversion.
            Console.WriteLine("\nArray to List conversion:");
            Customer[] arrayCustomers = new Customer[3];
            arrayCustomers[0] = customer1;
            arrayCustomers[1] = customer2;
            arrayCustomers[2] = customer3;

            List<Customer> arrayToListCustomers = arrayCustomers.ToList();
            foreach (Customer c in arrayToListCustomers)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            #region 9. List to Array conversion
            Console.WriteLine("\nList to Array conversion:");
            Customer[] listToArray = listCustomers.ToArray();
            foreach (Customer c in listToArray)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            #region 10. List to Dictionary conversion.
            Console.WriteLine("\nList to Dictionary conversion:");
            Dictionary <int,Customer> listToDictonary = listCustomers.ToDictionary(cus => cus.ID);
            foreach (KeyValuePair<int, Customer> kvp in listToDictonary)
            {
                Customer c = kvp.Value;
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            Console.ReadKey();
        }
Esempio n. 21
0
 private int GetSwipeTrafficStatisticsTruck(AscmDoor ascmDoor, DateTime dt1, string direction)
 {
     try
     {
         string sql = "from AscmTruckSwipeLog where doorId=" + ascmDoor.id + " and direction like '" + direction + "%' and createTime>='" + dt1.ToString("yyyy-MM-dd 00:00:00") + "' and createTime<'" + dt1.AddDays(1).ToString("yyyy-MM-dd 00:00:00") + "'";
         List<AscmTruckSwipeLog> listAscmTruckSwipeLog = AscmTruckSwipeLogService.GetInstance().GetList(sql + " order by id");
         List<AscmTruckSwipeLog> listAscmTruckSwipeLog_tmp = new List<AscmTruckSwipeLog>();
         //for (int irow = listAscmEmpCarSwipeLog.Count - 1; irow >= 0; irow--)
         foreach (AscmTruckSwipeLog ascmTruckSwipeLog in listAscmTruckSwipeLog)
         {
             AscmTruckSwipeLog ascmTruckSwipeLog_tmp = listAscmTruckSwipeLog_tmp.FindLast(item => item.rfid == ascmTruckSwipeLog.rfid);
             int count = listAscmTruckSwipeLog_tmp.Count(item => item.rfid == ascmTruckSwipeLog.rfid);
             if (count > 5)
                 continue;
             if (ascmTruckSwipeLog_tmp == null)
             {
                 listAscmTruckSwipeLog_tmp.Add(ascmTruckSwipeLog);
             }
             else
             {
                 DateTime dtCreateTime = DateTime.Now;
                 DateTime dtCreateTime_tmp = DateTime.Now;
                 if (DateTime.TryParse(ascmTruckSwipeLog.createTime, out dtCreateTime) && DateTime.TryParse(ascmTruckSwipeLog_tmp.createTime, out dtCreateTime_tmp))
                 {
                     TimeSpan ts = dtCreateTime.Subtract(dtCreateTime_tmp);
                     if (ts.TotalMinutes > 5)
                     {
                         //10分钟内重复读过滤
                         listAscmTruckSwipeLog_tmp.Add(ascmTruckSwipeLog);
                     }
                     else
                     {
                         ascmTruckSwipeLog_tmp.createTime = ascmTruckSwipeLog.createTime;
                     }
                 }
             }
         }
         return listAscmTruckSwipeLog_tmp.Count;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 22
0
 // go thru setting the lastknowsystem
 public static VisitedSystemsClass FindByPos(List<VisitedSystemsClass> visitedSystems, Point3D p, double limit)
 {
     if (visitedSystems != null)
     {
         VisitedSystemsClass vs = visitedSystems.FindLast(x => x.curSystem.HasCoordinate &&
                                         Math.Abs(x.curSystem.x - p.X) < limit &&
                                         Math.Abs(x.curSystem.y - p.Y) < limit &&
                                         Math.Abs(x.curSystem.z - p.Z) < limit);
         return vs;
     }
     else
         return null;
 }
Esempio n. 23
0
 public T FindLast(Predicate <T> match)
 {
     lock (lockList) return(list.FindLast(match));
 }
        public virtual MyExecutionBlock CreateCustomExecutionPlan(MyExecutionBlock defaultPlan)
        {
            List<IMyExecutable> selected = new List<IMyExecutable>();
            List<IMyExecutable> newPlan = new List<IMyExecutable>();

            // copy default plan content to new plan content
            foreach (IMyExecutable groupTask in defaultPlan.Children)
                if (groupTask is MyExecutionBlock)
                    foreach (IMyExecutable nodeTask in (groupTask as MyExecutionBlock).Children)
                        newPlan.Add(nodeTask); // add individual node tasks
                else
                    newPlan.Add(groupTask); // add group tasks

            // remove group backprop tasks (they should be called from the individual layers)
            selected = newPlan.Where(task => task is MyAbstractBackpropTask).ToList();
            newPlan.RemoveAll(selected.Contains);

            // move MyCreateDropoutMaskTask(s) before the first MyForwardTask
            selected = newPlan.Where(task => task is MyCreateDropoutMaskTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.Find(task => task is IMyForwardTask)), selected);

            // move reversed MyOutputDeltaTask(s) after the last MyForwardTask (usually there is only one)
            selected = newPlan.Where(task => task is IMyOutputDeltaTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            selected.Reverse();
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyForwardTask)) + 1, selected);

            // move reversed MyDeltaTask(s) after the last MyOutputDeltaTask
            selected = newPlan.Where(task => task is IMyDeltaTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            selected.Reverse();
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyOutputDeltaTask)) + 1, selected);

            // move MyGradientCheckTask after the last MyDeltaTask
            selected = newPlan.Where(task => task is MyGradientCheckTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyDeltaTask)) + 1, selected);

            // move MyUpdateWeightsTask(s) after the last MyGradientCheckTask
            selected = newPlan.Where(task => task is IMyUpdateWeightsTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is MyGradientCheckTask)) + 1, selected);

            // move MyQLearningTask after the last MyForwardTask
            selected = newPlan.Where(task => task is MyQLearningTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyForwardTask)) + 1, selected);

            // move MyRestoreValuesTask after the last MyAbstractBackPropTask
            selected = newPlan.Where(task => task is MyRestoreValuesTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyUpdateWeightsTask)) + 1, selected);

            // move MySaveActionTask to the end of the task list
            selected = newPlan.Where(task => task is MySaveActionTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.AddRange(selected);

            // return new plan as MyExecutionBlock
            return new MyExecutionBlock(newPlan.ToArray());
        }
Esempio n. 25
0
        private DataGridViewRow MakeRow(GUIMod mod, List <ModChange> changes, string instanceName, bool hideEpochs = false, bool hideV = false)
        {
            DataGridViewRow item = new DataGridViewRow()
            {
                Tag = mod
            };

            Color?myColor = ModuleLabels.LabelsFor(instanceName)
                            .FirstOrDefault(l => l.ModuleIdentifiers.Contains(mod.Identifier))
                            ?.Color;

            if (myColor.HasValue)
            {
                item.DefaultCellStyle.BackColor = myColor.Value;
            }

            ModChange myChange = changes?.FindLast((ModChange ch) => ch.Mod.Equals(mod));

            var selecting = mod.IsAutodetected
                ? new DataGridViewTextBoxCell()
            {
                Value = Properties.Resources.MainModListAutoDetected
            }
                : mod.IsInstallable()
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = myChange == null ? mod.IsInstalled
                        : myChange.ChangeType == GUIModChangeType.Install ? true
                        : myChange.ChangeType == GUIModChangeType.Remove  ? false
                        : mod.IsInstalled
            }
                : new DataGridViewTextBoxCell()
            {
                Value = "-"
            };

            var autoInstalled = mod.IsInstalled && !mod.IsAutodetected
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = mod.IsAutoInstalled
            }
                : new DataGridViewTextBoxCell()
            {
                Value = "-"
            };

            var updating = mod.IsInstallable() && mod.HasUpdate
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = myChange == null ? false
                        : myChange.ChangeType == GUIModChangeType.Update ? true
                        : false
            }
                : new DataGridViewTextBoxCell()
            {
                Value = "-"
            };

            var replacing = IsModInFilter(GUIModFilter.Replaceable, null, null, mod)
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = myChange == null ? false
                        : myChange.ChangeType == GUIModChangeType.Replace ? true
                        : false
            }
                : new DataGridViewTextBoxCell()
            {
                Value = "-"
            };

            var name = new DataGridViewTextBoxCell {
                Value = mod.Name.Replace("&", "&&")
            };
            var author = new DataGridViewTextBoxCell {
                Value = mod.Authors.Replace("&", "&&")
            };

            var installVersion = new DataGridViewTextBoxCell()
            {
                Value = hideEpochs
                    ? (hideV
                        ? ModuleInstaller.StripEpoch(ModuleInstaller.StripV(mod.InstalledVersion ?? ""))
                        : ModuleInstaller.StripEpoch(mod.InstalledVersion ?? ""))
                    : (hideV
                        ? ModuleInstaller.StripV(mod.InstalledVersion ?? "")
                        : mod.InstalledVersion ?? "")
            };

            var latestVersion = new DataGridViewTextBoxCell()
            {
                Value =
                    hideEpochs ?
                    (hideV ? ModuleInstaller.StripEpoch(ModuleInstaller.StripV(mod.LatestVersion))
                        : ModuleInstaller.StripEpoch(mod.LatestVersion))
                    : (hideV ? ModuleInstaller.StripV(mod.LatestVersion)
                        : mod.LatestVersion)
            };

            var downloadCount = new DataGridViewTextBoxCell {
                Value = $"{mod.DownloadCount:N0}"
            };
            var compat = new DataGridViewTextBoxCell {
                Value = mod.GameCompatibility
            };
            var size = new DataGridViewTextBoxCell {
                Value = mod.DownloadSize
            };
            var releaseDate = new DataGridViewTextBoxCell {
                Value = mod.ToModule().release_date
            };
            var installDate = new DataGridViewTextBoxCell {
                Value = mod.InstallDate
            };
            var desc = new DataGridViewTextBoxCell {
                Value = mod.Abstract.Replace("&", "&&")
            };

            item.Cells.AddRange(selecting, autoInstalled, updating, replacing, name, author, installVersion, latestVersion, compat, size, releaseDate, installDate, downloadCount, desc);

            selecting.ReadOnly     = selecting     is DataGridViewTextBoxCell;
            autoInstalled.ReadOnly = autoInstalled is DataGridViewTextBoxCell;
            updating.ReadOnly      = updating      is DataGridViewTextBoxCell;

            return(item);
        }
        public virtual MyExecutionBlock CreateCustomExecutionPlan(MyExecutionBlock defaultPlan)
        {
            List<IMyExecutable> selected = new List<IMyExecutable>();
            List<IMyExecutable> newPlan = new List<IMyExecutable>();

            // copy default plan content to new plan content
            foreach (IMyExecutable groupTask in defaultPlan.Children)
                if (groupTask is MyExecutionBlock)
                    foreach (IMyExecutable nodeTask in (groupTask as MyExecutionBlock).Children)
                        newPlan.Add(nodeTask); // add individual node tasks
                else
                    newPlan.Add(groupTask); // add group tasks

            // remove group backprop tasks (they should be called from the individual layers)
            // DO NOT remove RBM tasks
            // DO NOT remove the currently selected backprop task (it handles batch learning)
            selected = newPlan.Where(task => task is MyAbstractBackpropTask &&  !(task.Enabled) && !(task is MyRBMLearningTask || task is MyRBMReconstructionTask)).ToList();
            newPlan.RemoveAll(selected.Contains);

            // move MyCreateDropoutMaskTask(s) before the first MyForwardTask
            selected = newPlan.Where(task => task is MyCreateDropoutMaskTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.Find(task => task is IMyForwardTask)), selected);

            // move reversed MyOutputDeltaTask(s) after the last MyForwardTask (usually there is only one)
            selected = newPlan.Where(task => task is IMyOutputDeltaTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            if ((selected.Where(task => task.Enabled)).Count() > 1)
                MyLog.WARNING.WriteLine("More than one output tasks are active!");
            if (selected.Count <= 0)
                MyLog.WARNING.WriteLine("No output tasks are active! Planning (of SGD, RMS, Adadelta etc.) might not work properly. Possible cause: no output layer is present.\nIgnore this if RBM task is currently selected.");
            selected.Reverse();
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyForwardTask)) + 1, selected);

            // move reversed MyDeltaTask(s) after the last MyOutputDeltaTask
            selected = newPlan.Where(task => task is IMyDeltaTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            selected.Reverse();
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyOutputDeltaTask)) + 1, selected);

            // move MyGradientCheckTask after the last MyDeltaTask
            selected = newPlan.Where(task => task is MyGradientCheckTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyDeltaTask)) + 1, selected);

            // move currently selected backprop task between Delta tasks and UpdateWeights task
            selected = newPlan.Where(task => task is MyAbstractBackpropTask && (task.Enabled)).ToList();
            if (selected.Count > 1)
                MyLog.WARNING.WriteLine("Two or more backprop tasks selected.");
            if (selected.Count <= 0)
                MyLog.WARNING.WriteLine("No backprop task selected.");
            newPlan.RemoveAll(selected.Contains);
            selected.Reverse();
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyDeltaTask)) + 1, selected);

            // move MyUpdateWeightsTask(s) after the last MyGradientCheckTask
            selected = newPlan.Where(task => task is IMyUpdateWeightsTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is MyGradientCheckTask)) + 1, selected);

            // move MyQLearningTask after the last MyForwardTask
            selected = newPlan.Where(task => task is MyQLearningTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyForwardTask)) + 1, selected);

            // move MyRestoreValuesTask after the last MyAbstractBackPropTask
            selected = newPlan.Where(task => task is MyRestoreValuesTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyUpdateWeightsTask)) + 1, selected);

            // move MyLSTMPartialDerivativesTask after the last MyForwardTask
            selected = newPlan.Where(task => task is MyLSTMPartialDerivativesTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyForwardTask)) + 1, selected);

            // move MySaveActionTask to the end of the task list
            selected = newPlan.Where(task => task is MySaveActionTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.AddRange(selected);

            // return new plan as MyExecutionBlock
            return new MyExecutionBlock(newPlan.ToArray());
        }
Esempio n. 27
0
 private static Pair pump(Table table, List<Pair> path)
 {
     double min = path.Where((x, ind) => ind % 2 == 1).Min(x => x.value);
     foreach (Pair p in path)
     {
         table.matrix[p.i, p.j].value += min;
         min *= -1;
     }
     Pair pair = path.FindLast(x => x.value == min);
     table.matrix[pair.i, pair.j].bas = false;
     return pair;
 }
    private IMarker GetTargetMarker(NavDestination destination)
    {
      if ( destination == NavDestination.None || CodeRush.Documents.ActiveTextDocument == null )
        return null;

      TextView activeView = CodeRush.Documents.ActiveTextDocument.ActiveView;
      if ( activeView == null )
        return null;

      var markers = new List<IMarker>();
      LoadMarkerList(markers, _settings.SkipSelectionMarkers);
      if ( markers.Count == 0 )
        return null;

      // all non-stack operations require the marker list to be in document order
      if ( destination != NavDestination.StackTop && destination != NavDestination.StackBottom )
        SortMarkerListInDocumentOrder(markers);

      IMarker closestMarker = null;
      IMarker firstMarker = markers[0];
      IMarker lastMarker = markers[markers.Count - 1];
      int caretLine = activeView.Caret.Line;
      int caretColumn = activeView.Caret.ViewColumn;
      switch ( destination )
      {
        case NavDestination.First:
        case NavDestination.StackBottom:
          closestMarker = firstMarker;
          break;
        case NavDestination.Prev:
        case NavDestination.Next:
          if ( destination == NavDestination.Prev )
            closestMarker = markers.FindLast(marker =>
              marker.Line < caretLine || (marker.Line == caretLine && marker.Column < caretColumn));
          else
            closestMarker = markers.Find(marker =>
              marker.Line > caretLine || (marker.Line == caretLine && marker.Column > caretColumn));

          // if no target found and we have only a single marker, that's the new target
          if ( closestMarker == null && markers.Count == 1 )
          {
            IMarker marker = firstMarker;
            if ( marker.Line == caretLine && marker.Column == caretColumn )
              closestMarker = marker;
          }
          // if we allow "rolling over" on prev/next, do so
          if ( _settings.RollOverOnPrevNext && closestMarker == null )
          {
            if ( destination == NavDestination.Prev )
              closestMarker = lastMarker;
            else if ( destination == NavDestination.Next )
              closestMarker = firstMarker;
          }
          break;
        case NavDestination.Last:
        case NavDestination.StackTop:
          closestMarker = lastMarker;
          break;
        case NavDestination.AtCaret:
          closestMarker = markers.FindLast(marker => marker.Line == caretLine && marker.Column == caretColumn);
          break;
      }
      return closestMarker;
    }
Esempio n. 29
0
        protected HostPlan GetUpdatePlanActionsForHost(Host host, List <Host> hosts, List <XenServerPatch> minimalPatches,
                                                       List <XenServerPatch> uploadedPatches, KeyValuePair <XenServerPatch, string> patchFromDisk, bool repatriateVms = true)
        {
            var patchSequence = Updates.GetPatchSequenceForHost(host, minimalPatches);

            if (patchSequence == null)
            {
                return(new HostPlan(host, null, null, null));
            }

            var planActionsPerHost    = new List <PlanAction>();
            var delayedActionsPerHost = new List <PlanAction>();

            foreach (var patch in patchSequence)
            {
                // if the patchSequence contains a patch that requires a host reboot (excluding livepatches), then add the Evacuate action as the first action in the sequence
                if (patch.after_apply_guidance == after_apply_guidance.restartHost &&
                    !patch.ContainsLivepatch &&
                    (planActionsPerHost.Count == 0 || !(planActionsPerHost[0] is EvacuateHostPlanAction)))
                {
                    planActionsPerHost.Insert(0, new EvacuateHostPlanAction(host));
                }

                if (!uploadedPatches.Contains(patch))
                {
                    planActionsPerHost.Add(new DownloadPatchPlanAction(host.Connection, patch, AllDownloadedPatches, patchFromDisk));
                    planActionsPerHost.Add(new UploadPatchToMasterPlanAction(this, host.Connection, patch, patchMappings, AllDownloadedPatches, patchFromDisk, true));
                    uploadedPatches.Add(patch);
                }

                planActionsPerHost.Add(new PatchPrecheckOnHostPlanAction(host.Connection, patch, host, patchMappings, hostsThatWillRequireReboot, livePatchAttempts));
                planActionsPerHost.Add(new ApplyXenServerPatchPlanAction(host, patch, patchMappings));

                var action = GetAfterApplyGuidanceAction(host, patch.after_apply_guidance);
                if (action != null)
                {
                    if (patch.GuidanceMandatory)
                    {
                        // if this update requires a mandatory toolstack restart and there is a pending host reboot in the delayed actions,
                        // then the pending reboot should be carried out instead
                        if (patch.after_apply_guidance == after_apply_guidance.restartXAPI && delayedActionsPerHost.Any(a => a is RestartHostPlanAction))
                        {
                            // replace the action with a host reboot action which will fall back to a toolstack restart if the reboot is not needed because the live patching succedeed
                            action = new RestartHostPlanAction(host, host.GetRunningVMs(), true, true, hostsThatWillRequireReboot);
                        }

                        planActionsPerHost.Add(action);
                        // remove all delayed actions of the same kind that has already been added
                        // (because this action is guidance-mandatory=true, therefore
                        // it will run immediately, making delayed ones obsolete)
                        delayedActionsPerHost.RemoveAll(a => action.GetType() == a.GetType());
                    }
                    else
                    {
                        // add the action if it's not already in the list
                        if (delayedActionsPerHost.All(a => a.GetType() != action.GetType()))
                        {
                            delayedActionsPerHost.Add(action);
                        }
                    }
                }

                var isLastHostInPool = hosts.IndexOf(host) == hosts.Count - 1;
                if (isLastHostInPool)
                {
                    // add cleanup action for current patch at the end of the update seuence for the last host in the pool
                    var master = Helpers.GetMaster(host.Connection);
                    planActionsPerHost.Add(new RemoveUpdateFileFromMasterPlanAction(master, patchMappings, patch));
                }
            }

            if (repatriateVms)
            {
                var lastRestart = delayedActionsPerHost.FindLast(a => a is RestartHostPlanAction)
                                  ?? planActionsPerHost.FindLast(a => a is RestartHostPlanAction);

                if (lastRestart != null)
                {
                    ((RestartHostPlanAction)lastRestart).EnableOnly = false;
                }
            }

            return(new HostPlan(host, null, planActionsPerHost, delayedActionsPerHost));
        }
        public virtual MyExecutionBlock CreateCustomExecutionPlan(MyExecutionBlock defaultPlan)
        {
            List<IMyExecutable> selected = new List<IMyExecutable>();
            List<IMyExecutable> newPlan = new List<IMyExecutable>();

            List<IMyExecutable> BPTTSingleStep = new List<IMyExecutable>();
            List<IMyExecutable> BPTTAllSteps = new List<IMyExecutable>();

            // copy default plan content to new plan content
            foreach (IMyExecutable groupTask in defaultPlan.Children)
                if (groupTask.GetType() == typeof(MyExecutionBlock))
                    foreach (IMyExecutable nodeTask in (groupTask as MyExecutionBlock).Children)
                        newPlan.Add(nodeTask); // add individual node tasks
                else
                    newPlan.Add(groupTask); // add group tasks

            // remove group backprop tasks (they should be called from the individual layers)
            // DO NOT remove RBM tasks
            // DO NOT remove the currently selected backprop task (it handles batch learning)
            selected = newPlan.Where(task => task is MyAbstractBackpropTask &&  !(task.Enabled) && !(task is MyRBMLearningTask || task is MyRBMReconstructionTask)).ToList();
            newPlan.RemoveAll(selected.Contains);
            // bbpt single step
            BPTTSingleStep.AddRange(newPlan.Where(task => task is IMyDeltaTask).ToList().Reverse<IMyExecutable>());
            BPTTSingleStep.AddRange(newPlan.Where(task => task is MyLSTMPartialDerivativesTask).ToList());
            BPTTSingleStep.AddRange(newPlan.Where(task => task is MyGradientCheckTask).ToList());
            BPTTSingleStep.Add(DecrementTimeStep);

            // backprop until unfolded (timestep=0)
            MyExecutionBlock BPTTLoop = new MyLoopBlock(i => TimeStep != -1,
                BPTTSingleStep.ToArray()
            );

            // if learning is globally disabled, removed update weights tasks
            MyExecutionBlock UpdateWeightsIfNotDisabled = new MyIfBlock(() => GetActiveBackpropTask() != null && GetActiveBackpropTask().DisableLearning == false,
                newPlan.Where(task => task is IMyUpdateWeightsTask).ToArray()
            );
            if (GetActiveBackpropTask() != null && GetActiveBackpropTask().DisableLearning)
            {
                MyLog.WARNING.WriteLine("Learning is globally disabled for the network " + this.Name + " in the " + GetActiveBackpropTask().Name + " backprop task.");
            }

            // bptt architecture
            BPTTAllSteps.Add(BPTTLoop);
            BPTTAllSteps.Add(IncrementTimeStep);
            BPTTAllSteps.Add(RunTemporalBlocksMode);
            BPTTAllSteps.Add(UpdateWeightsIfNotDisabled);
            BPTTAllSteps.Add(DecrementTimeStep);

            // if current time is time for bbp, do it
            MyExecutionBlock BPTTExecuteBPTTIfTimeCountReachedSequenceLength = new MyIfBlock(() => TimeStep == SequenceLength-1,
                BPTTAllSteps.ToArray()
            );

            // remove group backprop tasks (they should be called from the individual layers)
            newPlan.RemoveAll(newPlan.Where(task => task is MyAbstractBackpropTask && !(task is MyRBMLearningTask || task is MyRBMReconstructionTask)).ToList().Contains);
            //TODO - include dropout in the new version of planner
            newPlan.RemoveAll(newPlan.Where(task => task is MyCreateDropoutMaskTask).ToList().Contains);
            //newPlan.RemoveAll(newPlan.Where(task => task is IMyOutputDeltaTask).ToList().Contains);
            newPlan.RemoveAll(newPlan.Where(task => task is IMyDeltaTask).ToList().Contains);
            newPlan.RemoveAll(newPlan.Where(task => task is MyGradientCheckTask).ToList().Contains);
            newPlan.RemoveAll(newPlan.Where(task => task is IMyUpdateWeightsTask).ToList().Contains);
            newPlan.RemoveAll(newPlan.Where(task => task is MyLSTMPartialDerivativesTask).ToList().Contains);
            newPlan.RemoveAll(newPlan.Where(task => task is MyIncrementTimeStepTask).ToList().Contains);
            newPlan.RemoveAll(newPlan.Where(task => task is MyDecrementTimeStepTask).ToList().Contains);
            newPlan.RemoveAll(newPlan.Where(task => task is MyRunTemporalBlocksModeTask).ToList().Contains);

            //selected = newPlan.Where(task => task is IMyOutputDeltaTask).ToList();
            //newPlan.RemoveAll(selected.Contains);

            // after FF add deltaoutput and bptt if needed, then increment one step :)
            newPlan.Insert(0, IncrementTimeStep);

            // Move output delta tasks after all forward tasks.
            selected = newPlan.Where(task => task is IMyOutputDeltaTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyForwardTask)) + 1, selected.Reverse<IMyExecutable>());

            // Move Q-learning tasks between forward tasks and output delta tasks.
            selected = newPlan.Where(task => task is MyQLearningTask || task is MyQLearningBatchTask).ToList();
            newPlan.RemoveAll(selected.Contains);
            newPlan.InsertRange(newPlan.IndexOf(newPlan.FindLast(task => task is IMyForwardTask)) + 1, selected.Reverse<IMyExecutable>());

            newPlan.Add(BPTTExecuteBPTTIfTimeCountReachedSequenceLength);

            // return new plan as MyExecutionBlock
            return new MyExecutionBlock(newPlan.ToArray());
        }
Esempio n. 31
0
        protected HostPlan GetUpdatePlanActionsForHost(Host host, List <Host> hosts, List <XenServerPatch> minimalPatches,
                                                       List <XenServerPatch> uploadedPatches, KeyValuePair <XenServerPatch, string> patchFromDisk, bool repatriateVms = true)
        {
            var patchSequence = Updates.GetPatchSequenceForHost(host, minimalPatches);

            if (patchSequence == null)
            {
                return(new HostPlan(host, null, null, null));
            }

            var planActionsPerHost    = new List <PlanAction>();
            var delayedActionsPerHost = new List <PlanAction>();

            foreach (var patch in patchSequence)
            {
                if (!uploadedPatches.Contains(patch))
                {
                    planActionsPerHost.Add(new DownloadPatchPlanAction(host.Connection, patch, AllDownloadedPatches, patchFromDisk));
                    planActionsPerHost.Add(new UploadPatchToMasterPlanAction(host.Connection, patch, patchMappings, AllDownloadedPatches, patchFromDisk));
                    uploadedPatches.Add(patch);
                }

                planActionsPerHost.Add(new PatchPrecheckOnHostPlanAction(host.Connection, patch, host, patchMappings, hostsThatWillRequireReboot));
                planActionsPerHost.Add(new ApplyXenServerPatchPlanAction(host, patch, patchMappings));

                var action = GetAfterApplyGuidanceAction(host, patch.after_apply_guidance);
                if (action != null)
                {
                    if (patch.GuidanceMandatory)
                    {
                        planActionsPerHost.Add(action);
                        // remove all delayed actions of the same kind that has already been added
                        // (because this action is guidance-mandatory=true, therefore
                        // it will run immediately, making delayed ones obsolete)
                        delayedActionsPerHost.RemoveAll(a => action.GetType() == a.GetType());
                    }
                    else
                    {
                        // add the action if it's not already in the list
                        if (delayedActionsPerHost.All(a => a.GetType() != action.GetType()))
                        {
                            delayedActionsPerHost.Add(action);
                        }
                    }
                }

                var isLastHostInPool = hosts.IndexOf(host) == hosts.Count - 1;
                if (isLastHostInPool)
                {
                    // add cleanup action for current patch at the end of the update seuence for the last host in the pool
                    var master = Helpers.GetMaster(host.Connection);
                    planActionsPerHost.Add(new RemoveUpdateFileFromMasterPlanAction(master, patchMappings, patch));
                }
            }

            if (repatriateVms)
            {
                var lastRestart = delayedActionsPerHost.FindLast(a => a is RestartHostPlanAction)
                                  ?? planActionsPerHost.FindLast(a => a is RestartHostPlanAction);

                if (lastRestart != null)
                {
                    ((RestartHostPlanAction)lastRestart).EnableOnly = false;
                }
            }

            return(new HostPlan(host, null, planActionsPerHost, delayedActionsPerHost));
        }
Esempio n. 32
0
        static void Main(string[] args)
        {
            // inicalizando uma lista (tipo string) passando os valores a serem alucados
            List <string> nomes;

            nomes = new List <string> {
                "ana", "maria", "alex", "bia", "joao", "paulo", "lucas", "leo", "pedro", "paty"
            };

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

            // inicializando uma lista "tipo string" vazia, e adicionando valores uma a um

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

            // adicinando valores com Add() que por padrao insere ao final da lista
            listaNomes.Add("mario");
            listaNomes.Add("laura");
            listaNomes.Add("leandro");
            listaNomes.Add("sara");
            listaNomes.Add("victor");
            listaNomes.Add("henrique");
            listaNomes.Add("bernardo");
            listaNomes.Add("denis");
            listaNomes.Add("lucio");
            listaNomes.Add("mateus");
            listaNomes.Add("lia");
            listaNomes.Add("beca");
            listaNomes.Add("dora");

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

            // adicinando valores com Insert() que permite escolher o indice para alocar o elemento na lista

            listaNomes.Insert(3, "MARCELA");

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

            // contar o numero de elementos da lista
            Console.WriteLine(listaNomes.Count());

            Console.ReadKey();
            Console.WriteLine();

            // encontar a primeira ocorrencia que satisfaça um predicado  + "expressao lambda: (x => x[0] == 'm')"
            var encontrarPrimeiraOcorrencia = listaNomes.Find(x => x[0] == 'm');

            Console.WriteLine(encontrarPrimeiraOcorrencia);

            Console.ReadKey();
            Console.WriteLine();

            // encontar a ultima ocorrencia que satisfaça um predicado  + "expressao lambda: (x => x[0] == 'm')"
            var encontrarUltimaOcorrencia = listaNomes.FindLast(x => x[0] == 'm');

            Console.WriteLine(encontrarUltimaOcorrencia);

            Console.ReadKey();
            Console.WriteLine();

            // encontar a primeira posicao que satisfaça um predicado  + "expressao lambda: (x => x[0] == 'm')"
            var encontrarPrimeiraPosicao = listaNomes.FindIndex(x => x[0] == 'm');

            Console.WriteLine(encontrarPrimeiraPosicao);

            Console.ReadKey();
            Console.WriteLine();

            // encontar a ultima posicao que satisfaça um predicado  + "expressao lambda: (x => x[0] == 'm')"
            var encontrarultimaPosicao = listaNomes.FindLastIndex(x => x[0] == 'm');

            Console.WriteLine(encontrarultimaPosicao);

            Console.ReadKey();
            Console.WriteLine();

            // criar umanova lista apenas contendo os elementos que satisfacao um predicado  + "expressao lambda: (x => x[0] == 'm')"
            List <string> listaFiltro = listaNomes.FindAll(x => x.Length <= 4);

            foreach (var obj in listaFiltro)
            {
                Console.WriteLine(obj);
            }

            Console.ReadKey();
            Console.WriteLine();

            // removendo elementos especifico da lista
            listaNomes.Remove("mateus");

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

            // removendo todos os elementos da lista que atendem a uma satisfacao  + "expressao lambda: (x => x[0] == 'm')"
            listaNomes.RemoveAll(x => x[0] == 'l');

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

            // removendo elementos especifico da lista pela posicao que ele ocupa RemoveAt()
            listaNomes.RemoveAt(3);

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

            // removendo elementos DE UMA DETERMINADA FAIXA "RemoveRange(1,5)" => apartir da posicar "x", retirar "y" elementos
            listaNomes.RemoveRange(1, 5);

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

            //var removerPrimeiroElemento = listaNomes.Remove(x => x[0] == 'M');
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            List <string> lista = new List <string> {
                "Valor 1", "Valor 2"
            };
            List <string> list = new List <string>();

            list.Add("Gabriel"); //insere ao final da lista
            list.Add("Rafael");
            list.Add("Lucas");
            list.Add("Ana");
            list.Insert(1, "Alex"); //adciona elemento passando posiçao

            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("Tamanho da lista: " + list.Count); //mostra o tamanho da lista

            //pode ser passado uma funçao booleana ou uma expressao lambda(funçao anonima)
            Console.WriteLine(list.Find(Test));

            //retorne o obj x tal que x na posiçao 0 (primeira posiçao) seja igual a A
            Console.WriteLine(list.Find(x => x[0] == 'A'));    //retorna a primeira ocorrencia de um valor que comece com A

            string elemento = list.FindLast(x => x[0] == 'A'); //retorna a ultima ocorrencia de um elemnto que comece com A

            Console.WriteLine(elemento);

            Console.WriteLine(list.FindIndex(x => x[0] == 'A')); //retorna a posiçao da primeira ocorrencia de um elemento que comece com A

            int posiçao = list.FindLastIndex(x => x[0] == 'A');  //retorna a posiçao da ultima ocorrencia de um elemento que comece com A

            Console.WriteLine(posiçao);

            Console.WriteLine("-----------------------------------------------------");

            //findAll criar uma nova lista com elementos que satisfaça a exressao
            List <string> list2 = list.FindAll(x => x.Length == 5); //retorna um filtro com todos os elementos que possuem 5 caracteres

            foreach (string obj in list2)
            {
                Console.WriteLine(obj);
            }

            list.Remove("Gabriel"); //remove o elmento passado
            Console.WriteLine("-----------------------------------------------------");
            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }

            list.RemoveAll(x => x[0] == 'A'); //remove os elmentos que satisfaçam a expressao
            Console.WriteLine("-----------------------------------------------------");
            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }

            list.RemoveAt(2); //remove o elemento que foi passada a posiçao
            Console.WriteLine("-----------------------------------------------------");
            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }

            list.RemoveRange(1, 2); //remove uma quantidade de elementos passados a partir de uma posiçao passada
            Console.WriteLine("-----------------------------------------------------");
            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }
        }
Esempio n. 34
0
 /// <summary>
 /// Returns the last item matching the predicate.
 /// </summary>
 public T FindLast(Predicate <T> predicate)
 {
     return(_list.FindLast(predicate));
 }
Esempio n. 35
0
 /// <inheritdoc cref="List{T}.FindLast" />
 public T FindLast(Predicate <T> match)
 {
     using (EnterReadLock.Enter(LockObject))
         return(_lstData.FindLast(match));
 }
Esempio n. 36
0
 /// <summary>
 /// 获取最后一条个人消息记录
 /// </summary>
 /// <param name="id">个人IP</param>
 /// <returns></returns>
 public static Chat GetLastChat(IPAddress id)
 {
     return(chatList.FindLast(e => e.ReceiverIP.ToString() == id.ToString()));
 }
Esempio n. 37
0
        public static AccountPO SaveAccount(
            ChannelPO channel,
            AccountPO account,
            AccountAvatarsPO avatar,
            List <AccountContactsPO> contacts,
            List <AccountMessagesPO> messages,
            List <SchedulePO> schedules
            )
        {
            var now = DateTime.Now;

            var trans = new Transaction();

            try
            {
                trans.Begin();

                #region DBOP

                var bllAccount         = new DB.Agent.MssqlHelper <AccountPO>();
                var bllAccountAvatars  = new DB.Agent.MssqlHelper <AccountAvatarsPO>();
                var bllAccountContacts = new DB.Agent.MssqlHelper <AccountContactsPO>();
                var bllAccountMessages = new DB.Agent.MssqlHelper <AccountMessagesPO>();
                var bllProject         = new DB.Agent.MssqlHelper <ProjectPO>();
                var bllSchedule        = new DB.Agent.MssqlHelper <SchedulePO>();

                #region avatar and account

                var condition =
                    account == null
                        ? string.Format("ChannelId={0} AND ChannelIdentity='{1}'", avatar.ChannelId,
                                        avatar.ChannelIdentity)
                        : string.Format("ChannelId={0} AND ChannelIdentity='{1}' AND AccountId={2}", avatar.ChannelId,
                                        avatar.ChannelIdentity, account.Id);

                var avatarExists = bllAccountAvatars.FindSingle(condition, trans.DbConnection, trans.DbTrans);
                if (avatarExists == null)
                {
                    if (account == null)
                    {
                        account = new DB.Entity.Base.AccountPO
                        {
                            NickName         = avatar.DisplayName,
                            Valid            = true,
                            UpdateTime       = now,
                            CreateTime       = now,
                            LastSignin       = now,
                            MobileVerifyTime = now,
                            EmailVerifyTime  = now
                        };
                        Logger.Debug(account.SerializeXml());
                        account = bllAccount.Insert(account, trans.DbConnection, trans.DbTrans);
                    }

                    avatarExists = new AccountAvatarsPO
                    {
                        ChannelId       = avatar.ChannelId,
                        ChannelIdentity = avatar.ChannelIdentity,
                        DisplayName     = avatar.DisplayName,
                        Code            = avatar.Code,
                        Token           = avatar.Token,
                        TokenGenerated  = avatar.TokenGenerated,
                        TokenExpires    = avatar.TokenExpires,
                        UpdateTime      = avatar.UpdateTime,
                        RefreshToken    = avatar.RefreshToken,
                        AccountId       = account.Id,
                        Valid           = true,
                        CreateTime      = now,
                        SynchroTime     = now,
                        SynchroDuration = 600
                    };

                    avatarExists.UpdateTime = now;
                    Logger.Debug(avatarExists.SerializeXml());

                    avatar = bllAccountAvatars.Insert(avatarExists, trans.DbConnection, trans.DbTrans);
                }
                else
                {
                    avatar.Id          = avatarExists.Id;
                    avatar.AccountId   = avatarExists.AccountId;
                    avatar.Valid       = avatarExists.Valid;
                    avatar.CreateTime  = avatarExists.CreateTime;
                    avatar.UpdateTime  = now;
                    avatar.SynchroTime = now;
                    if (avatar.SynchroDuration == 0)
                    {
                        avatar.SynchroDuration = 600;
                    }

                    Logger.Info(avatar.SerializeXml());
                    bllAccountAvatars.Update(avatarExists, avatar, trans.DbConnection, trans.DbTrans);

                    account = bllAccount.FindById(avatar.AccountId, trans.DbConnection, trans.DbTrans);
                }

                Utility.DataCache.AccountAvatars.InitCache(account.Id);

                #endregion

                Logger.Debug("REFRESH ACCOUNT CACHE");
                var all = Refresh(account);

                #region contacts

                if (contacts != null && contacts.Any())
                {
                    Logger.Debug("SAVE CONTACTS");
                    foreach (var a in contacts)
                    {
                        var a0 =
                            all.Contacts.FindLast(
                                o =>
                                o.ChannelId == a.ChannelId && o.ChannelIdentity == a.ChannelIdentity &&
                                o.AccountId == account.Id);
                        if (a0 == null)
                        {
                            a0 = new AccountContactsPO
                            {
                                AccountId       = account.Id,
                                ChannelId       = a.ChannelId,
                                ChannelIdentity = a.ChannelIdentity,
                                DisplayName     = a.DisplayName,
                                Detail          = a.Detail,
                                CreateTime      = now,
                                Valid           = true,
                                UpdateTime      = now
                            };
                            a0 = bllAccountContacts.Insert(a0, trans.DbConnection, trans.DbTrans);
                        }
                        else
                        {
                            a0.DisplayName = a.DisplayName;
                            a0.Detail      = a.Detail;
                            a0.UpdateTime  = now;

                            bllAccountContacts.Update(a, a0, trans.DbConnection, trans.DbTrans);
                        }
                    }
                    Utility.DataCache.AccountContacts.InitCache(account.Id);
                }

                #endregion

                #region messages

                if (messages != null && messages.Any())
                {
                    Logger.Debug("SAVE MESSAGES");

                    foreach (var b in messages)
                    {
                        var b0 =
                            all.Messages.FindLast(
                                o =>
                                o.ChannelId == b.ChannelId &&
                                o.ChannelIdentity == b.ChannelIdentity &&
                                o.ToAccountId == account.Id);
                        if (b0 == null)
                        {
                            b0 = new AccountMessagesPO
                            {
                                ToAccountId     = account.Id,
                                ChannelId       = b.ChannelId,
                                ChannelIdentity = b.ChannelIdentity,
                                MessageType     = b.MessageType,
                                MessageSubject  = b.MessageSubject,
                                MessageContent  = b.MessageContent,
                                CreateTime      = b.CreateTime,
                                Valid           = true,
                                Weblink         = b.Weblink,
                                UpdateTime      = now
                            };
                            b0 = bllAccountMessages.Insert(b0, trans.DbConnection, trans.DbTrans);
                        }
                        else
                        {
                            b0.MessageType    = b.MessageType;
                            b0.MessageSubject = b.MessageSubject;
                            b0.MessageContent = b.MessageContent;
                            b0.Weblink        = b.Weblink;
                            b0.UpdateTime     = now;
                            b0.CreateTime     = b.CreateTime;

                            bllAccountMessages.Update(b, b0, trans.DbConnection, trans.DbTrans);
                        }
                    }
                    Utility.DataCache.AccountMessages.InitCache(account.Id);
                }

                #endregion

                #region p&s

                if (schedules != null && schedules.Any())
                {
                    Logger.Debug("SAVE SCHEDULES");

                    var projectCode   = avatar.Code + "." + account.Id + "." + channel.Id;
                    var projectExists = Utility.DataCache.Project.CacheList().FindLast(o =>
                                                                                       o.ChannelId == channel.Id &&
                                                                                       o.CreatorAccountId == account.Id &&
                                                                                       o.ProjectCode == projectCode);

                    var projectSchedules = new List <SchedulePO>();

                    if (projectExists == null)
                    {
                        projectExists = new ProjectPO
                        {
                            ProjectCode      = projectCode,
                            Valid            = true,
                            CreateTime       = now,
                            UpdateTime       = now,
                            ProjectName      = avatar.DisplayName + "@" + channel.ChannelName,
                            ChannelId        = channel.Id,
                            CreatorAccountId = account.Id,
                            EnterDeadline    = now
                        };
                        Logger.Debug(projectExists.SerializeXml());
                        projectExists = bllProject.Insert(projectExists, trans.DbConnection, trans.DbTrans);
                    }
                    else
                    {
                        projectSchedules = Utility.DataCache.Schedule.CacheList(projectExists.Id);
                    }

                    Utility.DataCache.Project.InitCache();

                    foreach (var c in schedules)
                    {
                        var c0 =
                            projectSchedules.FindLast(
                                o =>
                                o.ProjectId == projectExists.Id &&
                                o.ScheduleIdentity == c.ScheduleIdentity);
                        if (c0 == null)
                        {
                            c0 = new SchedulePO
                            {
                                ProjectId        = projectExists.Id,
                                ScheduleIdentity = c.ScheduleIdentity,
                                Cycle            = c.Cycle,
                                ScheduleTitle    = c.ScheduleTitle,
                                ScheduleLead     = c.ScheduleLead,
                                BeginDate        = c.BeginDate,
                                BeginTime        = c.BeginTime,
                                EndDate          = c.EndDate,
                                EndTime          = c.EndTime,
                                Weblink          = c.Weblink,
                                CreateTime       = now,
                                Valid            = true,
                                UpdateTime       = now
                            };
                            c0 = bllSchedule.Insert(c0, trans.DbConnection, trans.DbTrans);
                        }
                        else
                        {
                            c0.Cycle         = c.Cycle;
                            c0.ScheduleTitle = c.ScheduleTitle;
                            c0.ScheduleLead  = c.ScheduleLead;
                            c0.BeginDate     = c.BeginDate;
                            c0.BeginTime     = c.BeginTime;
                            c0.EndDate       = c.EndDate;
                            c0.EndTime       = c.EndTime;
                            c0.Weblink       = c.Weblink;
                            c0.UpdateTime    = now;

                            bllSchedule.Update(c, c0, trans.DbConnection, trans.DbTrans);
                        }
                    }
                    Utility.DataCache.Schedule.InitCache(projectExists.Id);
                }

                #endregion

                #endregion
                trans.Commit();

                Logger.Info("处理完结");
            }
            catch (Exception ex)
            {
                trans.RollBack();
                Logger.Error(ex);
            }
            finally
            {
                trans.Dispose();
            }

            return(account);
        }
Esempio n. 38
0
        static void Main(string[] args)
        {
            CultureInfo CI = CultureInfo.InvariantCulture;

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

            List <string> Santos = new List <string> {
                "Santo Antônio",
                "Santo Agostinho"
            };

            Santos.Add("Santo Anselmo");
            Santos.Add("Santa Catarina");
            Santos.Add("Santa Josefina");

            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine("**************");

            Santos.Insert(1, "Santa Genoveva");
            Santos.Insert(4, "Santa Margarida");
            Santos.Insert(6, "Santa Cecília");

            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine("**************");
            Console.WriteLine();
            Console.WriteLine("List Count = " + Santos.Count + " Elemento(s)");
            Console.WriteLine("**************");

            string s1 = Santos.Find(x => x[0] == 'S');

            Console.WriteLine("Primeira Pessoa com a letra inicial 'S' = " + s1);
            Console.WriteLine("**************");

            string s2 = Santos.FindLast(x => x[0] == 'S');

            Console.WriteLine("Última pessoa com letra incial 'S' = " + s2);
            Console.WriteLine("**************");

            int pos1 = Santos.FindIndex(x => x[0] == 'S');

            Console.WriteLine("Posição do primeiro com 'S' = " + pos1);
            Console.WriteLine("**************");

            int pos2 = Santos.FindLastIndex(x => x[0] == 'S');

            Console.WriteLine("Posição do último com 'S' = " + pos2);
            Console.WriteLine("**************");

            List <string> Resultado = Santos.FindAll(x => x.Length == 13);

            foreach (string obj in Resultado)
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine("**************");

            Santos.Remove("Santo Anselmo");
            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("List Count = " + Santos.Count + " Elemento(s)");
            Console.WriteLine("**************");

            Santos.RemoveAll(x => x[0] == 'S');
            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("List Count = " + Santos.Count + " Elemento(s)");
            Console.WriteLine("**************");

            Santos.Add("Santo Anselmo");
            Santos.Add("Santa Catarina");
            Santos.Add("Santa Josefina");

            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("List Count = " + Santos.Count + " Elemento(s)");
            Console.WriteLine("**************");

            Santos.RemoveAt(2);
            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("List Count = " + Santos.Count + " Elemento(s)");
            Console.WriteLine("**************");

            Santos.Add("Santo Irineu");
            Santos.Add("Santa Teresa D'Avila");
            Santos.Add("Santa Margarida");
            Santos.Add("Santo Inácio");
            Santos.Add("Santa Catarina de Sena");
            Santos.Add("Santa Josefina Bakhita");

            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("List Count = " + Santos.Count + " Elemento(s)");
            Console.WriteLine("**************");

            Santos.RemoveRange(5, 2);
            foreach (string obj in Santos)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("List Count = " + Santos.Count + " Elemento(s)");
            Console.WriteLine("**************");
        }
Esempio n. 39
0
 public T FindLast(Predicate <T> match)
 {
     return(list.FindLast(match));
 }
Esempio n. 40
0
        /// <summary>
        /// 选择一个可用的rtp端口,仅使用偶数端口
        /// </summary>
        /// <param name="minPort"></param>
        /// <param name="maxPort"></param>
        /// <returns></returns>
        private static ushort _guessAnRtpPort(ushort minPort, ushort maxPort)
        {
            lock (Common._getRtpPortLock)
            {
                IPGlobalProperties ipProperties   = IPGlobalProperties.GetIPGlobalProperties();
                List <IPEndPoint>  tcpIpEndPoints = ipProperties.GetActiveTcpListeners().ToList();
                List <IPEndPoint>  udpIpEndPoints = ipProperties.GetActiveUdpListeners().ToList();
                if (minPort > maxPort)
                {
                    var tmp = minPort;
                    maxPort = minPort;
                    minPort = tmp;
                }


                if (minPort == maxPort)
                {
                    var tcp      = tcpIpEndPoints.FindLast(x => x.Port == minPort);
                    var udp      = udpIpEndPoints.FindLast(x => x.Port == minPort);
                    var portUsed = Common.PortInfoList.FindLast(x => x.Port.Equals(minPort));
                    if (tcp == null && udp == null)
                    {
                        if (portUsed == null)
                        {
                            Common.PortInfoList.Add(new PortInfo()
                            {
                                DateTime = DateTime.Now,
                                Port     = minPort,
                                Useed    = true,
                            });
                            Logger.Info($"[{Common.LoggerHead}]->获取可用rtp端口:{minPort}");
                            return(minPort);
                        }

                        if (!portUsed.Useed.Equals(true))
                        {
                            if ((DateTime.Now - portUsed.DateTime).TotalSeconds >
                                Common.AkStreamKeeperConfig.RtpPortCdTime)
                            {
                                portUsed.DateTime = DateTime.Now;
                                Logger.Info($"[{Common.LoggerHead}]->获取可用rtp端口:{minPort}");
                                return(minPort);
                            }
                        }
                    }

                    Logger.Warn($"[{Common.LoggerHead}]->获取可用rtp端口失败");
                    return(0);
                }

                for (ushort port = minPort; port <= maxPort; port++)
                {
                    if (UtilsHelper.IsOdd(port)) //如果是奇数则跳过
                    {
                        continue;
                    }

                    var tcp2      = tcpIpEndPoints.FindLast(x => x.Port == port);
                    var udp2      = udpIpEndPoints.FindLast(x => x.Port == port);
                    var portUsed2 = Common.PortInfoList.FindLast(x => x.Port.Equals(port));
                    if (tcp2 == null && udp2 == null)
                    {
                        if (portUsed2 == null)
                        {
                            Common.PortInfoList.Add(new PortInfo()
                            {
                                DateTime = DateTime.Now,
                                Port     = port,
                                Useed    = true,
                            });
                            Logger.Info($"[{Common.LoggerHead}]->获取可用rtp端口:{port}");
                            return(port);
                        }

                        if (!portUsed2.Useed.Equals(true))
                        {
                            if ((DateTime.Now - portUsed2.DateTime).TotalSeconds >
                                Common.AkStreamKeeperConfig.RtpPortCdTime)
                            {
                                portUsed2.DateTime = DateTime.Now;
                                Logger.Info($"[{Common.LoggerHead}]->获取可用rtp端口:{port}");
                                return(port);
                            }
                        }
                    }
                }
            }

            Logger.Warn($"[{Common.LoggerHead}]->获取可用rtp端口失败");
            return(0);
        }
Esempio n. 41
0
        public static IPAddress ResolveHostNameToIP(string hostname, AddressFamily addressVersion = AddressFamily.InterNetwork)
        {
            try
            {
                if (!String.IsNullOrEmpty(hostname))
                {
                    List<IPAddress> addresses = new List<IPAddress>(Dns.GetHostAddresses(hostname));

                    return addresses.FindLast(ip => ip.AddressFamily == addressVersion);
                }

                return null;
            }
            catch (Exception ex)
            {
                
            }
            return null;
        }
Esempio n. 42
0
            /// <summary>
            /// Load data into memory.
            /// </summary>
            /// <param name="startTime">start of load range</param>
            /// <param name="endTime">end of load range</param>
            public override IEnumerable <Bar> LoadData(DateTime startTime, DateTime endTime)
            {
                List <Bar> data = new List <Bar>();

                try
                {
                    if (startTime < (DateTime)_firstTime)
                    {
                        startTime = (DateTime)_firstTime;
                    }

                    //if (endTime > (DateTime)LastTime)
                    //    endTime = (DateTime)LastTime;

                    var cacheKey = new CacheId().AddParameters(
                        Info[DataSourceParam.nickName].GetHashCode(),
                        startTime.GetHashCode(),
                        endTime.GetHashCode());

                    List <Bar> retrievalFunction()
                    {
                        DateTime t1 = DateTime.Now;

                        Output.Write(string.Format("DataSourceFred: loading data for {0}...", Info[DataSourceParam.nickName]));

                        List <Bar> rawBars = new List <Bar>();

                        JObject jsonData = getData(startTime, endTime);
                        var     e        = ((JArray)jsonData["observations"]).GetEnumerator();

                        while (e.MoveNext())
                        {
                            var bar = e.Current;

                            DateTime date = DateTime.Parse((string)bar["date"], CultureInfo.InvariantCulture).Date
                                            + DateTime.Parse(Info[DataSourceParam.time], CultureInfo.InvariantCulture).TimeOfDay;

                            string valueString = (string)bar["value"];

                            if (valueString == ".")
                            {
                                continue; // missing value, avoid throwing exception here
                            }
                            double value;
                            try
                            {
                                value = double.Parse(valueString, CultureInfo.InvariantCulture);
                            }
                            catch
                            {
                                // when we get here, this was probably a missing value,
                                // which FRED substitutes with "."
                                // we ignore and move on, AlignWithMarket will take
                                // care of the issue gracefully
                                continue;
                            }

                            rawBars.Add(Bar.NewOHLC(
                                            Info[DataSourceParam.ticker],
                                            date,
                                            value, value, value, value,
                                            0));
                        }

                        List <Bar> alignedBars = DataSourceHelper.AlignWithMarket(rawBars, startTime, endTime);

                        DateTime t2 = DateTime.Now;

                        Output.WriteLine(string.Format(" finished after {0:F1} seconds", (t2 - t1).TotalSeconds));

                        return(alignedBars);
                    };

                    data = Cache <List <Bar> > .GetData(cacheKey, retrievalFunction, true);

                    // FIXME: this is far from ideal. We want to make sure that retired
                    //        series are not extended indefinitely
                    _lastTime = data.FindLast(b => true).Time;
                }

                catch (Exception e)
                {
                    throw new Exception(
                              string.Format("DataSourceFred: failed to load quotes for {0}, {1}",
                                            Info[DataSourceParam.nickName], e.Message));
                }

                if (data.Count == 0)
                {
                    throw new Exception(string.Format("DataSourceFred: no data for {0}", Info[DataSourceParam.nickName]));
                }

                CachedData = data;
                return(data);
            }
Esempio n. 43
0
 public static VisitedSystemsClass FindByName(List<VisitedSystemsClass> visitedSystems, string name )
 {
     if (visitedSystems != null)
     {
         VisitedSystemsClass vs = visitedSystems.FindLast(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
         return vs;
     }
     else
         return null;
 }
Esempio n. 44
0
        public override bool Execute()
        {
            if (FudgeFactor >= 0 && Timeout < Int32.MaxValue)
            {
                Timeout *= FudgeFactor;
            }

            bool retVal = true;

            if (Timeout == Int32.MaxValue)
            {
                Log.LogMessage(MessageImportance.Normal, "Running {0}", TestProgramName);
            }
            else
            {
                Log.LogMessage(MessageImportance.Normal, "Running {0} (timeout = {1} seconds)", TestProgramName, ((double)Timeout / 1000.0).ToString("F1"));
            }

            Thread outputThread = null;
            Thread errorThread  = null;

            var dtStart = DateTime.Now;

            try
            {
                // Start the external process
                var process = StartProcess();
                outputThread = new Thread(StreamReaderThread_Output);
                errorThread  = new Thread(StreamReaderThread_Error);

                m_StdOut   = process.StandardOutput;
                m_StdError = process.StandardError;

                outputThread.Start();
                errorThread.Start();

                // Wait for the process to terminate
                process.WaitForExit(Timeout);

                // Wait for the threads to terminate
                outputThread.Join(2000);
                errorThread.Join(2000);

                bool fTimedOut = !process.WaitForExit(0);                       // returns false immediately if still running.
                if (fTimedOut)
                {
                    try
                    {
                        bool testLooksToHaveFinished;
                        lock (LockObject)
                        {
                            testLooksToHaveFinished = !string.IsNullOrEmpty(m_TestLog.FindLast(line => line.Contains(GetTestsCompletedString())));
                        }
                        if (testLooksToHaveFinished)
                        {
                            Log.LogMessage(MessageImportance.Normal, "Tests for {0} timed out, but appear to have finished. Giving 2 seconds for log to be written.", TestProgramName);
                            Thread.Sleep(2000);
                            // If the tests completed, don't fail with a timeout; if missing Dispose calls caused NUnit to hang, that should be caught as a different failure.
                            fTimedOut = false;
                        }
                        if (!process.HasExited)                        // If the tests looked to have finished the process might have exited normally by now
                        {
                            process.Kill();                            // This will set the exit code to -1 and the suite will be added as a failed suite below
                        }
                    }
                    catch
                    {
                        // ignore possible exceptions that are thrown when the
                        // process is terminated
                    }
                }

                TimeSpan delta = DateTime.Now - dtStart;
                Log.LogMessage(MessageImportance.Normal, "Total time for running {0} = {1}", TestProgramName, delta);

                try
                {
                    ProcessOutput(fTimedOut, delta);
                }
                catch                 //(Exception e)
                {
                    //Console.WriteLine("CAUGHT EXCEPTION: {0}", e.Message);
                    //Console.WriteLine("STACK: {0}", e.StackTrace);
                }

                // If the test timed out, it was killed and its ExitCode is not available.
                // So check for a timeout first.
                if (fTimedOut)
                {
                    Log.LogError("The tests in {0} did not finish in {1} milliseconds.",
                                 TestProgramName, Timeout);
                    FailedSuites = FailedSuiteNames;
                    retVal       = false;
                }
                else if (process.ExitCode != 0)
                {
                    Log.LogWarning("{0} returned with exit code {1}", TestProgramName,
                                   process.ExitCode);
                    FailedSuites = FailedSuiteNames;
                    // Return true in this case - at least NUnit returns non-zero exit code when
                    // a test fails, but we don't want to stop the build.
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e, true);
                retVal = false;
            }
            finally
            {
                // ensure outputThread is always aborted
                if (outputThread != null && outputThread.IsAlive)
                {
                    outputThread.Abort();
                }
                // ensure errorThread is always aborted
                if (errorThread != null && errorThread.IsAlive)
                {
                    errorThread.Abort();
                }
            }
            // Return retVal instead of !Log.HasLoggedErrors - if we get test failures we log
            // those but don't want the build to fail. However, if we get an exception from the
            // test or if we get a timeout we want to fail the build.
            return(retVal);
        }
Esempio n. 45
0
        private CompletionSet CreateCompletionSet(CompletionContext context, List<DesignerNode> nodes, SnapshotPoint point)
        {
            switch (context)
            {
                case CompletionContext.Tag:
                    return TagCompletionSet.Create(nodes, point);

                case CompletionContext.Variable:
                    return VariableCompletionSet.Create(nodes, point);

                case CompletionContext.FilterName:
                    return FilterCompletionSet.Create(nodes, point);

                case CompletionContext.Other:
                    DesignerNode node = nodes.FindLast(n => n.NodeType != NodeType.ParsingContext);
                    if (node == null)
                        return null;
                    if (node.NodeType == NodeType.TagName)
                        return new TagNameCompletionSet(node, point);
                    return new CompletionSet(node, point);

                default:
                    return null;

            }
        }
Esempio n. 46
0
 public T FindLast(Predicate <T> match)
 {
     return(Internal.FindLast(match));
 }
Esempio n. 47
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iDias">Número N de dias para o qual se quer o calculo</param>
        /// <param name="LstHistMov">Lista de Movimentacoes para uma acao</param>
        /// <param name="day">O dia atual</param>
        /// <returns></returns>
        public double MediaMovelExponencial(int iDias, List<HistMovimentacao> LstHistMov, DateTime day)
        {
            double MediaExponencial = 0d;

            if (LstHistMov.FindAll(a => a.DtNegociada == day.AddDays(-1)).Count <= 0)
            {
                return MediaMovelSimples(LstHistMov);
            }
            else
            {
                MediaExponencial = MediaMovelExponencial(iDias - 1, LstHistMov.FindAll(a => a.DtNegociada < day).ToList(), day.AddDays(-1)) + (2 / (float.Parse(iDias.ToString()) + 1)) * (LstHistMov.FindLast(a => a.DtNegociada == day).FValorNegociado - MediaMovelExponencial(iDias - 1, LstHistMov.FindAll(a => a.DtNegociada < day).ToList(), day.AddDays(-1)));
            }
            return MediaExponencial;
        }
Esempio n. 48
0
        public static Vieta parseSuvirinimas(VietosKodas kodas)
        {
            // AA.BCCC.DD.EE.F

            int aa  = kodas.aa;
            int b   = kodas.b;
            int ccc = kodas.ccc;
            int dd  = kodas.dd;
            int ee  = kodas.ee;
            int f   = kodas.f;


            Vieta vieta = new Vieta();

            vieta.galimosLinijos = new List <Linija>();

            vieta.kodas = aa.ToString("00") + "." + b.ToString() + ccc.ToString("000") + "." + dd.ToString("00") + "." + ee.ToString("00") + "." + f.ToString();

            // ar linija
            List <Stotis> lin = null;
            Stotis        stt = null;
            int           dist;

            if (LGIF.infrastruktūra.ContainsKey(aa)) // jeigu yra tokia linija, kokia nurodyta AA
            {
                lin = LGIF.infrastruktūra[aa];
                if (b == 8)
                {
                    throw new InvalidKodasException(ExceptMsgs["xx.Xxxx.xx.xx.x negali būti 8"]);
                }
                vieta.galimosLinijos.Add(LGIF.linijos[aa]);

                if (b == 9) //  jeigu iešmas
                {
                    if (f != 0)
                    {
                        throw new InvalidKodasException(ExceptMsgs["xx.xxxx.xx.xx.X turi būti 0"]);
                    }

                    // ieškoma mažos stoties, kurios ribose būtų ccc nurodytas kilometras
                    {
                        int cccPradzia = (ccc - 1) * 1000;   // ccc kilometro pradžia
                        int cccPabaiga = cccPradzia + 1000;  // ccc kilometro pabaiga
                        stt = lin.Find(delegate(Stotis stotis)
                        {
                            return(!((stotis.iki == -1 ? true : stotis.iki <= cccPradzia) || stotis.nuo >= cccPabaiga));
                        });
                    }
                    if (stt == null)
                    {
                        throw new InvalidKodasException(ExceptMsgs["xx.xXXX.xx.xx.x netinka mažai stočiai"]);
                    }
                    vieta.stotis = stt;
                    if (dd < 1 || dd > 8)
                    {
                        throw new InvalidKodasException(ExceptMsgs["xx.xxxx.XX.xx.x gali būti nuo 1 iki 8"]);
                    }
                    if (ee < 1 || ee > MAX_SANDURU_IESME)
                    {
                        throw new InvalidKodasException(string.Format(ExceptMsgs["xx.xxxx.xx.XX.x gali būti nuo 1 iki MAX_SANDŪRŲ"], MAX_SANDURU_IESME));
                    }
                    // suvirinimas mažos stoties iešme - baigta
                    vieta.stotis         = stt;
                    vieta.koordinatė     = new KelioKoordinatė(ccc);
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.iešmas, dd);
                    vieta.iešmoSandūra   = new Sandūra(ee);
                    return(vieta);
                }

                else // jeigu ne iešmas
                {
                    if (dd < 1 || dd > 10)
                    {
                        throw new InvalidKodasException(ExceptMsgs["xx.xxxx.XX.xx.x gali būti nuo 1 iki 10"]);
                    }
                    if ((b != 6 && b != 7) && (f != 0 && f != 9))
                    {
                        throw new InvalidKodasException(ExceptMsgs["Mažoje stotyje netrumpajame kelyje xx.xxxx.xx.xx.X gali būti 0 arba 9"]);
                    }
                    if ((b == 6 || b == 7) && (f == 0 || f == 9))
                    {
                        throw new InvalidKodasException(ExceptMsgs["Mažoje stotyje trumpajame kelyje xx.xxxx.xx.xx.X gali būti 1-8"]);
                    }
                    vieta.koordinatė = new KelioKoordinatė(ccc, dd, ee);

                    // ar ccc.dd.ee tinka mažai stočiai
                    dist = (ccc - 1) * 1000 + (dd - 1) * 100 + ee;
                    stt  = lin.Find(delegate(Stotis stotis) { return((stotis.nuo == -1 ? false : dist >= stotis.nuo) && dist <= stotis.iki); });
                    if (stt != null) // ccc.ee.dd mažai stočiai tinka
                    {
                        vieta.stotis = stt;
                        switch (b)
                        {
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                            vieta.kelioElementas = new KelioElementas(KelioElementoTipas.stoties_kelias, b);
                            vieta.siūlė          = new Siūlė(f);
                            break;

                        case 6:
                            vieta.kelioElementas = new KelioElementas(KelioElementoTipas.trumpasis_kelias_nuo_iešmo_kairėn, f);
                            break;

                        case 7:
                            vieta.kelioElementas = new KelioElementas(KelioElementoTipas.trumpasis_kelias_nuo_iešmo_dešinėn, f);
                            break;
                        }
                        return(vieta);
                    }
                    else // ccc.dd.ee mažai stočiai netinka
                    {
                        if (b != 1 && b != 2)
                        {
                            throw new InvalidKodasException(ExceptMsgs["xx.Xxxx.xx.xx.x gali būti 1 arba 2"]);
                        }
                        // rasti tarpstotį
                        {
                            Stotis stotis1 = lin.FindLast(delegate(Stotis stotis) { return(stotis.iki == -1 ? false : dist > stotis.iki); });
                            Stotis stotis2 = lin.Find(delegate(Stotis stotis) { return(dist < stotis.nuo); });
                            if (stotis1 == null || stotis2 == null)
                            {
                                throw new InvalidKodasException(ExceptMsgs["xx.xXXX.XX.XX.x netinka linijai"]);
                            }
                            vieta.tarpstotis = new Tarpstotis(stotis1, stotis2);
                        }
                        vieta.siūlė = new Siūlė(f);
                        switch (b)
                        {
                        case 1:
                            vieta.kelioElementas = new KelioElementas(KelioElementoTipas.tarpstočio_nelyginis_kelias, b);
                            break;

                        case 2:
                            vieta.kelioElementas = new KelioElementas(KelioElementoTipas.tarpstočio_lyginis_kelias, b);
                            break;
                        }
                        return(vieta);
                    }
                }
            }
            else // jeigu tokios linijos nėra
            {
                List <Stotis> galimosStotys = new List <Stotis>();
                // ieškoma stoties aa;
                foreach (List <Stotis> linijosStotys in LGIF.infrastruktūra.Values)
                {
                    stt = linijosStotys.Find(delegate(Stotis stotis) { return(stotis.kodas == aa); });
                    if (stt != null)
                    {
                        galimosStotys.Add(stt);
                    }
                }
                if (galimosStotys.Count == 0)
                {
                    throw new InvalidKodasException(ExceptMsgs["Tokios stoties nėra"]);
                }
                if (b == 9)
                {
                    throw new InvalidKodasException(ExceptMsgs["DS b negali būti 9"]);
                }
                if (b == 8)
                {
                    if (dd != 0 || f != 0)
                    {
                        throw new InvalidKodasException(ExceptMsgs["Kai suvirinimas DSI, xx.xxxx.XX.xx.X turi būti 0."]);
                    }
                    if (ee < 1 || ee > MAX_SANDURU_IESME)
                    {
                        throw new InvalidKodasException(string.Format(ExceptMsgs["DSI xx.xxxx.xx.XX.x gali būti nuo 1 iki {0}."], MAX_SANDURU_IESME));
                    }

                    foreach (Stotis st in galimosStotys)
                    {
                        vieta.galimosLinijos.Add(st.linija);
                    }
                    vieta.stotis         = stt; // įdedama paskutinė rastoji
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.iešmas, ccc);
                    vieta.iešmoSandūra   = new Sandūra(ee);
                    return(vieta);
                }
                if (f != 0 && f != 9)
                {
                    throw new InvalidKodasException(ExceptMsgs["xx.xxxx.xx.xx.X gali būti 0 arba 9"]);
                }
                if (b == 1)
                {
                    if (dd == 0)
                    {
                        throw new InvalidKodasException(ExceptMsgs["xx.xxxx.XX.xx.x gali būti nuo 1 iki 10"]);
                    }
                    // tikrinti, ar koordinate ccc.dd.ee tinka didelei stočiai aa
                    dist = (ccc - 1) * 1000 + (dd - 1) * 100 + ee;
                    stt  = null;
                    stt  = galimosStotys.Find(delegate(Stotis stotis) { return((stotis.nuo == -1 ? false : stotis.nuo <= dist) && (stotis.iki >= dist)); });
                    if (stt == null)
                    {
                        throw new InvalidKodasException(ExceptMsgs["xx.xXXX.XX.XX.x netinka stočiai"]);
                    }
                    vieta.galimosLinijos.Add(stt.linija);
                    vieta.stotis         = stt;
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.stoties_pagrindinis_kelias);
                    vieta.koordinatė     = new KelioKoordinatė(ccc, dd, ee);
                    vieta.siūlė          = new Siūlė(f);
                    return(vieta);
                }
                foreach (Stotis st in galimosStotys)
                {
                    vieta.galimosLinijos.Add(st.linija);
                }
                vieta.stotis           = stt; // įdedama paskutinė rastoji
                vieta.atstumasNuoIešmo = new Atstumas(dd * 100 + ee);
                vieta.siūlė            = new Siūlė(f);
                switch (b)
                {
                case 2:
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.stoties_pagrindinis_kelias, ccc);
                    break;

                case 3:
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.atvykimo_išvykimo_kelias, ccc);
                    break;

                case 4:
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.stoties_kelias, ccc);
                    break;

                case 5:
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.sankirta, ccc);
                    break;

                case 6:
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.trumpasis_kelias_nuo_iešmo_kairėn, ccc);
                    break;

                case 7:
                    vieta.kelioElementas = new KelioElementas(KelioElementoTipas.trumpasis_kelias_nuo_iešmo_dešinėn, ccc);
                    break;
                }
                return(vieta);
            }
        }
Esempio n. 49
0
        private DataGridViewRow MakeRow(GUIMod mod, List <ModChange> changes, bool hideEpochs = false, bool hideV = false)
        {
            DataGridViewRow item = new DataGridViewRow()
            {
                Tag = mod
            };

            ModChange myChange = changes?.FindLast((ModChange ch) => ch.Mod.Identifier == mod.Identifier);

            var selecting = mod.IsInstallable()
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = myChange == null ? mod.IsInstalled
                        : myChange.ChangeType == GUIModChangeType.Install ? true
                        : myChange.ChangeType == GUIModChangeType.Remove  ? false
                        : mod.IsInstalled
            }
                : new DataGridViewTextBoxCell()
            {
                Value = mod.IsAutodetected ? Properties.Resources.MainModListAutoDetected : "-"
            };

            var autoInstalled = mod.IsInstalled && !mod.IsAutodetected
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = mod.IsAutoInstalled
            }
                : new DataGridViewTextBoxCell()
            {
                Value = "-"
            };

            var updating = mod.IsInstallable() && mod.HasUpdate
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = myChange == null ? false
                        : myChange.ChangeType == GUIModChangeType.Update ? true
                        : false
            }
                : new DataGridViewTextBoxCell()
            {
                Value = "-"
            };

            var replacing = IsModInFilter(GUIModFilter.Replaceable, mod)
                ? (DataGridViewCell) new DataGridViewCheckBoxCell()
            {
                Value = myChange == null ? false
                        : myChange.ChangeType == GUIModChangeType.Replace ? true
                        : false
            }
                : new DataGridViewTextBoxCell()
            {
                Value = "-"
            };

            var name = new DataGridViewTextBoxCell()
            {
                Value = mod.Name
            };
            var author = new DataGridViewTextBoxCell()
            {
                Value = mod.Authors
            };

            var installVersion = new DataGridViewTextBoxCell()
            {
                Value = hideEpochs
                    ? (hideV
                        ? ModuleInstaller.StripEpoch(ModuleInstaller.StripV(mod.InstalledVersion ?? ""))
                        : ModuleInstaller.StripEpoch(mod.InstalledVersion ?? ""))
                    : (hideV
                        ? ModuleInstaller.StripV(mod.InstalledVersion ?? "")
                        : mod.InstalledVersion ?? "")
            };

            var latestVersion = new DataGridViewTextBoxCell()
            {
                Value =
                    hideEpochs ?
                    (hideV ? ModuleInstaller.StripEpoch(ModuleInstaller.StripV(mod.LatestVersion))
                        : ModuleInstaller.StripEpoch(mod.LatestVersion))
                    : (hideV ? ModuleInstaller.StripV(mod.LatestVersion)
                        : mod.LatestVersion)
            };

            var downloadCount = new DataGridViewTextBoxCell()
            {
                Value = String.Format("{0:N0}", mod.DownloadCount)
            };
            var compat = new DataGridViewTextBoxCell()
            {
                Value = mod.KSPCompatibility
            };
            var size = new DataGridViewTextBoxCell()
            {
                Value = mod.DownloadSize
            };
            var installDate = new DataGridViewTextBoxCell()
            {
                Value = mod.InstallDate
            };
            var desc = new DataGridViewTextBoxCell()
            {
                Value = mod.Abstract
            };

            item.Cells.AddRange(selecting, autoInstalled, updating, replacing, name, author, installVersion, latestVersion, compat, size, installDate, downloadCount, desc);

            selecting.ReadOnly     = selecting     is DataGridViewTextBoxCell;
            autoInstalled.ReadOnly = autoInstalled is DataGridViewTextBoxCell;
            updating.ReadOnly      = updating      is DataGridViewTextBoxCell;

            return(item);
        }
Esempio n. 50
0
 public HistoryEntry GetLastHistoryEntry(Predicate <HistoryEntry> where)
 {
     return(historylist.FindLast(where));
 }
Esempio n. 51
0
 public static HistoryEntry FindLastFSDKnownPosition(List <HistoryEntry> syslist)
 {
     return(syslist.FindLast(x => x.System.HasCoordinate && x.IsLocOrJump));
 }
Esempio n. 52
0
        static void Main(string[] args)
        {
            int count = 0;

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

            list1.Add("Fernando");
            list1.Add("Lucas");
            list1.Add("Maria");
            list1.Add("Leonardo");
            list1.Add("Marcos");
            list1.Add("Leopoldo");
            list1.Add("Mateus");
            list1.Add("Luiz");
            list1.Add("Lidio");


            int length = list1.Count;

            //Listar todos
            list1.ForEach(nome =>
            {
                count++;
                string symbol = count != length ? ", " : ".";
                Console.Write($"{nome}{symbol}");
            });
            Console.WriteLine("\n============================\n");

            count = 0;
            List <string> list2 = new List <string> {
                "Gomes", "Souza", "Leonardo"
            };
            int length2 = list2.Count;

            //Listar todos
            foreach (var nome2 in list2)
            {
                count++;
                string symbol = count != length2 ? ", " : ".";
                Console.Write($"{nome2}{symbol}");
            }
            Console.WriteLine("\n============================\n");

            //Listar primeiro casdastrado que começe com L
            string first = list1.Find(x => x[0] == 'L');

            Console.WriteLine($"Primeiro nom a letra 'L' : {first}");

            //Listar ultimo casdastrado que começe com L
            string last = list1.FindLast(x => x[0] == 'L');

            Console.WriteLine($"Ultimo nom a letra 'L' : {last}\n");

            //Primeira e ultima  posição de casdastrado que começe com L
            int primera_posicao = list1.FindIndex(x => x[0] == 'L');
            int ultima_posicao  = list1.FindLastIndex(x => x[0] == 'L');

            Console.WriteLine($"Primeira posição == 'L' : {primera_posicao};\nultima posição == 'L' : {ultima_posicao}\n");

            //Filtrar todos casdastrados que contenham 5 caracters
            Console.Write($"Cadastrados com 5 caracteres : ");
            var filter_five = list1.FindAll(x => x.Length == 5);

            foreach (var item in filter_five)
            {
                Console.Write($"{item}, ");
            }

            Console.WriteLine("\n============================\n");
            Console.WriteLine("REMOVE:\n");
            //REMOVE

            //Antes de remover
            Console.WriteLine("Todos Cadastrados:");
            foreach (var item in list1)
            {
                Console.Write($"{item}, ");
            }
            Console.WriteLine("\n---\n");

            //1 cadastrado especifico
            string nome = "Mateus";

            Console.WriteLine($"Removendo: {nome}");
            list1.Remove(nome);
            foreach (var item in list1)
            {
                Console.Write($"{item}, ");
            }
            Console.WriteLine("\n---\n");

            //todos cadastrados que começão com a letra 'M'
            Console.WriteLine($"Removendo que começam com a letra 'M'");
            list1.RemoveAll(x => x[0] == 'M');
            foreach (var item in list1)
            {
                Console.Write($"{item}, ");
            }
            Console.WriteLine("\n---\n");

            //todos cadastrados que começão com a letra 'M'
            int posicao = 2;

            Console.WriteLine($"Removendo na posição : {posicao}");
            list1.RemoveAt(posicao);
            foreach (var item in list1)
            {
                Console.Write($"{item}, ");
            }
            Console.WriteLine("\n---\n");


            //remove range
            int posicao_init = 2;
            int quantidade   = 2;

            list1.RemoveRange(posicao_init, quantidade);
            Console.WriteLine($"Removendo a partir da posicao {posicao_init} o total de {quantidade} itens");
            foreach (var item in list1)
            {
                Console.Write($"{item}, ");
            }
            Console.WriteLine("\n---\n");
        }
Esempio n. 53
0
 void MoveBy(List<Hex> path)
 {
     Move (path.Count);
     Hex prevHex = Hex;
     Hex newHex = path.FindLast(h => true);
     List<Transform> p = path.ConvertAll<Transform>(h => h.transform);
     gameObject.GetComponent<AudioSource>().Play();
     if(p.Count > 1) {
         iTween.MoveTo(gameObject, iTween.Hash (
             "path", p.ToArray(),
             "time", p.Count,
             "orienttopath", true,
             "easetype", "easeInOutQuad",
             "oncomplete", "MovementDone",
             "name", Id));
     } else {
         iTween.MoveTo(gameObject, iTween.Hash (
             "position", p[0],
             "time", p.Count,
             "orienttopath", true,
             "easetype", "easeInOutQuad",
             "oncomplete", "MovementDone",
             "name", Id));
     }
     prevHex.Unit = null;
     Hex = newHex;
     newHex.Unit = this;
 }
 private static Round GetTheMostRecentlyPlayedRound(List<Round> rounds)
 {
     Round result;
     result = rounds.FindLast(r => r.RoundPlayed);
     return result;
 }