Пример #1
0
        public AppConfig()
        {
            InitializeComponent();

            // Region.
            _cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures).OrderBy(i => i.DisplayName).ToList();
            cbLocation.ItemsSource = _cultureInfos.Select(c => c.DisplayName);
            cbLocation.SelectedIndex = _cultureInfos.FindIndex(c => c.Name == "ja-JP");

            //Timezone.
            _timezones = TimeZoneInfo.GetSystemTimeZones().ToList();
            cbTimezone.ItemsSource = _timezones.Select(t => t.DisplayName);
            cbTimezone.SelectedIndex = _timezones.FindIndex(tz => tz.Id == "Tokyo Standard Time");

            // Load exists config.
            var configs = LEConfig.GetProfiles(App.StandaloneFilePath);
            if (configs.Length > 0)
            {
                var conf = configs[0];

                if (!String.IsNullOrEmpty(conf.Parameter))
                {
                    tbAppParameter.FontStyle = FontStyles.Normal;
                    tbAppParameter.Text = conf.Parameter;
                }
                cbTimezone.SelectedIndex = _timezones.FindIndex(tz => tz.Id == conf.Timezone);
                cbLocation.SelectedIndex = _cultureInfos.FindIndex(ci => ci.Name == conf.Location);

                cbStartAsAdmin.IsChecked = conf.RunAsAdmin;
                cbRedirectRegistry.IsChecked = conf.RedirectRegistry;
                cbStartAsSuspend.IsChecked = conf.RunWithSuspend;
            }
        }
        public static void AddTimeSlotToAvailability(List<TimeSlot> availability, TimeSlot timeSlot)
        {
            foreach (var availableTimeSlot in availability.Where(a => a.Day == timeSlot.Day))
            {
                if (availableTimeSlot.EndHour == timeSlot.StartHour)
                {
                    availableTimeSlot.AddAfter(timeSlot);

                    var index = availability.FindIndex(a => a.Day == timeSlot.Day && a.StartHour == availableTimeSlot.EndHour);
                    if (index != -1)
                    {
                        availableTimeSlot.AddAfter(availability[index]);
                        availability.RemoveAt(index);
                    }
                    break;
                }
                if (availableTimeSlot.StartHour == timeSlot.EndHour)
                {
                    availableTimeSlot.AddBefore(timeSlot);

                    var index = availability.FindIndex(a => a.Day == timeSlot.Day && a.EndHour == availableTimeSlot.StartHour);
                    if (index != -1)
                    {
                        availableTimeSlot.AddBefore(availability[index]);
                        availability.RemoveAt(index);
                    }
                    break;
                }
            }
        }
Пример #3
0
        public void RunProgram()
        {
            List<Paragraph> paragraphs = new List<Paragraph>()
            {
                new Paragraph() { Text = "hello", Styles = new Style[] { Style.Bold } },
                new Paragraph() { Text = "there", Styles = new Style[] { Style.Italic, Style.Bold } },
                new Paragraph() { Text = "to", Styles = new Style[] { Style.Italic, Style.Superscript, Style.Bold } },
                new Paragraph() { Text = "you", Styles = new Style[] { Style.Superscript, Style.Bold } }
            };

            //3 identical methods

            Console.WriteLine(paragraphs.FindIndex(
                delegate(Paragraph p)
                {
                    foreach (var style in p.Styles)
                    {
                        if (style == Style.Superscript)
                        {
                            return true;
                        }
                    }
                    return false;
                }));

            Console.WriteLine(paragraphs.FindIndex(new Predicate<Paragraph>(HasSuperscript)));

            Console.WriteLine(paragraphs.FindIndex(HasSuperscript));
        }
Пример #4
0
        public Boolean EnrolStudent(StudentEnrollment studentEnr)
        {
            GradeSectionLogic gsl = new GradeSectionLogic();
            StudentService ss = new StudentService();
            StudentEnrollmentBDO studentBDO = new StudentEnrollmentBDO();

            string message = string.Empty;

            List<GradeSectionBDO> sections = new List<GradeSectionBDO>();
            string grade = studentEnr.GradeLevel;
            sections = (gsl.GetAllSectionsofGrade(grade));

            int div = studentEnr.Rank / 20;
            div++;
            int index = sections.FindIndex(item => item.Class == div);
            studentEnr.GradeSectionCode = (int?)sections[index].GradeSectionCode;
            TranslatEnrolToEnrolBDO(studentEnr, studentBDO);
            if (sel.RegisterStudent(studentBDO, ref message))
            {
                string section = String.Empty;
                studentBDO.GradeSectionCode = studentEnr.GradeSectionCode;
                index = sections.FindIndex(item => item.GradeSectionCode == studentEnr.GradeSectionCode);
                section = sections[index].Section;
                ss.UpdateStudent(studentEnr.StudentId, studentEnr.GradeLevel, studentEnr.Rank, section);
                ControlStudentCharacters(studentBDO);
                return true;

            }
            else return false;
        }
 public static void Main(string[] args)
 {
     person tempperson;
     int day=0;
     string statpark = Console.ReadLine();
     while (!string.IsNullOrEmpty(statpark))
     {
         //initialize hash
         List<person> lp=new List<person>();
         while (!statpark.Equals("CLOSE"))
         {
             if (statpark.Equals("OPEN"))//next
             {
                 statpark = Console.ReadLine();day++;
             }
             string[] tempsplit = statpark.Split();
             if (tempsplit[0].Equals("ENTER"))
             {
                 if (lp.Exists(item => item.name == tempsplit[1]))
                 {
                     int idx = lp.FindIndex(item => item.name == tempsplit[1]);
                     int min=int.Parse(tempsplit[2]);
                     string nma=lp[idx].name;
                     double pri=lp[idx].price;
                     lp[idx] = new person(nma,pri,min);
                 }
                 else
                 {
                     tempperson.currminute = int.Parse(tempsplit[2]);
                     tempperson.name = tempsplit[1];
                     tempperson.price = 0;
                     lp.Add(tempperson);
                 }
             }
             else //EXIT
             {
                 int idx = lp.FindIndex(item => item.name == tempsplit[1]);
                 int myminutes=int.Parse(tempsplit[2]);
                 string nama=lp[idx].name;
                 double harga=lp[idx].price+((myminutes-lp[idx].currminute)*0.1);
                 int menitsekarang=lp[idx].currminute;
                 lp[idx]=new person(nama,harga,menitsekarang);
             }
             statpark = Console.ReadLine();
         }
         //output
         var tempc=from x in lp orderby x.name select x;
         lp = tempc.ToList();
         Console.WriteLine("Day {0}",day);
         foreach (person prs in lp)
         {
             Console.WriteLine(String.Format("{0} ${1:F2}", prs.name, prs.price));
         }
         Console.WriteLine();
         //clear hash
         lp=new List<person>();
         statpark = Console.ReadLine();
     }
 }
        static void Main()
        {
            var graham = new Racer(7, "Graham", "Hill", "UK", 14);
            var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14);
            var mario = new Racer(16, "Mario", "Andretti", "USA", 12);

            var racers = new List<Racer>(20) { graham, emerson, mario };

            racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91));
            racers.Add(new Racer(27, "Mika", "Hakkinen", "Finland", 20));

            racers.AddRange(new Racer[] {
               new Racer(14, "Niki", "Lauda", "Austria", 25),
               new Racer(21, "Alain", "Prost", "France", 51)});

            // insert elements

            racers.Insert(3, new Racer(6, "Phil", "Hill", "USA", 3));

            // accessing elements

            for (int i = 0; i < racers.Count; i++)
            {
                WriteLine(racers[i]);
            }

            foreach (var r in racers)
            {
                WriteLine(r);
            }

            // searching
            int index1 = racers.IndexOf(mario);
            int index2 = racers.FindIndex(new FindCountry("Finland").FindCountryPredicate);
            int index3 = racers.FindIndex(r => r.Country == "Finland");
            Racer racer = racers.Find(r => r.FirstName == "Niki");
            List<Racer> bigWinners = racers.FindAll(r => r.Wins > 20);
            foreach (Racer r in bigWinners)
            {
                WriteLine($"{r:A}");
            }

            WriteLine();


            // remove elements

            if (!racers.Remove(graham))
            {
                WriteLine("object not found in collection");
            }



            var racers2 = new List<Racer>(new Racer[] {
               new Racer(12, "Jochen", "Rindt", "Austria", 6),
               new Racer(22, "Ayrton", "Senna", "Brazil", 41) });
        }
Пример #7
0
        public void Can_find_index_of_list()
        {
            var array = new List<int> { 1, 2, 3, 4, 5, 6 };
            Assert.Equal(0, array.FindIndex(1));
            Assert.Equal(0, array.FindIndex(i => i == 1));

            Assert.Equal(5, array.FindIndex(6));
            Assert.Equal(5, array.FindIndex(i => i == 6));
        }
Пример #8
0
        public static void CD(List<List<NHIRD_DataTypes.ActionBasedData_CD>> ActionBasedData_CD, string str_CDpath, int int_DataGroupCount)
        {
            Console.WriteLine("Call: GetActionBasedData.CD");
            Console.WriteLine(" - CD path: {0}", str_CDpath);
            ActionBasedData_CD = new List<List<NHIRD_DataTypes.ActionBasedData_CD>>();

            //讀取CD檔
            int errorCount = 0;
            using (var sr = new StreamReader(str_CDpath))
            {
                // -- 取得欄位index
                List<string> title = new List<string>(sr.ReadLine().Split('\t'));
                int int_FEE_YM_index = title.FindIndex(x => x.IndexOf("FEE_YM") >= 0);
                int int_HOSP_ID_index = title.FindIndex(x => x.IndexOf("HOSP_ID") >= 0);
                int int_APPL_DATE_index = title.FindIndex(x => x.IndexOf("APPL_DATE") >= 0);
                int int_SEQ_NO_index = title.FindIndex(x => x.IndexOf("SEQ_NO") >= 0);
                int int_ID_index = title.FindIndex(x => x == "ID");
                int int_Birthday_index = title.FindIndex(x => x.IndexOf("ID_BIRTHDAY") >= 0);
                int int_FuncDate_index = title.FindIndex(x => x.IndexOf("FUNC_DATE") >= 0);
                int int_Gender_index = title.FindIndex(x => x.IndexOf("ID_SEX") >= 0);
                int int_ICD_index = title.FindIndex(x => x.IndexOf("ACODE_ICD9_1") >= 0);
                int int_FuncType_index = title.FindIndex(x => x.IndexOf("FUNC_TYPE") >= 0);
                // -- streamreader 迴圈
                int datacount = 0;
                while (!sr.EndOfStream)
                {
                    string[] SplitLine = sr.ReadLine().Split('\t');
                    NHIRD_DataTypes.ActionBasedData_CD DataToAdd = new NHIRD_DataTypes.ActionBasedData_CD(int_DataGroupCount);
                    DataToAdd.str_Fee_YM = SplitLine[int_FEE_YM_index];
                    DataToAdd.str_HospID = SplitLine[int_HOSP_ID_index];
                    DataToAdd.str_ApplDate = SplitLine[int_APPL_DATE_index];
                    DataToAdd.str_SeqNO = SplitLine[int_SEQ_NO_index];
                    DataToAdd.str_ID = SplitLine[int_ID_index];
                    DataToAdd.str_Birthday = SplitLine[int_Birthday_index];
                    DataToAdd.str_FuncDate = SplitLine[int_FuncDate_index];
                    DataToAdd.str_Gender = SplitLine[int_Gender_index];
                    DataToAdd.array_ICD = new string[] { SplitLine[int_ICD_index], SplitLine[int_ICD_index + 1], SplitLine[int_ICD_index + 2] };
                    DataToAdd.str_FuncType = SplitLine[int_FuncType_index];
                    //  使用ActionBasedData_OrderComparer 依序存入ActionBasedData List
                    int SearchIndex = ActionBasedData_CD.BinarySearch(
                       DataToAdd, new NHIRD_DataTypes.ActionBasedData_OrderComparer());
                    if (SearchIndex < 0)
                    {
                        ActionBasedData_CD.Insert(-SearchIndex - 1, DataToAdd);
                        datacount++;
                        if (datacount % 10000 == 0)
                            Console.WriteL("Data Readed: {0}\r", datacount);
                    }
                    else { errorCount++; }
                }
            }
            Console.WriteLine("\nRetrun: {0} Action based data was loaded, error count: {1}. \r\n", ActionBasedData_CD.Count(), errorCount);
        }
Пример #9
0
 public static IEnumerable<AttributeVariant> GetNextAttributeVariants(object context, List<AttributeVariant> attributes)
 {
     var variants = new List<AttributeVariant> ();
     for (int i = 0; i < AttributeValues.Length; i++) {
         if (attributes.FindIndex(a => a.AttributeIndex == i) != -1)
             continue;
         for (int j = 0; j < AttributeValues[i].Length; j++) {
             if (attributes.FindIndex(a => AttributeValues[a.AttributeIndex][a.ValueIndex][0] == AttributeValues[i][j][0]) != -1)
                 continue;
             variants.Add(new AttributeVariant(i, j));
         }
     }
     return variants;
 }
Пример #10
0
        /// <summary>
        ///     Comes up with a 'pure' psuedo-random color
        /// </summary>
        /// <returns>The color</returns>
        public static Color GetRandomRainbowColor()
        {
            var colors = new List<int>();
            for (var i = 0; i < 3; i++)
                colors.Add(_rand.Next(0, 256));

            var highest = colors.Max();
            var lowest = colors.Min();
            colors[colors.FindIndex(c => c == highest)] = 255;
            colors[colors.FindIndex(c => c == lowest)] = 0;

            var returnColor = Color.FromArgb(255, colors[0], colors[1], colors[2]);

            return returnColor;
        }
Пример #11
0
        public static System.Windows.Media.Color GetRandomRainbowMediaColor()
        {
            var colors = new List<byte>();
            for (var i = 0; i < 3; i++)
                colors.Add((byte) _rand.Next(0, 256));

            var highest = colors.Max();
            var lowest = colors.Min();
            colors[colors.FindIndex(c => c == highest)] = 255;
            colors[colors.FindIndex(c => c == lowest)] = 0;

            var returnColor = System.Windows.Media.Color.FromArgb(255, colors[0], colors[1], colors[2]);

            return returnColor;
        }
Пример #12
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.SoundSelection);
            _items = new List<SoundItem>();
            _selectSoundListView = FindViewById<ListView>(Resource.Id.selectSound);
            _selectSoundListView.ChoiceMode = ChoiceMode.Single;

            var applyBtn = FindViewById<Button>(Resource.Id.Apply_btn);
            applyBtn.Click += ApplyBtnOnClick;

            var fields = typeof(Resource.Raw).GetFields();
            int index = 0;
            foreach (var fieldInfo in fields.ToList())
            {
                _items.Add(new SoundItem { Position = index, SoundName = fieldInfo.Name});
                index++;
            }

            _adapter = new SelectSoundAdapter(this, _items);
            _selectSoundListView.Adapter = _adapter;
            _selectSoundListView.ItemClick += selectSoundListView_ItemClick;

            if (!string.IsNullOrEmpty(Settings.WakeUpSound))
            {
                var previouslySelectedItemIndex = _items.FindIndex(i=> i.SoundName == Settings.WakeUpSound);
                _selectSoundListView.SetItemChecked(previouslySelectedItemIndex, true);
            }
        }
Пример #13
0
 public static bool IsLastRankInLine(Rank rank, List<Rank> line)
 {
     if (line.FindIndex(r => r.Equals(rank)) == line.Count - 1)
         return true;
     else
         return false;
 }
Пример #14
0
 public double Get(int productID)
 {
     double cartitemscount = 0;
     var Session = HttpContext.Current.Session;
     List<ProductModel> product = new List<ProductModel>();
     if (Session["ShoppingCartItems"] != null)
     {
         product = Session["ShoppingCartItems"] as List<ProductModel>;
         ProductModel selected = product.Find(p => p.price == productID);
         if (selected != null)
         {
             selected.price++;
             int index = product.FindIndex(p => p.Id == productID);
             product[index] = selected;
         }
         else
         {
             selected = new ProductModel() { Id = productID, price = 1 };
             product.Add(selected);
         }
         Session["ShoppingCartItems"] = product;
     }
     else
     {
         ProductModel selected = new ProductModel() { Id = productID, price = 1 };
         product.Add(selected);
         Session["ShoppingCartItems"] = product;
     }
     foreach (var productInShoppingCart in product)
     {
         cartitemscount += productInShoppingCart.price;
     }
     return cartitemscount;
 }
Пример #15
0
 public int GetTargetIndex(List<WorldObject> availableTargets)
 {
     var attackableTargets = availableTargets.Where(target => target.Owner > 0 && target.Owner != this.Owner);
     var highestHitPoints  = attackableTargets.Max(t => t.HitPoints);
     int index = availableTargets.FindIndex(item => item.HitPoints == highestHitPoints);
     return index;
 }
        public static HandType Execute(int[] handCards, int[] boardCards)
        {
            List<int> handCardsRanks = new List<int>();
            List<int> boardCardsRanks = new List<int>();

            PrepareLists(handCardsRanks, boardCardsRanks, handCards, boardCards);

            if (handCardsRanks.Count == 0)
                return HandType.None;

            HandType result = FindStraightDrawForHandCards(handCardsRanks, boardCardsRanks);

            if (result == HandType.None)
            {
                //Меняем туза с кодом 13 на туза с кодом 0, чтобы вычислить стриты "снизу"
                int handIndexToChange = handCardsRanks.FindIndex((int item) => { return item == 13/*A*/; });
                int boardIndexToChange = boardCardsRanks.FindIndex((int item) => { return item == 13/*A*/; });

                if (handIndexToChange != -1)
                    handCardsRanks[handIndexToChange] = 0;

                if (boardIndexToChange != -1)
                    boardCardsRanks[boardIndexToChange] = 0;

                if (boardIndexToChange != -1 || handIndexToChange != -1)
                    result = FindStraightDrawForHandCards(handCardsRanks, boardCardsRanks);
            }

            return result;
        }
Пример #17
0
 static void Main(string[] args)
 {
     Random random = new Random();
     List<Box> boxList = new List<Box>
     {
         new Box("Параллелепипед A") { Area = random.Next(12, 78), Volume = random.Next(4523, 9453), Diagonal = random.Next(146, 274)},
         new Box("Параллелепипед B") { Area = random.Next(12, 78), Volume = random.Next(4523, 9453), Diagonal = random.Next(146, 274)},
         new Box("Параллелепипед C") { Area = random.Next(12, 78), Volume = random.Next(4523, 9453), Diagonal = random.Next(146, 274)},
         new Box("Параллелепипед D") { Area = random.Next(12, 78), Volume = random.Next(4523, 9453), Diagonal = random.Next(146, 274)},
         new Box("Параллелепипед E") { Area = random.Next(12, 78), Volume = random.Next(4523, 9453), Diagonal = random.Next(146, 274)}
     };
     Console.WriteLine("Список:");
     StaticBox.PrintList(boxList);
     Console.WriteLine("\nСписок в обратном порядке:");
     boxList.Reverse();
     StaticBox.PrintList(boxList);
     Console.WriteLine("\nСписок по объёму: ");
     StaticBox.PrintList(boxList.OrderBy(b => b.Volume).ToList());
     boxList.Add(new Box("Параллелепипед F") { Area = random.Next(12, 78), Volume = random.Next(4523, 9453), Diagonal = random.Next(146, 274) });
     Console.WriteLine("\nСписок с добавленным элементом");
     StaticBox.PrintList(boxList);
     boxList.Insert(3, new Box("Параллелепипед G") { Area = random.Next(12, 78), Volume = random.Next(4523, 9453), Diagonal = random.Next(146, 274) });
     Console.WriteLine("\nСписок со вставленным элементом");
     StaticBox.PrintList(boxList);
     boxList.RemoveAt(3);
     Console.WriteLine("\nСписок с удалённым вставленным элементом");
     StaticBox.PrintList(boxList);
     int index = boxList.FindIndex(b => b.Name == "Параллелепипед C");
     Console.WriteLine("\nНайденный элемент списка");
     boxList[index].Print();
     boxList.Clear();
     Console.WriteLine("\nПустой список");
     StaticBox.PrintList(boxList);
     Console.ReadKey();
 }
        public List<WorldRefExcelDataModel> ReturnCountryOnly()
        {
            List<WorldRefExcelDataModel> listExcelProject = new List<WorldRefExcelDataModel>();

            var Countries = (from Coun in context.WorldRefExcelDataProjects where Coun.IsAuthorized == 1 select Coun).AsEnumerable();

            var countt = Countries.GroupBy(x => x.Country).Select(x => x.First());

            foreach (var country in countt)
            {
                if (!string.IsNullOrEmpty(country.Country))
                {
                    int index = listExcelProject.FindIndex(x => x.Country.ToLower() == country.Country.ToLower());
                    if (index == -1)
                    {
                        listExcelProject.Add(new WorldRefExcelDataModel()
                        {
                            Country = country.Country
                        });
                    }
                }

            }

            return listExcelProject;
        }
Пример #19
0
        /// <summary>
        /// Declares a variable if there is a declaration and deletes unnessesary stuff
        /// </summary>
        /// <param name="listE"> stream of tokens </param>
        /// <returns> true if we need to launch the function again </returns>
        public static bool DeclareVariable(List<Element> listE)
        {
            if (listE.Count > 2) // it can be a declaration only if the list has more than 2 elements
            {
                if (listE[0].Type == C.Number && listE[1].Type == C.Control) // if it is a number
                {
                    string name = listE[0].GetNumber().Name;
                    if (name != "" && listE[1].ToString() == "=") // if it is a variable
                    {
                        listE.RemoveRange(0, 2);
                        Number num = new Number(Parse(listE).Value.ToString());
                        num.Name = name;
                        Variable.Add(num);

                        return false;
                    }
                }
            }

            int index = listE.FindIndex(delegate(Element e)
                                        { if (e.ToString() == "=") return true; return false; });
            if (index != -1) { listE.RemoveRange(0, index + 1); return true; }

            return false;
        }
Пример #20
0
        public void CamereLensId(List<Camera> L1,List<Lens>L2,Exif check)
        {
            int index = L1.FindIndex(item => item.CameraID == check.Camera);
            if (index == 0)
            {
                // element not exists, do what you need
                L1.Add(new Camera { CameraID = check.Camera, CamCount = 1 });
            }
            else
            {
                foreach (var cc in L1.Where(x => x.CameraID == check.Camera))
                    cc.CamCount++;
            }

            int index2 = L2.FindIndex(item => item.LensID == check.Lens);
            if (index2 == 0)
            {
                // element not exists, do what you need
                L2.Add(new Lens { LensID = check.Lens, LensCount = 1 });
            }
            else
            {
                foreach (var lc in L2.Where(x => x.LensID == check.Lens))
                    lc.LensCount++;
            }
        }
Пример #21
0
 public bool SellPolicy(StockEntity currentStockEntity, StockEntity lastBoughtStockEntity, StockEntity lastSoldStockEntity, List<StockEntity> sortedAllStockEntities)
 {
     if (currentStockEntity.Close == 0)
     {
         return false;
     }
     bool biasSellDecesion = false;
     if (currentStockEntity.GetMA(20) != 0)
     {
         double bias = (currentStockEntity.GetMA(5) - currentStockEntity.GetMA(20)) / currentStockEntity.GetMA(5);
         if (bias > tooStrongTheashold)
         {
             biasSellDecesion = true;
             int index = sortedAllStockEntities.FindIndex(entity => entity.RowKey == currentStockEntity.RowKey);
             if (index > 1)
             {
                 var lastStockEntity = sortedAllStockEntities[index - 1];
                 if ((currentStockEntity.Close - lastStockEntity.Close) / lastStockEntity.Close > 0.05)
                 {
                     Console.WriteLine("Stock is too strong, ignore sell decesion.");
                     biasSellDecesion = false;
                 }
             }
         }
         else if (bias < balenceThreshold && bias >= tooWeakThreshold)
         {
             biasSellDecesion = true;
         }
     }
     return biasSellDecesion;
 }
Пример #22
0
        public async Task<IHttpActionResult> Waypoints(int id)
        {
            Mission mission = await db.Missions.FindAsync(id);
            if (mission == null)
            {
                return BadRequest();
            }
            var wps = mission.Waypoints;
            List<Waypoint> wpsInOrder = new List<Waypoint>();
            if (wps.Count == 0)
            {
                return Ok(wpsInOrder.AsQueryable());
            }
            var activeWps = from wp in mission.Waypoints
                            where wp.IsActive
                            select wp;
            var tail = activeWps.First(wp => wp.NextWaypoint == null && wp.IsActive);
            wpsInOrder.Add(tail);
            foreach (var wp in activeWps)
            {
                if (wp.Id == tail.Id)
                {
                    //This is already in the list we don't want to insert it.
                    continue;
                }
                var next = wp.NextWaypoint;
                int index = next != null ? wpsInOrder.FindIndex(n => n.Id == next.Id) : -1;
                if (index == -1)
                {
                    //The next waypoint of this waypoint is not in this list, just insert it behind the last waypoint.
                    int len = wpsInOrder.Count;
                    wpsInOrder.Insert(len - 1, wp);
                }
                else
                {
                    //Insert the waypoint behind its next waypoint.
                    wpsInOrder.Insert(index, wp);
                }

            }

            var diffType = from wp in wpsInOrder.AsQueryable()
                           select new
                           {
                               MissionId = wp.MissionId,
                               NextWaypointId = wp.NextWaypointId,
                               Latitude = wp.Latitude,
                               Longitude = wp.Longitude,
                               Altitude = wp.Altitude,
                               IsActive = wp.IsActive,
                               Id = wp.Id,
                               TimeCompleted = wp.TimeCompleted,
                               WaypointName = wp.WaypointName,
                               Action = wp.Action,
                               GeneratedBy = wp.GeneratedBy,
                           };


            return Ok(diffType);
        }
Пример #23
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            db = new DBPOS();
            users = db.GetUserAccounts();
            current = 0;

            if (String.IsNullOrEmpty(txtBxUserName.Text) && String.IsNullOrEmpty(txtBxPassword.Text))
            {
                lblLoginErrorMsg.Text = "Please ensure all fields are entered";
                txtBxUserName.ResetText();
                txtBxPassword.ResetText();
            }
            else if (users.Exists(u => u.Username.Equals(txtBxUserName.Text)))
            {
                current = users.FindIndex(u => u.Username.Equals(txtBxUserName.Text));
                if (users[current].Username.Equals(txtBxUserName.Text) && users[current].Password.Equals(txtBxPassword.Text))
                {
                    lblLoginErrorMsg.Text = "";
                    txtBxUserName.ResetText();
                    txtBxPassword.ResetText();
                    MessageBox.Show(string.Format("Welcome {0}! Your AccountType is {1}.", users[current].Username, users[current].AccountType));
                    UserControlPanel cp = new UserControlPanel();
                    cp.CurrentUser = users[current];
                    cp.ShowDialog();
                }
            }

            else
            {
                txtBxUserName.ResetText();
                txtBxPassword.ResetText();
                lblLoginErrorMsg.Text = "Either the username or password was incorrect.";
            }
        }
Пример #24
0
        // Methods
        public FieldGenerator( MetaTable table, Control dataBoundControl, DataBoundControlMode mode )
        {
            this._table = table;
            this._dataBoundControl = dataBoundControl;
            this._mode = mode;

            List<MetaColumn> columns = new List<MetaColumn>( _table.Columns );

            //упорядочить колонки в порядке следования в мета-классе.
            var metadataTypeAttribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute( _table.EntityType, typeof( MetadataTypeAttribute ), false );
            if( metadataTypeAttribute != null )
            {
                int index = 0;
                foreach( var memberInfo in metadataTypeAttribute.MetadataClassType.GetMembers().Where( m => m.MemberType == MemberTypes.Field || m.MemberType == MemberTypes.Property ) )
                {
                    int pos = columns.FindIndex( c => c.Name == memberInfo.Name );
                    if( pos >= 0 )
                    {
                        MetaColumn column = columns[ pos ];
                        columns.RemoveAt( pos );
                        columns.Insert( index++, column );
                    }
                }
            }
            _columns = columns;
        }
        private IList<IMenuModel> SortByAfter(IList<IMenuModel> menuModels)
        {
            var sorted = new List<IMenuModel>(menuModels);

            foreach (IMenuModel model in menuModels)
            {
                int newIndex =
                    sorted.FindIndex(m => m.Name.Equals(model.After, StringComparison.InvariantCultureIgnoreCase));

                if (newIndex < 0) continue;

                int currentIndex = sorted.IndexOf(model);

                if (currentIndex < newIndex)
                {
                    sorted.Remove(model);
                    sorted.Insert(newIndex, model);
                }
                else
                {
                    sorted.Remove(model);
                    sorted.Insert(newIndex + 1, model);
                }
            }

            return sorted;
        }
Пример #26
0
        /// <summary>
        /// Process a method declaration for documentation.
        /// </summary>
        /// <param name="symbol">The method in question.</param>
        /// <returns><c>Docs</c> if the method contains any, otherwise <c>null</c>.</returns>
        public static Doc ForMethod(IMethodSymbol symbol)
        {
            var doc = symbol.GetDocumentationCommentXml();
              if (string.IsNullOrEmpty(doc))
              {
            return null;
              }

              var sections = new List<Tuple<int, string, string>>();
              var xdoc = XDocument.Parse(doc).Root;

              ProcessFull(xdoc, sections);
              var cursor = sections.FindIndex(t => t.Item2 == "Summary");
              var paramsSection = ProcessParameters(xdoc, symbol.Parameters.Select(p => p.Name).ToList());
              sections.Insert(cursor + 1, paramsSection);

              var returnElement = xdoc.Element("returns");
              if (returnElement != null)
              {
            var content = ProcessContent(returnElement);
            if (!string.IsNullOrEmpty(content))
            {
              sections.Insert(cursor + 2, Tuple.Create(2, "Return value", $"<p>{content}</p>"));
            }
              }

              var resultString = string.Join("\n", sections.Select(t => $"<h{t.Item1 + 2}>{t.Item2}</h{t.Item1 + 2}>{t.Item3}"));

              return new Doc
              {
            Format = "text/html",
            Data = resultString
              };
        }
        public Frm_BrightnessAdjustmentSetting(BrightnessConfigInfo brightnessCfg, AutoBrightExtendData autoBrightData, List<BrightnessConfigInfo> brightnessConfigList)
        {
            InitializeComponent();

            UpdateLang(CommonUI.BrightnessConfigLangPath);

            _brightnessConfigList = brightnessConfigList;
            _brightnessCfg = brightnessCfg;
            if (_brightnessCfg != null)
            {
                _currentIndex = brightnessConfigList.FindIndex(a => a.Time.Equals(brightnessCfg.Time));
            }
            else
            {
                _brightnessCfg = new BrightnessConfigInfo();
            }

            InitializeViewData();

            //if (autoBrightData == null || autoBrightData.UseLightSensorList == null || autoBrightData.UseLightSensorList.Count == 0)
            //{
            //    HideBrightnessValueOptions();
            //    _brightnessCfg.Type = SmartBrightAdjustType.FixBright;
            //    autoBrightnessRadioButton.Enabled = false;
            //}

            LoadBrightnessAdjustmentSetting(_brightnessCfg);
        }
Пример #28
0
        public void GetState()
        {
            try
            {
                List<Process> allProcesses = new List<Process>( Process.GetProcesses() );
                int index = allProcesses.FindIndex( p => p.ProcessName.ToLower() == ProcessName.ToLower() );
                if (index >= 0 && !State)
                {
                    State = true;
                    if (StateChanged != null)
                        StateChanged.Invoke( State );
                }
                else if (index < 0 && State)
                {
                    State = false;
                    if (StateChanged != null)
                        StateChanged.Invoke( State );
                }
            }
            catch (System.Exception ex)
            {
                Debug.Assert( false, "Error in GetState()\n\n" + ex.Message );
            }

        }
Пример #29
0
 private static void UseGrenade(List<Item> inventory, string itemName, NpcAndPc monster)
 {
     monster.HitPoints -= 200;
     inventory[inventory.FindIndex(p => p.ItemName.ToUpper().Equals(itemName))].ItemQuantity--;
     WriteLine(monster.Name + " gets hit for 200 points of damage.");
     WriteLine(monster.Name + " has " + monster.HitPoints + " HP left.");
 }
Пример #30
0
        public ReadOnlyMesh(IEnumerable<Triangle> triangles)
        {
            List<Vertex> vertices = new List<Vertex>();
            List<int> triangleIndices = new List<int>();

            foreach (Triangle t in triangles)
            {
                int[] triangle = new int[3];
                for (int j = 0; j < 3; j++)
                {
                    Vertex v = t[0].ShallowClone();
                    int index = vertices.FindIndex(item => v.Equals(item));
                    if (index != -1)
                    {
                        triangle[j] = index;
                    }
                    else
                    {
                        triangle[j] = vertices.Count - 1;
                    }
                }
                triangleIndices.AddRange(triangle);
            }

            Vertices = new ReadOnlyCollection<Vertex>(vertices);
            Indices = new ReadOnlyCollection<int>(triangleIndices);
        }
Пример #31
0
        private void RemoveMiniGroupList(string namePerson, TypeWorkout arg)
        {
            var item = MiniGroupList?.FindIndex((x => x.NamePerson.Equals(namePerson)));

            if (item == null)
            {
                return;
            }
            MiniGroupList.RemoveAt((int)item);
        }
 private static void DropdownForCourses(List <Student> students, out List <Course> courses, out List <SelectListItem> stringCourses)
 {
     courses       = students.Select(x => x.StudentCourses?.FirstOrDefault(y => y.Priority == 1)?.Course).DistinctBy(x => $"{x.Title} {x.StartYear.Year}").ToList();
     stringCourses = new List <SelectListItem>();
     foreach (var p in courses)
     {
         stringCourses?.Add(new SelectListItem {
             Value = courses?.FindIndex(a => a == p).ToString(), Text = $"{p.Title} {p.StartYear.Year}"
         });
     }
     stringCourses.Add(new SelectListItem {
         Value = null, Text = ""
     });
 }
        /// <summary>
        ///     Marca como seleccionadas los generos que tenga el creador de contenido
        /// </summary>
        private List <Genero> InicializarEstadoCheckBox(List <Genero> generos)
        {
            foreach (var genero in _creadorContenidoAEditar.generos)
            {
                var index = generos?.FindIndex(g => g.id == genero.id);
                if (index != null)
                {
                    generos[(int)index].seleccionado = true;
                    _listaGenero.Add(generos[(int)index]);
                }
            }

            return(generos);
        }
        /// <summary>
        ///     Recupera los generos de la cancion y marca como seleccionadas los generos que tenga la cancion
        /// </summary>
        private async Task <List <Genero> > InicializarEstadoCheckBox(List <Genero> generos)
        {
            _cancionAEditar.generos = await CancionClient.GetGenerosFromCancion(_cancionAEditar.id, _idAlbum);

            foreach (var genero in _cancionAEditar.generos)
            {
                var index = generos?.FindIndex(g => g.id == genero.id);
                if (index != null)
                {
                    generos[(int)index].seleccionado = true;
                    _listaGeneros.Add(generos[(int)index]);
                }
            }

            return(generos);
        }
Пример #35
0
        private ColumnModel BuildColumnModel(ColumnRawModel rawColumn, List <IndexColumnModel>?pkCols, List <ColumnRef>?fkList)
        {
            string clrName = ToColCrlName(rawColumn.DbName);

            var pkIndex = pkCols?.FindIndex(c => c.DbName.Equals(rawColumn.DbName));

            PkInfo?pkInfo = null;

            if (pkIndex >= 0 && pkCols != null)
            {
                pkInfo = new PkInfo(pkIndex.Value, pkCols[pkIndex.Value].IsDescending);
            }

            return(new ColumnModel(
                       name: clrName,
                       dbName: rawColumn.DbName,
                       ordinalPosition: rawColumn.OrdinalPosition,
                       columnType: this.Database.GetColType(raw: rawColumn),
                       pk: pkInfo,
                       identity: rawColumn.Identity,
                       defaultValue: this.Database.ParseDefaultValue(rawColumn.DefaultValue),
                       fk: fkList));
        }
Пример #36
0
        public void detect_surfaces(ref List <pslg_datastructure.surface_store> set_surfaces)
        {
            // Find the closed loop which are not self intersecting
            // transfer to temporary nodes and temporary edges
            // List<map_node> temp_border_nodes = new List<map_node>();
            List <map_edge> temp_border_edges = new List <map_edge>();

            //temp_border_nodes = the_squaregrid.border_nodes;
            temp_border_edges.AddRange(the_squaregrid.border_edges);

            //bool is_closed = false;
            //int i, j;
            // temporary surfaces
            List <pslg_datastructure.surface_store> temp_surfaces = new List <pslg_datastructure.surface_store>();


            while (temp_border_edges.Count > 0)                              // loop until all the border edges are visited
            {
                List <map_edge> temp_border_edges_1 = new List <map_edge>(); // border edge sublist 1
                temp_border_edges_1.AddRange(temp_border_edges);             // add the main list to sublist 1
                temp_border_edges_1.RemoveAt(0);                             // remove the first edge


                List <map_edge> temp_border_edges_2 = new List <map_edge>(); // border edge sublist 2
                temp_border_edges_2.Add(temp_border_edges[0]);               // add only the first edge frpm mail list
                int current_edge_end_node = temp_border_edges_2[0].index_1;  // only one object is at the list


                while (temp_border_edges_1.Count > 0)
                {
                    map_edge connected_edge = temp_border_edges_1.Find(obj => obj.index_0 == current_edge_end_node || obj.index_1 == current_edge_end_node); // find the connected edge
                    if (connected_edge != null)
                    {
                        if (connected_edge.index_1 == current_edge_end_node) // if the edge end
                        {
                            // then the orientation is towards this point so reverse orientation
                            connected_edge.change_orientation();
                        }

                        current_edge_end_node = connected_edge.index_1;                                                         // index 0 is connected
                        temp_border_edges_2.Add(connected_edge);                                                                // add to the sub list
                        temp_border_edges_1.RemoveAt(temp_border_edges_1.FindIndex(obj => obj.Equals(connected_edge) == true)); //remove from the sub list 1
                    }
                    else
                    {
                        break; // exit because there is no edge connected to the current edge end node
                    }
                }
                //_________________________________________
                if (temp_border_edges_2[0].index_0 == current_edge_end_node) // we started with index_0 so check whether index_1 is connected to the last in the list
                {
                    // pslg_datastructure Edges and Points
                    List <pslg_datastructure.edge2d>  surf_edges  = new List <pslg_datastructure.edge2d>();
                    List <pslg_datastructure.point2d> surf_points = new List <pslg_datastructure.point2d>();

                    // closed boundary is confirmed
                    List <map_node> temp_border_nodes = new List <map_node>();
                    foreach (map_edge edg in temp_border_edges_2)
                    {
                        map_node the_node_1 = the_squaregrid.all_nodes[edg.index_0];
                        map_node the_node_2 = the_squaregrid.all_nodes[edg.index_1];

                        //pslg_datastructure.point2d pt1,pt2;

                        // Add first node
                        if (temp_border_nodes.Exists(obj => obj.Equals(the_node_1) == true) == false)
                        {
                            temp_border_nodes.Add(the_node_1);
                            //pslg_datastructure.point2d pt1 = new pslg_datastructure.point2d(surf_points.Count, the_node_1.x, the_node_1.y);
                            surf_points.Add(new pslg_datastructure.point2d(surf_points.Count, the_node_1.x, the_node_1.y));
                        }

                        // Add second node
                        if (temp_border_nodes.Exists(obj => obj.Equals(the_node_2) == true) == false)
                        {
                            temp_border_nodes.Add(the_node_2);
                            //pslg_datastructure.point2d pt2 = new pslg_datastructure.point2d(surf_points.Count, the_node_2.x, the_node_2.y);
                            surf_points.Add(new pslg_datastructure.point2d(surf_points.Count, the_node_2.x, the_node_2.y));
                        }

                        // Add the edges
                        pslg_datastructure.point2d pt1 = surf_points.Find(obj => obj.Equals(new pslg_datastructure.point2d(-1, the_node_1.x, the_node_1.y)) == true);
                        pslg_datastructure.point2d pt2 = surf_points.Find(obj => obj.Equals(new pslg_datastructure.point2d(-1, the_node_2.x, the_node_2.y)) == true);

                        surf_edges.Add(new pslg_datastructure.edge2d(surf_edges.Count, pt1, pt2));
                    }

                    // check the surface orientation
                    pslg_datastructure.surface_store t_surf = new pslg_datastructure.surface_store(temp_surfaces.Count, surf_points, surf_edges, temp_surfaces.Count);

                    //if (t_surf.signedpolygonarea() < 0)// check whether the outter surface is oriented anti clockwise (negative area = clockwise)
                    //{
                    //    // clockwise orientation detected so reverse the orientation to be anti-clockwise
                    //    t_surf.reverse_surface_orinetation();
                    //}

                    temp_surfaces.Add(t_surf);
                    //System.Threading.Thread.Sleep(200);
                }

                foreach (map_edge edg in temp_border_edges_2)
                {
                    //remove from the main edge
                    temp_border_edges.RemoveAt(temp_border_edges.FindIndex(obj => obj.Equals(edg) == true));
                }
            }

            // sort the surfaces with surface area
            temp_surfaces = temp_surfaces.OrderBy(obj => obj.surface_area).ToList();

            // Set the polygon inside polygon
            List <int> skip_index = new List <int>();

            for (int i = 1; i < temp_surfaces.Count; i++)
            {
                for (int j = i - 1; j >= 0; j--) // cycle through all the other surface except this one
                {
                    if (skip_index.Contains(j) == true)
                    {
                        continue; // skip the nested surfaces
                    }

                    bool is_contain = true;                                                   // variable to store the point is inside true or false
                    foreach (pslg_datastructure.point2d pt in temp_surfaces[j].surface_nodes) // cycle thro all the point of j_th polygon
                    {
                        if (temp_surfaces[i].pointinpolygon(pt.x, pt.y) == false)             // check whether outter polygon contains the inner polygon
                        {
                            is_contain = false;
                            break;
                        }
                    }

                    if (is_contain == true)
                    {
                        skip_index.Add(j);                                            // skip index is used to avoid adding nested surfaces
                        temp_surfaces[i].set_inner_surfaces(temp_surfaces[j]);
                        temp_surfaces[j].set_encapsulating_surface(temp_surfaces[i]); // also set the encapsulating surface id
                    }
                }
            }

            // Surface detection complete add to the main list
            set_surfaces = new List <pslg_datastructure.surface_store>();
            set_surfaces.AddRange(temp_surfaces);
        }
Пример #37
0
        public List <Sys_MenuResult> GetEmpMenuTree(Sys_MenuParam param)
        {
            this.CheckSession();
            List <Sys_MenuResult> allRet          = new List <Sys_MenuResult>();
            List <Sys_MenuResult> ret             = new List <Sys_MenuResult>();
            List <int?>           arrHasModuleIDs = new List <int?>();

            try
            {
                //Sys_Module._.OrderSeq.At("b"), Sys_Module._.ActionCode.At("b"), Sys_Module._.ModuleCode.At("b"), Sys_Module._.ModuleName.At("b"), Sys_Module._.TargetForm.At("b"), Sys_Module._.ModuleID.At("b")
                #region 获取对应员工角色与权限
                List <Sys_RoleRight> roleRightList = new List <Sys_RoleRight>();
                Sys_EmpDataRight     formRight     = this.Select <Sys_EmpDataRight>(Sys_EmpDataRight._.EmpID == this.SessionInfo.UserID && Sys_EmpDataRight._.IsDeleted == false && Sys_EmpDataRight._.GCompanyID == this.SessionInfo.CompanyID);
                if (formRight != null)
                {
                    int?[] arrRightID = formRight.RoleIDs.Split(',').Where(a => a.ToStringHasNull().Trim() != "").Select(a => (int?)a.ToInt32()).ToArray();
                    if (arrRightID.Length > 0)
                    {
                        roleRightList = this.SelectList <Sys_RoleRight>(Sys_RoleRight._.RoleID.In(arrRightID) && Sys_RoleRight._.IsDeleted == false);
                        arrHasModuleIDs.AddRange(roleRightList.Select(a => a.ModuleID).Distinct().ToList());
                    }
                }
                #endregion
                #region 获取对应员工个人权限
                List <Sys_EmpRight> lstEmpRight = new List <Sys_EmpRight>();
                lstEmpRight = this.SelectList <Sys_EmpRight>(Sys_EmpRight._.EmpID == this.SessionInfo.UserID && Sys_EmpRight._.IsDeleted == false);
                arrHasModuleIDs.AddRange(lstEmpRight.Select(a => a.ModuleID).Distinct().ToList());
                #endregion
                #region 获取菜单列表
                List <Sys_Module> lstModule   = new List <Sys_Module>();
                WhereClip         whereModule = Sys_Module._.IsDeleted == false;
                if (lstEmpRight.Count > 0)
                {
                    whereModule = whereModule && Sys_Module._.ModuleID.In(lstEmpRight.ToArray());
                }
                lstModule = this.SelectList <Sys_Module>(whereModule);
                List <string> lstEmpMdlCode = lstModule.Where(a => a.ModuleCode.ToStringHasNull() != "").Select(a => a.ModuleCode.ToStringHasNull().Trim()).ToList();
                ret = this.SelectList <Sys_MenuResult>(Sys_Menu._.IsDeleted == false, Sys_Menu._.MenuCode.Asc);
                ret = ret.Where(a => !lstEmpMdlCode.Contains(a.MenuCode)).ToList();
                foreach (Sys_Module info in lstModule)
                {
                    ret.Add(new Sys_MenuResult()
                    {
                        MenuID     = info.ModuleID * -1,
                        MenuCode   = info.ModuleCode,
                        MenuName   = info.ModuleName,
                        TargetForm = info.TargetForm,
                        OrderSeq   = info.OrderSeq,
                        MenuType   = "Leaf"
                    });
                }
                #endregion
                #region old code
                //GroupByClip groupByClip = new GroupByClip("b.OrderSeq,b.ActionCode,b.ModuleCode,b.ModuleName,b.TargetForm,b.ModuleID");
                //DataTable lstEmpModeule = this.SelectList<Sys_EmpRight, Sys_Module>(JoinType.InnerJoin
                //                , Sys_EmpRight._.ModuleID == Sys_Module._.ModuleID.At("b")
                //                  , 1, int.MaxValue
                //                  , new List<Field>() {Sys_Module._.OrderSeq.At("b"), Sys_Module._.ActionCode.At("b"), Sys_Module._.ModuleCode.At("b"), Sys_Module._.ModuleName.At("b"), Sys_Module._.TargetForm.At("b"), Sys_Module._.ModuleID.At("b") },
                //                  Sys_EmpRight._.EmpID == this.SessionInfo.UserID && Sys_EmpRight._.IsDeleted == false
                //                  , Sys_Module._.ModuleCode.At("b").Asc, groupByClip, null).ResultJoinList;
                //List<string> lstEmpMdlCode = lstEmpModeule.Select("ModuleCode<>''").Select(a => a["ModuleCode"].ToStringHasNull()).ToList();
                //ret = this.SelectList<Sys_MenuResult>(Sys_Menu._.IsDeleted == false, Sys_Menu._.MenuCode.Asc);
                //ret = ret.Where(a => !lstEmpMdlCode.Contains(a.MenuCode)).ToList();
                //#region 将模块添加至菜单集合
                //foreach (DataRow row in lstEmpModeule.Rows)
                //{
                //    ret.Add(new Sys_MenuResult()
                //    {
                //        MenuID = row["ModuleID"].ToInt32() * -1,
                //        MenuCode = row["ModuleCode"].ToStringHasNull(),
                //        MenuName = row["ModuleName"].ToStringHasNull(),
                //        TargetForm = row["TargetForm"].ToStringHasNull(),
                //        OrderSeq = row["OrderSeq"].ToInt32(),
                //        MenuType = "Leaf"
                //    });
                //}
                //#endregion
                #endregion
                #region  指定的次序号重新排序
                List <Sys_MenuResult> newRet = new List <Sys_MenuResult>();
                int atIdx = 0;
                for (int i = 3; i <= 3 * 5; i = i + 3)
                {
                    newRet = ret.Where(a => a.MenuCode.Length == i).OrderBy(a => a.OrderSeq).ToList();
                    if (i > 3)
                    {
                        foreach (Sys_MenuResult info in newRet)
                        {
                            atIdx = allRet.FindIndex(a => a.MenuCode.Length == i - 3 && info.MenuCode.StartsWith(a.MenuCode));
                            if (atIdx < 0)
                            {
                                continue;
                            }
                            allRet.Insert(atIdx + 1, info);
                        }
                    }
                    else
                    {
                        allRet = ret.Where(a => a.MenuCode.Length == i).OrderBy(a => a.OrderSeq).ToList();
                    }
                }
                #endregion
            }
            catch (WarnException exp)
            {
                throw exp;
            }
            catch (System.Exception exp)
            {
                LogInfoBLL.WriteLog(this.SessionInfo, exp);
            }
            return(allRet);
        }
Пример #38
0
        private void ApplyQuestCampaignParams(string[] campaignIds)
        {
            this.AcquiredUnitExp = new int[this.mRaidResult.members.Count];
            if (campaignIds != null)
            {
                QuestCampaignData[] questCampaigns = MonoSingleton <GameManager> .GetInstanceDirect().FindQuestCampaigns(campaignIds);

                List <UnitData> members  = this.mRaidResult.members;
                float[]         numArray = new float[members.Count];
                float           num1     = 1f;
                for (int index = 0; index < numArray.Length; ++index)
                {
                    numArray[index] = 1f;
                }
                // ISSUE: object of a compiler-generated type is created
                // ISSUE: variable of a compiler-generated type
                RaidResultWindow.\u003CApplyQuestCampaignParams\u003Ec__AnonStorey26C paramsCAnonStorey26C = new RaidResultWindow.\u003CApplyQuestCampaignParams\u003Ec__AnonStorey26C();
                foreach (QuestCampaignData questCampaignData in questCampaigns)
                {
                    // ISSUE: reference to a compiler-generated field
                    paramsCAnonStorey26C.data = questCampaignData;
                    // ISSUE: reference to a compiler-generated field
                    if (paramsCAnonStorey26C.data.type == QuestCampaignValueTypes.ExpUnit)
                    {
                        // ISSUE: reference to a compiler-generated field
                        if (string.IsNullOrEmpty(paramsCAnonStorey26C.data.unit))
                        {
                            // ISSUE: reference to a compiler-generated field
                            num1 = paramsCAnonStorey26C.data.GetRate();
                        }
                        else
                        {
                            // ISSUE: reference to a compiler-generated method
                            int index = members.FindIndex(new Predicate <UnitData>(paramsCAnonStorey26C.\u003C\u003Em__2D3));
                            if (index >= 0)
                            {
                                // ISSUE: reference to a compiler-generated field
                                numArray[index] = paramsCAnonStorey26C.data.GetRate();
                            }
                        }
                    }
                    else
                    {
                        // ISSUE: reference to a compiler-generated field
                        if (paramsCAnonStorey26C.data.type == QuestCampaignValueTypes.ExpPlayer)
                        {
                            // ISSUE: reference to a compiler-generated field
                            this.mRaidResult.pexp = Mathf.RoundToInt((float)this.mRaidResult.pexp * paramsCAnonStorey26C.data.GetRate());
                        }
                    }
                }
                int uexp = this.mRaidResult.uexp;
                for (int index = 0; index < numArray.Length; ++index)
                {
                    float num2 = 1f;
                    if ((double)num1 != 1.0 && (double)numArray[index] != 1.0)
                    {
                        num2 = num1 + numArray[index];
                    }
                    else if ((double)num1 != 1.0)
                    {
                        num2 = num1;
                    }
                    else if ((double)numArray[index] != 1.0)
                    {
                        num2 = numArray[index];
                    }
                    this.AcquiredUnitExp[index] = Mathf.RoundToInt((float)uexp * num2);
                }
            }
            else
            {
                for (int index = 0; index < this.AcquiredUnitExp.Length; ++index)
                {
                    this.AcquiredUnitExp[index] = this.mRaidResult.uexp;
                }
            }
        }
Пример #39
0
        /// <summary>
        /// 检查网格
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name="checkRows">检查行(为空表全部)</param>
        /// <param name="uniqueCol">唯一列名(为空则没有主键)</param>
        /// <param name="errMsg">错误信息</param>
        /// <param name="errCol">错误列名</param>
        /// <param name="errRow">错误行索引</param>
        /// <returns>是否有重复记录</returns>
        public bool CheckDetails(DataTable dtSource, List <int> checkRows, string[] uniqueCol, out string errMsg, out string errCol, out int errRow)
        {
            errMsg = string.Empty;
            errCol = string.Empty;
            errRow = -1;
            for (int index = 0; index < dtSource.Rows.Count; index++)
            {
                if (checkRows != null &&
                    checkRows.FindIndex((x) => { return(x == index); }) < 0)
                {
                    continue;
                }

                DataRow dRow = dtSource.Rows[index];
                //重复性检查
                if (uniqueCol != null)
                {
                    string colName = string.Empty;
                    for (int temp = index + 1; temp < dtSource.Rows.Count; temp++)
                    {
                        bool isUnique = false;
                        foreach (string name in uniqueCol)
                        {
                            errCol   = name;
                            colName += (name + ",");
                            if (dRow[name].ToString() != dtSource.Rows[temp][name].ToString())
                            {
                                isUnique = true;
                                break;
                            }
                        }

                        if (!isUnique)
                        {
                            errRow = temp;
                            errMsg = "【{0}】不允许重复,请重新录入";
                            return(false);
                        }
                    }
                }

                //按每列对正则表达式判断
                for (int count = 0; count < dtSource.Columns.Count; count++)
                {
                    object key = "Regex";
                    if (dtSource.Columns[count].ExtendedProperties.Contains(key))
                    {
                        string express = dtSource.Columns[count].ExtendedProperties[key].ToString();
                        if (express != string.Empty)
                        {
                            if (Regex.IsMatch(dRow[count].ToString(), express))
                            {
                                continue;
                            }
                            else
                            {
                                errMsg = "【{0}】的录入数据格式不正确,请重新录入";
                                errCol = dtSource.Columns[count].ColumnName;
                                errRow = index;
                                return(false);
                            }
                        }
                    }
                }

                if (Convert.ToDateTime(dRow["ValidityDate"].ToString()) < Convert.ToDateTime(System.DateTime.Now.Date.ToLongDateString()))
                {
                    errMsg = "时间不能小于当前时间";
                    errCol = dtSource.Columns["ValidityDate"].ColumnName;
                    errRow = index;
                    return(false);
                }

                if (CampareLarge(Math.Abs(Convert.ToDecimal(dRow["StockPrice"].ToString())), Math.Abs(Convert.ToDecimal(dRow["RetailPrice"].ToString()))))
                {
                    errMsg = "进货价不能大于售货价格";
                    errCol = dtSource.Columns["StockPrice"].ColumnName;
                    errRow = index;
                    return(false);
                }
            }

            return(true);
        }
Пример #40
0
        public void Reset()
        {
            Invoke(
                new Action(
                    () =>
                    loadingLabel.Text = "Resetting data..."));

            if (_projectFileCreated)
            {
                try
                {
                    string localPath = null;
                    Invoke(new Action(() => localPath = localPathTextBox.Text));
                    File.Delete(localPath);
                    _projectFileCreated = false;
                }
                catch (Exception ex)
                {
                    Invoke(
                        new Action(
                            () =>
                            Popup.ShowPopup(this, SystemIcons.Error,
                                            "Error while deleting the project file.",
                                            ex, PopupButtons.Ok)));
                }
            }

            if (_projectConfigurationEdited)
            {
                string name = null;
                Invoke(
                    new Action(
                        () =>
                        name = nameTextBox.Text));
                _projectConfiguration.RemoveAt(_projectConfiguration.FindIndex(item => item.Name == name));

                try
                {
                    File.WriteAllText(Program.ProjectsConfigFilePath, Serializer.Serialize(_projectConfiguration));
                    _projectConfigurationEdited = false;
                }
                catch (Exception ex)
                {
                    Invoke(
                        new Action(
                            () =>
                            Popup.ShowPopup(this, SystemIcons.Error,
                                            "Error while deleting the project file.",
                                            ex, PopupButtons.Ok)));
                }
            }

            if (_phpFileCreated)
            {
                var phpFilePath = Path.Combine(Program.Path, "Projects", nameTextBox.Text, "statistics.php");
                try
                {
                    File.Delete(phpFilePath);
                    _phpFileCreated = false;
                }
                catch (Exception ex)
                {
                    Invoke(
                        new Action(
                            () =>
                            Popup.ShowPopup(this, SystemIcons.Error,
                                            "Error while deleting \"statistics.php\" again.",
                                            ex, PopupButtons.Ok)));
                }
            }

            if (_phpFileUploaded)
            {
                try
                {
                    _ftp.DeleteFile("statistics.php");
                    _phpFileUploaded = false;
                }
                catch (Exception ex)
                {
                    Invoke(
                        new Action(
                            () =>
                            Popup.ShowPopup(this, SystemIcons.Error,
                                            "Error while deleting \"statistics.php\" on the server again.",
                                            ex, PopupButtons.Ok)));
                }
            }

            bool useStatistics = false;

            Invoke(new Action(() => useStatistics = useStatisticsServerRadioButton.Checked));
            if (useStatistics)
            {
                Settings.Default.ApplicationID -= 1;
                Settings.Default.Save();
            }

            SetUiState(true);
            if (_mustClose)
            {
                Invoke(new Action(Close));
            }
        }
Пример #41
0
        private void EditItem()
        {
            if (!HasActiveLink())
            {
                return;
            }

            var editLink = linkTable[datagrid_Links.SelectedIndex];

            //Set new Link
            var links = new List <string>();
            int l     = editLink.Index; //Get current link

            if (IsReply)
            {
                foreach (var entry in ParentWindow.SelectedConv.EntryList)
                {
                    links.Add($"{entry.NodeCount}: {entry.LineStrRef} {entry.Line}");
                }
            }
            else
            {
                foreach (var entry in ParentWindow.SelectedConv.ReplyList)
                {
                    links.Add($"{entry.NodeCount}: {entry.LineStrRef} {entry.Line}");
                }
            }
            string ldlg = InputComboBoxWPF.GetValue(this, "Pick the next dialogue node to link to", "Dialogue Editor", links, links[l]);

            if (string.IsNullOrEmpty(ldlg))
            {
                return;
            }
            editLink.Index = links.FindIndex(ldlg.Equals);

            if (!IsReply)
            {
                //Set StrRef
                int  strRef   = 0;
                bool isNumber = false;
                while (!isNumber)
                {
                    var response = PromptDialog.Prompt(this, "Enter the TLK String Reference for the dialogue wheel:", "Link Editor", editLink.ReplyStrRef.ToString());
                    if (response == null || response == "0")
                    {
                        return;
                    }
                    isNumber = int.TryParse(response, out strRef);
                    if (!isNumber || strRef <= 0)
                    {
                        var wdlg = MessageBox.Show("The string reference must be a positive whole number.", "Dialogue Editor", MessageBoxButton.OKCancel);
                        if (wdlg == MessageBoxResult.Cancel)
                        {
                            return;
                        }
                    }
                }
                editLink.ReplyStrRef = strRef;

                ////Set GUI Reply style
                var rc = editLink.RCategory; //Get current link

                string rdlg = InputComboBoxWPF.GetValue(this, "Pick the wheel position or interrupt:", "Dialogue Editor", Enums.GetNames <EReplyCategory>(), rc.ToString());

                if (string.IsNullOrEmpty(rdlg))
                {
                    return;
                }
                rc = Enums.Parse <EReplyCategory>(rdlg);
                editLink.RCategory = rc;
            }
            ParseLink(editLink);
            ReOrderTable();
            NeedsSave = true;
        }
        public override void ModifyTooltips(List <TooltipLine> tooltips)
        {
            if (SGAWorld.downedHellion < 2)
            {
                TooltipLine tt = tooltips.FirstOrDefault(x => x.Name == "Material" && x.mod == "Terraria");
                if (tt != null)
                {
                    int index = tooltips.FindIndex(here => here == tt);
                    tooltips.RemoveAt(index);
                }
            }
            else
            {
                tooltips.Add(new TooltipLine(mod, "Nmxx", "Useable in crafting"));
            }

            if (SGAWorld.downedSPinky && SGAWorld.downedCratrosityPML && SGAWorld.downedWraiths > 3)
            {
                if (SGAWorld.downedHellion > 0)
                {
                    tooltips.Add(new TooltipLine(mod, "Nmxx", "Hold 'left control' while you use the item to skip Hellion Core, this costs 25 Souls of Byte"));
                }
                if (SGAWorld.downedHellion < 2)
                {
                    if (SGAWorld.downedHellion == 0)
                    {
                        tooltips.Add(new TooltipLine(mod, "Nmxx", "'Well done " + SGAmod.HellionUserName + ". Yes, I know your real name behind that facade you call " + Main.LocalPlayer.name + ".'"));
                        tooltips.Add(new TooltipLine(mod, "Nmxx", "'And thanks to your Dragon's signal, I have found my way to your world, this one tear which will let me invade your puny little " + Main.worldName + "'"));
                        tooltips.Add(new TooltipLine(mod, "Nmxx", "'Spend what little time you have left meaningful, if you were expecting to save him, I doubt it'"));
                        tooltips.Add(new TooltipLine(mod, "Nmxx", "'But let us not waste anymore time, come, face me'"));
                    }
                    else
                    {
                        tooltips.Add(new TooltipLine(mod, "Nmxx", "'Getting closer, I guess now I'll just have to use more power to stop you'"));
                        tooltips.Add(new TooltipLine(mod, "Nmxx", "'But enough talk, lets finish this'"));
                    }
                }
                else
                {
                    tooltips.Add(new TooltipLine(mod, "Nmxx", "'Hmp, very Well done " + SGAmod.HellionUserName + ", you've bested me, this time"));
                    tooltips.Add(new TooltipLine(mod, "Nmxx", "But next time you won't be so lucky..."));
                    tooltips.Add(new TooltipLine(mod, "Nmxx", "My tears have stablized..."));
                    tooltips.Add(new TooltipLine(mod, "Nmxx", "Enjoy your fancy reward, you've earned that much..."));
                    tooltips[0].text += " (Stablized)";
                }
                tooltips.Add(new TooltipLine(mod, "Nmxx", "Tears a hole in the bastion of reality to bring forth the Paradox General, Helen 'Hellion' Weygold"));
                tooltips.Add(new TooltipLine(mod, "Nmxx", "Non Consumable"));


                foreach (TooltipLine line in tooltips)
                {
                    string text    = line.text;
                    string newline = "";
                    for (int i = 0; i < text.Length; i += 1)
                    {
                        newline += Idglib.ColorText(Color.Lerp(Color.White, Main.hslToRgb((Main.rand.NextFloat(0, 1)) % 1f, 0.75f, Main.rand.NextFloat(0.25f, 0.5f)), MathHelper.Clamp(0.5f + (float)Math.Sin(Main.GlobalTime * 2f) / 1.5f, 0.2f, 1f)), text[i].ToString());
                    }
                    line.text = newline;
                }
            }
            else
            {
                tooltips = new List <TooltipLine>();
            }
        }
Пример #43
0
        public void UpdateDummyList(Notification notification)
        {
            int index = notificationList.FindIndex(st => st.ID == notification.ID);

            notificationList[index] = notification;
        }
Пример #44
0
        public FKelolaUser(string iduser)
        {
            InitializeComponent();
            this.SetControlFrom();
            this.Load += (sender, e) =>
            {
                idakses = CbHakAkses.LoadAkses();
                CbHakAkses.SelectedIndex = 0;

                foreach (DataRow b in A.GetData("SELECT `username`,`password`,`id_akses` FROM `m_user` WHERE `id_user`=" + iduser).Rows)
                {
                    TbUsername.Text          = b["username"].ToString();
                    TbPassword.Text          = b["password"].ToString();
                    CbHakAkses.SelectedIndex = idakses.FindIndex(x => x.Equals(b["id_akses"].ToString()));
                }

                CbHakAkses.Enabled = false;
                if (S.GetUseracces() == "1")
                {
                    CbHakAkses.Enabled = true;
                }
            };

            BSimpan.Click += (sender, e) => {
                A.SetQueri("SELECT COUNT(*) FROM `m_user` WHERE `userdelete`='N' AND `username`='" + TbUsername.Text + "' AND `id_user`<>'" + iduser + "'");
                if (A.GetQueri().SingelData().ToInteger() > 1)
                {
                    MessageBox.Show("Nama Username telah digunakan Orang lain!!", "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (TbUsername.Text == string.Empty)
                {
                    MessageBox.Show("Username Kosong!", "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (TbPassword.Text == string.Empty)
                {
                    MessageBox.Show("Password Kosong!", "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (CbHakAkses.Text == string.Empty)
                {
                    MessageBox.Show("Hak Akses Kosong!", "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (TbPassword.Text.Length <= 3)
                {
                    MessageBox.Show("Password Harus Lebih dari 3 Karakter", "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (TbPassword.Text != TbUlangPassword.Text)
                {
                    MessageBox.Show("Password Tidak Sesuai!", "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    if (MessageBox.Show("Simpan data ini?", "Pertanyaan?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string pass = "";
                        if (TbUlangPassword.TextLength > 0)
                        {
                            if (TbPassword.Text == TbUlangPassword.Text)
                            {
                                pass = "******" + TbPassword.Text + "')";
                            }
                        }
                        A.SetQueri("UPDATE `m_user` SET `id_akses` = '" + idakses[CbHakAkses.SelectedIndex] + "', `username` = '" + TbUsername.Text + "' " + pass + " WHERE `id_user` =" + iduser + ";");
                        if (A.GetQueri().ManipulasiData())
                        {
                            MessageBox.Show("Berhasil Di Simpan!", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            if (iduser == S.GetUserid())
                            {
                                Application.Restart();
                                Environment.Exit(0);
                            }
                            else
                            {
                                Close();
                            }
                        }
                        else
                        {
                            MessageBox.Show("Gagal Menyimpan!", "Kesalahan", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            };
        }
 private int FindIndexOfChannelId(string id)
 {
     return(Channels.FindIndex(channel => channel.ChannelId == id));
 }
 private int FindIndexOfSettingId(string id)
 {
     return(Settings.FindIndex(set => set.ChannelId == id));
 }
Пример #47
0
        ///<summary>Scans the convert scripts for preferences that are not present in the database and addes them.</summary>
        ///<param name="logFileName">If this is blank, will display the results in a MessageBox, otherwise writes the results to the file.</param>
        public static void AddMissingPreferences(string convertDbFileName, string logFileName = "")
        {
            //This method is not exhaustive. I didn't bother making this script work for preferences that were added before version 14.
            List <PrefName> listPrefs = Enum.GetValues(typeof(PrefName)).OfType <PrefName>().Where(x => !x.In(
                                                                                                       //HQ only prefs
                                                                                                       PrefName.AsteriskServerHeartbeat,
                                                                                                       PrefName.AsteriskServerIp,
                                                                                                       PrefName.CustListenerConnectionRequestTimeoutMS,
                                                                                                       PrefName.CustListenerHeartbeatFrequencyMinutes,
                                                                                                       PrefName.CustListenerPort,
                                                                                                       PrefName.CustListenerSocketTimeoutMS,
                                                                                                       PrefName.CustListenerTransmissionTimeoutMS,
                                                                                                       PrefName.HQTriageCoordinator,
                                                                                                       PrefName.VoiceMailMonitorHeartBeat,
                                                                                                       PrefName.VoiceMailDeleteAfterDays,
                                                                                                       PrefName.WebCamFrequencyMS,
                                                                                                       PrefName.StopWebCamSnapshot,
                                                                                                       PrefName.VoiceMailArchivePath,
                                                                                                       PrefName.VoiceMailCreatePath,
                                                                                                       PrefName.VoiceMailOriginationPath,
                                                                                                       PrefName.VoiceMailSMB2UserName,
                                                                                                       PrefName.VoiceMailSMB2Password,
                                                                                                       PrefName.VoiceMailSMB2Enabled,
                                                                                                       PrefName.CustomersHQDatabase,
                                                                                                       PrefName.CustomersHQMySqlPassHash,
                                                                                                       PrefName.CustomersHQMySqlUser,
                                                                                                       PrefName.CustomersHQServer,
                                                                                                       PrefName.TriageCalls,
                                                                                                       PrefName.TriageRedCalls,
                                                                                                       PrefName.TriageRedTime,
                                                                                                       PrefName.TriageTime,
                                                                                                       PrefName.TriageTimeWarning,
                                                                                                       PrefName.VoicemailCalls,
                                                                                                       PrefName.VoicemailTime,
                                                                                                       PrefName.IntrospectionItems,
                                                                                                       PrefName.AsteriskConferenceApplication,
                                                                                                       PrefName.ServicesHqDatabase,
                                                                                                       PrefName.ServicesHqDoNotConnect,
                                                                                                       PrefName.ServicesHqMySqlUser,
                                                                                                       PrefName.ServicesHqMySqpPasswordObf,
                                                                                                       PrefName.ServicesHqServer,
                                                                                                       //Deprecated prefs
                                                                                                       PrefName.ScannerCompression,
                                                                                                       PrefName.RequiredFieldColor,
                                                                                                       //Secret prefs
                                                                                                       PrefName.UpdateAlterLargeTablesDirectly,
                                                                                                       PrefName.UpdateStreamLinePassword,
                                                                                                       //Clinicpref only prefs
                                                                                                       PrefName.PatientPortalInviteUseDefaults,
                                                                                                       //Not really used
                                                                                                       PrefName.CentralManagerPassSalt,
                                                                                                       PrefName.NotApplicable
                                                                                                       )).ToList();
            List <string>   listLines            = null;
            List <PrefName> listPrefsAdded       = new List <PrefName>();
            List <PrefName> listPrefsUnableToAdd = new List <PrefName>();

            foreach (PrefName pref in listPrefs)
            {
                if (Prefs.GetContainsKey(pref.ToString()))
                {
                    continue;
                }
                if (listLines == null)
                {
                    listLines = GetConvertScriptLines(convertDbFileName);
                }
                Regex insertRegex = new Regex(@"INSERT INTO preference(\s*)\(PrefName,(\s*)ValueString\) (VALUES(\s*)\(|SELECT(\s*))'" + pref.ToString() + "'");
                int   lineIndex   = listLines.FindIndex(x => insertRegex.IsMatch(x) ||
                                                        x.Contains("UPDATE preference SET PrefName='" + pref.ToString()));
                if (lineIndex == -1)
                {
                    listPrefsUnableToAdd.Add(pref);
                    continue;
                }
                string prefCommandLine = listLines[lineIndex];
                while (!prefCommandLine.Contains(";"))
                {
                    prefCommandLine += listLines[++lineIndex];
                }
                string prefCommand = prefCommandLine.Trim();
                if (prefCommand.StartsWith("string"))
                {
                    prefCommand = prefCommand.Substring("string command=".Length).TrimStart('"', '@', '$');
                }
                else
                {
                    prefCommand = prefCommand.Substring("command=".Length).TrimStart('"', '@', '$');
                }
                int endOfCommand = prefCommand.IndexOf("')\";") + 2;
                if (endOfCommand == 1)
                {
                    endOfCommand = prefCommand.IndexOf(")\";") + 1;                        //E.g. command="INSERT INTO preference(PrefName,ValueString) VALUES('RadiologyDateStartedUsing154',"+POut.DateT(DateTime.Now.Date)+")";
                    if (endOfCommand == 0)
                    {
                        endOfCommand = prefCommand.IndexOf("'\";") + 1;                            //E.g. command="INSERT INTO preference(PrefName,ValueString) SELECT 'InsHistExamCodes',ValueString FROM preference WHERE PrefName='InsBenExamCodes'";
                    }
                }
                if (prefCommand.StartsWith("UPDATE preference SET PrefName='"))
                {
                    endOfCommand = prefCommand.IndexOf(";") - 1;                //Eg. command="UPDATE preference SET PrefName='InsChecksFrequency' WHERE PrefName='InsTpChecksFrequency'";
                }
                prefCommand = prefCommand.Substring(0, endOfCommand);
                DataCore.NonQ(prefCommand);
                listPrefsAdded.Add(pref);
            }
            string unableToAdd = string.Join("\r\n", listPrefsUnableToAdd.Select(x => x.ToString()));
            string prefsAdded  = string.Join("\r\n", listPrefsAdded.Select(x => x.ToString()));
            string message     = "";

            if (unableToAdd != "")
            {
                message += "Unable to add these preferences:\r\n" + unableToAdd + "\r\n";
            }
            if (prefsAdded != "")
            {
                message += "Preferences added:\r\n" + prefsAdded + "\r\n";
            }
            if (message == "")
            {
                message += "No preferences added.\r\n";
            }
            message += "Done";
            if (string.IsNullOrEmpty(logFileName))
            {
                MessageBox.Show(message);
            }
            else
            {
                File.AppendAllText(logFileName, message + "\r\n");
            }
            Prefs.RefreshCache();
        }
Пример #48
0
        public void ReadFromStream(TextReader sr)
        {
            Clear();
            m_RootElements = ParseContent(sr.ReadToEnd());

            if (!m_RootElements.Contains("objects"))
            {
                throw new Exception("Invalid PBX project file: no objects element");
            }

            var objects = m_RootElements["objects"].AsDict();

            m_RootElements.Remove("objects");
            m_RootElements.SetString("objects", "OBJMARKER");

            if (m_RootElements.Contains("objectVersion"))
            {
                m_ObjectVersion = m_RootElements["objectVersion"].AsString();
                m_RootElements.Remove("objectVersion");
            }

            var    allGuids        = new List <string>();
            string prevSectionName = null;

            foreach (var kv in objects.values)
            {
                allGuids.Add(kv.Key);
                var el = kv.Value;

                if (!(el is PBXElementDict) || !el.AsDict().Contains("isa"))
                {
                    m_UnknownObjects.values.Add(kv.Key, el);
                    continue;
                }
                var dict        = el.AsDict();
                var sectionName = dict["isa"].AsString();

                if (m_Section.ContainsKey(sectionName))
                {
                    var section = m_Section[sectionName];
                    section.AddObject(kv.Key, dict);
                }
                else
                {
                    UnknownSection section;
                    if (m_UnknownSections.ContainsKey(sectionName))
                    {
                        section = m_UnknownSections[sectionName];
                    }
                    else
                    {
                        section = new UnknownSection(sectionName);
                        m_UnknownSections.Add(sectionName, section);
                    }
                    section.AddObject(kv.Key, dict);

                    // update section order
                    if (!m_SectionOrder.Contains(sectionName))
                    {
                        int pos = 0;
                        if (prevSectionName != null)
                        {
                            // this never fails, because we already added any previous unknown sections
                            // to m_SectionOrder
                            pos  = m_SectionOrder.FindIndex(x => x == prevSectionName);
                            pos += 1;
                        }
                        m_SectionOrder.Insert(pos, sectionName);
                    }
                }
                prevSectionName = sectionName;
            }
            RepairStructure(allGuids);
            RefreshAuxMaps();
        }
Пример #49
0
        }   //  end Update3Ptally

        //  August 2016 -- need to replace tally for STR method when
        //  multiple species in a sample group were tallied by sample group and not
        //  by species.  Replace with sum of expansion factor
        private void UpdateSTRtally(string fileName, string currST, List <LCDDO> justCurrentLCD,
                                    List <CountTreeDO> ctList, List <LCDDO> lcdList)
        {
            //Possibly update this from Sample group instead of strata.  See templeton.
            //  pull count records for STR stratum
            List <CountTreeDO> currentGroups = ctList.FindAll(
                delegate(CountTreeDO cg)
            {
                return(cg.SampleGroup.Stratum.Code == currST);
            });


            string sampleGroupCN = "";
            //  see if TreeDefaultValue_CN is zero indicating BySampleGroup
            int totalTDV = 0;

            foreach (CountTreeDO cg in currentGroups)
            {
                if (cg.TreeDefaultValue_CN != null)
                {
                    //Don't apply if count tree has a CN (meaning its selected coby species)
                    //totalTDV++;
                }//end if
                else
                {
                    string strataCode = "";

                    string sampleGroupCode = "";

                    if (cg.SampleGroup != null)
                    {
                        sampleGroupCode = cg.SampleGroup.Code;
                        if (cg.SampleGroup.Stratum != null)
                        {
                            strataCode = cg.SampleGroup.Stratum.Code;
                        } //end if
                    }     //end if


                    //  replace tally with sum of expansion factor
                    foreach (LCDDO jg in justCurrentLCD)
                    {
                        if (jg.SampleGroup == sampleGroupCode && jg.Stratum == strataCode)
                        {
                            //  find in original to update
                            int nthRow = lcdList.FindIndex(
                                delegate(LCDDO ll)
                            {
                                return(ll.LCD_CN == jg.LCD_CN);
                            });

                            if (nthRow >= 0)
                            {
                                lcdList[nthRow].TalliedTrees = lcdList[nthRow].SumExpanFactor;
                            } //end if
                        }     //end if
                    }   //  end foreach loop

                    totalTDV += 0;
                } //end else
            }     //  end foreach loop

            ////  what was sampling method
            //if (totalTDV == 0.0)
            //{

            //}   //  endif

            return;
        }  //  end UpdateSTRtally
Пример #50
0
 internal bool ContainsProjectIdentifier(string projId)
 {
     return(libraries.FindIndex(x => (x.library == projId)) >= 0);
 }
Пример #51
0
 public int GetIndexForKeyCode(KeyboardKeyCode keyCode)
 {
     return(glyphMappings.FindIndex((x) => x.keyCode == keyCode));
 }
        // Choose which elevator should be called from the chosen column
        public Elevator ChooseElevator()
        {
            List <int> elevatorScores = new List <int>();
            var        chosenColumn   = ChooseColumn();

            foreach (var elevator in chosenColumn.ElevatorList)
            {
                // Initialize score to 0
                int score = 0;

                // Calculate floor difference differently based on whether or not elevator is already at RC or not
                // Remember: Each column has a floor range that its elevators must respect. The RC is not included in the range, so to make the calculations fair, if elevator is already at RC the floor difference will still look normal thanks to the 2nd calculation option as it will start from the column's lowest floor instead of at RC.
                int floorDifference;

                if (elevator.CurrentFloor != Elevator.OriginFloor)
                {
                    floorDifference = elevator.CurrentFloor - chosenColumn.LowestFloor;
                }
                else
                {
                    floorDifference = 0;
                }

                // Prevents use of any offline/under-maintenance elevators
                if (elevator.Status != "online")
                {
                    score = -1;
                }
                else
                {
                    // Bonify score based on floor difference
                    if (floorDifference == 0)
                    {
                        score += 5000;
                    }
                    else
                    {
                        score += 5000 / (Math.Abs(floorDifference) + 1);
                    }

                    // Bonify score based on direction (highest priority)
                    if (elevator.Movement != "idle")
                    {
                        if (floorDifference < 0 && Direction == "down" && elevator.Movement == "down")
                        {
                            // Paths are not crossed, therefore try avoiding the use of this elevator
                            score = 0;
                        }
                        else if (floorDifference > 0 && Direction == "up" && elevator.Movement == "up")
                        {
                            // Paths are not crossed, therefore try avoiding the use of this elevator
                            score = 0;
                        }
                        else
                        {
                            // Paths are crossed, therefore favor this elevator
                            score += 1000;

                            // Calculate next floor difference differently based on whether or not elevator's next floor will be at RC or not
                            int nextFloorDifference;
                            if (elevator.NextFloor != Elevator.OriginFloor)
                            {
                                nextFloorDifference = elevator.NextFloor - chosenColumn.LowestFloor;
                            }
                            else
                            {
                                nextFloorDifference = 0;
                            }

                            // Give redemption points, in worst case scenario where all elevators never cross paths
                            if (nextFloorDifference == 0)
                            {
                                score += 500;
                            }
                            else
                            {
                                score += 500 / (Math.Abs(nextFloorDifference) + 1);
                            }
                        }
                    }

                    // Bonify score on request queue size (the smaller number of pre-existing requests, the faster therefore the better)
                    if (elevator.RequestsQueue.Count <= 3)
                    {
                        score += 1000;
                    }
                    else if (elevator.RequestsQueue.Count <= 7)
                    {
                        score += 250;
                    }
                }
                // Send total score of elevator to the scores list
                elevatorScores.Add(score);
            }

            // Get value of highest score
            int highestScore = -1;

            foreach (int score in elevatorScores)
            {
                if (score > highestScore)
                {
                    highestScore = score;
                }
            }

            // Get the elevator with the highest score (or NULL if all elevators were offline)
            Elevator chosenElevator = null;

            if (highestScore > -1)
            {
                int index = elevatorScores.FindIndex(score => score == highestScore);
                chosenElevator = chosenColumn.ElevatorList[index];

                WriteLine($"Chosen elevator of Column {chosenColumn.ID}: Elevator {chosenElevator.ID}\n");
            }
            return(chosenElevator);
        }
Пример #53
0
        /// <summary>
        /// Process a prop group (logical collection of related props).
        /// </summary>
        /// <param name="group"></param>
        static void ProcessPropGroup(XmlElement group)
        {
            string writeDirectory = group.GetAttribute("folder");

            if (string.IsNullOrEmpty(writeDirectory))
            {
                // If the write directory is unspecified, set it to the
                // current working directory.
                writeDirectory = ".";
            }
            writeDirectory = writeDirectory + "\\";

            Console.WriteLine("Processing {0} group props", group.Name);

            List <Style> style = new List <Style>();

            // Find all of the style elements
            foreach (XmlNode child in group)
            {
                if (child is XmlElement)
                {
                    XmlElement elem = child as XmlElement;
                    if (elem.Name == "style")
                    {
                        string styleName = elem.GetAttribute("name");
                        if (!string.IsNullOrEmpty(styleName))
                        {
                            Style st = new Style();
                            st.name = styleName;
                            ProcessStyle(elem, st);
                            if (style.FindIndex(x => x.name == st.name) < 0)
                            {
                                style.Add(st);
                            }
                            else
                            {
                                Console.WriteLine("Duplicate style {0} ignored (accidental duplicate?).", styleName);
                            }
                        }
                    }
                }
            }

            // Now process props.
            foreach (XmlNode child in group)
            {
                if (child is XmlElement)
                {
                    XmlElement elem = child as XmlElement;
                    if (elem.Name == "prop")
                    {
                        XmlElement nameElem = elem["name"];
                        if (nameElem == null)
                        {
                            Console.WriteLine("<prop> found that does not have a <name>");
                        }
                        else
                        {
                            string propName = nameElem.InnerText.Replace(' ', '_');

                            XmlElement styleElem = elem["style"];
                            Style      selectedStyle;
                            if (styleElem == null)
                            {
                                // empty style
                                selectedStyle = new Style();
                            }
                            else
                            {
                                string styleName = styleElem.InnerText;
                                selectedStyle = style.Find(x => x.name == styleName);
                                if (selectedStyle == null)
                                {
                                    Console.WriteLine("Unable to find <style> \"{0}\" for <prop> {1}", styleName, propName);
                                }
                            }

                            if (selectedStyle != null)
                            {
                                XmlElement startupElem   = elem["startupScript"];
                                string     startupScript = string.Empty;
                                if (startupElem != null)
                                {
                                    startupScript = startupElem.InnerText;
                                }

                                GenerateProp(propName, selectedStyle, startupScript, elem, writeDirectory);
                            }
                        }
                    }
                }
            }
        }
Пример #54
0
        //Khi người dùng ấn vào nút xóa
        private void btnXoa_Click(object sender, EventArgs e)
        {
            //biến chứa số lượng phần tử trong bảng hiện bên phía giao diện người dùng
            int sizeOfTable = dgvTrinhDo.Rows.Count;
            // danh sách các bản ghi được người dùng chọn
            List <DataGridViewRow> selectedRows = new List <DataGridViewRow>();

            // chạy vòng for duyệt qua hết các bản ghi trong bảng dữ liệu đang được hiển thị
            // nếu có bản ghi nào đang được chọn thì thêm vào danh sách các bản ghi được chọn
            foreach (DataGridViewRow row in dgvTrinhDo.Rows)
            {
                if (row.Selected)
                {
                    selectedRows.Add(row);
                }
            }

            // Danh sách các bản ghi được chọn có số lượng lớn hơn không
            if (selectedRows.Count > 0)
            {
                //Hiển thị thông báo yêu cầu người dùng xác thực lựa chọn có xóa hay không?
                DialogResult result = TienIch.ShowXacThuc("Xác Thực", "Bạn có chắc chắn muốn xóa vĩnh viễn các bản ghi đã chọn?");
                //Người dùng chọn có
                if (result == DialogResult.Yes)
                {
                    List <int> removeIds = new List <int>();
                    foreach (DataGridViewRow row in selectedRows)
                    {
                        // bản ghi hiện tại phải khác bản ghi cuối cùng trong bảng
                        //(vì nó luôn luôn là null nên cần tránh)
                        if (row.Index != dgvTrinhDo.Rows[sizeOfTable - 1].Index)
                        {
                            //Xác thực xem bản ghi này đã có trong database chưa?
                            //Neu ban ghi nay chua duoc cap nhat vao trong db thi cot Id se không có giá trị
                            //Nếu cột Id có giá trị và khác rỗng thì thực hiện xóa khỏi db
                            if (!string.IsNullOrEmpty(row.Cells[0].Value.ToString()))
                            {
                                if (!string.IsNullOrEmpty(row.Cells[0].Value.ToString()))
                                {
                                    string sqlDelete = "Delete From TrinhDo where Id=" + row.Cells[0].Value;
                                    DataBaseFunction.Delete(sqlDelete);
                                }
                                //thực hiện lưu vị trí bản ghi cần xóa để xóa bản ghi ở phía giao diện người dùng
                                removeIds.Add(Int32.Parse(row.Cells[0].Value.ToString()));

                                // biến flag được dùng để lưu vị trí của phần tử trong mảng
                                // danh sách các bản ghi có thực hiện chỉnh sửa có giá trị = editedText,
                                int flag = editedRows.FindIndex(x => x.Ten.Equals(row.Cells[1]));
                                //  nếu flag > 0 tức mảng chứa phần tử này
                                // thực hiện xóa Đối tượng đó khỏi danh sách
                                if (flag > 0)
                                {
                                    editedRows.RemoveAt(flag);
                                }
                            }
                            //Nếu cột Id khộng có giá trị thì tìm trong list insert xem đã có phần tử này chưa
                            else
                            {
                                //Nếu list insert mới có chứa thì xóa
                                if (insertRows.Contains(row.Cells[1].Value.ToString()))
                                {
                                    insertRows.Remove(row.Cells[1].Value.ToString());
                                }
                                dgvTrinhDo.Rows.RemoveAt(row.Index);
                            }
                        }
                    }
                    foreach (int giaTriIdCanTimDeXoa in removeIds)
                    {
                        foreach (DataGridViewRow jow in dgvTrinhDo.Rows)
                        {
                            if (Int32.Parse(jow.Cells[0].Value.ToString()) == giaTriIdCanTimDeXoa)
                            {
                                dgvTrinhDo.Rows.RemoveAt(jow.Index);
                                break;
                            }
                        }
                    }
                    TienIch.ShowThanhCong("Thành Công", "Đã thực hiện xóa thành công!");
                }
                //Người dùng chọn không
                else if (result == DialogResult.No)
                {
                    TienIch.ShowThanhCong("Thông Báo", "Không có bản ghi nào bị xóa khỏi cơ sở dữ liệu cả!");
                }
            }
            // Chưa có bản ghi nào được chọn
            else
            {
                TienIch.ShowCanhBao("Cảnh Báo", "Vui lòng chọn bản ghi muốn xóa");
            }
        }
Пример #55
0
        public async void HandleUpdate(Update update, ITelegramBotClient client)
        {
            string answer;

            //\U0000270A - Камень
            //\U0000270B - Бумага
            //\U0000270C - Ножницы
            string[] presentations = new string[] { "\U0000270A", "\U0000270B", "\U0000270C" };
            var      keyboard      = new InlineKeyboardMarkup(new InlineKeyboardButton[][]
            {
                new InlineKeyboardButton[]
                {
                    new InlineKeyboardCallbackButton(presentations[0], presentations[0]),
                    new InlineKeyboardCallbackButton(presentations[1], presentations[1]),
                    new InlineKeyboardCallbackButton(presentations[2], presentations[2])
                }
            });

            //if someone just wants to start a game
            if (update.Type == UpdateType.MessageUpdate &&
                Utils.PrettifyCommand(update.Message.Text) == "/rockpaperscissors")
            {
                answer = "Камень, ножницы, бумага:";
                Game game = new Game
                {
                    gameMessage = await client.SendTextMessageAsync(update.Message.Chat.Id, answer, replyToMessageId : update.Message.MessageId, replyMarkup : keyboard)
                };
                _logger?.LogUpdate(update, game.gameMessage);
                //adding new game to list of current games
                currentGames.Add(game);
                return;
            }

            //if someone presses the button
            if (update.Type == UpdateType.CallbackQueryUpdate)
            {
                //check if this game exist
                if (currentGames.FindAll(
                        g =>
                        (g.gameMessage.Chat.Id == update.CallbackQuery.Message.Chat.Id &&
                         g.gameMessage.MessageId == update.CallbackQuery.Message.MessageId))
                    .Count != 1)
                {
                    //if it doesn't, GTFO
                    var popup = await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "Низзя!");

                    _logger?.LogUpdate(update, answerQuery: "Низзя!");
                    return;
                }

                //if yes then obtaining its index
                int gameIndex = currentGames.FindIndex(g =>
                                                       (g.gameMessage.Chat.Id == update.CallbackQuery.Message.Chat.Id &&
                                                        g.gameMessage.MessageId == update.CallbackQuery.Message.MessageId));

                Game game = currentGames[gameIndex];

                //if there's no one playing yet, then someone who pressed is the first player
                if (game.player1 == null)
                {
                    game.player1       = update.CallbackQuery.From;
                    game.player1Answer = Array.IndexOf(presentations, update.CallbackQuery.Data);

                    //edit game message
                    answer = "Камень, ножницы, бумага:\r\n" +
                             $"{game.player1.FirstName} {game.player1.LastName}\r\n" +
                             $"vs\r\n" +
                             $"Пока никого... Сыграй!";
                    var edit = await client.EditMessageTextAsync(game.gameMessage.Chat, game.gameMessage.MessageId, answer, replyMarkup : keyboard);

                    _logger?.LogUpdate(update, edit);
                }

                //else he is the second player
                else if (game.player2 == null)
                {
                    //if player1 and player2 are same user
                    if (game.player1.Id == update.CallbackQuery.From.Id)
                    {
                        var popup = await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "Низзя!");

                        _logger?.LogUpdate(update, answerQuery: "Низзя!");
                        return;
                    }

                    game.player2       = update.CallbackQuery.From;
                    game.player2Answer = Array.IndexOf(presentations, update.CallbackQuery.Data);

                    //determining R-P-S outcome
                    string outcome;
                    if (game.player1Answer == game.player2Answer)
                    {
                        outcome = "Ганьба, это ничья.";
                    }
                    else if ((game.player1Answer == game.player2Answer + 1) || (game.player1Answer == 0 && game.player2Answer == 2))
                    {
                        outcome = $"{game.player1.FirstName} {game.player1.LastName}, це перемога!";
                    }
                    else
                    {
                        outcome = $"{game.player2.FirstName} {game.player2.LastName}, це перемога!";
                    }

                    //editing game message with results
                    answer = $"{game.player1.FirstName} {game.player1.LastName}: {presentations[game.player1Answer]}\r\n" +
                             $"vs\r\n" +
                             $"{game.player2.FirstName} {game.player2.LastName}: {presentations[game.player2Answer]}\r\n" +
                             $"Результат: {outcome}";

                    var edit = await client.EditMessageTextAsync(game.gameMessage.Chat, game.gameMessage.MessageId, answer);

                    _logger?.LogUpdate(update, edit);

                    //removing game from list of current games
                    currentGames.RemoveAt(gameIndex);
                }
            }
        }
Пример #56
0
        /// <summary>
        /// Execute a remote procedure.
        /// </summary>
        /// <param name="netInstanceID">The <see cref="NetworkIdentity.InstanceID"/>.</param>
        /// <param name="function">The name of the function.</param>
        /// <param name="parameters">The function parameters.</param>
        public void Call(NetworkIdentity identity, RPCType type, string function, params object[] parameters)
        {
            int connectionID = NetworkController.Instance.IsServer ? identity.OwnerConnection?.ConnectionID ?? -1 : NetworkController.Instance.ConnectionID;

            if (!NetworkController.Instance.IsServer)
            {
                if (type == RPCType.Target)
                {
                    throw new InvalidOperationException("You cannot send a targetted RPC because you are not the server.");
                }

                if (identity.OwnerConnection == null)
                {
                    throw new InvalidOperationException("The network identity has no owner and cannot execute any RPCs");
                }

                if (identity == null)
                {
                    throw new InvalidOperationException("The network identity specified does not exist on this client: " + identity.InstanceID);
                }

                if (identity.OwnerConnection.ConnectionID != NetworkController.Instance.LocalConnectionID)
                {
                    throw new InvalidOperationException("You are not the owner of this object and cannot execute RPCs on it.");
                }
            }

            int index = m_Methods?.FindIndex(x => x.m_MethodName == function) ?? -1;

            if (index == -1)
            {
                return;
            }

            RPCMethodInfo rpc = m_Methods[index];

            if (rpc.m_ArgumentCount != parameters.Length)
            {
                throw new InvalidOperationException("Given argument count for " + function + " does not match the argument count specified.");
            }

            NetworkWriter writer = GetRPCWriter(NetworkController.Instance.LocalConnectionID, identity.InstanceID, (byte)type, index, rpc.m_ArgumentCount, parameters);

            byte[] data = writer.ToArray();

            switch (type)
            {
            case RPCType.All:
            {
                if (NetworkController.Instance.IsServer)
                {
                    NetworkController.Instance.SendToAll(NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                else
                {
                    NetworkController.Instance.Send(connectionID, NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                break;
            }

            case RPCType.Others:
            {
                if (NetworkController.Instance.IsServer)
                {
                    NetworkController.Instance.SendToAll(NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                else
                {
                    NetworkController.Instance.Send(connectionID, NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                break;
            }

            case RPCType.ServerOnly:
            {
                if (NetworkController.Instance.IsServer)
                {
                    NetworkBehaviour networkBehaviour = identity.GetComponent <NetworkBehaviour>();
                    networkBehaviour.InvokeRPC(function, parameters);
                }
                else
                {
                    NetworkController.Instance.Send(connectionID, NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                break;
            }

            case RPCType.AllBuffered:
            {
                if (NetworkController.Instance.IsServer)
                {
                    InitBuffer(identity.InstanceID);
                    m_BufferedMessages[identity.InstanceID].Add(new NetworkWriter(writer.ToArray()));
                    NetworkController.Instance.SendToAll(NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                else
                {
                    NetworkController.Instance.Send(connectionID, NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                break;
            }

            case RPCType.OthersBuffered:
            {
                if (NetworkController.Instance.IsServer)
                {
                    InitBuffer(identity.InstanceID);
                    m_BufferedMessages[identity.InstanceID].Add(new NetworkWriter(writer.ToArray()));
                    NetworkController.Instance.SendToAll(NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                else
                {
                    NetworkController.Instance.Send(connectionID, NetworkController.ReliableSequencedChannel, RPCMsg, data);
                }
                break;
            }

            case RPCType.Target:
            {
                if (parameters.Length > 0)
                {
                    NetworkConnection connection = (NetworkConnection)parameters[0];
                    if (connection != null)
                    {
                        connection.Send(NetworkController.ReliableSequencedChannel, RPCMsg, data);
                    }
                }
                break;
            }
            }
        }
Пример #57
0
            public static void receiveProtocolMessage(ProtocolMessageCode code, byte[] data, byte[] checksum, RemoteEndpoint endpoint)
            {
                QueueMessageRecv message = new QueueMessageRecv
                {
                    code       = code,
                    data       = data,
                    length     = data.Length,
                    checksum   = checksum,
                    endpoint   = endpoint,
                    helperData = extractHelperData(code, data)
                };


                lock (txqueueMessages)
                {
                    // Move transaction messages to the transaction queue
                    if (code == ProtocolMessageCode.newTransaction || code == ProtocolMessageCode.transactionData ||
                        code == ProtocolMessageCode.transactionsChunk || code == ProtocolMessageCode.newBlock || code == ProtocolMessageCode.blockData ||
                        code == ProtocolMessageCode.newBlockSignature || code == ProtocolMessageCode.blockSignatures)
                    {
                        if (message.helperData != null)
                        {
                            if (txqueueMessages.Exists(x => x.code == message.code && x.helperData.SequenceEqual(message.helperData)))
                            {
                                int msg_index = txqueueMessages.FindIndex(x => x.code == message.code && message.helperData.SequenceEqual(x.helperData));
                                if (txqueueMessages[msg_index].length < message.length)
                                {
                                    txqueueMessages[msg_index] = message;
                                }
                                return;
                            }
                        }

                        if (txqueueMessages.Exists(x => x.code == message.code && x.checksum.SequenceEqual(message.checksum)))
                        {
                            //Logging.warn(string.Format("Attempting to add a duplicate message (code: {0}) to the network queue", code));
                            return;
                        }

                        if (txqueueMessages.Count > 20 &&
                            (code == ProtocolMessageCode.transactionsChunk || code == ProtocolMessageCode.newBlock || code == ProtocolMessageCode.blockData || code == ProtocolMessageCode.blockSignatures))
                        {
                            txqueueMessages.Insert(5, message);
                        }
                        else
                        {
                            // Add it to the tx queue
                            txqueueMessages.Add(message);
                        }
                        return;
                    }
                }

                lock (queueMessages)
                {
                    // ignore duplicates
                    if (queueMessages.Exists(x => x.code == message.code && x.checksum.SequenceEqual(message.checksum) && x.endpoint == message.endpoint))
                    {
                        //Logging.warn(string.Format("Attempting to add a duplicate message (code: {0}) to the network queue", code));
                        return;
                    }

                    // Handle normal messages, but prioritize block-related messages
                    if (code == ProtocolMessageCode.bye || code == ProtocolMessageCode.hello || code == ProtocolMessageCode.helloData)
                    {
                        queueMessages.Insert(0, message);
                        return;
                    }
                    else if (code == ProtocolMessageCode.keepAlivePresence || code == ProtocolMessageCode.getPresence ||
                             code == ProtocolMessageCode.updatePresence)
                    {
                        // Prioritize if queue is large
                        if (queueMessages.Count > 10)
                        {
                            queueMessages.Insert(5, message);
                            return;
                        }
                    }

                    // Add it to the normal queue
                    queueMessages.Add(message);
                }
            }
Пример #58
0
        /// <summary>
        /// Parses a list block.
        /// </summary>
        /// <param name="markdown"> The markdown text. </param>
        /// <param name="start"> The location of the first character in the block. </param>
        /// <param name="maxEnd"> The location to stop parsing. </param>
        /// <param name="quoteDepth"> The current nesting level for block quoting. </param>
        /// <param name="actualEnd"> Set to the end of the block when the return value is non-null. </param>
        /// <returns> A parsed list block, or <c>null</c> if this is not a list block. </returns>
        internal static ListBlock Parse(string markdown, int start, int maxEnd, int quoteDepth, out int actualEnd)
        {
            var           russianDolls         = new List <NestedListInfo>();
            int           russianDollIndex     = -1;
            bool          previousLineWasBlank = false;
            bool          inCodeBlock          = false;
            ListItemBlock currentListItem      = null;

            actualEnd = start;

            foreach (var lineInfo in Common.ParseLines(markdown, start, maxEnd, quoteDepth))
            {
                // Is this line blank?
                if (lineInfo.IsLineBlank)
                {
                    // The line is blank, which means the next line which contains text may end the list (or it may not...).
                    previousLineWasBlank = true;
                }
                else
                {
                    // Does the line contain a list item?
                    ListItemPreamble listItemPreamble = null;
                    if (lineInfo.FirstNonWhitespaceChar - lineInfo.StartOfLine < (russianDollIndex + 2) * 4)
                    {
                        listItemPreamble = ParseItemPreamble(markdown, lineInfo.FirstNonWhitespaceChar, lineInfo.EndOfLine);
                    }

                    if (listItemPreamble != null)
                    {
                        // Yes, this line contains a list item.

                        // Determining the nesting level is done as follows:
                        // 1. If this is the first line, then the list is not nested.
                        // 2. If the number of spaces at the start of the line is equal to that of
                        //    an existing list, then the nesting level is the same as that list.
                        // 3. Otherwise, if the number of spaces is 0-4, then the nesting level
                        //    is one level deep.
                        // 4. Otherwise, if the number of spaces is 5-8, then the nesting level
                        //    is two levels deep (but no deeper than one level more than the
                        //    previous list item).
                        // 5. Etcetera.
                        ListBlock listToAddTo = null;
                        int       spaceCount  = lineInfo.FirstNonWhitespaceChar - lineInfo.StartOfLine;
                        russianDollIndex = russianDolls.FindIndex(rd => rd.SpaceCount == spaceCount);
                        if (russianDollIndex >= 0)
                        {
                            // Add the new list item to an existing list.
                            listToAddTo = russianDolls[russianDollIndex].List;

                            // Don't add new list items to items higher up in the list.
                            russianDolls.RemoveRange(russianDollIndex + 1, russianDolls.Count - (russianDollIndex + 1));
                        }
                        else
                        {
                            russianDollIndex = Math.Max(1, 1 + ((spaceCount - 1) / 4));
                            if (russianDollIndex < russianDolls.Count)
                            {
                                // Add the new list item to an existing list.
                                listToAddTo = russianDolls[russianDollIndex].List;

                                // Don't add new list items to items higher up in the list.
                                russianDolls.RemoveRange(russianDollIndex + 1, russianDolls.Count - (russianDollIndex + 1));
                            }
                            else
                            {
                                // Create a new list.
                                listToAddTo = new ListBlock {
                                    Style = listItemPreamble.Style, Items = new List <ListItemBlock>()
                                };
                                if (russianDolls.Count > 0)
                                {
                                    currentListItem.Blocks.Add(listToAddTo);
                                }

                                russianDollIndex = russianDolls.Count;
                                russianDolls.Add(new NestedListInfo {
                                    List = listToAddTo, SpaceCount = spaceCount
                                });
                            }
                        }

                        // Add a new list item.
                        currentListItem = new ListItemBlock()
                        {
                            Blocks = new List <MarkdownBlock>()
                        };
                        listToAddTo.Items.Add(currentListItem);

                        // Add the rest of the line to the builder.
                        AppendTextToListItem(currentListItem, markdown, listItemPreamble.ContentStartPos, lineInfo.EndOfLine);
                    }
                    else
                    {
                        // No, this line contains text.

                        // Is there even a list in progress?
                        if (currentListItem == null)
                        {
                            actualEnd = start;
                            return(null);
                        }

                        // This is the start of a new paragraph.
                        int spaceCount = lineInfo.FirstNonWhitespaceChar - lineInfo.StartOfLine;
                        if (spaceCount == 0)
                        {
                            break;
                        }

                        russianDollIndex = Math.Min(russianDollIndex, (spaceCount - 1) / 4);
                        int linestart = Math.Min(lineInfo.FirstNonWhitespaceChar, lineInfo.StartOfLine + ((russianDollIndex + 1) * 4));

                        // 0 spaces = end of the list.
                        // 1-4 spaces = first level.
                        // 5-8 spaces = second level, etc.
                        if (previousLineWasBlank)
                        {
                            ListBlock listToAddTo = russianDolls[russianDollIndex].List;
                            currentListItem = listToAddTo.Items[listToAddTo.Items.Count - 1];

                            ListItemBuilder builder;

                            // Prevents new Block creation if still in a Code Block.
                            if (!inCodeBlock)
                            {
                                builder = new ListItemBuilder();
                                currentListItem.Blocks.Add(builder);
                            }
                            else
                            {
                                // This can only ever be a ListItemBuilder, so it is not a null reference.
                                builder = currentListItem.Blocks.Last() as ListItemBuilder;

                                // Make up for the escaped NewLines.
                                builder.Builder.AppendLine();
                                builder.Builder.AppendLine();
                            }

                            AppendTextToListItem(currentListItem, markdown, linestart, lineInfo.EndOfLine);
                        }
                        else
                        {
                            // Inline text. Ignores the 4 spaces that are used to continue the list.
                            AppendTextToListItem(currentListItem, markdown, linestart, lineInfo.EndOfLine, true);
                        }
                    }

                    // Check for Closing Code Blocks.
                    if (currentListItem.Blocks.Last() is ListItemBuilder currentBlock)
                    {
                        var blockmatchcount = Regex.Matches(currentBlock.Builder.ToString(), "```").Count;
                        if (blockmatchcount > 0 && blockmatchcount % 2 != 0)
                        {
                            inCodeBlock = true;
                        }
                        else
                        {
                            inCodeBlock = false;
                        }
                    }

                    // The line was not blank.
                    previousLineWasBlank = false;
                }

                // Go to the next line.
                actualEnd = lineInfo.EndOfLine;
            }

            var result = russianDolls[0].List;

            ReplaceStringBuilders(result);
            return(result);
        }
Пример #59
0
        public void Delete(int id)
        {
            var productIndex = _products.FindIndex(p => p.id == id);

            _products.RemoveAt(productIndex);
        }
Пример #60
0
 public int GetPathIndex(Point point)
 {
     return(Path?.FindIndex(x => point == x) ?? -1);
 }