Example #1
0
    public static void Render(string pointFilePath, Size?resolution)
    {
        using var points = PointStream.Load(pointFilePath);
        var viewPort         = points.ViewPort;
        var actualResolution = resolution ?? points.ViewPort.Resolution;

        if (actualResolution != points.ViewPort.Resolution)
        {
            viewPort = new ViewPort(viewPort.Area, actualResolution);
        }

        var imageFilePath = pointFilePath + $".{actualResolution.Width}x{actualResolution.Height}.png";

        using var timer = TimedOperation.Start("points", totalWork: actualResolution.Area());
        var image = new FastImage(actualResolution);

        image.Fill(Color.White);

        Parallel.ForEach(points, point =>
        {
            image.SetPixel(viewPort.GetPosition(point), Color.Black);
            timer.AddWorkDone(1);
        });

        image.Save(imageFilePath);
    }
Example #2
0
 //reading from file command
 public ActionResult DisplayFile(String filename, int freq)
 {
     PointStream.Instance(new PointFromFile(Path(filename)));
     ViewBag.Freq = freq;
     ViewBag.Time = 0;
     return(View());
 }
        /// <summary>
        /// 创建 <see cref="LatestArticleList"/>
        /// </summary>
        /// <param name="pointId">据点 ID</param>
        /// <param name="page">分页页码</param>
        /// <param name="returnPageCount">是否返回总页数</param>
        /// <param name="returnFirstCoverImage">是否返回第一篇文章封面图</param>
        /// <param name="dbContext"><see cref="KeylolDbContext"/></param>
        /// <param name="cachedData"><see cref="CachedDataProvider"/></param>
        /// <returns>Item1 表示 <see cref="LatestArticleList"/>,Item2 表示总页数,Item3 表示第一篇文章封面图</returns>
        public static async Task <Tuple <LatestArticleList, int, string> > CreateAsync(string pointId, int page,
                                                                                       bool returnPageCount, bool returnFirstCoverImage, KeylolDbContext dbContext, CachedDataProvider cachedData)
        {
            var streamName     = PointStream.Name(pointId);
            var conditionQuery = from feed in dbContext.Feeds
                                 where feed.StreamName == streamName && feed.EntryType == FeedEntryType.ArticleId
                                 join article in dbContext.Articles on feed.Entry equals article.Id
                                 where article.Archived == ArchivedState.None && article.Rejected == false
                                 orderby feed.Id descending
                                 select article;
            var queryResult = await conditionQuery.Select(a => new
            {
                Count      = returnPageCount ? conditionQuery.Count() : 1,
                CoverImage = returnFirstCoverImage ? a.CoverImage : null,
                a.Id,
                a.SidForAuthor,
                a.Title,
                a.PublishTime,
                AuthorIdCode      = a.Author.IdCode,
                AuthorAvatarImage = a.Author.AvatarImage,
                AuthorUserName    = a.Author.UserName,
                PointIdCode       = a.TargetPoint.IdCode,
                PointType         = a.TargetPoint.Type,
                PointAvatarImage  = a.TargetPoint.AvatarImage,
                PointChineseName  = a.TargetPoint.ChineseName,
                PointEnglishName  = a.TargetPoint.EnglishName
            }).TakePage(page, RecordsPerPage).ToListAsync();

            var result = new LatestArticleList(queryResult.Count);

            foreach (var a in queryResult)
            {
                result.Add(new LatestArticle
                {
                    LikeCount         = await cachedData.Likes.GetTargetLikeCountAsync(a.Id, LikeTargetType.Article),
                    CommentCount      = await cachedData.ArticleComments.GetArticleCommentCountAsync(a.Id),
                    SidForAuthor      = a.SidForAuthor,
                    Title             = a.Title,
                    PublishTime       = a.PublishTime,
                    AuthorIdCode      = a.AuthorIdCode,
                    AuthorAvatarImage = a.AuthorAvatarImage,
                    AuthorUserName    = a.AuthorUserName,
                    PointIdCode       = a.PointIdCode,
                    PointType         = a.PointType,
                    PointAvatarImage  = a.PointAvatarImage,
                    PointChineseName  = a.PointChineseName,
                    PointEnglishName  = a.PointEnglishName
                });
            }
            var firstRecord = queryResult.FirstOrDefault(r => !string.IsNullOrWhiteSpace(r.CoverImage));

            return(new Tuple <LatestArticleList, int, string>(
                       result,
                       (int)Math.Ceiling(firstRecord?.Count / (double)RecordsPerPage ?? 1),
                       firstRecord?.CoverImage));
        }
Example #4
0
        public string GetPoint()
        {
            Point p = PointStream.Instance().GetPoint();

            if (p == null)
            {
                return(null);
            }
            return(ToXml(p));
        }
 /// <summary>
 /// 创建 <see cref="TimelinePage"/>
 /// </summary>
 /// <param name="pointId">据点 ID</param>
 /// <param name="currentUserId">当前登录用户 ID</param>
 /// <param name="dbContext"><see cref="KeylolDbContext"/></param>
 /// <param name="cachedData"><see cref="CachedDataProvider"/></param>
 /// <returns><see cref="TimelinePage"/></returns>
 public static async Task <TimelinePage> CreateAsync(string pointId, string currentUserId,
                                                     KeylolDbContext dbContext,
                                                     CachedDataProvider cachedData)
 {
     return(new TimelinePage
     {
         Cards = await TimelineCardList.CreateAsync(PointStream.Name(pointId), currentUserId,
                                                    18, false, dbContext, cachedData)
     });
 }
Example #6
0
        //the display frequency command
        public ActionResult DisplayFreq(String ip, int port, int freq)
        {
            IClient client;

            try
            {
                client = new Client(ip, port);
                client.Connect();
            } catch (Exception e)
            {
                ViewBag.Error = e;
                return(View("Error", e));
            }
            PointStream.Instance(new PointFromNetwork(client));
            ViewBag.Freq = freq;
            ViewBag.Time = 0;
            return(View());
        }
    public static void CalculateWithDoubles(string edgeSpansPath, int pointsToCalculate)
    {
        using var edgeSpans      = EdgeSpanStream.Load(edgeSpansPath);
        using var timedOperation = TimedOperation.Start("edge spans", totalWork: pointsToCalculate > 0 ? pointsToCalculate : edgeSpans.Count);
        var points =
            edgeSpans.Take((int)timedOperation.TotalWork).
            AsParallel().
            Select(span => span.
                   ToConcreteDouble(edgeSpans.ViewPort).
                   FindBoundaryPoint(Constant.IterationRange.Max)).
            Where(point =>
        {
            var escapeTime = ScalarDoubleKernel.FindEscapeTime(point, Constant.IterationRange.Max);
            timedOperation.AddWorkDone(1);
            return(Constant.IterationRange.IsInside(escapeTime));
        });

        PointStream.Write(edgeSpansPath + $".{timedOperation.TotalWork}.doublePoints", edgeSpans.ViewPort, points);
    }
Example #8
0
        // GET: Save
        public ActionResult SaveFile(String ip, int port, int freq, int time, String filename)
        {
            IClient client;

            try
            {
                client = new Client(ip, port);
                client.Connect();
            }
            catch (Exception e)
            {
                ViewBag.Error = e;
                return(View("Error", e));
            }
            PointStream.Instance(new PointToFile(new PointFromNetwork(client), Path(filename)));
            ViewBag.Freq = freq;
            ViewBag.Time = time;
            return(View());
        }
Example #9
0
    private void InitializeStreams()
    {
        try
        {
            AstraUnityContext.Instance.WaitForUpdate(AstraBackgroundUpdater.WaitIndefinitely);

            _streamSet = Astra.StreamSet.Open();

            _readerDepth         = _streamSet.CreateReader();
            _readerColor         = _streamSet.CreateReader();
            _readerBody          = _streamSet.CreateReader();
            _readerMaskedColor   = _streamSet.CreateReader();
            _readerColorizedBody = _streamSet.CreateReader();
            _readerPoint         = _streamSet.CreateReader();

            _depthStream = _readerDepth.GetStream <DepthStream>();

            var       depthModes        = _depthStream.AvailableModes;
            ImageMode selectedDepthMode = depthModes[0];

    #if ASTRA_UNITY_ANDROID_NATIVE
            int targetDepthWidth  = 160;
            int targetDepthHeight = 120;
            int targetDepthFps    = 30;
    #else
            int targetDepthWidth  = 320;
            int targetDepthHeight = 240;
            int targetDepthFps    = 30;
    #endif

            foreach (var m in depthModes)
            {
                if (m.Width == targetDepthWidth &&
                    m.Height == targetDepthHeight &&
                    m.FramesPerSecond == targetDepthFps)
                {
                    selectedDepthMode = m;
                    break;
                }
            }

            _depthStream.SetMode(selectedDepthMode);

            _colorStream = _readerColor.GetStream <ColorStream>();

            var       colorModes        = _colorStream.AvailableModes;
            ImageMode selectedColorMode = colorModes[0];

    #if ASTRA_UNITY_ANDROID_NATIVE
            int targetColorWidth  = 320;
            int targetColorHeight = 240;
            int targetColorFps    = 30;
    #else
            int targetColorWidth  = 640;
            int targetColorHeight = 480;
            int targetColorFps    = 30;
    #endif

            foreach (var m in colorModes)
            {
                if (m.Width == targetColorWidth &&
                    m.Height == targetColorHeight &&
                    m.FramesPerSecond == targetColorFps)
                {
                    selectedColorMode = m;
                    break;
                }
            }

            _colorStream.SetMode(selectedColorMode);

            _bodyStream = _readerBody.GetStream <BodyStream>();

            _maskedColorStream = _readerMaskedColor.GetStream <MaskedColorStream>();

            _colorizedBodyStream = _readerColorizedBody.GetStream <ColorizedBodyStream>();

            _pointStream = _readerPoint.GetStream <PointStream>();

            _areStreamsInitialized = true;
        }
        catch (AstraException e)
        {
            Debug.Log("AstraController: Couldn't initialize streams: " + e.ToString());
            UninitializeStreams();
        }
    }
 public DataFillAdapter(PointStream stream)
 {
     m_stream = stream;
     m_stream.Read();
 }
Example #11
0
        protected override void OnStart(string[] args)
        {
            _mqChannel.BasicQos(0, 5, false);
            var consumer = new EventingBasicConsumer(_mqChannel);

            consumer.Received += async(sender, eventArgs) =>
            {
                try
                {
                    using (var streamReader = new StreamReader(new MemoryStream(eventArgs.Body)))
                        using (var dbContext = new KeylolDbContext())
                        {
                            var serializer = new JsonSerializer();
                            var requestDto =
                                serializer.Deserialize <PushHubRequestDto>(new JsonTextReader(streamReader));

                            string            entryId;
                            FeedEntryType     entryType;
                            List <string>     pointsToPush;
                            List <UserToPush> usersToPush = new List <UserToPush>();
                            var count = 0;
                            switch (requestDto.Type)
                            {
                            case ContentPushType.Article:
                            {
                                var article = await dbContext.Articles.Where(a => a.Id == requestDto.ContentId)
                                              .Select(a => new
                                    {
                                        a.Id,
                                        a.AuthorId,
                                        a.AttachedPoints,
                                        a.TargetPointId
                                    }).SingleAsync();

                                usersToPush.Add(new UserToPush
                                    {
                                        UserId = article.AuthorId,
                                        SubscriberTimelineReason = "author"
                                    });
                                entryId      = article.Id;
                                entryType    = FeedEntryType.ArticleId;
                                pointsToPush = Helpers.SafeDeserialize <List <string> >(article.AttachedPoints) ??
                                               new List <string>();
                                pointsToPush.Add(article.TargetPointId);
                                break;
                            }

                            case ContentPushType.Activity:
                            {
                                var activity = await dbContext.Activities.Where(a => a.Id == requestDto.ContentId)
                                               .Select(a => new
                                    {
                                        a.Id,
                                        a.AuthorId,
                                        a.AttachedPoints,
                                        a.TargetPointId
                                    }).SingleAsync();

                                usersToPush.Add(new UserToPush
                                    {
                                        UserId = activity.AuthorId,
                                        SubscriberTimelineReason = "author"
                                    });
                                entryId      = activity.Id;
                                entryType    = FeedEntryType.ActivityId;
                                pointsToPush = Helpers.SafeDeserialize <List <string> >(activity.AttachedPoints) ??
                                               new List <string>();
                                pointsToPush.Add(activity.TargetPointId);
                                if (await AddOrUpdateFeedAsync(LatestActivityStream.Name, entryId, entryType, null,
                                                               dbContext))
                                {
                                    count++;
                                }
                                break;
                            }

                            case ContentPushType.Like:
                            {
                                var like = await dbContext.Likes.FindAsync(requestDto.ContentId);

                                entryId      = like.TargetId;
                                pointsToPush = new List <string>();
                                usersToPush.Add(new UserToPush
                                    {
                                        UserId                   = like.OperatorId,
                                        UserTimelineReason       = "like",
                                        SubscriberTimelineReason = $"like:{like.OperatorId}"
                                    });
                                switch (like.TargetType)
                                {
                                case LikeTargetType.Article:
                                    entryType = FeedEntryType.ArticleId;
                                    break;

                                case LikeTargetType.Activity:
                                    entryType = FeedEntryType.ActivityId;
                                    break;

                                default:
                                    _mqChannel.BasicAck(eventArgs.DeliveryTag, false);
                                    return;
                                }
                                break;
                            }

                            default:
                                throw new ArgumentOutOfRangeException();
                            }

                            foreach (var user in usersToPush)
                            {
                                if (await AddOrUpdateFeedAsync(UserStream.Name(user.UserId),
                                                               entryId, entryType, user.UserTimelineReason, dbContext))
                                {
                                    count++;
                                }

                                foreach (var subscriberId in await dbContext.Subscriptions
                                         .Where(s => s.TargetId == user.UserId &&
                                                s.TargetType == SubscriptionTargetType.User)
                                         .Select(s => s.SubscriberId).ToListAsync())
                                {
                                    if (await AddOrUpdateFeedAsync(SubscriptionStream.Name(subscriberId),
                                                                   entryId, entryType, user.SubscriberTimelineReason, dbContext))
                                    {
                                        count++;
                                    }
                                }
                            }


                            foreach (var pointId in pointsToPush)
                            {
                                var point = await dbContext.Points.Where(p => p.Id == pointId)
                                            .Select(p => new { p.Id }).SingleOrDefaultAsync();

                                if (point == null)
                                {
                                    continue;
                                }
                                if (await AddOrUpdateFeedAsync(PointStream.Name(point.Id),
                                                               entryId, entryType, null, dbContext))
                                {
                                    count++;
                                }

                                foreach (var subscriberId in await dbContext.Subscriptions
                                         .Where(s => s.TargetId == point.Id &&
                                                s.TargetType == SubscriptionTargetType.Point)
                                         .Select(s => s.SubscriberId).ToListAsync())
                                {
                                    if (await AddOrUpdateFeedAsync(SubscriptionStream.Name(subscriberId),
                                                                   entryId, entryType, $"point:{point.Id}", dbContext))
                                    {
                                        count++;
                                    }
                                }
                            }

                            _mqChannel.BasicAck(eventArgs.DeliveryTag, false);
                            _logger.Info($"{count} feeds pushed. Content: ({requestDto.Type}) {requestDto.ContentId}");
                        }
                }
                catch (Exception e)
                {
                    _mqChannel.BasicNack(eventArgs.DeliveryTag, false, false);
                    _logger.Fatal("RabbitMQ unhandled callback exception.", e);
                }
            };
            _mqChannel.BasicConsume(MqClientProvider.PushHubRequestQueue, false, consumer);
        }
 public FrameReader(PointStream stream)
 {
     m_stream = stream;
     Frame = new SortedList<ulong, HistorianValueStruct>();
     m_stream.Read();
 }
Example #13
0
 public void Close()
 {
     PointStream.Instance().Close();
 }
 /// <summary>
 /// 获取时间轴卡片列表
 /// </summary>
 /// <param name="pointId">据点 ID</param>
 /// <param name="before">起始位置</param>
 /// <param name="take">获取数量</param>
 /// <param name="dbContext"><see cref="KeylolDbContext"/></param>
 /// <param name="cachedData"><see cref="CachedDataProvider"/></param>
 /// <returns><see cref="TimelineCardList"/></returns>
 public static async Task <TimelineCardList> GetCards(string pointId, int before, int take,
                                                      [Injected] KeylolDbContext dbContext, [Injected] CachedDataProvider cachedData)
 {
     return(await TimelineCardList.CreateAsync(PointStream.Name(pointId), StateTreeHelper.GetCurrentUserId(),
                                               take, false, dbContext, cachedData, before));
 }