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(); }
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); } }
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()); }
// 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()); }
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); } } }
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(); }
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; }
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 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(); }
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; }
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))); }
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); }
/// <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 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; }
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)); }
/// <summary> /// </summary> /// <param name="snapshot"></param> /// <param name="businessCriterias"></param> /// <param name="count"></param> /// <returns></returns> public static IEnumerable <TechnicalCriteriaResultDTO> GetTechnicalCriteriasByBusinessCriterias(Snapshot snapshot, IEnumerable <string> businessCriterias, int count) { var listBCs = businessCriterias as IList <string> ?? businessCriterias.ToList(); if (snapshot?.QIBusinessCriterias == null || listBCs.Count == 0 || !listBCs.Any()) { return(null); } List <TechnicalCriteriaResultDTO> technicalCriteriasResults = null; var technicalCriterias = snapshot.QIBusinessCriterias.Where(_ => listBCs.Contains(_.Key.ToString()) && _.Contributors != null) .SelectMany(_ => _.Contributors) .Select(_ => _.Key).ToList(); if (technicalCriterias.Count != 0) { technicalCriteriasResults = (from result in snapshot.TechnicalCriteriaResults where technicalCriterias.Contains(result.Reference.Key) && result.DetailResult != null select new TechnicalCriteriaResultDTO { Key = result.Reference.Key, Name = result.Reference.Name, Grade = MathUtility.GetRound(result.DetailResult.Grade) }) .OrderBy(_ => _.Name) .ToList(); } if (count > 0) { technicalCriteriasResults = technicalCriteriasResults?.Take(count).ToList(); } return(technicalCriteriasResults); }
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; }
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; }
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; }
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 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); } }
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; }
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); } }
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))); }
//[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(); }
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; }
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(); }
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]); }
/// <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 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 void FirstPage() { CurrentPage = 1; int maxNum = Total >= MaxSize ? MaxSize : Total; var list = Source?.Take(maxNum); PagePagingEvent?.Invoke(list, CurrentPage, TotalPage); }
private void ResetCursor(bool resetUnit = true) { Log("Cursor Reset"); CursorState = Enums.CursorState.Default; _pM.ResetBlockGrid(); if (CurrentUnit != null && resetUnit) { CurrentUnit.OnUnitInterupt -= OnCurrentUnitInterupt; Log("Current Unit null"); var pathColor = Colors.GetPathColor(); var savedPath = _moves?.Take(_moves.Count - 1).ToList(); savedPath?.ForEach(m => m.Path_Save(CurrentUnit, pathColor)); CurrentUnit = null; } _moves = null; }
//internal static string GetFormattedItemSearchQueryFromEntities(Rasa.ApiClient.Model.ParseResult parseResult) //{ // if (!string.IsNullOrWhiteSpace(parseResult?.Text)) // { // if (parseResult.Entities != null && parseResult.Entities.Count > 0) // { // var etis = parseResult.Entities.Where(a => a._Entity == "brand" || a._Entity == "product").ToList(); // if (etis.Count(a => a._Entity == "brand") == 1 && etis.Count(a => a._Entity == "product") == 1) // { // return etis.First(a => a._Entity == "brand").Value.ToString() + " " + etis.First(a => a._Entity == "product").Value.ToString(); // } // else if (etis.Count == 1 && etis.Any(a => a._Entity == "product")) // { // return etis.First(a => a._Entity == "product").Value.ToString(); // } // else if (etis.Count > 2) // { // return string.Join(" ", etis.OrderBy(a => a.Start).Select(a => a.Value?.ToString() ?? string.Empty).Where(a => !string.IsNullOrWhiteSpace(a))); // } // else if ((etis.Count == 1 && etis.Any(a => a._Entity == "brand")) || etis.All(a => a._Entity == "brand")) // { // return null; // //return parseResult.Text.ToLower().Trim(); // } // } // } // return null; //} //internal static FacebookChannelData<TemplatePayload> CreateFacebookReciptAttachmentFromCartVM(CartVM cartVM, string recipientName) //{ // var data = new FacebookChannelData<TemplatePayload>(); // var payload = new ReceiptTemplatePayload(); // payload.Elements = new List<ReceiptTemplatePayloadElement>(); // foreach (var item in cartVM.CartItems) // { // payload.Elements.Add(new ReceiptTemplatePayloadElement { Title = item.ProductName, /*Subtitle = "100% Soft and Luxurious Cotton",*/ Quantity = item.Quantity, Price = item.Price, Currency = "LKR", ImageUrl = item.ImageUrl }); // } // payload.Sharable = false; // payload.RecipientName = recipientName; // payload.OrderNumber = cartVM.Id.ToString("N"); // payload.Currency = "LKR"; // payload.PaymentMethod = "Cash on Delivery"; // //payload.OrderURL = "http=//petersapparel.parseapp.com/order?order_id=123456"; // //payload.Timestamp = "1428444852"; // //payload.Elements = receiptTemplatePayloadElements; // //payload.Address = new ReceiptTemplatePayloadAddress() // //{ // // Street_1 = "1 Hacker Way", // // //Street_2 = "", // // City = "Menlo Park", // // PostalCode = "94025", // // State = "CA", // // Country = "US" // //}; // payload.Summary = new ReceiptTemplatePayloadSummary // { // //Subtotal = 75.00m, // //ShippingCost = 4.95m, // //TotalTax = 6.19m, // TotalCost = cartVM.TotalPrice, // }; // //payload.Adjustments = new List<ReceiptTemplatePayloadAdjustments> // //{ // // new ReceiptTemplatePayloadAdjustments // // { // // Name="New Customer Discount", // // Amount=20m // // }, // // new ReceiptTemplatePayloadAdjustments // // { // // Name="$10 Off Coupon", // // Amount=10m // // } // //}; // data.Attachment.Payload = payload; // return data; //} //internal static FacebookChannelData<TemplatePayload> CreateFacebookGenericCardAttachment(List<ProductSearchService.ProductSearchResult> ProductList) //{ // var data = new FacebookChannelData<TemplatePayload>(); // var payload = new GenericTemplatePayload(); // ProductList = ProductList?.Take(6).ToList(); // if (ProductList != null && ProductList.Count > 0) // { // foreach (var product in ProductList) // { // payload.Elements.Add(new GenericTemplatePayloadElement // { // Title = product.Product.ProductName, // Subtitle = $"{"රු "}{product.Product.Price}{"/="}", // ImageUrl = product.Product.ImageUrl, // Buttons = new List<Button>{ // new PostBackButton(){Title="Buy One",Payload=$"{"buynow"}{"!@#$"}{product.Product.Id}{"!@#$"}{1}"}, // new PostBackButton(){Title="Buy Two",Payload=$"{"buynow"}{"!@#$"}{product.Product.Id}{"!@#$"}{2}"}, // new PostBackButton(){Title="Buy More",Payload=$"{"buynow"}{"!@#$"}{product.Product.Id}{"!@#$"}{"more"}"}, // } // }); // } // data.Attachment.Payload = payload; // return data; // } // else // { // return null; // } //} internal static List <Attachment> CreateHeroCardAttachments(List <Product> ProductList) { var attachments = new List <Attachment>(); ProductList = ProductList?.Take(6).ToList(); if (ProductList != null && ProductList.Count > 0) { foreach (var product in ProductList) { var card = new HeroCard { Images = new List <CardImage> { new CardImage { Url = product.ImageUrl } }, Title = product.Name_SI, Subtitle = $"{"රු "}{product.Price}{"/="}", Buttons = new List <CardAction> { new CardAction { Title = "Buy One", Value = $"{"buynow"}{"!@#$"}{product.Id}{"!@#$"}{1}", Type = ActionTypes.PostBack, DisplayText = "Buy One" }, new CardAction { Title = "Buy Two", Value = $"{"buynow"}{"!@#$"}{product.Id}{"!@#$"}{2}", Type = ActionTypes.PostBack, DisplayText = "Buy Two" }, new CardAction { Title = "Buy More", Value = $"{"buynow"}{"!@#$"}{product.Id}{"!@#$"}{"more"}", Type = ActionTypes.PostBack, DisplayText = "Buy More" } } }; attachments.Add(card.ToAttachment()); } return(attachments); } else { return(null); } }
//internal static string GetFormattedItemSearchQueryFromEntities(Rasa.ApiClient.Model.ParseResult parseResult) //{ // if (!string.IsNullOrWhiteSpace(parseResult?.Text)) // { // if (parseResult.Entities != null && parseResult.Entities.Count > 0) // { // var etis = parseResult.Entities.Where(a => a._Entity == "brand" || a._Entity == "product").ToList(); // if (etis.Count(a => a._Entity == "brand") == 1 && etis.Count(a => a._Entity == "product") == 1) // { // return etis.First(a => a._Entity == "brand").Value.ToString() + " " + etis.First(a => a._Entity == "product").Value.ToString(); // } // else if (etis.Count == 1 && etis.Any(a => a._Entity == "product")) // { // return etis.First(a => a._Entity == "product").Value.ToString(); // } // else if (etis.Count > 2) // { // return string.Join(" ", etis.OrderBy(a => a.Start).Select(a => a.Value?.ToString() ?? string.Empty).Where(a => !string.IsNullOrWhiteSpace(a))); // } // else if ((etis.Count == 1 && etis.Any(a => a._Entity == "brand")) || etis.All(a => a._Entity == "brand")) // { // return null; // //return parseResult.Text.ToLower().Trim(); // } // } // } // return null; //} //internal static FacebookChannelData<TemplatePayload> CreateFacebookReciptAttachmentFromCartVM(CartVM cartVM, string recipientName) //{ // var data = new FacebookChannelData<TemplatePayload>(); // var payload = new ReceiptTemplatePayload(); // payload.Elements = new List<ReceiptTemplatePayloadElement>(); // foreach (var item in cartVM.CartItems) // { // payload.Elements.Add(new ReceiptTemplatePayloadElement { Title = item.ProductName, /*Subtitle = "100% Soft and Luxurious Cotton",*/ Quantity = item.Quantity, Price = item.Price, Currency = "LKR", ImageUrl = item.ImageUrl }); // } // payload.Sharable = false; // payload.RecipientName = recipientName; // payload.OrderNumber = cartVM.Id.ToString("N"); // payload.Currency = "LKR"; // payload.PaymentMethod = "Cash on Delivery"; // //payload.OrderURL = "http=//petersapparel.parseapp.com/order?order_id=123456"; // //payload.Timestamp = "1428444852"; // //payload.Elements = receiptTemplatePayloadElements; // //payload.Address = new ReceiptTemplatePayloadAddress() // //{ // // Street_1 = "1 Hacker Way", // // //Street_2 = "", // // City = "Menlo Park", // // PostalCode = "94025", // // State = "CA", // // Country = "US" // //}; // payload.Summary = new ReceiptTemplatePayloadSummary // { // //Subtotal = 75.00m, // //ShippingCost = 4.95m, // //TotalTax = 6.19m, // TotalCost = cartVM.TotalPrice, // }; // //payload.Adjustments = new List<ReceiptTemplatePayloadAdjustments> // //{ // // new ReceiptTemplatePayloadAdjustments // // { // // Name="New Customer Discount", // // Amount=20m // // }, // // new ReceiptTemplatePayloadAdjustments // // { // // Name="$10 Off Coupon", // // Amount=10m // // } // //}; // data.Attachment.Payload = payload; // return data; //} internal static FacebookChannelData <TemplatePayload> CreateFacebookGenericCardAttachment(List <Product> ProductList) { var data = new FacebookChannelData <TemplatePayload>(); var payload = new GenericTemplatePayload(); ProductList = ProductList?.Take(6).ToList(); if (ProductList != null && ProductList.Count > 0) { foreach (var product in ProductList) { payload.Elements.Add(new GenericTemplatePayloadElement { Title = product.Name_SI, Subtitle = $"{"රු "}{product.Price}{"/="}", ImageUrl = product.ImageUrl, Buttons = new List <Button> { new PostBackButton() { Title = "Buy One", Payload = $"{"buynow"}{"!@#$"}{product.Id}{"!@#$"}{1}" }, new PostBackButton() { Title = "Buy Two", Payload = $"{"buynow"}{"!@#$"}{product.Id}{"!@#$"}{2}" }, new PostBackButton() { Title = "Buy More", Payload = $"{"buynow"}{"!@#$"}{product.Id}{"!@#$"}{"more"}" }, } }); } data.Attachment.Payload = payload; return(data); } else { return(null); } }
private double IndexToVerticalOffset(int index) { return(_offsets?.Take(index).Sum() ?? 0D); }
static void Main(string[] args) { String[] months = new String[] { "June", "July", "August", "September", "October", "November", "December", "January", "February", "March", "April", "May" }; var selectedMonths = months.Where(t => t.Length == 5); foreach (var month in selectedMonths) { Console.WriteLine(month); } Console.WriteLine(new String('_', 40));/////////////////////////////////////////////// var selectMonthsSummer = months.Where(t => t == "June" || t == "July" || t == "August"); foreach (var month in selectMonthsSummer) { Console.WriteLine(month); } Console.WriteLine(new String('_', 40));/////////////////////////////////////////////////// var selectMonthAlph = months.Where(t => t.IndexOf("u") > -1).OrderBy(t => t); foreach (var month in selectMonthAlph) { Console.WriteLine(month); } var games = new List <Vector>(); games.AddRange(new Vector[] { new Vector(1, 1), new Vector(44, 14), new Vector(13, 11), new Vector(22, 22), new Vector(24, 19), new Vector(42, 12), }); Console.WriteLine(new String('_', 40));/////////////////////////////////////////// var zeroVector = games.Where(t => t.X == 44 || t.Y == 22).Count(); Console.WriteLine(zeroVector); Console.WriteLine(new String('_', 40));///////////////////////////////////////////// var low = games.Where(t => t.Module() < 20); foreach (var VARIABLE in low) { VARIABLE.ShowDetail(); } //foreach (var mod in games) //{ // Double b = mod.Module(); // if (b < a) // { // a = b; // } // else // Console.WriteLine(mod.Module()); //} Console.WriteLine(new String('_', 40));////////////////////////////////////// var massive = games.Where(t => t.Scalar() == 3 || t.Scalar() == 5 || t.Scalar() == 7); foreach (var VARIABLE in massive) { VARIABLE.ShowDetail(); } Console.WriteLine(new String('_', 40));////////////////////////////////////// var minus = games.Select(t => t.Scalar()).Min(); Console.WriteLine(minus); var sort = games.OrderBy(t => t.Scalar()); foreach (var VARIABLE in sort) { VARIABLE.ShowDetail(); } var gae = new List <Game>(); gae.AddRange(new Game[] { new Game(2016, "RPG", 18, "The Witcher 3: Wild Hunt"), new Game(2015, "Action", 16, "GTA 5"), new Game(2016, "Action", 12, "GTA: SanAndreas"), new Game(2009, "FPS", 18, "Call Of Duty: MW"), }); Console.WriteLine(new String('_', 40));////////////////////////////////// var genreGame = gae.Where(t => t.Genre == "Action"); foreach (var VARIABLE in genreGame) { Console.WriteLine(VARIABLE.TitleName); } Console.WriteLine(new String('_', 40)); /////////////////////////////// /// var selectAge = gae.Select(t => t.AgeLimit); foreach (var VARIABLE in selectAge) { Console.WriteLine(VARIABLE); } Console.WriteLine(new String('_', 40));/////////////////////////////// var sortedGames = gae.OrderBy(t => t.YearOfPublication); foreach (var VARIABLE in sortedGames) { Console.WriteLine(VARIABLE.TitleName); } Console.WriteLine(new String('_', 40)); ///////////////////////////// /// var groupedGames = gae.GroupBy(t => t.TitleName); foreach (var VARIABLE in groupedGames) { Console.WriteLine(VARIABLE.Key); } Console.WriteLine(new String('_', 40));//////////////////////// int[] numbers = { 1, 2, 3, 4, 5 }; int query = numbers.Aggregate((x, y) => x - y); Console.WriteLine(new String('_', 40));////////////////////// var average = gae.Average(t => t.AgeLimit); Console.WriteLine(average); Console.WriteLine(new String('_', 40));////////////////////// var takeGame = gae.Take(3); foreach (var VARIABLE in takeGame) { Console.WriteLine(VARIABLE.TitleName); } Console.WriteLine(new String('_', 40));////////////////////// List <Team> teams = new List <Team>() { new Team { Name = "Бавария", Country = "Германия" }, new Team { Name = "Барселона", Country = "Испания" }, new Team { Name = "Ювентус", Country = "Италия" } }; List <Player> players = new List <Player>() { new Player { Name = "Роббен", Team = "Бавария" }, new Player { Name = "Неймар", Team = "Барселона" }, new Player { Name = "Буффон", Team = "Ювентус" } }; var result = players.Join(teams, p => p.Team, t => t.Name, (p, t) => new { Name = p.Name, Team = p.Team, Country = t.Country }); foreach (var item in result) { Console.WriteLine("{0} - {1} ({2})", item.Name, item.Team, item.Country); } }
public void BoardMoveEquality() { List <UnitMove> mv = new List <UnitMove>() { new UnitMove(Fleet.Get(Powers.Austria), MapNodes.Get("nao")), //0 new UnitMove(Fleet.Get(Powers.Austria), MapNodes.Get("nth")), //1 new UnitMove(Army.Get(Powers.Austria), MapNodes.Get("edi")), //2 new UnitMove(Army.Get(Powers.Austria), MapNodes.Get("mun"), true), //3 new UnitMove(Army.Get(Powers.Austria), MapNodes.Get("stp"), true), //4 new UnitMove(Army.Get(Powers.England), MapNodes.Get("eng"), true), //5 new UnitMove(Fleet.Get(Powers.England), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("nwy"), MapNodes.Get("bar"))), //6 new UnitMove(Fleet.Get(Powers.England), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("mao"), MapNodes.Get("wes"))), //7 new UnitMove(Army.Get(Powers.Germany), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("mun"), MapNodes.Get("boh"))), //8 new UnitMove(Army.Get(Powers.Germany), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("sil"), MapNodes.Get("war"))), //9 new UnitMove(Army.Get(Powers.Russia), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("stp"), MapNodes.Get("swe")), new List <MapNode> { MapNodes.Get("bot"), }), //10 new UnitMove(Army.Get(Powers.Russia), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("sev"), MapNodes.Get("ank")), new List <MapNode> { MapNodes.Get("bla"), }), //11 new UnitMove(Army.Get(Powers.France), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("mar"), MapNodes.Get("tus")), new List <MapNode> { MapNodes.Get("lyo"), MapNodes.Get("wes"), MapNodes.Get("tys"), }), //12 }; List <UnitMove> mv2 = new List <UnitMove>() { new UnitMove(Fleet.Get(Powers.Austria), MapNodes.Get("nao")), //0 new UnitMove(Fleet.Get(Powers.Austria), MapNodes.Get("nth")), //1 new UnitMove(Army.Get(Powers.Austria), MapNodes.Get("edi")), //2 new UnitMove(Army.Get(Powers.Austria), MapNodes.Get("mun"), true), //3 new UnitMove(Army.Get(Powers.Austria), MapNodes.Get("stp"), true), //4 new UnitMove(Army.Get(Powers.England), MapNodes.Get("eng"), true), //5 new UnitMove(Fleet.Get(Powers.England), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("nwy"), MapNodes.Get("bar"))), //6 new UnitMove(Fleet.Get(Powers.England), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("mao"), MapNodes.Get("wes"))), //7 new UnitMove(Army.Get(Powers.Germany), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("mun"), MapNodes.Get("boh"))), //8 new UnitMove(Army.Get(Powers.Germany), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("sil"), MapNodes.Get("war"))), //9 new UnitMove(Army.Get(Powers.Russia), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("stp"), MapNodes.Get("swe")), new List <MapNode> { MapNodes.Get("bot"), }), //10 new UnitMove(Army.Get(Powers.Russia), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("sev"), MapNodes.Get("ank")), new List <MapNode> { MapNodes.Get("bla"), }), //11 new UnitMove(Army.Get(Powers.France), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("mar"), MapNodes.Get("tus")), new List <MapNode> { MapNodes.Get("lyo"), MapNodes.Get("wes"), MapNodes.Get("tys"), }), //12 }; BoardMove boardMove1 = new BoardMove(); boardMove1.AddRange(mv); BoardMove boardMove2 = new BoardMove(); boardMove2.AddRange(mv2); BoardMove boardMove3 = new BoardMove(); boardMove3.AddRange(mv.Where(um => um.Unit.UnitType == UnitType.Army)); Assert.AreNotEqual(boardMove1, boardMove3); BoardMove boardMove4 = new BoardMove(); boardMove4.AddRange(mv.Take(12)); boardMove4.Add(new UnitMove(Army.Get(Powers.Germany), new QuickGraph.UndirectedEdge <MapNode>(MapNodes.Get("mar"), MapNodes.Get("tus")), new List <MapNode> { MapNodes.Get("lyo"), MapNodes.Get("wes"), MapNodes.Get("tys"), })); Assert.AreNotEqual(boardMove1, boardMove4); }
public async Task <ActionResult> searchData(string fromMenu) { IList <Product> alcoholProductList = new List <Product>(); IList <Product> cigarProductList = new List <Product>(); IList <Bundle> BundleList = new List <Bundle>(); IList <SearchItem> resultList = new List <SearchItem>(); IList <SearchItem> returnList = new List <SearchItem>(); string searchItem = Request.Form["searchItem"]; string minPrice = Request.Form["minPrice"]; string maxPrice = Request.Form["maxPrice"]; string categoryID = Request.Form["categoryID"]; string alcoholOrigin = Request.Form["alcoholOrigin"]; string cigarBrand = Request.Form["cigarBrand"]; string wrapperType = Request.Form["wrapperType"]; string strengthID = Request.Form["strengthID"]; string cigarOrigin = Request.Form["cigarOrigin"]; string pageNumber = Request.Form["pageNumber"]; string choices = Request.Form["choice"]; if (fromMenu != null) { alcoholProductList = await searchAlcoholProducts(fromMenu, 0, 10000, "", ""); cigarProductList = await searchCigarProducts(fromMenu, 0, 10000, "", "", "", ""); await convertToSearchItemList(resultList, "alcohol", alcoholProductList, null); await convertToSearchItemList(resultList, "cigar", cigarProductList, null); return(View("Search", resultList)); } int pageNum = int.Parse(pageNumber); if (pageNum == 1) { Thread.Sleep(2000); } else { Thread.Sleep(1000); } if (choices != null && choices.Contains("Alcohol")) { alcoholProductList = await searchAlcoholProducts(searchItem, int.Parse(minPrice), int.Parse(maxPrice), categoryID, alcoholOrigin); await convertToSearchItemList(resultList, "alcohol", alcoholProductList, null); } if (choices != null && choices.Contains("Cigar")) { cigarProductList = await searchCigarProducts(searchItem, int.Parse(minPrice), int.Parse(maxPrice), cigarBrand, wrapperType, strengthID, cigarOrigin); await convertToSearchItemList(resultList, "cigar", cigarProductList, null); } if (choices != null && choices.Contains("Bundle")) { alcoholProductList = await searchAlcoholProducts(searchItem, int.Parse(minPrice), int.Parse(maxPrice), categoryID, alcoholOrigin); cigarProductList = await searchCigarProducts(searchItem, int.Parse(minPrice), int.Parse(maxPrice), cigarBrand, wrapperType, strengthID, cigarOrigin); BundleList = await searchBundles(alcoholProductList, cigarProductList); await convertToSearchItemList(resultList, "bundle", null, BundleList); } returnList = resultList.Take(pageNum * 6).ToList(); string more = ""; if (returnList.Count == resultList.Count) { more = "no"; } else { more = "yes"; } var ret = new { pList = returnList, more = more }; JavaScriptSerializer myJSS = new JavaScriptSerializer(); return(Json(myJSS.Serialize(ret), JsonRequestBehavior.AllowGet)); }
private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (_isRunning) { return; } _isRunning = true; try { Execute(OpCode.QUERY_PACKET, 100); _buffer.AddRange(IO.ReadBytes(IO.BytesToRead)); while (_buffer.Count >= 80 && _timer != null) { var data = _buffer.Take(80).ToArray(); _buffer.RemoveRange(0, 80); var sensorData = new SensorData(data); ARC.Scripting.VariableManager.SetVariable("$RoombaAngle", sensorData.Angle); ARC.Scripting.VariableManager.SetVariable("$RoombaBatteryCapacity", sensorData.BatteryCapacity); ARC.Scripting.VariableManager.SetVariable("$RoombaBatteryCharge", sensorData.BatteryCharge); ARC.Scripting.VariableManager.SetVariable("$RoombaBumpLeft", sensorData.BumpLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaBumpRight", sensorData.BumpRight); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonClean", sensorData.ButtonClean); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonClock", sensorData.ButtonClock); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonDay", sensorData.ButtonDay); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonDock", sensorData.ButtonDock); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonHour", sensorData.ButtonHour); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonMinute", sensorData.ButtonMinute); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonSchedule", sensorData.ButtonSchedule); ARC.Scripting.VariableManager.SetVariable("$RoombaButtonSpot", sensorData.ButtonSpot); bool btnState = sensorData.ButtonState > 0; if (btnState && !_lastButtonState) { OnButtonPressed?.Invoke(this, btnState); } _lastButtonState = btnState; ARC.Scripting.VariableManager.SetVariable("$RoombaChargingSourceHomeBase", sensorData.ChargingSourceHomeBase); ARC.Scripting.VariableManager.SetVariable("$RoombaChargingSourceCharger", sensorData.ChargingSourceInternalCharger); ARC.Scripting.VariableManager.SetVariable("$RoombaChargingState", sensorData.ChargingState); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffFrontLeft", sensorData.CliffFrontLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffFrontLeftSignal", sensorData.CliffFrontLeftSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffFrontRight", sensorData.CliffFrontRight); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffFrontRightSignal", sensorData.CliffFrontRightSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffLeft", sensorData.CliffLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffLeftSignal", sensorData.CliffLeftSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffRight", sensorData.CliffRight); ARC.Scripting.VariableManager.SetVariable("$RoombaCliffRightSignal", sensorData.CliffRightSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaCurrent", sensorData.Current); ARC.Scripting.VariableManager.SetVariable("$RoombaDirtDetect", sensorData.DirtDetect); ARC.Scripting.VariableManager.SetVariable("$RoombaDistance", sensorData.Distance); ARC.Scripting.VariableManager.SetVariable("$RoombaInfraredCharacterLeft", sensorData.InfraredCharacterLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaInfraredCharacterOmni", sensorData.InfraredCharacterOmni); ARC.Scripting.VariableManager.SetVariable("$RoombaInfraredCharacterRight", sensorData.InfraredCharacterRight); ARC.Scripting.VariableManager.SetVariable("$RoombaLeftEncoderCounts", sensorData.LeftEncoderCounts); ARC.Scripting.VariableManager.SetVariable("$RoombaLeftMotorCurrent", sensorData.LeftMotorCurrent); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperCenterLeft", sensorData.LightBumperCenterLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperCenterLeftSignal", sensorData.LightBumperCenterLeftSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperCenterRight", sensorData.LightBumperCenterRight); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperCenterRightSignal", sensorData.LightBumperCenterRightSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperFrontLeft", sensorData.LightBumperFrontLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperFrontLeftSignal", sensorData.LightBumperFrontLeftSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperFrontRight", sensorData.LightBumperFrontRight); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperFrontRightSignal", sensorData.LightBumperFrontRightSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperLeft", sensorData.LightBumperLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperLeftSignal", sensorData.LightBumperLeftSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperRight", sensorData.LightBumperRight); ARC.Scripting.VariableManager.SetVariable("$RoombaLightBumperRightSignal", sensorData.LightBumperRightSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaMainBrushMotorCurrent", sensorData.MainBrushMotorCurrent); ARC.Scripting.VariableManager.SetVariable("$RoombaNumberOfStreamPackets", sensorData.NumberOfStreamPackets); ARC.Scripting.VariableManager.SetVariable("$RoombaOIMode", sensorData.OIMode); ARC.Scripting.VariableManager.SetVariable("$RoombaOverCurrentLeftWheel", sensorData.OverCurrentLeftWheel); ARC.Scripting.VariableManager.SetVariable("$RoombaOverCurrentMainBrush", sensorData.OverCurrentMainBrush); ARC.Scripting.VariableManager.SetVariable("$RoombaOverCurrentRightWheel", sensorData.OverCurrentRightWheel); ARC.Scripting.VariableManager.SetVariable("$RoombaOverCurrentSideBrush", sensorData.OverCurrentSideBrush); ARC.Scripting.VariableManager.SetVariable("$RoombaRequestedLeftVelocity", sensorData.RequestedLeftVelocity); ARC.Scripting.VariableManager.SetVariable("$RoombaRequestedRadius", sensorData.RequestedRadius); ARC.Scripting.VariableManager.SetVariable("$RoombaRequestedRightVelocity", sensorData.RequestedRightVelocity); ARC.Scripting.VariableManager.SetVariable("$RoombaRequestedVelocity", sensorData.RequestedVelocity); ARC.Scripting.VariableManager.SetVariable("$RoombaRightEncoderCounts", sensorData.RightEncoderCounts); ARC.Scripting.VariableManager.SetVariable("$RoombaRightMotorCurrent", sensorData.RightMotorCurrent); ARC.Scripting.VariableManager.SetVariable("$RoombaSideBrushMotorCurrent", sensorData.SideBrushMotorCurrent); ARC.Scripting.VariableManager.SetVariable("$RoombaSongNumber", sensorData.SongNumber); ARC.Scripting.VariableManager.SetVariable("$RoombaSongPlaying", sensorData.SongPlaying); ARC.Scripting.VariableManager.SetVariable("$RoombaStatis", sensorData.Statis); ARC.Scripting.VariableManager.SetVariable("$RoombaTemperature", sensorData.Temperature); ARC.Scripting.VariableManager.SetVariable("$RoombaVirtualWall", sensorData.VirtualWall); ARC.Scripting.VariableManager.SetVariable("$RoombaVoltage", Math.Round((decimal)sensorData.Voltage / 1000, 2)); ARC.Scripting.VariableManager.SetVariable("$RoombaWall", sensorData.Wall); ARC.Scripting.VariableManager.SetVariable("$RoombaWallSignal", sensorData.WallSignal); ARC.Scripting.VariableManager.SetVariable("$RoombaWheelDropLeft", sensorData.WheelDropLeft); ARC.Scripting.VariableManager.SetVariable("$RoombaWheelDropRight", sensorData.WheelDropRight); //if (_sendNMS) { // var distance = ((sensorData.RightEncoderCounts + sensorData.LeftEncoderCounts) / 2d) / 25.8d; // ARC.MessagingService.Navigation2DV1.Messenger.UpdateLocation( // (int)EZ_B.Functions.DegX2(distance, sensorData.Angle), // (int)EZ_B.Functions.DegY2(distance, sensorData.Angle), // 255, // (int)delta); //} _streamPacketCnt++; OnStreamPacketCnt?.Invoke(this, _streamPacketCnt); sensorData = null; } } catch (Exception ex) { OnError?.Invoke(this, ex); StopStreaming(); } finally { _isRunning = false; } }
public OrganizationResponse Execute(OrganizationRequest req, XrmFakedContext ctx) { var request = req as RetrieveMultipleRequest; List <Entity> list = null; PagingInfo pageInfo = null; QueryExpression qe; string entityName = null; if (request.Query is QueryExpression) { qe = (request.Query as QueryExpression).Clone(); entityName = qe.EntityName; var linqQuery = XrmFakedContext.TranslateQueryExpressionToLinq(ctx, qe); list = linqQuery.ToList(); } else if (request.Query is FetchExpression) { var fetchXml = (request.Query as FetchExpression).Query; var xmlDoc = XrmFakedContext.ParseFetchXml(fetchXml); qe = XrmFakedContext.TranslateFetchXmlDocumentToQueryExpression(ctx, xmlDoc); entityName = qe.EntityName; var linqQuery = XrmFakedContext.TranslateQueryExpressionToLinq(ctx, qe); list = linqQuery.ToList(); if (xmlDoc.IsAggregateFetchXml()) { list = XrmFakedContext.ProcessAggregateFetchXml(ctx, xmlDoc, list); } } else if (request.Query is QueryByAttribute) { //We instantiate a QueryExpression to be executed as we have the implementation done already var query = request.Query as QueryByAttribute; qe = new QueryExpression(query.EntityName); entityName = qe.EntityName; qe.ColumnSet = query.ColumnSet; qe.Criteria = new FilterExpression(); for (var i = 0; i < query.Attributes.Count; i++) { qe.Criteria.AddCondition(new ConditionExpression(query.Attributes[i], ConditionOperator.Equal, query.Values[i])); } //QueryExpression now done... execute it! var linqQuery = XrmFakedContext.TranslateQueryExpressionToLinq(ctx, qe as QueryExpression); list = linqQuery.ToList(); } else { throw PullRequestException.NotImplementedOrganizationRequest(request.Query.GetType()); } if (qe.Distinct) { list = GetDistinctEntities(list); } // Handle the top count before taking paging into account if (qe.TopCount != null && qe.TopCount.Value < list.Count) { list = list.Take(qe.TopCount.Value).ToList(); } // Handle paging var pageSize = ctx.MaxRetrieveCount; pageInfo = qe.PageInfo; int pageNumber = 1; if (pageInfo != null && pageInfo.PageNumber > 0) { pageNumber = pageInfo.PageNumber; pageSize = pageInfo.Count == 0 ? ctx.MaxRetrieveCount : pageInfo.Count; } // Figure out where in the list we need to start and how many items we need to grab int numberToGet = pageSize; int startPosition = 0; if (pageNumber != 1) { startPosition = (pageNumber - 1) * pageSize - 1; } if (list.Count < pageSize) { numberToGet = list.Count; } else if (list.Count - pageSize * (pageNumber - 1) < pageSize) { numberToGet = list.Count - (pageSize * (pageNumber - 1)); } var recordsToReturn = startPosition + numberToGet > list.Count ? new List <Entity>() : list.GetRange(startPosition, numberToGet); recordsToReturn.ForEach(e => e.ApplyDateBehaviour(ctx)); recordsToReturn.ForEach(e => PopulateFormattedValues(e)); var response = new RetrieveMultipleResponse { Results = new ParameterCollection { { "EntityCollection", new EntityCollection(recordsToReturn) } } }; response.EntityCollection.EntityName = entityName; response.EntityCollection.MoreRecords = (list.Count - pageSize * pageNumber) > 0; if (response.EntityCollection.MoreRecords) { var first = response.EntityCollection.Entities.First(); var last = response.EntityCollection.Entities.Last(); response.EntityCollection.PagingCookie = String.Format( "<cookie page=\"{0}\"><{1}id last=\"{2}\" first=\"{3}\" /></cookie>", pageNumber, first.LogicalName, last.Id.ToString("B").ToUpper(), first.Id.ToString("B").ToUpper()); } return(response); }
private List<List<object>> CreateParameterCombinations(List<List<object>> parametersList, int topParameterCombinations) { for(int i =parametersList.Count-1; i>=0;i--) { parametersList[i] = parametersList[i].Distinct().ToList(); } var tmpd = parametersList.Select(x => x.Count); int combinations = 1; foreach (var t in tmpd) { combinations *= t; } int couuntY = parametersList.Count; List <List<object>> combinationList = new List<List<object>>(); for (int i = 0; i < combinations; i++) { List<object> list = new List<object>(); for (int j = 0; j < parametersList.Count; j++) { list.Add(null); } combinationList.Add(list); } int tmp = combinations; for (int i = 0; i < parametersList.Count; i++) { tmp /= parametersList[i].Count; int o = 0; for (int j = 0; j < combinationList.Count;) { for (int k = 0; k < tmp; k++, j++) { combinationList[j][i] = parametersList[i][o]; } o++; o %= parametersList[i].Count; } } int count = combinations > topParameterCombinations ? topParameterCombinations : combinations; if(autoCoverOptions.AllowRandomizeParametersWithTopCount) { if(count!= combinations) { Random r = new Random(combinations); List<int> randomizeItem = new List<int>(); List<List<object>> randomizedCombinationList = new List<List<object>>(); while(randomizedCombinationList.Count< topParameterCombinations) { int rand = r.Next()% combinations; if (randomizeItem.Contains(rand)) { continue; } randomizeItem.Add(rand); randomizedCombinationList.Add(combinationList[rand]); } return randomizedCombinationList; } } return combinationList.Take(count).ToList(); }
public async Task<ActionResult> ExportDataToExcel() { //查询出的数据 var list = new List<TestDataViewModel>(); list.Add(new TestDataViewModel { PlanSubject = "test1", MobileNo = "13577778888", TelcoOperatorText = "移动" }); list.Add(new TestDataViewModel { PlanSubject = "test2", MobileNo = "13577779999", TelcoOperatorText = "移动" }); list.Add(new TestDataViewModel { PlanSubject = "test3", MobileNo = "8077778888", TelcoOperatorText = "电信" }); //var model = await DataTrafficGiftRecordQueryEntry.SelectAsync(); //已经领取了流量 //var hasGetList = model.Where(m => !string.IsNullOrWhiteSpace(m.MobileNo) && m.MobileNo.Length == 11); //var result = hasGetList.MapList<DataTrafficGiftRecordViewModel>().ToList(); var setting = new ExcelExportOption<TestDataViewModel> { FileName = "客户领取流量记录", DefaultRowHeight = 270 }; if (list.Count() >= 65535) setting.Description = "结果数据总数:" + list.Count() + "但Excel最多支持65535条数据, 请分开条件导出"; setting.Source = list.Take(65534); var colums = new List<ExcelColum<TestDataViewModel>> { new ExcelColum<TestDataViewModel> { Name = "赠送计划标题", Width = 7000, ColumType = ExcelColumType.String, ResultFunc = x => x.PlanSubject }, new ExcelColum<TestDataViewModel> { Name = "手机号码", Width = 7000, ColumType = ExcelColumType.String, ResultFunc = x => x.MobileNo }, new ExcelColum<TestDataViewModel> { Name = "手机运营商", Width = 7000, ColumType = ExcelColumType.String, ResultFunc = x => x.TelcoOperatorText }, }; setting.Colums = colums; //发送文件路径到客户端 var steam = ExcelUtility.ExportToStream(setting); var filename = HttpUtility.UrlEncode(setting.FileName + DateTime.Now.ToString("_yyyyMMdd-HHmmss") + ".xls", System.Text.Encoding.UTF8); return File(steam, "application/vnd.ms-excel", filename); //Response.AddHeader("Content-Disposition", $"attachment;filename={filename}"); //Response.Clear(); //Response.BinaryWrite(steam.GetBuffer()); //Response.End(); }
public static List <T> QueryList <T>(QuerySearch query, string className) { if (query == null) { query = new QuerySearch(); } IEnumerable <Book> books = new List <Book>(); IEnumerable <Author> authors = new List <Author>(); IEnumerable <Category> categories = new List <Category>(); IEnumerable <BookReview> bookReviews = new List <BookReview>(); if (!string.IsNullOrWhiteSpace(query.BookName)) { books = BookCollection.Books.Where(x => x.Title == query.BookName); } if (!string.IsNullOrWhiteSpace(query.AuthorFirst) && !string.IsNullOrWhiteSpace(query.AuthorLast)) { authors = AuthorCollection.Authors.Where(x => x.FirstName == query.AuthorFirst && x.LastName == query.AuthorLast); } else if (!string.IsNullOrWhiteSpace(query.AuthorFirst)) { authors = AuthorCollection.Authors.Where(x => x.FirstName == query.AuthorFirst); } else if (!string.IsNullOrWhiteSpace(query.AuthorLast)) { authors = AuthorCollection.Authors.Where(x => x.LastName == query.AuthorLast); } if (!string.IsNullOrWhiteSpace(query.CategoryName)) { categories = CategoryCollection.Categories.Where(x => x.Name == query.CategoryName); } if (!string.IsNullOrWhiteSpace(query.ReviewerName)) { bookReviews = BookReviewCollection.BookReviews.Where(x => x.ReviewerName == query.ReviewerName); } if (className == "author") { if (!authors.Any()) { authors = AuthorCollection.Authors; } if (books.Any()) { var bookIds = books.Select(x => x.Id); authors = authors.Where(x => bookIds.Any(y => x.BookIds.Contains(y))); } if (categories.Any()) { var catIds = categories.Select(x => x.Id); authors = authors.Where(x => catIds.Any(y => x.CategoryIds.Contains(y))); } return(authors?.Take(query.MaxReturn).ToList() as List <T>); } if (className == "bookReview") { if (!bookReviews.Any()) { bookReviews = BookReviewCollection.BookReviews; } if (books.Any()) { var bookIds = books.Select(x => x.Id); bookReviews = bookReviews.Where(x => bookIds.Contains(x.BookId)); } return(bookReviews?.Take(query.MaxReturn).ToList() as List <T>); } if (className == "category") { if (!categories.Any()) { categories = CategoryCollection.Categories; } if (books.Any()) { var bookIds = books.Select(x => x.Id); categories = categories.Where(x => bookIds.Any(y => x.BookIds.Contains(y))); } if (authors.Any()) { var autIds = authors.Select(x => x.Id); categories = categories.Where(x => autIds.Any(y => x.AuthorIds.Contains(y))); } return(categories?.Take(query.MaxReturn).ToList() as List <T>); } if (!books.Any()) { books = BookCollection.Books; } if (authors.Any()) { var autIds = authors.Select(x => x.Id); books = books.Where(x => autIds.Any(y => x.AuthorIds.Contains(y))); } if (categories.Any()) { var catIds = categories.Select(x => x.Id); books = books.Where(x => catIds.Any(y => x.CategoryIds.Contains(y))); } if (bookReviews.Any()) { var brIds = bookReviews.Select(x => x.Id); books = books.Where(x => brIds.Any(y => x.BookReviewIds.Contains(y))); } return(books?.Take(query.MaxReturn).ToList() as List <T>); }
public async Task ExportDataToExcel2() { //查询出的数据 // 1.获取数据集合 var list = new List<UserViewModel>() { new UserViewModel{Name="刘一",Age=22,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=80,MathScores=90}}, new UserViewModel{Name="陈二",Age=23,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=81,MathScores=91} }, new UserViewModel{Name="张三",Age=24,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=82,MathScores=92} }, new UserViewModel{Name="李四",Age=25,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=83,MathScores=93} }, new UserViewModel{Name="王五",Age=26,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=84,MathScores=94} }, }; var setting = new ExcelExportOption<UserViewModel> { FileName = "客户领取流量记录", DefaultRowHeight = 270 }; if (list.Count() >= 65535) setting.Description = "结果数据总数:" + list.Count() + "但Excel最多支持65535条数据, 请分开条件导出"; setting.Source = list.Take(65534); // 2.设置单元格抬头 // key:实体对象属性名称,可通过反射获取值 // value:Excel列的名称 Dictionary<string, string> cellheader = new Dictionary<string, string> { { "Name", "姓名" }, { "Age", "年龄" }, { "GenderName", "性别" }, { "TranscriptsEn", "成绩" }, { "TranscriptsEn.ChineseScores", "语文成绩" }, { "TranscriptsEn.MathScores", "数学成绩" }, }; //发送文件路径到客户端 var urlPath = ExcelUtility.ExportExcel(cellheader, list, "学生成绩"); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.Write(js.Serialize(urlPath)); // 返回Json格式的内容 //var column = new List<ExcelColum<UserViewModel>> //{ // new ExcelColum<UserViewModel> // { // Name = "姓名", // Width = 7000, // ColumType = ExcelColumType.String, // ResultFunc = x => x.Name // }, // new ExcelColum<UserViewModel> // { // Name = "年龄", // Width = 7000, // ColumType = ExcelColumType.String, // ResultFunc = x => x.Age // }, // new ExcelColum<UserViewModel> // { // Name = "性别", // Width = 7000, // ColumType = ExcelColumType.String, // ResultFunc = x => x.GenderName // }, // new ExcelColum<UserViewModel> // { // Name = "语文成绩", // Width = 7000, // ColumType = ExcelColumType.String, // ResultFunc = x => x.TranscriptsEn.ChineseScores // }, // new ExcelColum<UserViewModel> // { // Name = "数学成绩", // Width = 7000, // ColumType = ExcelColumType.String, // ResultFunc = x => x.TranscriptsEn.MathScores // }, //}; //var option = new ExcelExportOption<UserViewModel> //{ // Title = "学生成绩", // Source = list, // Colums = column //}; //var filename = $"民办初中-{DateTime.Now:yyyyMMddHHmmssfff}.xls"; //var file = ExcelUtility.ExportToStream<UserViewModel>(option); //return File(file, "application/vnd.ms-excel", filename); }
// todo: add meta data like who created report and when... // signatures or similar stuff. /// <summary> /// /// </summary> /// <returns>return report as CSV string</returns> public string ToCsv(char separator = ';', bool headerLine = true, string lineTerminator = "\\n", List <Dictionary <string, string> > reihenfolge = null) { var type = this.GetType(); string returnStr = string.Empty; List <string> result = new List <string>(); List <string> headerNames = new List <string>(); Dictionary <List <string>, List <string> > reterned = new Dictionary <List <string>, List <string> >() { [headerNames] = result }; reterned = Detect(type, separator, this, reterned); headerNames = reterned.Keys.First(); headerNames.AddRange(new List <string>() { "gap.startDatum", "gap.endDatum" }); result = reterned.Values.First(); List <string> sortedResults = new List <string>(); List <string> sortedHeaderNamesList = new List <string>(); var parallelItems = headerNames.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(y => new { Element = y.Key, Counter = y.Count() }) .ToList(); if (parallelItems.Count() > 0) { for (int i = 0; i < parallelItems.First().Counter; i++) { sortedResults.Clear(); if (reihenfolge != null) { reihenfolge = reihenfolge.Where(x => x != null).ToList(); foreach (var reihenItem in reihenfolge) { if (!string.IsNullOrEmpty(reihenItem.Values.First()) && !string.IsNullOrEmpty(reihenItem.Keys.First())) { int index = headerNames.IndexOf(reihenItem.Keys.First()); if (index != -1) { sortedHeaderNamesList.Add(reihenItem.Values.First()); string CurFieldName = reihenItem.Keys.First(); if (parallelItems.Where(g => g.Element == CurFieldName).Count() > 0) { sortedResults.Add(result[index]); int indx = headerNames.IndexOf(CurFieldName); headerNames.RemoveAt(indx); result.RemoveAt(indx); } else { sortedResults.Add(result[index]); } } else { throw new ArgumentException("invalid values", nameof(reihenfolge)); } } else { throw new ArgumentNullException("null value", nameof(reihenfolge)); } } } else { int userPropertiesIndex = headerNames.IndexOf(BusinessObject.USER_PROPERTIES_NAME); if (userPropertiesIndex >= 0) { headerNames.RemoveAt(userPropertiesIndex); result.RemoveAt(userPropertiesIndex); } //Values organize int index = headerNames.IndexOf(parallelItems.First().Element); if (i == 0) { headerNames.RemoveRange(index + 3, 3 * (parallelItems.First().Counter - 1)); sortedHeaderNamesList.AddRange(headerNames); } int valueIndex = index + (i * 3); var curValues = result.Skip(valueIndex).Take(3); var startfix = result.Take(index); int indexEndSection = index + (3 * parallelItems.First().Counter); var endfix = result.Skip(indexEndSection).Take(result.Count - indexEndSection); sortedResults.AddRange(startfix); sortedResults.AddRange(curValues); sortedResults.AddRange(endfix); } if (i == 0 && headerLine) { returnStr = string.Join(separator.ToString(), sortedHeaderNamesList) + lineTerminator; } returnStr += string.Join(separator.ToString(), sortedResults) + lineTerminator; } } else { if (reihenfolge != null) { reihenfolge = reihenfolge.Where(x => x != null).ToList(); foreach (var reihenItem in reihenfolge) { if (!string.IsNullOrEmpty(reihenItem.Values.First()) && !string.IsNullOrEmpty(reihenItem.Keys.First())) { int index = headerNames.IndexOf(reihenItem.Keys.First()); if (index != -1) { sortedHeaderNamesList.Add(reihenItem.Values.First()); sortedResults.Add(result[index]); } else { throw new ArgumentException($"'{reihenItem.Keys.First()}' was not part of {nameof(headerNames)}=[{string.Join(", ", headerNames)}]", nameof(reihenfolge)); } } else { throw new ArgumentNullException("null value", nameof(reihenfolge)); } } } else { int userPropertiesIndex = headerNames.IndexOf(BusinessObject.USER_PROPERTIES_NAME); if (userPropertiesIndex >= 0) { headerNames.RemoveAt(userPropertiesIndex); result.RemoveAt(userPropertiesIndex); } sortedHeaderNamesList.AddRange(headerNames); sortedResults.AddRange(result); } if (headerLine) { returnStr = string.Join(separator.ToString(), sortedHeaderNamesList) + lineTerminator; } returnStr += string.Join(separator.ToString(), sortedResults); } List <string> gapdata = new List <string>(); List <string> gapHeaderNames = new List <string>(); Dictionary <List <string>, List <string> > gapReterned = new Dictionary <List <string>, List <string> >() { [gapHeaderNames] = gapdata }; gapReterned = DetectGaps(type, separator, this, gapReterned); List <string> gapSortedResults = new List <string>(); var gapParallelItems = gapHeaderNames.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(y => new { Element = y.Key, Counter = y.Count() }) .ToList(); if (gapParallelItems.Count() > 0) { for (int i = 0; i < gapParallelItems.First().Counter; i++) { gapSortedResults.Clear(); int index = gapHeaderNames.IndexOf(gapParallelItems.First().Element); int valueIndex = index + (i * 2); var curValues = gapdata.Skip(valueIndex).Take(2); gapSortedResults.AddRange(curValues); returnStr += lineTerminator; for (int z = 2; z < sortedHeaderNamesList.Count(); z++) { returnStr += separator.ToString(); } returnStr += String.Join(separator.ToString(), gapSortedResults); } } else { gapSortedResults.AddRange(gapdata); returnStr += separator.ToString() + string.Join(separator.ToString(), gapSortedResults); } return(returnStr); }
public virtual List <Creature> GetTargets(Xml.Castable castable, Creature target = null) { List <Creature> actualTargets = new List <Creature>(); /* INTENT HANDLING FOR TARGETING * * This is particularly confusing so it is documented here. * UseType=Target Radius=0 Direction=None -> exact clicked target * UseType=Target Radius=0 Direction=!None -> invalid * UseType=Target Radius=>0 Direction=None -> rect centered on target * UseType=Target Radius>0 Direction=(anything but none) -> directional rect target based on click x/y * UseType=NoTarget Radius=0 Direction=None -> self (wings of protection, maybe custom spells / mentoring / lore / etc)? * UseType=NoTarget Radius>0 Direction=None -> rect from self in all directions * UseType=NoTarget Radius>0 Direction=!None -> rect from self in specific direction */ var intents = castable.Intents; foreach (var intent in intents) { var possibleTargets = new List <VisibleObject>(); if (intent.UseType == Xml.SpellUseType.NoTarget && intent.Target.Contains(Xml.IntentTarget.Group)) { // Targeting group members var user = this as User; if (user != null && user.Group != null) { possibleTargets.AddRange(user.Group.Members.Where(m => m.Map.Id == Map.Id && m.Distance(this) < intent.Radius)); } } else if (intent.UseType == Xml.SpellUseType.Target && intent.Radius == 0 && intent.Direction == Xml.IntentDirection.None) { // Targeting the exact clicked target if (target == null) { GameLog.Error($"GetTargets: {castable.Name} - intent was for exact clicked target but no target was passed?"); } else // If we're doing damage, ensure the target is attackable if (!castable.Effects.Damage.IsEmpty && target.Condition.IsAttackable) { possibleTargets.Add(target); } else if (castable.Effects.Damage.IsEmpty) { possibleTargets.Add(target); } } else if (intent.UseType == Xml.SpellUseType.NoTarget && intent.Radius == 0 && intent.Direction == Xml.IntentDirection.None) { // Targeting self - which, currently, is only allowed for non-damaging spells if (castable.Effects.Damage.IsEmpty) { possibleTargets.Add(this); } } else { // Area targeting, directional or otherwise Rectangle rect = new Rectangle(0, 0, 0, 0); byte X = this.X; byte Y = this.Y; // Handle area targeting with click target as the source if (intent.UseType == Xml.SpellUseType.Target) { X = target.X; Y = target.Y; } switch (intent.Direction) { case Xml.IntentDirection.Front: { switch (Direction) { case Xml.Direction.North: { //facing north, attack north rect = new Rectangle(X, Y - intent.Radius, 1, intent.Radius); } break; case Xml.Direction.South: { //facing south, attack south rect = new Rectangle(X, Y, 1, 1 + intent.Radius); } break; case Xml.Direction.East: { //facing east, attack east rect = new Rectangle(X, Y, 1 + intent.Radius, 1); } break; case Xml.Direction.West: { //facing west, attack west rect = new Rectangle(X - intent.Radius, Y, intent.Radius, 1); } break; } } break; case Xml.IntentDirection.Back: { switch (Direction) { case Xml.Direction.North: { //facing north, attack south rect = new Rectangle(X, Y, 1, 1 + intent.Radius); } break; case Xml.Direction.South: { //facing south, attack north rect = new Rectangle(X, Y - intent.Radius, 1, intent.Radius); } break; case Xml.Direction.East: { //facing east, attack west rect = new Rectangle(X - intent.Radius, Y, intent.Radius, 1); } break; case Xml.Direction.West: { //facing west, attack east rect = new Rectangle(X, Y, 1 + intent.Radius, 1); } break; } } break; case Xml.IntentDirection.Left: { switch (Direction) { case Xml.Direction.North: { //facing north, attack west rect = new Rectangle(X - intent.Radius, Y, intent.Radius, 1); } break; case Xml.Direction.South: { //facing south, attack east rect = new Rectangle(X, Y, 1 + intent.Radius, 1); } break; case Xml.Direction.East: { //facing east, attack north rect = new Rectangle(X, Y, 1, 1 + intent.Radius); } break; case Xml.Direction.West: { //facing west, attack south rect = new Rectangle(X, Y - intent.Radius, 1, intent.Radius); } break; } } break; case Xml.IntentDirection.Right: { switch (Direction) { case Xml.Direction.North: { //facing north, attack east rect = new Rectangle(X, Y, 1 + intent.Radius, 1); } break; case Xml.Direction.South: { //facing south, attack west rect = new Rectangle(X - intent.Radius, Y, intent.Radius, 1); } break; case Xml.Direction.East: { //facing east, attack south rect = new Rectangle(X, Y - intent.Radius, 1, intent.Radius); } break; case Xml.Direction.West: { //facing west, attack north rect = new Rectangle(X, Y, 1, 1 + intent.Radius); } break; } } break; case Xml.IntentDirection.Nearby: case Xml.IntentDirection.None: { //attack radius rect = new Rectangle(X - intent.Radius, Y - intent.Radius, Math.Max(intent.Radius, (byte)1) * 2, Math.Max(intent.Radius, (byte)1) * 2); } break; } GameLog.Info($"Rectangle: x: {X - intent.Radius} y: {Y - intent.Radius}, radius: {intent.Radius} - LOCATION: {rect.Location} TOP: {rect.Top}, BOTTOM: {rect.Bottom}, RIGHT: {rect.Right}, LEFT: {rect.Left}"); if (rect.IsEmpty) { continue; } possibleTargets.AddRange(Map.EntityTree.GetObjects(rect).Where(obj => obj is Creature && obj != this)); } // Remove merchants possibleTargets = possibleTargets.Where(e => !(e is Merchant)).ToList(); // Handle intent flags if (this is Monster) { // No hostile flag: remove users // No friendly flag: remove monsters // Group / pvp: do not apply here if (!intent.Target.Contains(Xml.IntentTarget.Friendly)) { possibleTargets = possibleTargets.Where(e => !(e is Monster)).ToList(); } if (!intent.Target.Contains(Xml.IntentTarget.Hostile)) { possibleTargets = possibleTargets.Where(e => !(e is User)).ToList(); } } else if (this is User && intent.UseType != Xml.SpellUseType.NoTarget) { var user = this as User; // No hostile flag: remove monsters // No friendly flag: remove users with pvp disabled // No pvp: remove // If we aren't targeting friendlies or pvp, remove all users entirely if (!intent.Target.Contains(Xml.IntentTarget.Pvp)) { possibleTargets = possibleTargets.Where(e => !(e is User && (e as Creature).Condition.PvpEnabled == true)).ToList(); } if (!intent.Target.Contains(Xml.IntentTarget.Friendly)) { possibleTargets = possibleTargets.Where(e => !(e is User && (e as Creature).Condition.PvpEnabled == false)).ToList(); } // If we aren't targeting hostiles, remove all monsters if (!intent.Target.Contains(Xml.IntentTarget.Hostile)) { possibleTargets = possibleTargets.Where(e => !(e is Monster)).ToList(); } } // Finally, add the targets to our list List <Creature> possible = intent.MaxTargets > 0 ? possibleTargets.Take(intent.MaxTargets).OfType <Creature>().ToList() : possibleTargets.OfType <Creature>().ToList(); if (possible != null && possible.Count > 0) { actualTargets.AddRange(possible); } else { GameLog.Info("No targets found"); } } return(actualTargets); }
private void ll_wordCount_Click(object sender, EventArgs e) { // Toggle between full word list and top n word list. SetWordList(dgv_TopWords.Rows.Count < _lastGroupOfWords?.Count?_lastGroupOfWords:_lastGroupOfWords?.Take(CustomSettings.TopNumberOfWords)); }
public ActionResult Index() { List <Leader> leaderModel = new List <Leader>(); try { if (!(User.IsInRole("Admin") || User.IsInRole("Student"))) { return(View(leaderModel)); } var roleProvider = (SimpleRoleProvider)Roles.Provider; leaderModel = roleProvider.GetUsersInRole("Student") .Select(z => new { username = z, userid = WebSecurity.GetUserId(z) }) .Select( p => new Leader() { Username = p.username, Videos = _echoDb.Presentations.Count(n => n.UserId == p.userid), Comments = _echoDb.Comments.Count(m => m.UsesrId == p.userid), Likes = _echoDb.Comments.Count(z => z.UsesrId == p.userid) == 0 ? 0 : _echoDb.Comments.Where(o => o.UsesrId == p.userid) .Select(l => _echoDb.UpVotes.Count(k => k.CommentId == l.CommentId)) .Sum(), Watched = _echoDb.WatchedPresentations.Count(y => y.UserId == p.userid), VideosRate = _echoDb.RateVideos.Count(u => u.VideoCreatorId == p.userid) == 0 ? 0 : _echoDb.RateVideos.Where(u => u.VideoCreatorId == p.userid).Average(i => i.Rate), Points = 0 }) .Select( v => new Leader() { Username = v.Username, Videos = v.Videos, Comments = v.Comments, Likes = v.Likes, Watched = v.Watched, VideosRate = Math.Round(v.VideosRate, 2), Points = _oneVideoPoint * v.Videos + _oneCommentPoint * v.Comments + _oneLikePoint * v.Likes + _oneWatchedPoint * v.Watched + _oneRatingPoint * Math.Round(v.VideosRate, 2) }) .OrderByDescending(w => w.Points) .ToList(); if (User.IsInRole("Admin")) { return(View(leaderModel)); } else { return(View(leaderModel.Take(10).ToList())); } } catch (Exception) { return(View(leaderModel.Take(0).ToList())); } }
static void Main(string[] args) { Console.WriteLine("Visi miestai {0}", string.Join(", ", miestai)); // Sprendimas be LINQ foreach (var miestas in miestai) { if (miestas[0] == 'K') { Console.WriteLine($"miestas is K yra {miestas}"); } } //Sprendimas su LINQ(filtravimo funkcija) Console.WriteLine("Miestai is K raides {0}", string.Join(", ", miestai.Where(miestas => miestas.StartsWith("K")))); //Elementu kiekio skaiciavimas su filtravimu Console.WriteLine("Miestai is K raides kiekis {0}", miestai.Count(miestas => miestas.StartsWith("K"))); Console.WriteLine("Ar yra miestas Kaunas ? {0}", miestai.Any(miestas => miestas == "Kaunas") ? "Taip": "Ne"); Console.WriteLine("Ar yra miestas Utena ? {0}", miestai.Any(miestas => miestas == "Utena") ? "Taip" : "Ne"); var tikrinamiMiestai = new string[] { "Taurage", "Pabrade" }; Console.WriteLine("Ar yra miestu tarp miestu is masyvo [Taurage, Pabrade] ? {0}", miestai.Any(miestas => tikrinamiMiestai.Contains(miestas)) ? "Taip": "Ne" ); var tikrinamiMiestai1 = new string[] { "Vilnius", "Taurage", "Pabrade" }; Console.WriteLine("Ar yra miestu tarp miestu is masyvo [Vilnius, Taurage, Pabrade] ? {0}", miestai.Any(miestas => tikrinamiMiestai1.Contains(miestas)) ? "Taip" : "Ne" ); //Rusiuoja pagal abecele Console.WriteLine("Surusiuoti nuo A iki Z miestai {0}", string.Join(", ", miestai.OrderBy(miestas => miestas))); //Rusiuoja atvirksciai abecele Console.WriteLine("Surusiuoti nuo Z iki A miestai {0}", string.Join(", ", miestai.OrderByDescending(miestas => miestas))); //Paima pirmus 2 masyvo elementus Console.WriteLine("Du miestai is saraso {0}", string.Join(", ", miestai.Take(2))); //Paima visus masyvo elementus isskyrus pirmus 2 Console.WriteLine("Miestai is saraso be pirmu dvieju miestu {0}", string.Join(", ", miestai.Skip(2))); //Palieka tik unikalius masyvo elementus Console.WriteLine("Unikalus miestai {0}", string.Join(", ", miestai.Distinct())); Console.WriteLine("===================================================================================="); //Norime suskaiciuoti skaiciai suma be LINQ int suma = 0; foreach (var skaicius in skaiciai) { suma += skaicius; } Console.WriteLine("Skaicius suma {0}", suma); //Skaiciu suma su LINQ Console.WriteLine("Skaiciu suma {0}", skaiciai.Sum()); //Maziausias skaicius Console.WriteLine("Skaiciu minimali reiksme {0}", skaiciai.Min()); //Didziausias skaicius Console.WriteLine("Skaiciu maximali reiksme {0}", skaiciai.Max()); //Vidurkis Console.WriteLine("Skaicius vidurkis {0}", skaiciai.Average()); Console.WriteLine("Unikaliu mazesniu uz 5 skaiciu vidurkis {0}", skaiciai.Distinct().Where(s => s < 5).Average()); List <int> skaiciai2 = new List <int> { 88, 89 }; Console.WriteLine("Sujungti skaiciai {0}", string.Join(", ", skaiciai.Concat(skaiciai2))); Console.WriteLine("===================================="); //LINQ OBJECT //isvesti asmenis kurie vyresni nei 20 metu var asmenysVyresni = PersonInitialData.DataSeed.Where(p => p.Age > 20); foreach (var asmuo in asmenysVyresni) { Console.WriteLine($"{asmuo.FirstName} {asmuo.LastName} amzius {asmuo.Age}"); } Console.WriteLine("---------------------------------------"); //linq refleksija var asmenuSarasas = PersonInitialData.DataSeed.Select(p => new PersonDto { FirstName = p.FirstName, LastName = p.LastName, Age = p.Age, } ); foreach (var asmuo in asmenuSarasas) { Console.WriteLine($"{asmuo.FirstName} {asmuo.LastName} amzius {asmuo.Age}"); } Console.WriteLine("---------------------------------------"); //query syntax var personWithHobby = from p in PersonInitialData.DataSeed join h in PersonHobbyInitialData.DataSeed on p.FirstName equals h.FirstName into hobbyGroup select new PersonInfo { Person = p, PersonHobbies = hobbyGroup.ToList() }; foreach (var asmuo in personWithHobby) { List <string> hobbies = asmuo.PersonHobbies.Select(ph => ph.Text).ToList(); Console.WriteLine($"{asmuo.Person.FirstName} {asmuo.Person.LastName} {string.Join(", ", hobbies)}"); } //extension method syntax with nesting var personWithHobby1 = PersonInitialData.DataSeed.Select(p => new PersonInfo { Person = p, PersonHobbies = PersonHobbyInitialData.DataSeed.Where(h => h.FirstName == p.FirstName).ToList() } ); //query syntax with Anonymous type var personWithHobbyAnonymous = from p in PersonInitialData.DataSeed join h in PersonHobbyInitialData.DataSeed on p.FirstName equals h.FirstName into hobbyGroup select new { FullName = $"{p.FirstName} {p.LastName}", Hobbies = hobbyGroup.Select(hg => hg.Text).ToList() }; foreach (var asmuo in personWithHobbyAnonymous) { Console.WriteLine($"{asmuo.FullName} {string.Join(", ", asmuo.Hobbies)}"); } // SKAICIU UZDUOTIS int MinSkaicius = -100; int MaxSkaicius = 100; int[] randomMasyvas = new int[20]; Random randomNumber = new Random(); for (int i = 0; i < randomMasyvas.Length; i++) { randomMasyvas[i] = randomNumber.Next(MinSkaicius, MaxSkaicius); } var neigiamiSkaiciai = 0; var teigiamiSkaiciai = 0; Console.WriteLine("Masyvas: {0}", string.Join(", ", randomMasyvas)); Console.WriteLine("Neigiami skaiciai: {0}", neigiamiSkaiciai = randomMasyvas.Distinct().Where(s => s < 0).Count()); Console.WriteLine("Teigiami skaiciai: {0}", teigiamiSkaiciai = randomMasyvas.Distinct().Where(s => s > 0).Count()); if (neigiamiSkaiciai > teigiamiSkaiciai) { Console.WriteLine("Neigiamu skaiciu daugiau"); } if (neigiamiSkaiciai < teigiamiSkaiciai) { Console.WriteLine("Teigiamu skaiciu daugiau"); } if (neigiamiSkaiciai == teigiamiSkaiciai) { Console.WriteLine("Teigiamu ir neigiamu skaiciu kiekis yra vienodas"); } }
public static void Main(string[] args) { string key = Console.ReadLine(); Dictionary <string, ulong> pointsByTeam = new Dictionary <string, ulong>(); Dictionary <string, ulong> goalsByTeam = new Dictionary <string, ulong>(); while (true) { string input = Console.ReadLine(); if (input == "final") { break; } List <string> teamsAndScore = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string team1 = GetTeamName(teamsAndScore[0], key); string team2 = GetTeamName(teamsAndScore[1], key); ulong[] score = teamsAndScore[2].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(ulong.Parse).ToArray(); if (pointsByTeam.ContainsKey(team1)) { pointsByTeam[team1] += GetPoints(score, "firstTeam"); } else { pointsByTeam[team1] = GetPoints(score, "firstTeam"); } if (pointsByTeam.ContainsKey(team2)) { pointsByTeam[team2] += GetPoints(score, "secondTeam"); } else { pointsByTeam[team2] = GetPoints(score, "secondTeam"); } if (goalsByTeam.ContainsKey(team1)) { goalsByTeam[team1] += score[0]; } else { goalsByTeam[team1] = score[0]; } if (goalsByTeam.ContainsKey(team2)) { goalsByTeam[team2] += score[1]; } else { goalsByTeam[team2] = score[1]; } } List <string> teamsOrderedByPoints = Sort(pointsByTeam); List <string> teamsOrderedByGoals = Sort(goalsByTeam); Console.WriteLine("League standings:"); int place = 1; foreach (var team in teamsOrderedByPoints) { Console.WriteLine("{0}. {1} {2}", place, team, pointsByTeam[team]); ++place; } List <string> top3 = teamsOrderedByGoals.Take(3).ToList(); Console.WriteLine("Top 3 scored goals:"); foreach (var team in top3) { Console.WriteLine("- {0} -> {1}", team, goalsByTeam[team]); } }
public async Task TestRewindAsync() { uint256 tip = this.cachedCoinView.GetTipHash(); Assert.Equal(this.chainIndexer.Genesis.HashBlock, tip); int currentHeight = 0; // Create a lot of new coins. List<UnspentOutputs> outputsList = this.CreateOutputsList(currentHeight + 1, 100); this.SaveChanges(outputsList, new List<TxOut[]>(), currentHeight + 1); currentHeight++; this.cachedCoinView.Flush(true); uint256 tipAfterOriginalCoinsCreation = this.cachedCoinView.GetTipHash(); // Collection that will be used as a coinview that we will update in parallel. Needed to verify that actual coinview is ok. List<OutPoint> outPoints = this.ConvertToListOfOutputPoints(outputsList); // Copy of current state to later rewind and verify against it. List<OutPoint> copyOfOriginalOutPoints = new List<OutPoint>(outPoints); List<OutPoint> copyAfterHalfOfAdditions = new List<OutPoint>(); uint256 coinviewTipAfterHalf = null; int addChangesTimes = 500; // Spend some coins in the next N saves. for (int i = 0; i < addChangesTimes; ++i) { uint256 txId = outPoints[this.random.Next(0, outPoints.Count)].Hash; List<OutPoint> txPoints = outPoints.Where(x => x.Hash == txId).ToList(); this.Shuffle(txPoints); List<OutPoint> txPointsToSpend = txPoints.Take(txPoints.Count / 2).ToList(); // First spend in cached coinview FetchCoinsResponse response = this.cachedCoinView.FetchCoins(new[] { txId }); Assert.Single(response.UnspentOutputs); UnspentOutputs coins = response.UnspentOutputs[0]; UnspentOutputs unchangedClone = coins.Clone(); foreach (OutPoint outPointToSpend in txPointsToSpend) coins.Spend(outPointToSpend.N); // Spend from outPoints. outPoints.RemoveAll(x => txPointsToSpend.Contains(x)); // Save coinview this.SaveChanges(new List<UnspentOutputs>() { coins }, new List<TxOut[]>() { unchangedClone.Outputs }, currentHeight + 1); currentHeight++; if (i == addChangesTimes / 2) { copyAfterHalfOfAdditions = new List<OutPoint>(outPoints); coinviewTipAfterHalf = this.cachedCoinView.GetTipHash(); } } await this.ValidateCoinviewIntegrityAsync(outPoints); for (int i = 0; i < addChangesTimes; i++) { this.cachedCoinView.Rewind(); uint256 currentTip = this.cachedCoinView.GetTipHash(); if (currentTip == coinviewTipAfterHalf) await this.ValidateCoinviewIntegrityAsync(copyAfterHalfOfAdditions); } Assert.Equal(tipAfterOriginalCoinsCreation, this.cachedCoinView.GetTipHash()); await this.ValidateCoinviewIntegrityAsync(copyOfOriginalOutPoints); }
public static LambdaExpression GetSetterLambdaExpressionInstantiateNullInstances(this MemberAccessPath memberAccessPath) { var instanceType = memberAccessPath.First().ReflectedType; var valueType = memberAccessPath.Last().GetMemberType(); var value = Expression.Parameter(valueType, "value"); var entryInstance = Expression.Parameter(instanceType, "instance"); Expression accessPath = entryInstance; var memberAccesses = new List <Expression>(); foreach (var memberAccess in memberAccessPath) { if (memberAccess is MethodInfo methodInfo) { if (methodInfo.IsGetterMethod()) { accessPath = Expression.Call(accessPath, methodInfo); } else { accessPath = Expression.Call(accessPath, methodInfo, value); } } else { accessPath = Expression.MakeMemberAccess(accessPath, memberAccess); } memberAccesses.Add(accessPath); } if (!(accessPath is MethodCallExpression)) { accessPath = Expression.Assign(accessPath, value); } var nullConstant = Expression.Constant(null); var nullChecks = memberAccesses.Take(memberAccesses.Count - 1).Select((memberAccess, i) => { if (memberAccessPath[i] is MethodInfo methodInfo) { //nested method calls like GetCustomer().SetName() include non-writable member (GetCustomer). //Assigning a new instance in that case is more difficult. //In that case 'by convention' we should look for: // - A property named Customer // - A method named SetCustomer(argument type = getter return type) // (also take into account Set, Set_, set, set_) as for convention. var bindingAttributes = BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic; string setterMethodName = null; if (methodInfo.Name.StartsWith("Get")) { setterMethodName = methodInfo.Name.Replace("Get", "Set"); } else if (methodInfo.Name.StartsWith("get")) { setterMethodName = methodInfo.Name.Replace("get", "set"); } else if (methodInfo.Name.StartsWith("Get_")) { setterMethodName = methodInfo.Name.Replace("Get_", "Set_"); } else if (methodInfo.Name.StartsWith("get_")) { setterMethodName = methodInfo.Name.Replace("get_", "set_"); } var setterMethod = methodInfo.ReflectedType.GetMethod(setterMethodName, bindingAttributes); Expression setterAccessPath = entryInstance; for (int j = 0; j < i; j++) { if (memberAccessPath[j] is MethodInfo mi) { if (mi.IsGetterMethod()) { setterAccessPath = Expression.Call(accessPath, mi); } else { setterAccessPath = Expression.Call(accessPath, mi, value); } } else { setterAccessPath = Expression.MakeMemberAccess(setterAccessPath, memberAccessPath[j]); } } setterAccessPath = Expression.Call(setterAccessPath, setterMethod, Expression.New(memberAccess.Type)); var equalsNull = Expression.Equal(memberAccess, nullConstant); return((Expression)Expression.IfThen(equalsNull, setterAccessPath)); } else { var createInstance = Expression.Assign(memberAccess, Expression.New(memberAccess.Type)); var equalsNull = Expression.Equal(memberAccess, nullConstant); return((Expression)Expression.IfThen(equalsNull, createInstance)); } }).Where(nc => nc != null).ToList(); var exp = Expression.Block ( nullChecks.Any() ? Expression.Block(nullChecks.ToArray()) : (Expression)Expression.Empty(), accessPath ); var delegateType = typeof(Action <,>).MakeGenericType(instanceType, valueType); return(LambdaExpression.Lambda(delegateType, exp, entryInstance, value)); }
public static List <TourStop> GetTourStops(int count) { var result = _tourStops.Take(count).ToList <TourStop>(); return(result); }
public static List <T> Concat <T>(List <T> x, List <T> y, int take) { return(x.Concat(y.Take(take)).ToList()); }
public void CanGetMerkleRoot() { using (var builder = NodeBuilderEx.Create()) { var node = builder.CreateNode(true); var rpc = node.CreateRPCClient(); var nodeClient = node.CreateNodeClient(); rpc.Generate(101); List <TxDestination> knownAddresses = new List <TxDestination>(); var batch = rpc.PrepareBatch(); for (int i = 0; i < 20; i++) { var address = (BitcoinPubKeyAddress) new Key().PubKey.GetAddress(ScriptPubKeyType.Legacy, rpc.Network); knownAddresses.Add(address.Hash); #pragma warning disable CS4014 batch.SendToAddressAsync(address, Money.Coins(0.5m)); #pragma warning restore CS4014 } batch.SendBatch(); knownAddresses = knownAddresses.Take(10).ToList(); var blockId = rpc.Generate(1)[0]; var block = rpc.GetBlock(blockId); Assert.Equal(21, block.Transactions.Count); var knownTx = block.Transactions[1].GetHash(); nodeClient.VersionHandshake(); using (var list = nodeClient.CreateListener() .Where(m => m.Message.Payload is MerkleBlockPayload || m.Message.Payload is TxPayload)) { BloomFilter filter = new BloomFilter(1, 0.0001, 50, BloomFlags.UPDATE_NONE); foreach (var a in knownAddresses) { filter.Insert(a.ToBytes()); } nodeClient.SendMessageAsync(new FilterLoadPayload(filter)); nodeClient.SendMessageAsync(new GetDataPayload(new InventoryVector(InventoryType.MSG_FILTERED_BLOCK, block.GetHash()))); var merkle = list.ReceivePayload <MerkleBlockPayload>(); var tree = merkle.Object.PartialMerkleTree; Assert.True(tree.Check(block.Header.HashMerkleRoot)); Assert.True(tree.GetMatchedTransactions().Count() >= 10); Assert.Contains(knownTx, tree.GetMatchedTransactions()); List <Transaction> matched = new List <Transaction>(); for (int i = 0; i < tree.GetMatchedTransactions().Count(); i++) { matched.Add(list.ReceivePayload <TxPayload>().Object); } Assert.True(matched.Count >= 10); tree = tree.Trim(knownTx); Assert.True(tree.GetMatchedTransactions().Count() == 1); Assert.Contains(knownTx, tree.GetMatchedTransactions()); Action act = () => { foreach (var match in matched) { Assert.True(filter.IsRelevantAndUpdate(match)); } }; act(); filter = filter.Clone(); act(); var unknownBlock = uint256.Parse("00000000ad262227291eaf90cafdc56a8f8451e2d7653843122c5bb0bf2dfcdd"); nodeClient.SendMessageAsync(new GetDataPayload(new InventoryVector(InventoryType.MSG_FILTERED_BLOCK, Network.RegTest.GetGenesis().GetHash()))); merkle = list.ReceivePayload <MerkleBlockPayload>(); tree = merkle.Object.PartialMerkleTree; Assert.True(tree.Check(merkle.Object.Header.HashMerkleRoot)); Assert.True(!tree.GetMatchedTransactions().Contains(knownTx)); } } }
/// <summary> /// Create the template output /// </summary> public override string TransformText() { this.Write("\r\n"); this.Write(@"// ********************************************************************* // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License // ********************************************************************* using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using Microsoft.StreamProcessing; using Microsoft.StreamProcessing.Internal; using Microsoft.StreamProcessing.Internal.Collections; [assembly: IgnoresAccessChecksTo(""Microsoft.StreamProcessing"")] "); List <string> genericParamList = new List <string>(); var TOuterKey = outerKeyType.GetCSharpSourceSyntax(ref genericParamList); var outerKeyGenericParameterCount = genericParamList.Count; var TSource = sourceType.GetCSharpSourceSyntax(ref genericParamList); var sourceGenericParameterCount = genericParamList.Count; var sourceGenericParameters = 0 < genericParamList.Count ? "<" + String.Join(",", genericParamList) + ">" : string.Empty; var TInnerKey = innerKeyType.GetCSharpSourceSyntax(ref genericParamList); var genericParameters = 0 < genericParamList.Count ? "<" + String.Join(",", genericParamList) + ">" : string.Empty; var outKeyInnerKeyGenericParameterList = genericParamList.Take(outerKeyGenericParameterCount).Concat(genericParamList.Skip(sourceGenericParameterCount)); var TOuterKeyTInnerKeyGenericParameters = 0 < outKeyInnerKeyGenericParameterList.Count() ? "<" + String.Join(",", outKeyInnerKeyGenericParameterList) + ">" : string.Empty; var resultBatchGenericParameters = genericParameters; var resultBatchClassType = isFirstLevelGroup ? Transformer.GetBatchClassName(innerKeyType, sourceType) : Transformer.GetBatchClassName(typeof(CompoundGroupKey <,>).MakeGenericType(outerKeyType, innerKeyType), sourceType); var sourceBatchClassType = Transformer.GetBatchClassName(outerKeyType, sourceType); var innerKeyIsAnonymous = innerKeyType.IsAnonymousTypeName(); if (innerKeyIsAnonymous) { transformedKeySelectorAsString = string.Format("({0})Activator.CreateInstance(typeof({0}), {1} )", TInnerKey, transformedKeySelectorAsString); } var outputKey = !isFirstLevelGroup ? "CompoundGroupKey<" + TOuterKey + ", " + TInnerKey + ">" : TInnerKey; var nestedInfix = !isFirstLevelGroup ? "Nested" : string.Empty; var ungroupingToUnit = isFirstLevelGroup && innerKeyType == typeof(Empty); var swingingKeyFromField = isFirstLevelGroup && !this.swingingField.Equals(default(MyFieldInfo)); this.Write("\r\n// TOuterKey: "); this.Write(this.ToStringHelper.ToStringWithCulture(TOuterKey)); this.Write("\r\n// TInnerKey: "); this.Write(this.ToStringHelper.ToStringWithCulture(TInnerKey)); this.Write("\r\n// TSource: "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write("\r\n\r\n[DataContract]\r\ninternal sealed class "); this.Write(this.ToStringHelper.ToStringWithCulture(CLASSNAME)); this.Write(this.ToStringHelper.ToStringWithCulture(genericParameters)); this.Write(" :\r\n Pipe<"); this.Write(this.ToStringHelper.ToStringWithCulture(outputKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write(">, IStreamObserver<"); this.Write(this.ToStringHelper.ToStringWithCulture(TOuterKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write(">\r\n{\r\n"); if (innerKeyIsAnonymous) { this.Write(" [SchemaSerialization]\r\n private readonly Expression<Func<"); this.Write(this.ToStringHelper.ToStringWithCulture(TInnerKey)); this.Write(", int>> keyComparer;\r\n private readonly Func<"); this.Write(this.ToStringHelper.ToStringWithCulture(TInnerKey)); this.Write(", int> innerHashCode;\r\n"); } this.Write(" private readonly MemoryPool<"); this.Write(this.ToStringHelper.ToStringWithCulture(outputKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write("> l1Pool;\r\n private readonly Func<PlanNode, IQueryObject, PlanNode> queryPlanG" + "enerator;\r\n\r\n"); if (ungroupingToUnit) { this.Write("\r\n private readonly ColumnBatch<Microsoft.StreamProcessing.Empty> unitColumn;\r" + "\n private readonly ColumnBatch<int> unitHashColumn;\r\n"); } this.Write("\r\n "); this.Write(this.ToStringHelper.ToStringWithCulture(staticCtor)); this.Write("\r\n\r\n public "); this.Write(this.ToStringHelper.ToStringWithCulture(CLASSNAME)); this.Write("() { }\r\n\r\n public "); this.Write(this.ToStringHelper.ToStringWithCulture(CLASSNAME)); this.Write("(\r\n IStreamable<"); this.Write(this.ToStringHelper.ToStringWithCulture(outputKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write("> stream,\r\n IStreamObserver<"); this.Write(this.ToStringHelper.ToStringWithCulture(outputKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write("> observer,\r\n Expression<Func<"); this.Write(this.ToStringHelper.ToStringWithCulture(TInnerKey)); this.Write(", int>> keyComparer,\r\n Expression<Func<"); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TInnerKey)); this.Write(">> keySelector,\r\n Func<PlanNode, IQueryObject, PlanNode> queryPlanGenerato" + "r)\r\n : base(stream, observer)\r\n {\r\n"); if (innerKeyIsAnonymous) { if (isFirstLevelGroup) { this.Write(" var _keySelector = keySelector.Compile();\r\n"); } this.Write(" this.keyComparer = keyComparer;\r\n this.innerHashCode = keyComparer" + ".Compile();\r\n"); } this.Write(" this.l1Pool = MemoryManager.GetMemoryPool<"); this.Write(this.ToStringHelper.ToStringWithCulture(outputKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write(">(true);\r\n this.queryPlanGenerator = queryPlanGenerator;\r\n"); if (ungroupingToUnit) { this.Write("\r\n this.l1Pool.GetKey(out this.unitColumn);\r\n this.l1Pool.Get(out t" + "his.unitHashColumn);\r\n Array.Clear(this.unitHashColumn.col, 0, this.unitH" + "ashColumn.col.Length);\r\n"); } this.Write(@" } public override void ProduceQueryPlan(PlanNode previous) { Observer.ProduceQueryPlan(queryPlanGenerator(previous, this)); } protected override void FlushContents() { } public override int CurrentlyBufferedOutputCount => 0; public override int CurrentlyBufferedInputCount => 0; protected override void DisposeState() { "); if (ungroupingToUnit) { this.Write(" this.unitColumn.Return();\r\n this.unitHashColumn.Return();\r\n"); } this.Write(" }\r\n\r\n public unsafe void OnNext(StreamMessage<"); this.Write(this.ToStringHelper.ToStringWithCulture(TOuterKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write("> batch)\r\n {\r\n StreamMessage<"); this.Write(this.ToStringHelper.ToStringWithCulture(outputKey)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(TSource)); this.Write("> resultBatchUncast; // Need this type to call Get with so the right subtype will" + " be returned\r\n this.l1Pool.Get(out resultBatchUncast);\r\n\r\n "); this.Write(this.ToStringHelper.ToStringWithCulture(resultBatchClassType)); this.Write(this.ToStringHelper.ToStringWithCulture(resultBatchGenericParameters)); this.Write(" resultBatch = resultBatchUncast as "); this.Write(this.ToStringHelper.ToStringWithCulture(resultBatchClassType)); this.Write(this.ToStringHelper.ToStringWithCulture(resultBatchGenericParameters)); this.Write(";\r\n "); this.Write(this.ToStringHelper.ToStringWithCulture(sourceBatchClassType)); this.Write(this.ToStringHelper.ToStringWithCulture(sourceGenericParameters)); this.Write(" inputBatch = batch as "); this.Write(this.ToStringHelper.ToStringWithCulture(sourceBatchClassType)); this.Write(this.ToStringHelper.ToStringWithCulture(sourceGenericParameters)); this.Write(";\r\n\r\n resultBatch.vsync = batch.vsync;\r\n resultBatch.vother = batch" + ".vother;\r\n"); foreach (var f in this.fields) { this.Write(" resultBatch."); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write(" = inputBatch."); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write(";\r\n"); } if (this.payloadMightBeNull) { this.Write(" resultBatch._nullnessvector = inputBatch._nullnessvector;\r\n"); } this.Write("\r\n"); if (!ungroupingToUnit && !swingingHashColumn) { this.Write("\r\n resultBatch.hash = batch.hash.MakeWritable(this.l1Pool.intPool);\r\n"); } this.Write(" resultBatch.bitvector = batch.bitvector;\r\n\r\n"); if (!ungroupingToUnit && (!isFirstLevelGroup || this.swingingField.Equals(default(MyFieldInfo)))) { this.Write(" this.l1Pool.GetKey(out resultBatchUncast.key);\r\n"); } this.Write("\r\n resultBatch.Count = batch.Count;\r\n\r\n var count = batch.Count;\r\n\r" + "\n"); if (ungroupingToUnit) { this.Write(" this.unitColumn.IncrementRefCount(1);\r\n resultBatch.key = unitColu" + "mn;\r\n this.unitHashColumn.IncrementRefCount(1);\r\n resultBatch.hash" + " = unitHashColumn;\r\n"); } else { this.Write("\r\n var src_key = batch.key.col;\r\n"); if (!isFirstLevelGroup || this.swingingField.Equals(default(MyFieldInfo))) { this.Write("\r\n var dest_key = resultBatch.key.col;\r\n"); } this.Write(" var dest_payload = resultBatch;\r\n\r\n"); if (swingingKeyFromField) { this.Write(" // The key selector was just e => e.f *and* isFirstLevelGroup so just swi" + "ng the key field\r\n"); if (this.swingingField.OptimizeString()) { this.Write("\r\n resultBatch.key = resultBatch."); this.Write(this.ToStringHelper.ToStringWithCulture(this.swingingField.Name)); this.Write(".ToColumnBatch(this.l1Pool.stringPool, resultBatch.bitvector);\r\n"); } else { this.Write("\r\n resultBatch.key = resultBatch."); this.Write(this.ToStringHelper.ToStringWithCulture(this.swingingField.Name)); this.Write(";\r\n resultBatch.key.IncrementRefCount(1);\r\n"); } } this.Write("\r\n\r\n"); foreach (var f in this.fields) { this.Write("\r\n"); if (f.canBeFixed) { this.Write(" fixed ("); this.Write(this.ToStringHelper.ToStringWithCulture(f.TypeName)); this.Write("* "); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write("_col = resultBatch."); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write(".col)\r\n {\r\n"); } else { this.Write("\r\n"); if (f.OptimizeString()) { this.Write(" var "); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write("_col = resultBatch."); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write(";\r\n"); } else { this.Write(" var "); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write("_col = resultBatch."); this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); this.Write(".col;\r\n"); } } } this.Write("\r\n "); this.Write(this.ToStringHelper.ToStringWithCulture(vectorHashCodeInitialization)); this.Write("\r\n\r\n"); if (!swingingKeyFromField || !swingingHashColumn) { this.Write("\r\n fixed (long* src_bv = batch.bitvector.col) {\r\n"); if (!ungroupingToUnit) { this.Write(" fixed (int* dest_hash = resultBatch.hash.col) {\r\n"); } this.Write(" for (int i = 0; i < count; i++)\r\n {\r\n if ((" + "src_bv[i >> 6] & (1L << (i & 0x3f))) != 0) continue;\r\n\r\n"); if (!swingingKeyFromField || !this.swingingField.OptimizeString()) { this.Write("\r\n var key = "); this.Write(this.ToStringHelper.ToStringWithCulture(this.transformedKeySelectorAsString)); this.Write(";\r\n"); } if (innerKeyIsAnonymous) { this.Write(" var innerHash = this.innerHashCode(key);\r\n"); } else if (swingingHashColumn) { this.Write("\r\n // don\'t compute hash because that was done by calling MultiStr" + "ing.GetHashCode\r\n"); } else { this.Write(" var innerHash = "); this.Write(this.ToStringHelper.ToStringWithCulture(inlinedHashCodeComputation)); this.Write(";\r\n"); } this.Write("\r\n"); if (isFirstLevelGroup) { if (!this.swingingField.Equals(default(MyFieldInfo))) { this.Write(" // no assignment to key, pointer was swung!\r\n"); } else { this.Write(" dest_key[i] = key;\r\n"); } if (!swingingHashColumn) { this.Write("\r\n dest_hash[i] = innerHash;\r\n"); } } else { this.Write(" var hash = dest_hash[i] ^ innerHash;\r\n dest_key[i]" + ".outerGroup = src_key[i];\r\n dest_key[i].innerGroup = key;\r\n " + " dest_key[i].hashCode = hash;\r\n dest_hash[i] = hash;\r\n"); } this.Write(" }\r\n"); if (!ungroupingToUnit) { this.Write(" } // end of fixed for dest_hash\r\n"); } this.Write(" } // end of fixed for src_bv\r\n"); } this.Write("\r\n "); if (!String.IsNullOrWhiteSpace(vectorHashCodeInitialization) && !swingingHashColumn) { this.Write("\r\n this.hashCodeVector.Return();\r\n "); } this.Write("\r\n"); foreach (var f in this.fields.Where(fld => fld.canBeFixed)) { this.Write("\r\n }\r\n"); } this.Write("\r\n"); } this.Write(" batch.ReleaseKey();\r\n"); if (ungroupingToUnit || swingingHashColumn) { this.Write("\r\n batch.hash.Return();\r\n"); } this.Write("\r\n batch.Return();\r\n\r\n this.Observer.OnNext(resultBatch);\r\n }\r\n\r" + "\n public void OnError(Exception error)\r\n {\r\n Observer.OnError(error" + ");\r\n }\r\n}\r\n"); return(this.GenerationEnvironment.ToString()); }
private void ImportSpriteSheetIntoAnimation(Texture2D spriteSheet, int animIdx = -1) { string assetPath = AssetDatabase.GetAssetPath(spriteSheet); if (string.IsNullOrEmpty(assetPath)) { return; } TextureImporter spriteSheetImporter = (TextureImporter)TextureImporter.GetAtPath(assetPath); int characterNb; int charRowLength; int charColumnLength; int charFramesCount = m_target.DirectionsPerAnim * m_target.FramesPerAnim; int columns = 0, rows = 0; if (spriteSheetImporter.textureType != TextureImporterType.Sprite || spriteSheetImporter.spriteImportMode != SpriteImportMode.Multiple || spriteSheetImporter.spritesheet.Length == 0 || spriteSheetImporter.spritesheet.Length % charFramesCount != 0) { Rect[] rects = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(spriteSheet, 4, 0); if (rects.Length > 0 && rects.Length % charFramesCount == 0) { for (; columns < rects.Length; ++columns) { //NOTE: the order of slicing in GenerateAutomaticSpriteRectangles is from bottom to top, not from top to bottom like Sprite Editor Slicing if (rects[columns].yMin >= rects[0].yMax) { rows = rects.Length / columns; break; } } } else { columns = m_target.FramesPerAnim; rows = m_target.DirectionsPerAnim; } charRowLength = Mathf.Max(1, columns / m_target.FramesPerAnim); charColumnLength = Mathf.Max(1, rows / m_target.FramesPerAnim); characterNb = charRowLength * charColumnLength; int spriteCount = charFramesCount * characterNb; SpriteMetaData[] aSpriteMetaData = spriteSheetImporter.spritesheet; if (spriteSheetImporter.spritesheet.Length != spriteCount || spriteSheetImporter.spriteImportMode != SpriteImportMode.Multiple) { aSpriteMetaData = new SpriteMetaData[spriteCount]; spriteSheetImporter.textureType = TextureImporterType.Sprite; spriteSheetImporter.spriteImportMode = SpriteImportMode.Multiple; spriteSheetImporter.filterMode = FilterMode.Point; spriteSheetImporter.mipmapEnabled = false; #if UNITY_5_5_OR_NEWER spriteSheetImporter.textureCompression = TextureImporterCompression.Uncompressed; #else spriteSheetImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; #endif Rect spriteRect = new Rect(0, 0, spriteSheet.width / (m_target.FramesPerAnim * charRowLength), spriteSheet.height / (m_target.DirectionsPerAnim * charColumnLength)); for (int gy = 0, spriteIdx = 0; gy < rows; ++gy) { for (int gx = 0; gx < columns; ++gx, ++spriteIdx) { spriteRect.position = new Vector2(gx * spriteRect.width, spriteSheet.height - (1 + gy) * spriteRect.height); SpriteMetaData spriteMetaData = new SpriteMetaData(); //int characterIdx = (gy / m_target.DirectionNb) * charRowLength + (gx / m_target.FramesPerAnim); //NOTE: the sprites are sorted alphabetically, so spriteIdx should be in the first place after the name and nothing else spriteMetaData.name = spriteSheet.name + "_" + spriteIdx; // + (characterNb > 1 ? ("_" + characterIdx) : "") + "_" + gy + "_" + gx; spriteMetaData.rect = spriteRect; aSpriteMetaData[spriteIdx] = spriteMetaData; } } spriteSheetImporter.spritesheet = aSpriteMetaData; AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); } } UpdateAligmentAndPivot(spriteSheet); List <Sprite> sprites = new List <Sprite>(AssetDatabase.LoadAllAssetsAtPath(assetPath).OfType <Sprite>().ToArray()); //sort them properly using the last number sprites = sprites.OrderBy(s => int.Parse(s.name.Substring(s.name.LastIndexOf("_") + 1))).ToList(); for (; columns < sprites.Count; ++columns) { if (sprites[columns].rect.yMax <= sprites[0].rect.yMin) { rows = sprites.Count / columns; break; } } if (columns * rows != sprites.Count || columns % m_target.FramesPerAnim != 0 || rows % m_target.DirectionsPerAnim != 0) { Debug.LogError("Something was wrong with the sprite sheet. Try slicing it again using the Sprite Editor using grid settings or set the Sprite Mode to single and try again."); return; } List <Sprite> sortedSprites = new List <Sprite>(); charRowLength = Mathf.Max(1, columns / m_target.FramesPerAnim); charColumnLength = Mathf.Max(1, rows / m_target.DirectionsPerAnim); for (int charY = 0; charY < charColumnLength; ++charY) { for (int charX = 0; charX < charRowLength; ++charX) { for (int c = 0; c < m_target.DirectionsPerAnim; ++c) { for (int r = 0; r < m_target.FramesPerAnim; ++r) { int gx = charX * m_target.FramesPerAnim + r; int gy = charY * m_target.DirectionsPerAnim + c; sortedSprites.Add(sprites[gy * columns + gx]); } } } } characterNb = sortedSprites.Count / charFramesCount; if (animIdx >= 0) { ImportSpriteSheetIntoAnimation(spriteSheet, sortedSprites.Take(charFramesCount).ToArray(), animIdx, spriteSheet.name); } else { for (int characterIdx = 0; characterIdx < characterNb; ++characterIdx) { Sprite[] characterSprites = sortedSprites.Skip(characterIdx * charFramesCount).Take(charFramesCount).ToArray(); string charName = spriteSheet.name + (characterNb > 1? ("_" + characterIdx) : ""); ImportSpriteSheetIntoAnimation(spriteSheet, characterSprites, m_target.GetAnimList().FindIndex(x => x.name == charName), charName); } } }
internal override IEnumerable <AssociativeNode> BuildAst(List <AssociativeNode> inputAstNodes) { var resultAst = new List <AssociativeNode>(); string function = Definition.Name; AssociativeNode rhs; // All inputs are provided, then we should pack all inputs that // belong to variable input parameter into a single array. if (!HasUnconnectedInput()) { var paramCount = Definition.Parameters.Count(); var packId = "__var_arg_pack_" + GUID; resultAst.Add( AstFactory.BuildAssignment( AstFactory.BuildIdentifier(packId), AstFactory.BuildExprList(inputAstNodes.Skip(paramCount - 1).ToList()))); inputAstNodes = inputAstNodes.Take(paramCount - 1) .Concat(new[] { AstFactory.BuildIdentifier(packId) }) .ToList(); } switch (Definition.Type) { case FunctionType.Constructor: case FunctionType.StaticMethod: if (HasUnconnectedInput()) { var functionNode = new IdentifierListNode { LeftNode = new IdentifierNode(Definition.ClassName), RightNode = new IdentifierNode(Definition.Name) }; rhs = CreateFunctionObject(functionNode, inputAstNodes); } else { rhs = AstFactory.BuildFunctionCall(Definition.ClassName, Definition.Name, inputAstNodes); } break; case FunctionType.StaticProperty: var staticProp = new IdentifierListNode { LeftNode = new IdentifierNode(Definition.ClassName), RightNode = new IdentifierNode(Definition.Name) }; rhs = staticProp; break; case FunctionType.InstanceProperty: // Only handle getter here. Setter could be handled in CBN. rhs = new NullNode(); if (inputAstNodes != null && inputAstNodes.Count >= 1) { var thisNode = inputAstNodes[0]; if (thisNode != null && !(thisNode is NullNode)) { var insProp = new IdentifierListNode { LeftNode = inputAstNodes[0], RightNode = new IdentifierNode(Definition.Name) }; rhs = insProp; } } break; case FunctionType.InstanceMethod: rhs = new NullNode(); if (inputAstNodes != null && inputAstNodes.Count >= 1) { var thisNode = inputAstNodes[0]; inputAstNodes.RemoveAt(0); // remove this pointer if (thisNode != null && !(thisNode is NullNode)) { var memberFunc = new IdentifierListNode { LeftNode = thisNode, RightNode = AstFactory.BuildFunctionCall(function, inputAstNodes) }; rhs = memberFunc; } } break; default: if (HasUnconnectedInput()) { var functionNode = new IdentifierNode(function); rhs = CreateFunctionObject(functionNode, inputAstNodes); } else { rhs = AstFactory.BuildFunctionCall(function, inputAstNodes); } break; } resultAst.Add(AstFactory.BuildAssignment(AstIdentifierForPreview, rhs)); if (OutPortData.Count == 1) { var outputIdentiferNode = GetAstIdentifierForOutputIndex(0); string outputIdentifier = outputIdentiferNode.ToString(); string thisIdentifier = AstIdentifierForPreview.ToString(); if (!string.Equals(outputIdentifier, thisIdentifier)) { resultAst.Add( AstFactory.BuildAssignment(outputIdentiferNode, AstIdentifierForPreview)); } } else { var undefinedOutputs = Definition.ReturnKeys == null || !Definition.ReturnKeys.Any(); resultAst.AddRange( Enumerable.Range(0, OutPortData.Count) .Select( outputIdx => undefinedOutputs ? AstIdentifierForPreview : new IdentifierNode(AstIdentifierForPreview) { ArrayDimensions = new ArrayNode { Expr = new StringNode { value = Definition.ReturnKeys.ElementAt( outputIdx) } } })); } return(resultAst); }
public void SetupFactory(int botCount) { while (!factoryGame.LoggedIn) { Log("Waiting for BotFactory account to login"); Thread.Sleep(1000); } Log("Setting up bot factory with " + botCount + " bots"); int createdBots = 0; List <BotInfo> infos; if (Settings.Default.RandomBots) { infos = botInfos.TakeRandom(botCount).ToList(); } else { infos = botInfos.Take(botCount).ToList(); } Parallel.ForEach <BotInfo>(infos, info => { var bot = LoadBot(info); lock (bots) bots.Add(bot); Interlocked.Increment(ref createdBots); }); Parallel.For(createdBots, botCount, index => { try { var bot = CreateBot(); lock (bots) bots.Add(bot); } catch (Exception ex) { Log("Error creating new bot: " + ex.Message + "\n" + ex.StackTrace, LogLevel.Error); } }); Log("Finished setting up bot factory with " + botCount + " bots"); for (; ;) { string line = Console.ReadLine(); switch (line) { case "quit": case "exit": case "close": case "shutdown": return; case "info": case "infos": case "stats": case "statistics": Console.WriteLine(bots.Where(bot => bot.Running).Count() + " bots are active"); Console.WriteLine(bots.Where(bot => bot.Connected).Count() + " bots are connected"); Console.WriteLine(bots.Where(bot => bot.LoggedIn).Count() + " bots are ingame"); break; } } }