Пример #1
0
        private void VideosListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (VideosListView.SelectedItems.Count == 1)
            {
                Database.Types.Video selectedVideo = (Database.Types.Video)VideosListView.SelectedItems[0].Tag;
                string openVideoTip = $"Open video in browser.{Environment.NewLine}{selectedVideo.URL}";

                VideoPictureBox.Image   = Database.ImageFile.Get(selectedVideo.ID, ImageType.VideoThumbnail);
                VideoPictureBox.Visible = true;
                GeneralToolTip.SetToolTip(VideoPictureBox, openVideoTip);
                VideoDescriptionLabel.Text = StringUtils.FormatVideoDescription(selectedVideo.Description);

                VideoLinkLabel.Tag  = selectedVideo.URL;
                VideoLinkLabel.Text = selectedVideo.Title;
                GeneralToolTip.SetToolTip(VideoLinkLabel, openVideoTip);
                PostedLabel.Text   = selectedVideo.Posted.Value.ToString();
                DurationLabel.Text = TimeSpanUtils.ConvertDuration(selectedVideo.Duration);

                VideoInfoPanel.Visible = true;
            }
            else
            {
                VideosListViewChanged();
            }
        }
Пример #2
0
        /// <summary>
        /// Get information about a single video.
        /// </summary>
        /// <param name="id">ID of the video to get information for.</param>
        public Database.Types.Video Single(string id)
        {
            try {
                // https://developers.google.com/youtube/v3/docs/videos/list
                API.VideosResource.ListRequest videoSearch = APIService.Videos.List("id,snippet,contentDetails.duration");
                videoSearch.Id          = id;
                videoSearch.MaxResults  = 1;
                videoSearch.PrettyPrint = false;

                API.Data.Video response = videoSearch.Execute().Items[0];

                Database.Types.Video video = new Database.Types.Video {
                    ID           = response.Id,
                    ChannelID    = response.Snippet.ChannelId,
                    Title        = response.Snippet.Title,
                    Description  = response.Snippet.Description,
                    Duration     = TimeSpanUtils.ConvertDuration(response.ContentDetails.Duration),
                    Posted       = DateTime.Parse(response.Snippet.PublishedAt),
                    ThumbnailURL = GetBestThumbnail(response.Snippet.Thumbnails),
                    WatchStatus  = WatchStatus.Unwatched
                };

                LoggingManager.Log.Info($"Information processed for '{video.ID}' posted by '{video.ChannelID}'.");
                return(video);
            } catch (Exception ex) {
                LoggingManager.Log.Error(ex, $"Failed to get information for '{id}'.");
                return(null);
            }
        }
Пример #3
0
        public void Parse_HoursMinutesSeconds_Test()
        {
            var expected = TimeSpan.Parse("0.12:23:59");
            var actual   = TimeSpanUtils.Parse("12:23:59");

            Assert.Equal(expected, actual);
        }
Пример #4
0
        public void Parse_DaysHoursMinutesSecondsMilliseconds_Test()
        {
            var expected = TimeSpan.Parse("12.23:54:59.999");
            var actual   = TimeSpanUtils.Parse("12:23:54:59:999");

            Assert.Equal(expected, actual);
        }
Пример #5
0
        public void Parse_InvalidString_Test()
        {
            var expected = TimeSpan.Parse("0.00:00:00.000");
            var actual   = TimeSpanUtils.Parse("wefwef");

            Assert.Equal(expected, actual);
        }
Пример #6
0
        public void Parse_Ticks_Test()
        {
            var expected = TimeSpan.Parse("0.00:00:00.0000012");
            var actual   = TimeSpanUtils.Parse("12");

            Assert.Equal(expected, actual);
        }
Пример #7
0
        /// <summary>
        /// Wait for an event flag for a given bit pattern with callback.
        /// </summary>
        /// <param name="EventId">The event id returned by sceKernelCreateEventFlag.</param>
        /// <param name="Bits">The bit pattern to poll for.</param>
        /// <param name="Wait">Wait type, one or more of ::PspEventFlagWaitTypes or'ed together</param>
        /// <param name="OutBits">The bit pattern that was matched.</param>
        /// <param name="Timeout">Timeout in microseconds</param>
        /// <param name="HandleCallbacks"></param>
        /// <returns>
        ///		ERROR_KERNEL_NOT_FOUND_EVENT_FLAG - If can't find the eventFlag
        ///		ERROR_KERNEL_WAIT_TIMEOUT         - If there was a timeout
        ///		0                                 - On success
        /// </returns>
        public int _sceKernelWaitEventFlagCB(EventFlagId EventId, uint Bits, EventFlagWaitTypeSet Wait, uint *OutBits, uint *Timeout, bool HandleCallbacks)
        {
            var  EventFlag = HleState.EventFlagManager.EventFlags.Get(EventId);
            bool TimedOut  = false;

            HleState.ThreadManager.Current.SetWaitAndPrepareWakeUp(HleThread.WaitType.Semaphore, String.Format("_sceKernelWaitEventFlagCB(EventId={0}, Bits={1:X}, Wait={2})", EventId, Bits, Wait), WakeUpCallback =>
            {
                if (Timeout != null)
                {
                    HleState.PspRtc.RegisterTimerInOnce(TimeSpanUtils.FromMicroseconds(*Timeout), () =>
                    {
                        TimedOut = true;
                        WakeUpCallback();
                    });
                }

                EventFlag.AddWaitingThread(new HleEventFlag.WaitThread()
                {
                    HleThread      = HleState.ThreadManager.Current,
                    BitsToMatch    = Bits,
                    WaitType       = Wait,
                    WakeUpCallback = () => { WakeUpCallback(); },
                    OutBits        = OutBits,
                });
            }, HandleCallbacks: HandleCallbacks);

            if (TimedOut)
            {
                throw(new SceKernelException(SceKernelErrors.ERROR_KERNEL_WAIT_TIMEOUT));
            }

            //throw(new NotImplementedException());
            return(0);
        }
Пример #8
0
        public int sceKernelReceiveMbx(MessageBox MessageBox, PspPointer *PointerToMessage, uint *Timeout)
        {
            var  CurrentThread = ThreadManager.Current;
            bool TimedOut      = false;

            CurrentThread.SetWaitAndPrepareWakeUp(HleThread.WaitType.None, "sceKernelReceiveMbx", MessageBox,
                                                  WakeUpCallback =>
            {
                if (Timeout != null)
                {
                    PspRtc.RegisterTimerInOnce(TimeSpanUtils.FromMicroseconds(*Timeout), () =>
                    {
                        TimedOut = true;
                        WakeUpCallback();
                    });
                }
                MessageBox.Receive(PointerToMessage, WakeUpCallback);
            }, HandleCallbacks: false);

            if (TimedOut)
            {
                return((int)SceKernelErrors.ERROR_KERNEL_WAIT_TIMEOUT);
            }
            else
            {
                //if (Timeout)
                //return MessageBox.Receive(Message);
                return(0);
            }
        }
Пример #9
0
 public void RegisterTimeout(uint *timeout, Action wakeUpCallback)
 {
     if (timeout != null)
     {
         RegisterTimerInOnce(TimeSpanUtils.FromMicroseconds(*timeout), wakeUpCallback);
     }
 }
Пример #10
0
        /// <summary>
        ///   Get the timeout to wait for the next possible logging event, ensuring that
        ///   the time doesn't cause events in the buffer to be sent from being delayed
        ///   once the holddown timeout expires.
        /// </summary>
        private TimeSpan GetWaitTimeOut(WorkerState state)
        {
            DateTime now = DateTime.UtcNow;
            var      maxHolddownInterval = TimeSpanUtils.Max(state.LastSend + HolddownPeriod - now, TimeSpan.Zero);

            return(new TimeSpan(0, 0, 30));
        }
Пример #11
0
 protected void UpdateHandlerTime()
 {
     PspRtc.Update();
     Console.Error.WriteLine("UpdateHandlerTime: {0}", this.HandlerTime - ElapsedAccumulatedTime);
     this.Timer.DateTime = PspRtc.CurrentDateTime +
                           TimeSpanUtils.FromMicroseconds(this.HandlerTime - ElapsedAccumulatedTime);
 }
Пример #12
0
        public void Send(int id, string name, LuaTable tb)
        {
            if (SocketClient.State == SocketClient.ConnectState.DisConnect)
            {
                return;
            }
            var msg = ProtocolGroup.GetMsg(name);

            if (msg == null)
            {
                Debug.Log(String.Format("protocol {0} not exist", name));
                return
            }

            m_messageIndex++;
            ByteBuffer protoBuff = new ByteBuffer();

            ProtocolReadWriter.Req(msg.Id, buff, tb, ProtocolGroup);
            byteBuffer buff = new ByteBuffer();

            buff.WriteUshort(msg.Id);
            buff.WriteBytes(protoBuff.ToBytes());
            protoBuff.Close();

            byte[]     buffBytes   = buff.ToBytes();
            ByteBuffer contentBuff = new ByteBuffer();

            contentBuff.WriteVchar((uint)buffBytes.Length);
            contentBuff.WriteBytes(buffBytes);

            ByteBuffer sendBuff = new ByteBuffer();

            sendBuff.WriteUint(Convert.ToUInt32(buffBytes.Length) + 16);

            //CRC
            uint crc = CRC.GetCrc32(buffBytes);

            sendBuffer.WriteUint(crc);

            //Time
            uint       timeUint = TimeSpanUtils.ConvertDateTimeToUInt(DateTime.Now);
            ByteBuffer desBuff  = new ByteBuffer();

            desBuff.WriteBytes(BitConverter.GetBytes(timeUint));
            desBuff.WriteBytes(BitConverter.GetBytes(m_messageIndex));

            //DES
            ulong des = BitConverter.ToUInt64(desBuff.ToBytes(), 0);

            byte[] desBytes = DES.Encrypt(bitConverter.GetBytes(des));

            sendBuff.WriteUlong(BitConverter.ToUInt64(desBytes, 0));
            sendBuff.WriteBytes(buffBytes);
            client.SendMessage(sendBuff);

            contentBuff.Close();
            desBuff.Close();
            buff.Close();
        }
Пример #13
0
        private void UpdateDuration(SyncOperationStatus status)
        {
            Assert.IsNotNull(RunningOperation);
            var duration = !status.IsEnded() || !RunningOperation.FinishedAt.HasValue
                                ? DateTime.UtcNow - RunningOperation.StartedAt.Value
                                : RunningOperation.FinishedAt.Value - RunningOperation.StartedAt.Value;

            lblDuration.Text = TimeSpanUtils.GetReadableTimespan(duration);
        }
Пример #14
0
        private void LogEnd()
        {
            logger.Info(
#if DEBUG
                "{0}:{1}:{2} - ENDED {3} - TOOK {4}",
#else
                "{2} - ENDED {3} - TOOK {4}",
#endif
                SourceFilePath, SourceLineNumberCreated, MemberName, Identifier,
                TimeSpanUtils.GetReadableTimespan(Duration));
        }
        /// <summary>
        /// Wait for an event flag for a given bit pattern with callback.
        /// </summary>
        /// <param name="EventId">The event ID returned by <see cref="sceKernelCreateEventFlag"/>.</param>
        /// <param name="Bits">The bit pattern to poll for.</param>
        /// <param name="Wait">Wait type, one or more of PspEventFlagWaitTypes or'ed together</param>
        /// <param name="OutBits">The bit pattern that was matched.</param>
        /// <param name="Timeout">Timeout in microseconds</param>
        /// <param name="HandleCallbacks"></param>
        /// <returns>
        ///		ERROR_KERNEL_NOT_FOUND_EVENT_FLAG - If can't find the eventFlag
        ///		ERROR_KERNEL_WAIT_TIMEOUT         - If there was a timeout
        ///		0                                 - On success
        /// </returns>
        public int _sceKernelWaitEventFlagCB(HleEventFlag EventFlag, uint Bits, EventFlagWaitTypeSet Wait,
                                             uint *OutBits, uint *Timeout, bool HandleCallbacks)
        {
            if ((Wait & ~EventFlagWaitTypeSet.MaskValidBits) != 0)
            {
                throw new SceKernelException(SceKernelErrors.ERROR_KERNEL_ILLEGAL_MODE);
            }
            if (Bits == 0)
            {
                throw new SceKernelException(SceKernelErrors.ERROR_KERNEL_EVENT_FLAG_ILLEGAL_WAIT_PATTERN);
            }
            bool TimedOut = false;

            var PreviousPattern = EventFlag.Info.CurrentPattern;

            ThreadManager.Current.SetWaitAndPrepareWakeUp(
                HleThread.WaitType.Semaphore,
                $"_sceKernelWaitEventFlagCB(EventId={EventFlag.GetUidIndex(InjectContext)}, Bits={Bits:X}, Wait={Wait})",
                EventFlag,
                WakeUpCallback =>
            {
                if (Timeout != null)
                {
                    PspRtc.RegisterTimerInOnce(TimeSpanUtils.FromMicroseconds(*Timeout), () =>
                    {
                        TimedOut = true;
                        *Timeout = 0;
                        WakeUpCallback();
                    });
                }

                EventFlag.AddWaitingThread(new HleEventFlag.WaitThread()
                {
                    HleThread      = ThreadManager.Current,
                    BitsToMatch    = Bits,
                    WaitType       = Wait,
                    WakeUpCallback = () => { WakeUpCallback(); },
                    OutBits        = OutBits,
                });
            }, HandleCallbacks: HandleCallbacks);

            if (OutBits != null)
            {
                *OutBits = PreviousPattern;
            }

            if (TimedOut)
            {
                throw new SceKernelException(SceKernelErrors.ERROR_KERNEL_WAIT_TIMEOUT);
            }

            //throw(new NotImplementedException());
            return(0);
        }
Пример #16
0
        private int _sceKernelDelayThreadCB(uint DelayInMicroseconds, bool HandleCallbacks)
        {
            HleState.ThreadManager.Current.SetWaitAndPrepareWakeUp(HleThread.WaitType.Timer, "sceKernelDelayThread", WakeUpCallback =>
            {
                HleState.PspRtc.RegisterTimerInOnce(TimeSpanUtils.FromMicroseconds(DelayInMicroseconds), () =>
                {
                    WakeUpCallback();
                });
            }, HandleCallbacks: HandleCallbacks);

            return(0);
        }
Пример #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ThreadId"></param>
        /// <param name="Timeout"></param>
        /// <param name="HandleCallbacks"></param>
        /// <returns></returns>
        private int _sceKernelWaitThreadEndCB(int ThreadId, uint *Timeout, bool HandleCallbacks)
        {
            var ThreadToWaitEnd = GetThreadById(ThreadId);

            if (ThreadToWaitEnd.HasAnyStatus(HleThread.Status.Stopped))
            {
                return(0);
            }

            if (ThreadToWaitEnd.HasAnyStatus(HleThread.Status.Killed))
            {
                return(0);
            }

            bool TimedOut = false;

            ThreadManager.Current.SetWaitAndPrepareWakeUp(HleThread.WaitType.None,
                                                          $"sceKernelWaitThreadEnd('{ThreadToWaitEnd.Name}')", ThreadToWaitEnd, WakeUpCallback =>
            {
                if (Timeout != null)
                {
                    PspRtc.RegisterTimerInOnce(TimeSpanUtils.FromMicroseconds(*Timeout), () =>
                    {
                        TimedOut = true;
                        WakeUpCallback();
                    });
                }

                Console.WriteLine("Wait End!");
                Action OnTerminate = null;

                OnTerminate = () =>
                {
                    ThreadToWaitEnd.OnTerminate -= OnTerminate;
                    Console.WriteLine("Ended!");
                    //throw(new Exception("aaaaaaaaaaaa"));
                    WakeUpCallback();
                };

                ThreadToWaitEnd.OnTerminate += OnTerminate;
            }, HandleCallbacks: HandleCallbacks);

            if (TimedOut)
            {
                return((int)SceKernelErrors.ERROR_KERNEL_WAIT_TIMEOUT);
            }
            else
            {
                return(0);
            }
        }
Пример #18
0
        private int _sceKernelDelayThreadCB(uint DelayInMicroseconds, bool HandleCallbacks)
        {
            var CurrentThread = ThreadManager.Current;

            CurrentThread.SetWaitAndPrepareWakeUp(HleThread.WaitType.Timer,
                                                  $"sceKernelDelayThread({DelayInMicroseconds}, {HandleCallbacks})", null,
                                                  WakeUpCallback =>
            {
                PspRtc.RegisterTimerInOnce(TimeSpanUtils.FromMicroseconds(DelayInMicroseconds),
                                           () => { WakeUpCallback(); });
            }, HandleCallbacks: HandleCallbacks);

            return(0);
        }
Пример #19
0
        private void UpdateDuration(Commands.OperationStatus status)
        {
            // Prevent a NPE when accessing `CurrentOperation.StartedAt` below.
            if (!CurrentOperation.GotInitialInfo)
            {
                return;
            }

            // Calculate duration.
            var duration = !status.IsEnded() || !CurrentOperation.FinishedAt.HasValue
                                ? DateTime.UtcNow - CurrentOperation.StartedAt.Value
                                : CurrentOperation.FinishedAt.Value - CurrentOperation.StartedAt.Value;

            lblDuration.Text = TimeSpanUtils.GetReadableTimespan(duration);
        }
        private static IEnumerable <MatchEvent> ConvertTimeEventsDtoToTimelineEvents(
            IEnumerable <MatchEventDto> matchEventDtoList)
        {
            if (matchEventDtoList == null)
            {
                return(new List <MatchEvent>());
            }

            try
            {
                var matchEventList = new List <MatchEvent>();

                foreach (var matchEventDto in matchEventDtoList)
                {
                    matchEventList.Add(new MatchEvent
                    {
                        Type                  = matchEventDto.Type,
                        TimeStamp             = matchEventDto.Timestamp,
                        UserFriendlyTimestamp = TimeSpanUtils.ConvertTimespanToFriendly(Convert.ToInt32(matchEventDto.Timestamp.TotalSeconds)),
                        ParticipantId         = matchEventDto.ParticipantId,
                        ItemId                = matchEventDto.ItemId,
                        SkillSlot             = matchEventDto.SkillSlot,
                        LevelUpType           = matchEventDto.LevelUpType,
                        WardType              = matchEventDto.WardType,
                        CreatorId             = matchEventDto.CreatorId,
                        KillerId              = matchEventDto.KillerId,
                        VictimId              = matchEventDto.VictimId,
                        AfterId               = matchEventDto.AfterId,
                        BeforeId              = matchEventDto.BeforeId,
                        TeamId                = matchEventDto.TeamId,
                        BuildingType          = matchEventDto.BuildingType,
                        LaneType              = matchEventDto.LaneType,
                        TowerType             = matchEventDto.TowerType,
                        MonsterType           = matchEventDto.MonsterType,
                        MonsterSubType        = matchEventDto.MonsterSubType
                    });
                }

                return(matchEventList);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught when converting list of MatchEventDto to list of MatchEvent : " + e.Message);
            }

            return(new List <MatchEvent>());
        }
Пример #21
0
        public NotificationForm(Database.Types.Video video)
        {
            InitializeComponent();
            SetIcon();

            if (SettingsManager.Configuration.NotificationWindow.PositionSet())
            {
                Location = new Point(SettingsManager.Configuration.NotificationWindow.X, SettingsManager.Configuration.NotificationWindow.Y);
            }
            else
            {
                CenterToScreen();
            }

            _Video = video;

            Image channelImage        = Database.ImageFile.Get(_Video.ChannelID, ImageType.ChannelIcon);
            Image channelImageResized = ImageUtils.ResizeImage(channelImage, 365, 365);
            Image channelImageFaded   = ImageUtils.SetImageOpacity(channelImageResized, 0.16f);

            BackgroundImage = channelImageFaded;

            ChannelPictureBox.Image = channelImage;
            VideoPictureBox.Image   = Database.ImageFile.Get(_Video.ID, ImageType.VideoThumbnail);

            ChannelLabel.Text  = $"A new video was posted by {_Video.Channel.Title} {_Video.Posted.Value.Humanize()}.";
            DurationLabel.Text = TimeSpanUtils.ConvertDurationCompact(video.Duration);

            MarkButton.Text           = $"Close & mark as: (wait {(_Countdown + 1)}s)";
            OpenVideoCheckBox.Checked = SettingsManager.Configuration.NotificationOpenVideo;

            OpenVideoStatusComboBox.Items.Add(WatchStatus.Unwatched);
            OpenVideoStatusComboBox.Items.Add(WatchStatus.Watched);
            OpenVideoStatusComboBox.Items.Add(WatchStatus.Dismissed);
            OpenVideoStatusComboBox.Items.Add(WatchStatus.Ignored);
            OpenVideoStatusComboBox.SelectedItem = SettingsManager.Configuration.NotificationDefaultVideoStatus;

            ControlBox = false;
        }
        public static Match ConverMatchDtoToMatch(MatchDto matchDto, MatchTimelineDto matchTimelineDto)
        {
            if (matchDto == null || matchTimelineDto == null)
            {
                return(new Match());
            }

            try
            {
                return(new Match
                {
                    GameDuration = TimeSpanUtils.ConvertTimespanToFriendly(Convert.ToInt32(matchDto.GameDuration.TotalSeconds)),
                    GameDate = matchDto.GameDate,
                    GamePatch = matchDto.GamePatch,
                    WinningTeamId = matchDto.WinningTeamId,

                    TeamOne = ConvertMatchTeamDtoToMatchTeam
                              (
                        matchDto.Teams.ElementAtOrDefault(0),
                        matchTimelineDto.Events
                              ),

                    TeamTwo = ConvertMatchTeamDtoToMatchTeam
                              (
                        matchDto.Teams.ElementAtOrDefault(1),
                        matchTimelineDto.Events
                              )
                });
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught converting MatchDto to Match : " + e.Message);
            }

            return(new Match());
        }
Пример #23
0
        public void CalcularClassificacaoFinalPilotos(Dictionary <int, DadosCorridaPiloto> pPosicaoFinal)
        {
            StringBuilder classificacaoFinal = new StringBuilder();

            var formatString = "|{0,-30}|{1,-30}|{2,-30}|{3,-30}|{4,-30}|{5,-30}|";

            classificacaoFinal.AppendLine()
            .AppendFormat(Culture, formatString, "Posição Chegada", "Código Piloto", "Nome Piloto", "Qtde Voltas Completadas", "Tempo Total de Prova", "Tempo de Chegada Após Vencedor")
            .AppendLine();

            String primeiraLinha = CriarLinhaFormatadoraColunasTabelas(classificacaoFinal);

            classificacaoFinal.Insert(0, primeiraLinha);
            classificacaoFinal.Append(primeiraLinha).AppendLine();

            TimeSpan tempoChegadaVencedor = pPosicaoFinal.FirstOrDefault().Value.HoraUltimaVolta;
            int      count = 1;

            // constrói  relatorio da classificação final de cada piloto
            pPosicaoFinal.ToList().ForEach(x =>
            {
                int codigoPiloto     = x.Key;
                string nomePiloto    = x.Value.Piloto.NomePiloto;
                int qtdVoltas        = x.Value.NumeroDeVoltasTotais;
                string tempoTotal    = x.Value.TempoTotalCorrida.ToString(@"hh\:mm\:ss\:fff");
                TimeSpan horaChegada = x.Value.HoraUltimaVolta;

                string diferencaToVencedor = (tempoChegadaVencedor.CompareTo(horaChegada) == 0) ? "(Não se Aplica)" : TimeSpanUtils.OperarTimeSpans(horaChegada, tempoChegadaVencedor, ETimeSpanOperacao.Subtracao).ToString(@"hh\:mm\:ss\:fff");

                classificacaoFinal.AppendFormat(Culture, formatString, count++, codigoPiloto.ToString("D3"), nomePiloto, qtdVoltas, tempoTotal, diferencaToVencedor).AppendLine();
            });


            RelatorioFinal.Append("[ RESULTADO FINAL DA CORRIDA (CLASSIFICAÇÃO) E DIFERENÇA DE TEMPO DE CHEGADA DE CADA PILOTO PARA O VENCEDOR ]").AppendLine().AppendLine();
            RelatorioFinal.Append(classificacaoFinal.ToString());
        }
Пример #24
0
        // função que calcula e faz chamadas para métodos que ajudarão a construir o relatório final
        public string CalcularResultadoCorrida(List <IVoltaCorrida> pVoltas)
        {
            // Dicionário que conterá dados relevantes de cada piloto ao final da corrida
            var dDadosPilotosCorrida = new Dictionary <int, DadosCorridaPiloto>();

            // agrupa voltas por cada piloto
            var voltasGroupedByPiloto = pVoltas.GroupBy(x => x.Piloto.Codigo);

            // para cada piloto, itere sobre suas voltas

            foreach (var voltaG in voltasGroupedByPiloto)
            {
                var voltasPiloto = voltaG.Select(volta => volta);

                var somadorVelocidades = 0.0f;

                var ultimaVolta = voltasPiloto.Last();

                //para cada volta do piloto atual
                foreach (var volta in voltasPiloto)
                {
                    if (!dDadosPilotosCorrida.ContainsKey(voltaG.Key))
                    {
                        somadorVelocidades += volta.VelocidadeMediaVolta;

                        var dadosCorrida = new DadosCorridaPiloto(volta.HoraVolta, volta.NumeroVolta, volta.TempoVolta, volta.VelocidadeMediaVolta, volta.Piloto);

                        dDadosPilotosCorrida.Add(voltaG.Key, dadosCorrida);
                    }
                    else
                    {
                        //se o piloto já esta no hashmap dados_pilotos_final_da_corrida, atualize seus dados//
                        DadosCorridaPiloto dadosPiloto = dDadosPilotosCorrida[voltaG.Key];

                        //atualiza hora da última volta
                        dadosPiloto.HoraUltimaVolta = volta.HoraVolta;
                        //atualiza número da volta
                        dadosPiloto.NumeroDeVoltasTotais = volta.NumeroVolta;
                        //atualiza velocidadeTotal
                        dadosPiloto.VelocidadeTotalCorrida = dadosPiloto.VelocidadeTotalCorrida + volta.VelocidadeMediaVolta;
                        //atualiza tempo total durante a corrida
                        dadosPiloto.TempoTotalCorrida = TimeSpanUtils.OperarTimeSpans(dadosPiloto.TempoTotalCorrida, volta.TempoVolta, ETimeSpanOperacao.Adicao);

                        //se tempo da volta atual for melhor (menor) que o anterior, atualize este valor
                        if (volta.TempoVolta < dadosPiloto.MelhorVolta)
                        {
                            dadosPiloto.MelhorVolta = volta.TempoVolta;
                        }

                        // variável que armazena a soma das velocidades de cada volta do piloto atual
                        somadorVelocidades += volta.VelocidadeMediaVolta;

                        // se for a última volta do piloto atual calcule sua Velocidade Média
                        if (volta.Equals(ultimaVolta))
                        {
                            float velocidadeMedia = somadorVelocidades / voltasPiloto.Count();
                            dadosPiloto.VelocidadeMediaCorrida = velocidadeMedia;

                            somadorVelocidades = 0.0F; // reseta somadorVelocidades
                        }

                        //atualiza dados do piloto atual no dicionário dDadosPilotosCorrida
                        dDadosPilotosCorrida[voltaG.Key] = dadosPiloto;
                    }
                }
            }

            //Dicionário com classificação final dos pilotos
            Dictionary <int, DadosCorridaPiloto> posicaoFinal = ComputarPosicaoFinalDosPilotos(dDadosPilotosCorrida);

            //gera relatório da classificação final da corrida
            CalcularClassificacaoFinalPilotos(posicaoFinal);

            //gera relatório da melhor volta de cada piloto na corrida
            CalcularMelhorVoltaDeCadaPiloto(dDadosPilotosCorrida);

            //gera relatório da melhor volta da corrida
            CalcularMelhorVoltaDaCorrida(dDadosPilotosCorrida);

            //gera relatório da velocidade média de cada piloto na corrida
            CalcularVelocidadeMediaDeCadaPiloto(dDadosPilotosCorrida);

            return(RelatorioFinal.ToString());
        }
Пример #25
0
        /// <summary>
        /// Get information about mutiple videos.
        /// </summary>
        /// <param name="ids">Videos to get information for.</param>
        public List <Database.Types.Video> Bulk(List <string> ids)
        {
            try {
                // https://developers.google.com/youtube/v3/docs/videos/list
                if (ids.Count == 0)
                {
                    return(null);
                }

                List <(int chunkID, List <string> videoIDs)> videoIDChunks = new List <(int chunkID, List <string> videoIDs)>();
                List <Database.Types.Video> videosReturn = new List <Database.Types.Video>();
                int chunkNumber = 1;

SplitIntoChunksLoop:
                if (ids.Count > 0)
                {
                    if ((ids.Count > 50) || (ids.Count == 50))
                    {
                        videoIDChunks.Add((chunkNumber, ids.Take(50).ToList()));
                        ids.RemoveRange(0, 50);
                    }
                    else
                    {
                        videoIDChunks.Add((chunkNumber, ids.Take(ids.Count).ToList()));
                        ids.RemoveRange(0, ids.Count);
                    }

                    chunkNumber++;
                    goto SplitIntoChunksLoop;
                }
                LoggingManager.Log.Info($"Video chunk processing finished with {videoIDChunks.Count} total chunks.");

                foreach ((int chunkID, List <string> videoIDs) in videoIDChunks)
                {
                    API.VideosResource.ListRequest videoSearch = APIService.Videos.List("id,snippet,contentDetails");
                    videoSearch.Id          = string.Join(",", videoIDs);
                    videoSearch.MaxResults  = videoIDs.Count;
                    videoSearch.PrettyPrint = false;

                    API.Data.VideoListResponse response = videoSearch.Execute();

                    IList <API.Data.Video> videos = response.Items;
                    foreach (API.Data.Video video in videos)
                    {
                        Database.Types.Video videoInfo = new Database.Types.Video {
                            ID           = video.Id,
                            ChannelID    = video.Snippet.ChannelId,
                            Title        = video.Snippet.Title,
                            Description  = video.Snippet.Description,
                            Duration     = TimeSpanUtils.ConvertDuration(video.ContentDetails.Duration),
                            Posted       = DateTime.Parse(video.Snippet.PublishedAt),
                            ThumbnailURL = GetBestThumbnail(video.Snippet.Thumbnails),
                            WatchStatus  = WatchStatus.Unwatched
                        };

                        videosReturn.Add(videoInfo);
                        LoggingManager.Log.Info($"Chunk {chunkID}: Information processed for '{videoInfo.ID}' posted by '{videoInfo.ChannelID}'.");
                    }
                }

                return(videosReturn);
            } catch (Exception ex) {
                LoggingManager.Log.Error(ex, $"Failed to get information for '{string.Join(",", ids)}'.");
                return(null);
            }
        }
Пример #26
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (IsRunning)
            {
                return;
            }

            IsRunning = true;

            CancellationTokenSource = new CancellationTokenSource();

            var options = new TransferAgentOptions
            {
                UploadChunkSizeInBytes = 1 * 1024 * 1024,
            };

            string accessKey  = txtAccessKey.Text.Trim();
            string secretKey  = txtSecretKey.Text.Trim();
            string bucketName = txtBucketName.Text.Trim();
            BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
            string localFilePath            = txtFilePath.Text;
            bool   fileInformed             = !string.IsNullOrEmpty(localFilePath);
            bool   fileExists = fileInformed && FileManager.FileExists(localFilePath);

            if (!fileInformed || !fileExists)
            {
                string message = "";
                if (!fileInformed)
                {
                    message = "You have to inform a file for upload";
                }
                else if (!fileExists)
                {
                    message = string.Format("The informed file does not exist: {0}", localFilePath);
                }
                MessageBox.Show(message, "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                IsRunning = false;
                return;
            }

#if true
            string remoteFilePath = typeof(UploadPerfTestControl).Name + ".DELETE_ME";
#else
            S3PathBuilder pathBuilder    = new S3PathBuilder();
            string        remoteFilePath = pathBuilder.BuildRemotePath(localFilePath);
#endif
            long           fileSize = FileManager.UnsafeGetFileSize(localFilePath);
            BlockPerfStats stats    = new BlockPerfStats();

            S3TransferAgent xferAgent = new S3TransferAgent(options, credentials, bucketName, CancellationTokenSource.Token);
            xferAgent.UploadFileStarted += (object sender1, TransferFileProgressArgs e1) =>
            {
                stats.Begin();
            };
            xferAgent.UploadFileCanceled += (object sender1, TransferFileProgressArgs e1) =>
            {
                stats.End();
                string message = "Canceled file upload";
                MessageBox.Show(message, "Transfer canceled", MessageBoxButtons.OK, MessageBoxIcon.Information);
            };
            xferAgent.UploadFileFailed += (object sender1, TransferFileProgressArgs e1) =>
            {
                stats.End();
                string message = string.Format("Failed to upload file: {0}\n{1}", e1.Exception.GetType().Name, e1.Exception.Message);
                MessageBox.Show(message, "Transfer failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            };
            xferAgent.UploadFileCompleted += (object sender1, TransferFileProgressArgs e1) =>
            {
                stats.End();
                string message = string.Format(
                    "Took {0} to upload {1}",
                    TimeSpanUtils.GetReadableTimespan(stats.Duration),
                    FileSizeUtils.FileSizeToString(fileSize)
                    );
                MessageBox.Show(message, "Transfer completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
            };
            //xferAgent.UploadFileProgress += (object sender1, TransferFileProgressArgs e1) =>
            //{
            //	// ...
            //};

            xferAgent.UploadFile(localFilePath, remoteFilePath, null);

            IsRunning = false;
        }