Example #1
0
 // GET: Home/Index
 public async Task<ActionResult> Index()
 {
     // Get lift offers with min. 1 seat available, order by descending - most recent to oldest
     var offersAll = await db.LiftOffers.OrderByDescending(
                     o => o.LiftOfferID).Where(o => o.SeatsAvailable > 0).ToListAsync();
     // Create list with not expired offers to display in a view
     var offersNotExpired = new List<LiftOffer>();
     foreach (var off in offersAll)
     {
         // Check if EndDate is older then current date. If date null then set default - 01/01/0001
         int result = DateTime.Compare(off.EndDate.GetValueOrDefault(), DateTime.Today);
         // If EndDate greater or null, add offer to list of not expired offers
         if ((result >= 0) || (off.EndDate == null))
         {
             offersNotExpired.Add(off);
         }
     }
     var users = new List<User>();
     foreach (LiftOffer off in offersNotExpired.Take(3))
     {
         User usr = db.Users.Find(off.UserID);
         users.Add(usr);
     }
     ViewBag.Users = users.ToList();
     // Display only 3 most recent offers
     return View(offersNotExpired.Take(3).ToList());
 }
Example #2
0
        partial void SocketReadLine(ref string response)
        {
            var encoding = new Renci.SshNet.Common.ASCIIEncoding();

            var line = new StringBuilder();
            //  Read data one byte at a time to find end of line and leave any unhandled information in the buffer to be processed later
            var buffer = new List<byte>();

            var data = new byte[1];
            do
            {
                var received = this._socket.Receive(data);

                //  If zero bytes received then exit
                if (received == 0)
                    break;

                buffer.Add(data[0]);
            }
            while (!(buffer.Count > 1 && (buffer[buffer.Count - 1] == 0x0A || buffer[buffer.Count - 1] == 0x00)));

            // Return an empty version string if the buffer consists of a 0x00 character.
            if (buffer[buffer.Count - 1] == 0x00)
            {
                response = string.Empty;
            }
            else if (buffer.Count > 1 && buffer[buffer.Count - 2] == 0x0D)
                response = encoding.GetString(buffer.Take(buffer.Count - 2).ToArray());
            else
                response = encoding.GetString(buffer.Take(buffer.Count - 1).ToArray());
        }
Example #3
0
        public Gpu(IMmu mmu, params Color[] palette)
        {
            _mmu = mmu;

            _defaultPalette = new List<Color>()
            {
                Colors.GhostWhite,
                Colors.LightSlateGray,
                Colors.DarkSlateBlue,
                Colors.Black
            };

            for (int i = 0; i < 4; i++)
            {
                if (i < palette.Length)
                {
                    _defaultPalette[i] = palette[i];
                }
            }

            _bgPalette = _defaultPalette.Take(4).ToList();
            _spritePalette = _defaultPalette.Take(4).ToList();

            Reset();
        }
Example #4
0
        private void GetEventDetails()
        {
            try
            {
                //    EventListingViewModel _eventListingViewModel = new EventListingViewModel();
                //    List<EventListingModel> _eventListingModel = new List<EventListingModel>();

                //    rcontent.DataSource = _eventListingModel.Take(4);
                //    rcontent.DataBind();

                //    rQuickBook.DataSource = _eventListingModel;
                //    rQuickBook.DataBind();

                //    rFeatured.DataSource = _eventListingModel.Take(4);
                //    rFeatured.DataBind();

                EventListingViewModel _eventListingViewModel = new EventListingViewModel();
                List<EventListingModel> _eventListingModel = new List<EventListingModel>();

                _eventListingModel = _eventListingViewModel.GetEventListing();

                rcontent.DataSource = _eventListingModel.Take(4);
                rcontent.DataBind();

                rQuickBook.DataSource = _eventListingModel;
                rQuickBook.DataBind();

                rFeatured.DataSource = _eventListingModel.Take(4);
                rFeatured.DataBind();
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError(ex.Message);
            }
        }
        public List<TimeSpend> GetByFilter(TaskFilter filter)
        {
            var listTimeSpend = new List<TimeSpend>();

            while (true)
            {
                var timeSpend = _timeSpendDao.GetByFilter(filter);
                timeSpend = GetTasks(timeSpend).FindAll(r => ProjectSecurity.CanRead(r.Task));

                if (filter.LastId != 0)
                {
                    var lastTimeSpendIndex = timeSpend.FindIndex(r => r.ID == filter.LastId);

                    if (lastTimeSpendIndex >= 0)
                    {
                        timeSpend = timeSpend.SkipWhile((r, index) => index <= lastTimeSpendIndex).ToList();
                    }
                }

                listTimeSpend.AddRange(timeSpend);

                if (filter.Max <= 0 || filter.Max > 150000) break;

                listTimeSpend = listTimeSpend.Take((int)filter.Max).ToList();

                if (listTimeSpend.Count == filter.Max || timeSpend.Count == 0) break;

                if (listTimeSpend.Count != 0)
                    filter.LastId = listTimeSpend.Last().ID;

                filter.Offset += filter.Max;
            }

            return listTimeSpend;
        }
        public static string filteredNews(string _url, string _xpath, int _qty, string _categories, string _colleges, string _tags, string _fromDate, string _toDate, int _pageStart)
        {
            LocalItems xml = new LocalItems(_url, _xpath);

            // get count for pagination

            // start filtering ....

            List<EtsuRssItem> EtsuItemList = new List<EtsuRssItem>();

            string o = "<ul class=\"rss_hidelist\">";

            xml.items.ToList().ForEach(
                x =>
                    { EtsuRssItem currentEtsuItem = x.ToEtsuRssItem();
                        if (currentEtsuItem.dateIsGood(_fromDate, _toDate) &&
                            currentEtsuItem.hasCategory(_categories) &&
                            currentEtsuItem.hasAllColleges(_colleges) &&
                            currentEtsuItem.hasAllTags(_tags))
                        { EtsuItemList.Add(currentEtsuItem); }
                    }
             );

            EtsuItemList.Take(_qty).ToList().ForEach(
                x =>
                {
                    o += x.ToDefault();
                });
            o += "</ul>";
            return o;
        }
Example #7
0
        public override void Use(SteamID room, SteamID sender, string[] args)
        {
            new Thread(() =>
                           {
                               string arg = String.Join(" ", args);

                               var distances = new List<Tuple<int, string>>();
                               foreach (string s in File.ReadAllLines("enable1.txt"))
                               {
                                   int dist = Compute(arg, s);

                                   if (dist == 0)
                                   {
                                       Chat.Send(room, "This word isn't misspelled!");
                                       return;
                                   }

                                   distances.Add(new Tuple<int, string>(dist, s));
                               }

                               distances.Sort((t1, t2) => t1.Item1.CompareTo(t2.Item1));

                               Chat.Send(room, string.Format("Did you mean: {0}?", string.Join(", ", distances.Take(4))));

                           }).Start();
        }
        public void Write(Storage storage, string fileSpecificPath, string fileWordsPath)
        {
            var bitmap = new List<byte>();

            var words = GenerateWordsStringAndBitmap(bitmap, storage);
            if (words == null || words == "")
                return;
            var bytemap = new List<byte>();

            while (bitmap.Count > 0)
            {
                var oneByte = bitmap.Take(8).ToList();
                bitmap = bitmap.Skip(8).ToList();
                bytemap.Add(oneByte.Aggregate((byte)0, (result, bit) => (byte)((result << 1) | bit)));
            }

            using (var streamWriter = new StreamWriter(fileWordsPath))
            {
                streamWriter.Write(words);
            }
            using (var fileStream = new FileStream(fileSpecificPath, FileMode.OpenOrCreate))
            {
                fileStream.Write(bytemap.ToArray(), 0, bytemap.Count);
                fileStream.Close();
            }
        }
        public static void Main()
        {
            Console.Write("Enter the first number: ");

            Queue<int> queue = new Queue<int>();
            int number = 0;
            string input = Console.ReadLine();

            if (!int.TryParse(input, out number))
            {
                string message = string.Format(TextFormatErrorMessage, input);
                throw new InvalidCastException(message);
            }

            queue.Enqueue(number);
            int counter = 1;

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

            while (counter < Length)
            {
                queue.Enqueue(queue.Peek() + 1);
                queue.Enqueue((2 * queue.Peek()) + 1);
                queue.Enqueue(queue.Peek() + 2);
                result.Add(queue.Dequeue());
                counter += 3;
            }

            while (queue.Count != 0)
            {
                result.Add(queue.Dequeue());
            }

            Console.WriteLine(string.Join(", ", result.Take(50)));
        }
Example #10
0
        public static List<Models.GameContext.Guild> GetRankings(int topNumber = 0, Models.GameContext.GuildRankingOrderBy orderBy = GuildRankingOrderBy.Score)
        {
            List<Models.GameContext.Guild> guilds = new List<Models.GameContext.Guild>();

            using (var context = new GameDbContext())
            {
                guilds = context.Guilds.ToList();

                if(orderBy == GuildRankingOrderBy.Name)
                {
                    guilds = guilds.OrderByDescending(x => x.G_Name).ToList();
                }

                if(orderBy == GuildRankingOrderBy.Score)
                {
                    guilds = guilds.OrderByDescending(x => x.G_Score).ToList();
                }

                if(topNumber > 0)
                {
                    guilds = guilds.Take(topNumber).ToList();
                }
            }

            return guilds;
        }
        public async Task GetSeasons_WithFolders_ReturnsSeasons()
        {
            // Arrange
            const string path = @"C:\Folder";
            List<string> seasonFolders = new List<string>
            {
                @"C:\Folder\Season 1",
                @"C:\Folder\Season 2",
                @"C:\Folder\Specials"
            };
            _fileSystemService.FindDirectories(path, "Season *")
                .Returns(seasonFolders.Take(2).ToTask());
            _fileSystemService.FindDirectories(path, "Special*")
                .Returns(seasonFolders.Skip(2).ToTask());

            // Act
            IEnumerable<Season> seasons = await _service.GetSeasons(path);

            // Assert
            List<string> actualSeasonFolders = seasons.Select(s => s.Path).ToList();
            Assert.Equal(seasonFolders.Count, actualSeasonFolders.Count);
            // Seasons are sorted by season number
            Assert.Equal(seasonFolders[0], actualSeasonFolders[1]);
            Assert.Equal(seasonFolders[1], actualSeasonFolders[2]);
            Assert.Equal(seasonFolders[2], actualSeasonFolders[0]);
        }
		public override void RequestFileEdit (IEnumerable<FilePath> files)
		{
			base.RequestFileEdit (files);

			if (!IdeApp.IsInitialized)
				return;

			List<FilePath> readOnlyFiles = new List<FilePath> ();
			foreach (var f in files) {
				if (File.Exists (f) && File.GetAttributes (f).HasFlag (FileAttributes.ReadOnly))
					readOnlyFiles.Add (f);
			}
			string error;
			if (readOnlyFiles.Count == 1)
				error = GettextCatalog.GetString ("File {0} is read-only", readOnlyFiles [0].FileName);
			else if (readOnlyFiles.Count > 1) {
				var f1 = string.Join (", ", readOnlyFiles.Take (readOnlyFiles.Count - 1).ToArray ());
				var f2 = readOnlyFiles [readOnlyFiles.Count - 1];
				error = GettextCatalog.GetString ("Files {0} and {1} are read-only", f1, f2);
			} else
				return;

			var btn = new AlertButton (readOnlyFiles.Count == 1 ? GettextCatalog.GetString ("Make Writtable") : GettextCatalog.GetString ("Make Writtable"));
			var res = MessageService.AskQuestion (error, GettextCatalog.GetString ("Would you like MonoDevelop to attempt to make the file writable and try again?"), btn, AlertButton.Cancel);
			if (res == AlertButton.Cancel)
				throw new UserException (error) { AlreadyReportedToUser = true };

			foreach (var f in readOnlyFiles) {
				var atts = File.GetAttributes (f);
				File.SetAttributes (f, atts & ~FileAttributes.ReadOnly);
			}
		}
Example #13
0
        private double projEval(int[][] input, List<IntPoint> pts)
        {
            if (pts.Count() > 1) {
                pts = pts.Take(1).ToList();
            }

            double output = 1;
            foreach (var p in pts) {
                double refEval;
                double ref2Eval;
                if (HashedResults.ContainsKey(Ref.Eval)) {
                    refEval = HashedResults[Ref.Eval];
                } else {
                    refEval = Ref.Eval(input);
                }

                if (HashedResults.ContainsKey(Ref2.Eval)) {
                    ref2Eval = HashedResults[Ref2.Eval];
                } else {
                    ref2Eval = Ref2.Eval(input);
                }
                output = this.weight * refEval -
                    (1 - this.weight) * ref2Eval;
            }
            HashedResults[Eval] = output;
            return output;
        }
Example #14
0
        public void BindArticle()
        {
            var list = new List<Resource>();
            if (IsOnline)
            {
                var __courses = CurrentUser.Taught.Where(o => o.State < State.审核).Select(o => o.CourseId).ToList();
                foreach (var __c in __courses)
                {
                    list.AddRange(HomoryContext.Value.Resource.Where(o => o.State == State.启用 && o.UserId == CurrentUser.Id && o.ResourceCatalog.Count(p => p.CatalogId == __c && p.State < State.启用) > 0).Take(Count).ToList());
                    if (list.Count >= Count)
                        break;
                }
            }

            list = list.OrderByDescending(o => o.Time).ToList();

            if (list.Count < Count)
            {
                list.AddRange(HomoryContext.Value.Resource.Where(o => o.State < State.审核 && o.Type == ResourceType.视频)
                .OrderByDescending(o => o.Credit)
                .Take(Count - list.Count)
                .ToList());
            }

            homory_article.DataSource = list.Take(Count);
            homory_article.DataBind();
        }
Example #15
0
        private static List<List<int>> PowersetRecursive(List<int> set)
        {
            var result = new List<List<int>>();

            // Base case
            if (!set.Any())
            {
                // Add the empty set
                result.Add(new List<int>());
                return result;
            }

            // Recursive case
            // Will exist, since otherwise we would have returned before on the base case
            int head = set.Last();
            // Get the tail of the set by skipping the head or first item
            List<int> tail = set.Take(set.Count() - 1).ToList();
            List<List<int>> subsets = PowersetRecursive(tail);
            result.AddRange(subsets);

            // Need to create a copy (i.e. clone);
            var newSubsets = new List<List<int>>(subsets);
            foreach (List<int> subset in subsets)
            {
                var newSubset = new List<int>(subset);
                newSubset.Add(head);
                newSubsets.Add(newSubset);
            }
            result = newSubsets;
            return result;
        }
Example #16
0
        private readonly static String CON = "->"; // 项之间的分隔符

        static private void buildSubSet(List<String> sourceSet, List<List<String>> result) //建立频繁项集的子集
        {
            // 仅有一个元素时,递归终止。此时非空子集仅为其自身,所以直接添加到result中
            if (sourceSet.Count == 1)
            {
                List<String> set = new List<String>();
                set.Add(sourceSet[0]);
                result.Add(set);
            }
            else if (sourceSet.Count > 1)
            {
                // 当有n个元素时,递归求出前n-1个子集,在于result中
                buildSubSet(sourceSet.Take(sourceSet.Count - 1).ToList(), result);
                int size = result.Count;// 求出此时result的长度,用于后面的追加第n个元素时计数
                // 把第n个元素加入到集合中
                List<String> single = new List<String>();
                single.Add(sourceSet[sourceSet.Count - 1]);
                result.Add(single);
                // 在保留前面的n-1子集的情况下,把第n个元素分别加到前n个子集中,并把新的集加入到result中;
                // 为保留原有n-1的子集,所以需要先对其进行复制
                List<String> clone;
                for (int i = 0; i < size; i++)
                {
                    clone = new List<String>();
                    foreach (String str in result[i])
                    {
                        clone.Add(str);
                    }
                    clone.Add(sourceSet[sourceSet.Count - 1]);
                    result.Add(clone);
                }
            }
        }
Example #17
0
        private List<Song> QuickSort(List<Song> collection) {
            if (collection.Count == 1) {
                return collection;
            }    
            if (collection.Count != 1) {
                int key = collection.Count/2;
                List<Song> result = new List<Song>();
                result.Add(collection[key]);

                for (int i = 0; i < collection.Count(); i++) {
                    if (collection[i].CompareTo(collection[key]) == -1) {
                        result.Insert(0, collection[i]);
                    }
                    if (collection[i].CompareTo(collection[key]) == 1) {
                        result.Add(collection[i]);        
                    }
                    if (key == i)
                        continue;
                }
                List<Song> Left = QuickSort(result.Take(key).ToList());
                List<Song> Right = QuickSort(result.Skip(key).ToList());
                result = Left.Union(Right).ToList();
                
                return result;
            }
            
            return collection;
        }
Example #18
0
        /// <summary>
        /// Will communicate with Twitter to fetch the latest "x" tweets based on the account name passed in.
        /// </summary>
        /// <param name="twitterName">Twitter name</param>
        /// <param name="count">Number of tweets to get.</param>
        /// <returns>Collectin of tweets.</returns>
        public IEnumerable<Tweet> GetTweets(string twitterName, int count = 5)
        {
            if (twitterName.StartsWith("@"))
            {
                twitterName = twitterName.Replace("@", "");
            }

            try
            {
                var client = new WebClient();
                var response = client.DownloadString(new Uri(
                    string.Format("https://api.twitter.com/1/statuses/user_timeline.json?screen_name={0}", twitterName)));
                dynamic json = JArray.Parse(response);
                var tweets = new List<Tweet>();

                foreach (var item in json)
                {
                    tweets.Add(new Tweet
                    {
                        Message = LinkifyTweet(item.text.ToString()),
                        ImageUrl = item.user.profile_image_url,
                        ScreenName = item.user.screen_name,
                        RelativeDate = GetRelativeDate(item.created_at.ToString())
                    });
                }

                return tweets.Take(count);
            }
            catch
            {
                return new List<Tweet>();
            }
        }
        public List<Milestone> GetByFilter(TaskFilter filter)
        {
            var listMilestones = new List<Milestone>();

            while (true)
            {
                var milestones = _milestoneDao.GetByFilter(filter, ProjectSecurity.CurrentUserAdministrator);

                if (filter.LastId != 0)
                {
                    var lastMilestoneIndex = milestones.FindIndex(r => r.ID == filter.LastId);

                    if (lastMilestoneIndex >= 0)
                    {
                        milestones = milestones.SkipWhile((r, index) => index <= lastMilestoneIndex).ToList();
                    }
                }

                listMilestones.AddRange(milestones);

                if (filter.Max <= 0 || filter.Max > 150000) break;

                listMilestones = listMilestones.Take((int) filter.Max).ToList();

                if (listMilestones.Count == filter.Max || milestones.Count == 0) break;

                if (listMilestones.Count != 0)
                    filter.LastId = listMilestones.Last().ID;

                filter.Offset += filter.Max;
            }

            return listMilestones;
        }
Example #20
0
        public static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());

            var magicSequence = new Queue<int>();
            var seqNumbers = new List<int>
            {
                n
            };

            magicSequence.Enqueue(n);
            while (seqNumbers.Count < 50)
            {
                var firstItem = magicSequence.Peek() + 1;
                magicSequence.Enqueue(firstItem);
                var secondItem = (magicSequence.Peek() * 2) + 1;
                magicSequence.Enqueue(secondItem);
                var thirdItem = firstItem + 1;
                magicSequence.Enqueue(thirdItem);

                magicSequence.Dequeue();
                seqNumbers.Add(firstItem);
                seqNumbers.Add(secondItem);
                seqNumbers.Add(thirdItem);
            }

            Console.WriteLine(string.Join(", ", seqNumbers.Take(50)));
        }
Example #21
0
		static void Main(string[] args)
		{
			var arguments = new List<string>(args);
			var input = new List<string>();

			if (Console.IsInputRedirected)
			{
				string line;
				while ((line = Console.ReadLine()) != null)
				{
					input.Add(line);
				}
			}

			if (!arguments.Any())
			{
				//PrintHelp();
				return;
			}

			var fromEnd = false;
			if (arguments.Contains("-e"))
			{
				arguments.Remove("-e");
				fromEnd = true;
			}

			int take;
			if (!int.TryParse(arguments[0], out take))
			{
				return;
			}
			arguments.RemoveAt(0);

			var tempList = new List<string>(input);

			if (fromEnd)
			{
				tempList.Reverse();
			}

			if (take < 0)
			{
				take = tempList.Count + take;
			}

			tempList =
				//take < 0 ? tempList.Skip(tempList.Count + take).ToList() :
				tempList.Take(take).ToList();

			if (fromEnd)
			{
				tempList.Reverse();
			}

			foreach (var line in tempList)
			{
				Console.WriteLine(line);
			}
		}
Example #22
0
        public virtual List<FeedItem> ReadFeedItems(int count = 20)
        {
            List<FeedItem> items = new List<FeedItem>();
            XmlDocument rssXmlDoc = new XmlDocument();
            try
            {
                try
                {
                    rssXmlDoc.Load(this.FeedURL);
                }
                catch (Exception ex1)
                {
                }
                // Parse the Items in the RSS file
                XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");

                // Iterate through the items in the RSS file
                foreach (XmlNode rssNode in rssNodes)
                {
                    string title = ReadNodeElement(rssNode, "title");
                    string link = ReadNodeElement(rssNode, "link");
                    string description = ReadNodeElement(rssNode, "description");
                    DateTime pubDate = Utility.eDateTime.ToDateTime(ReadNodeElement(rssNode, "pubDate"));

                    items.Add(new FeedItem() { Title = this.Title, URL = this.URL, HeadLine = title, Description = description, Link = link, PublishedDate = pubDate });
                }
            }
            catch (Exception ex)
            {
            }
            return items.Take(count).ToList();
        }
Example #23
0
        //[UserAuthorize]
        public ActionResult Index()
        {
            //新闻
            AtlData2Model<News> a2m = new AtlData2Model<News>();
            List<News> newslist = new List<News>();

            ATLDATALib.IDBDataAtl rs = SM.RPC.ShipBoxPriceControl.GetNewsList("ntype", "");
            if (rs.IsOK()) {
                newslist = a2m.ConvertList(rs);
            } else {
                ViewBag.ErrorInfo = rs.GetErrorinfo();
            }
            newslist = newslist.Take(10).ToList();
            ViewBag.newslist = newslist;

            //客户列表
            AtlData2Model<Customer> c_a2m = new AtlData2Model<Customer>();
            List<Customer> customerlist = new List<Customer>();
            ATLDATALib.IDBDataAtl c_rs = SM.RPC.ShipBoxPriceControl.GetShipMemo("ntype", "");
            if (rs.IsOK()) {
                customerlist = c_a2m.ConvertList(c_rs);
            } else {
                ViewBag.ErrorInfo = rs.GetErrorinfo();
            }
            ViewBag.customerlist = customerlist;

            return View();
        }
        /// <summary>
        /// Add a PartID to our Recently Viewed Parts Session object
        /// </summary>
        /// <param name="id">ID of the part to be added.</param>
        internal static void AddRecentPart(int id)
        {
            try {
                HttpCookie recent_cookie = HttpContext.Current.Request.Cookies.Get("recent_parts");
                List<int> recent_parts = new List<int>();
                if (recent_cookie == null || recent_cookie.Value == null) {
                    recent_cookie = new HttpCookie("recent_parts");
                    recent_cookie.Expires = DateTime.Now.AddDays(30);

                    recent_parts.Add(id);

                    recent_cookie.Value = Newtonsoft.Json.JsonConvert.SerializeObject(recent_parts);
                    HttpContext.Current.Response.Cookies.Add(recent_cookie);
                } else {
                    List<int> unique_ids = new List<int>();
                    List<int> recent_partIds = new List<int>();

                    recent_partIds = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(recent_cookie.Value);
                    recent_cookie.Expires = DateTime.Now.AddDays(-1);

                    HttpCookie new_cookie = new HttpCookie("recent_parts");
                    new_cookie.Expires = DateTime.Now.AddDays(30);

                    if (!recent_partIds.Contains(id)) {
                        recent_partIds.Add(id);
                    }
                    recent_partIds = recent_partIds.Take(5).ToList<int>();
                    new_cookie.Value = Newtonsoft.Json.JsonConvert.SerializeObject(recent_partIds);
                    HttpContext.Current.Response.Cookies.Add(new_cookie);
                }
            } catch (Exception) { }
        }
        public Statistics(IEnumerable<double> values)
        {
            list = values.ToList();
            N = list.Count;
            if (N == 0)
                throw new InvalidOperationException("StatSummary: Sequence contains no elements");
            list.Sort();

            if (N == 1)
                Q1 = Median = Q3 = list[0];
            else
            {
                Func<IList<double>, double> getMedian = x => x.Count % 2 == 0
                    ? (x[x.Count / 2 - 1] + x[x.Count / 2]) / 2
                    : x[x.Count / 2];
                Median = getMedian(list);
                Q1 = getMedian(list.Take(N / 2).ToList());
                Q3 = getMedian(list.Skip((N + 1) / 2).ToList());
            }

            Min = list.First();
            Mean = list.Average();
            Max = list.Last();

            InterquartileRange = Q3 - Q1;
            LowerFence = Q1 - 1.5 * InterquartileRange;
            UpperFence = Q3 + 1.5 * InterquartileRange;

            Outliers = list.Where(IsOutlier).ToArray();

            StandardDeviation = N == 1 ? 0 : Math.Sqrt(list.Sum(d => Math.Pow(d - Mean, 2)) / (N - 1));
            StandardError = StandardDeviation / Math.Sqrt(N);
            ConfidenceInterval = new ConfidenceInterval(Mean, StandardError);
            Percentiles = new PercentileValues(list);
        }
        public static void Main()
        {
            var collectionOfProducts = new OrderedBag<Product>();

            for (int i = 0; i < NumberOfProducts; i++)
            {
                var product = new Product(RandomGenerator.GetRandomStringWithRandomLength(3, 7),
                    RandomGenerator.RandomDecimalBetween(1, 100));
                collectionOfProducts.Add(product);
            }

            Console.WriteLine("{0} products have been generated!", NumberOfProducts);

            var testSearch = new List<Product>();

            Console.WriteLine("Running {0} searches:", NumberOfSearches);
            for (int i = 0; i < NumberOfSearches; i++)
            {
                testSearch = SearchProductsByRange(collectionOfProducts, RandomGenerator.RandomDecimalBetween(1, 10),
                    RandomGenerator.RandomDecimalBetween(11, 100));

                if (i%100 == 0)
                {
                    Console.Write("=");
                }
            }

            Console.WriteLine("\r\nTotal products matching the last search criteria: {0}", testSearch.Count);
            Console.WriteLine("First 20 products:");
            foreach (var product in testSearch.Take(20))
            {
                Console.WriteLine(product);
            }
        }
        public override object Deserialize(List<byte> byteList, TLPropertyAttribute attribute)
        {
            int count = byteList.ReadByte();
            int startOffset = 1;

            if (count >= 254)
            {
                count = byteList.ReadByte();
                count += byteList.ReadByte() << 8;
                count += byteList.ReadByte() << 16;
                startOffset = 4;
            }

            TLBytes bytes = new TLBytes(byteList.Take(count).ToArray());
            byteList.RemoveRange(0, count);

            int offset = (count + startOffset) % 4;
            if (offset != 0)
            {
                int offsetCount = 4 - offset;
                for (int i = 0; i < offsetCount; i++)
                    byteList.ReadByte();
            }

            return bytes;
        }
Example #28
0
        public List<int> GetPriceSum(List<int> costs, int numberOfGroup)
        {
            var result = new List<int>();

            if (numberOfGroup < 0) numberOfGroup = 1;

            var group = costs.Count % numberOfGroup == 0 ?
                costs.Count / numberOfGroup : costs.Count / numberOfGroup + 1;

            for (int i = 0; i < group; i++)
            {
                int total;
                if (costs.Count >= numberOfGroup)
                {
                    total = costs.Take(numberOfGroup).Sum();
                    result.Add(total);
                }
                else
                {
                    total = costs.Sum();
                    result.Add(total);
                    break;
                }

                costs.RemoveRange(0, numberOfGroup);
            }

            return result;
        }
Example #29
0
        public MyDayViewModel(
            [Import] IEventAggregator aggregator,
            [Import] ITasksService tasksService,
            [Import] IProjectsService projectsService,
            [Import] ITeamService teamService,
            [Import] IBackgroundExecutor executor,
            [Import] IAuthorizationService authorizator)
            : base(aggregator, tasksService, projectsService, teamService, executor, authorizator)
        {
            aggregator.Subscribe<MemberProfile>(ScrumFactoryEvent.SignedMemberChanged, OnSignedMemberChanged);

            aggregator.Subscribe<Task>(ScrumFactoryEvent.TaskAdded, t => { UpdateTasks(); });
            aggregator.Subscribe<Task>(ScrumFactoryEvent.TaskAssigneeChanged, t => { UpdateTasks(); });
            aggregator.Subscribe<Task>(ScrumFactoryEvent.TaskChanged, t => { UpdateTasks(); });

            aggregator.Subscribe<ICollection<ProjectInfo>>(ScrumFactoryEvent.RecentProjectChanged, prjs => {
                List<ProjectInfo> prjs2 = new List<ProjectInfo>(prjs);
                if (MemberEngagedProjects != null)
                    prjs2.RemoveAll(p => MemberEngagedProjects.Any(ep => ep.ProjectUId == p.ProjectUId));
                RecentProjects = prjs2.Take(8).ToList();
                OnPropertyChanged("RecentProjects");
            });

            OnLoadCommand = new DelegateCommand(OnLoad);
            RefreshCommand = new DelegateCommand(Load);
            ShowMemberDetailCommand = new DelegateCommand<MemberProfile>(ShowMemberDetail);
            CreateNewProjectCommand = new DelegateCommand(CreateNewProject);

            eventsViewSource = new System.Windows.Data.CollectionViewSource();
        }
Example #30
0
        public async Task<IEnumerable<IGameServer>> GetServersAsync(MasterServerRequest masterServerRequest)
        {
            var endPoints = new List<IPEndPoint>();

            var packet = 0;
            using (var client = SteamAgent.GetUdpClient(_endpoint))
            {
                while (!masterServerRequest.MaximumPackets.HasValue || packet < masterServerRequest.MaximumPackets.Value)
                {
                    var request = GetRequest(endPoints.LastOrDefault(), masterServerRequest.Region, masterServerRequest.Filters);
                    var response = await SteamAgent.RequestResponseAsync(client, request, IpEndPointLength);

                    packet++;

                    var packetEndPoints = ReadEndPointsFromPacket(response);
                    endPoints.AddRange(packetEndPoints);

                    if (endPoints.Last().IsEmpty())
                    {
                        break;
                    }
                }
            }

            return endPoints.Take(endPoints.Count - 1).Select(e => new GameServer(e));
        }