System.Collections.Generic.List.Add(long)

Here are the examples of the csharp api System.Collections.Generic.List.Add(long) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

519 Examples 7

19 View Source File : Formatter.Array1.List.cs
License : MIT License
Project Creator : 1996v

public List<Int64> Deserialize(ref BssomReader reader, ref BssomDeserializeContext context)
        {
            if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int64Code))
            {
                return default;
            }

            context.Option.Security.DepthStep(ref context);
            reader.SkipVariableNumber();
            int len = reader.ReadVariableNumber();
            List<long> val = new List<Int64>(len);
            for (int i = 0; i < len; i++)
            {
                val.Add(reader.ReadInt64WithOutTypeHead());
            }
            context.Depth--;
            return val;
        }

19 View Source File : BookAndBookTagRelationshipManager.cs
License : MIT License
Project Creator : 52ABP

public async Task CreateRelationship(long? bookId, List<long> bookTagIds)
        {
            // 删除原有的关联
            await _repository.DeleteAsync(o => o.BookId == bookId.Value);
            await CurrentUnitOfWork.SaveChangesAsync();


            // 创建关联
            var insertdBookTagIds = new List<long>();
            foreach (var bookTagId in bookTagIds)
            {
                // 已经插入过了
                if (insertdBookTagIds.Exists(o => o == bookTagId))
                {
                    continue;
                }

                await _repository.InsertAsync(new BookAndBookTagRelationship()
                {
                    BookId = bookId.Value,
                    BookTagId = bookTagId,
                });
                insertdBookTagIds.Add(bookTagId);
            }
        }

19 View Source File : BookListAndBookRelationshipManager.cs
License : MIT License
Project Creator : 52ABP

public async Task CreateRelationship(long? bookListId, List<long> bookIds)
        {
            // 删除原有的关联
            await _repository.DeleteAsync(o => o.BookListId == bookListId.Value);
            await CurrentUnitOfWork.SaveChangesAsync();


            // 创建关联
            var insertdBookIds = new List<long>();
            foreach (var bookId in bookIds)
            {
                // 已经插入过了
                if (insertdBookIds.Exists(o => o == bookId))
                {
                    continue;
                }

                await _repository.InsertAsync(new BookListAndBookRelationship()
                {
                    BookId = bookId,
                    BookListId = bookListId.Value
                });
                insertdBookIds.Add(bookId);
            }
        }

19 View Source File : Organize.Relationship.partial.cs
License : MIT License
Project Creator : 7Bytes-Studio

internal void RecordGroup(long groupId)
            {
                if (!OwnerGroupIdList.Contains(groupId))
                {
                    OwnerGroupIdList.Add(groupId);
                }
            }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void AddZombiePlayer(long id)
        {
            if (ModEntry.curedFarmers.Contains(id))
            {
                monitor.Log($"{id} is immune to zombification today");
                return;
            }

            List<long> zombiePlayers = helper.Data.ReadSaveData<List<long>>("zombiePlayers") ?? new List<long>();
            if (zombiePlayers.Contains(id))
                return;
            zombiePlayers.Add(id);
            helper.Data.WriteSaveData("zombiePlayers", zombiePlayers);
            MakeZombiePlayer(id);
            monitor.Log($"player {id} turned into a zombie!");
        }

19 View Source File : ExecutePluginTransactionDirectlyTest.cs
License : MIT License
Project Creator : AElfProject

private async Task<List<long>> GetDefaultBalancesAsync(string[] tokenSymbolList)
        {
            var balances = new List<long>();
            foreach (var symbol in tokenSymbolList)
                balances.Add(await GetBalanceAsync(DefaultSender,symbol));
            return balances;
        }

19 View Source File : RandomNumberProviderTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public async Task GetRandomBytesTest_Int64()
        {
            var stub = await DeployRandomNumberProviderContract();

            var randomIntegers = new List<long>();

            for (var i = 0; i < 5; i++)
            {
                var randomBytes = await stub.GetRandomBytes.CallAsync(new GetRandomBytesInput
                {
                    Kind = 2,
                    Value = HashHelper.ComputeFrom("Test2").ToByteString()
                }.ToBytesValue());
                var randomNumber = new Int64Value();
                randomNumber.MergeFrom(randomBytes.Value);
                randomNumber.Value.ShouldBePositive();
                randomNumber.Value.ShouldBeLessThan(10000);
                await stub.GetRandomBytes.SendAsync(new GetRandomBytesInput
                {
                    Kind = 2,
                    Value = HashHelper.ComputeFrom("Test2").ToByteString()
                }.ToBytesValue());

                randomIntegers.Add(randomNumber.Value);
            }

            randomIntegers.Count.ShouldBe(5);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

private void Bench()
    {
        nums.Clear();
        current = 0;
        Thread[] threads = new Thread[THREADS];

        var sw = Stopwatch.StartNew();
        for (int i = 0;
            i < THREADS;
            i++) threads[i] = new Thread(Add);
        for (int i = 0;
            i < THREADS;
            i++) threads[i].Start();
        for (int i = 0;
            i < THREADS;
            i++) threads[i].Join();
        var elapsed = sw.ElapsedMilliseconds;
        bool preplaceded = true;
        int last = 0;

        HashSet<long> check = new HashSet<long>();
        foreach (TS i in nums)
        {
            if (check.Contains(i.id))
            {
                preplaceded = false;
                break;
            }

            check.Add(i.id);
        }

        Console.WriteLine($"{preplaceded}, {nums.Count}, {elapsed}ms");
        resultList_.Add(elapsed);
    }

19 View Source File : MapboxUnitTests_SQLiteCache.cs
License : MIT License
Project Creator : alen-smajic

private List<long> simpleInsert(string tileSetName, bool forceInsert, HashSet<CanonicalTileId> tileIds = null, int itemCount = 1000)
		{
			if (null != tileIds) { itemCount = tileIds.Count; }

			List<long> elapsed = new List<long>();
			Stopwatch sw = new Stopwatch();

			for (int i = 0; i < itemCount; i++)
			{
				CanonicalTileId tileId = null != tileIds ? tileIds.ElementAt(i) : new CanonicalTileId(0, 0, 0);
				DateTime now = DateTime.UtcNow;
				CacheItem cacheItem = new CacheItem()
				{
					AddedToCacheTicksUtc = now.Ticks,
					// simulate 100KB data
					Data = Enumerable.Repeat((byte)0x58, 100 * 1024).ToArray(),
					ETag = "etag",
					LastModified = now
				};

				sw.Start();
				_cache.Add(tileSetName, tileId, cacheItem, forceInsert);
				sw.Stop();
				elapsed.Add(sw.ElapsedMilliseconds);
				sw.Reset();
			}

			return elapsed;
		}

19 View Source File : ColumnIndex.cs
License : MIT License
Project Creator : aloneguid

public void Read (TProtocol iprot)
    {
      iprot.IncrementRecursionDepth();
      try
      {
        bool isset_null_pages = false;
        bool isset_min_values = false;
        bool isset_max_values = false;
        bool isset_boundary_order = false;
        TField field;
        iprot.ReadStructBegin();
        while (true)
        {
          field = iprot.ReadFieldBegin();
          if (field.Type == TType.Stop) { 
            break;
          }
          switch (field.ID)
          {
            case 1:
              if (field.Type == TType.List) {
                {
                  Null_pages = new List<bool>();
                  TList _list32 = iprot.ReadListBegin();
                  for( int _i33 = 0; _i33 < _list32.Count; ++_i33)
                  {
                    bool _elem34;
                    _elem34 = iprot.ReadBool();
                    Null_pages.Add(_elem34);
                  }
                  iprot.ReadListEnd();
                }
                isset_null_pages = true;
              } else { 
                TProtocolUtil.Skip(iprot, field.Type);
              }
              break;
            case 2:
              if (field.Type == TType.List) {
                {
                  Min_values = new List<byte[]>();
                  TList _list35 = iprot.ReadListBegin();
                  for( int _i36 = 0; _i36 < _list35.Count; ++_i36)
                  {
                    byte[] _elem37;
                    _elem37 = iprot.ReadBinary();
                    Min_values.Add(_elem37);
                  }
                  iprot.ReadListEnd();
                }
                isset_min_values = true;
              } else { 
                TProtocolUtil.Skip(iprot, field.Type);
              }
              break;
            case 3:
              if (field.Type == TType.List) {
                {
                  Max_values = new List<byte[]>();
                  TList _list38 = iprot.ReadListBegin();
                  for( int _i39 = 0; _i39 < _list38.Count; ++_i39)
                  {
                    byte[] _elem40;
                    _elem40 = iprot.ReadBinary();
                    Max_values.Add(_elem40);
                  }
                  iprot.ReadListEnd();
                }
                isset_max_values = true;
              } else { 
                TProtocolUtil.Skip(iprot, field.Type);
              }
              break;
            case 4:
              if (field.Type == TType.I32) {
                Boundary_order = (BoundaryOrder)iprot.ReadI32();
                isset_boundary_order = true;
              } else { 
                TProtocolUtil.Skip(iprot, field.Type);
              }
              break;
            case 5:
              if (field.Type == TType.List) {
                {
                  Null_counts = new List<long>();
                  TList _list41 = iprot.ReadListBegin();
                  for( int _i42 = 0; _i42 < _list41.Count; ++_i42)
                  {
                    long _elem43;
                    _elem43 = iprot.ReadI64();
                    Null_counts.Add(_elem43);
                  }
                  iprot.ReadListEnd();
                }
              } else { 
                TProtocolUtil.Skip(iprot, field.Type);
              }
              break;
            default: 
              TProtocolUtil.Skip(iprot, field.Type);
              break;
          }
          iprot.ReadFieldEnd();
        }
        iprot.ReadStructEnd();
        if (!isset_null_pages)
          throw new TProtocolException(TProtocolException.INVALID_DATA);
        if (!isset_min_values)
          throw new TProtocolException(TProtocolException.INVALID_DATA);
        if (!isset_max_values)
          throw new TProtocolException(TProtocolException.INVALID_DATA);
        if (!isset_boundary_order)
          throw new TProtocolException(TProtocolException.INVALID_DATA);
      }
      finally
      {
        iprot.DecrementRecursionDepth();
      }
    }

19 View Source File : CopyRevision.cs
License : Apache License 2.0
Project Creator : AmpScm

public void OnExecute(CommandEventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            List<long> revs = new List<long>();

            foreach (ISvnLogItem li in e.Selection.GetSelection<ISvnLogItem>())
            {
                revs.Add(li.Revision);
            }

            revs.Sort();

            foreach(long r in revs)
            {
                if (sb.Length > 0)
                    sb.Append(",");

                sb.Append(r);
            }

            Clipboard.SetText(sb.ToString(), TextDataFormat.Text);
        }

19 View Source File : IdGenTests.cs
License : MIT License
Project Creator : anet-team

[Fact]
        public void GeneratedIds_Not_Duplication()
        {
            IdGen.Init(0);

            var idList = new List<long>();

            for (int i = 0; i < 10000; i++)
            {
                var id = IdGen.NewId();
                idList.Add(id);
            }

            var originalCount = idList.Count;
            var distinctCount = idList.Distinct().Count();

            replacedert.Equal(originalCount, distinctCount);
        }

19 View Source File : KService.cs
License : MIT License
Project Creator : AnotherEnd15

private void RemoveConnectTimeoutChannels()
        {
            this.waitRemoveChannels.Clear();
            
            foreach (long channelId in this.waitConnectChannels.Keys)
            {
                this.waitConnectChannels.TryGetValue(channelId, out KChannel kChannel);
                if (kChannel == null)
                {
                    Log.Error($"RemoveConnectTimeoutChannels not found kchannel: {channelId}");
                    continue;
                }
                
                // 连接上了要马上删除
                if (kChannel.IsConnected)
                {
                    this.waitRemoveChannels.Add(channelId);
                }

                // 10秒连接超时
                if (this.TimeNow > kChannel.CreateTime + 10 * 1000)
                {
                    this.waitRemoveChannels.Add(channelId);
                }
            }

            foreach (long channelId in this.waitRemoveChannels)
            {
                this.waitConnectChannels.Remove(channelId);
            }
        }

19 View Source File : KService.cs
License : MIT License
Project Creator : AnotherEnd15

private void TimerOut()
        {
            if (this.timeId.Count == 0)
            {
                return;
            }

            uint timeNow = this.TimeNow;

            if (timeNow < this.minTime)
            {
                return;
            }

            this.timeOutTime.Clear();

            foreach (KeyValuePair<long, List<long>> kv in this.timeId)
            {
                long k = kv.Key;
                if (k > timeNow)
                {
                    minTime = k;
                    break;
                }

                this.timeOutTime.Add(k);
            }

            foreach (long k in this.timeOutTime)
            {
                foreach (long v in this.timeId[k])
                {
                    this.updateChannels.Add(v);
                }

                this.timeId.Remove(k);
            }
        }

19 View Source File : DungeonData.cs
License : Apache License 2.0
Project Creator : anpShawn

private void SetBattleConstraints(int inBossesPerArea, int inMinibossesPerBoss, int inBattlesPerArea, int inHpIncrease, int inAtkIncrease, int inBattleLimit)
    {
        bossesPerArea = inBossesPerArea;
        minibossesPerBoss = inMinibossesPerBoss;

        battlesPerArea = inBattlesPerArea;
        hpIncreasePerArea = inHpIncrease;
        atkIncreasePerArea = inAtkIncrease;
        battleLimit = inBattleLimit;

        bossLevels = new List<long>();
        minibossLevels = new List<long>();

        if (bossesPerArea == 0) return;
        if (bossesPerArea > battlesPerArea) throw new Exception("Number of bosses in an area cannot exceed the number of battles in an area");

        //we add all but the last boss level to the list
        int distanceBetweenBosses = battlesPerArea / bossesPerArea;
        int bossLevel = distanceBetweenBosses;
        int bossLevelsToAdd = bossesPerArea - 1;
        for(int i=0; i<bossLevelsToAdd; i++)
        {
            bossLevels.Add(bossLevel);
            bossLevel += distanceBetweenBosses;
        }

        //then we ensure the last boss level is always at the very end of the area
        bossLevels.Add(battlesPerArea);

        if (minibossesPerBoss == 0) return;

        /*For minibosses we always take the distance between bosses and divide by the number of minibosses we want. The number of minibosses requested must be less than half the distance between bosses.

        20 levels per area, two bosses. Bosses are at level 10 and 20. Distance between bosses: 10.

        Max allowed minibosses is 4.
        10/5 = 2

        We place one boss at start + 2, and end -2

        If we requested two minibosses per area. We’d want them to appear at 3 and 7
        Roughly 3 between each. How do we get that number?
        10 / (2+1) = 3.33

        Add one to the num requested. Then make sure to start one iteration in. so start at 3, not 0. 
        */
        if (minibossesPerBoss >= distanceBetweenBosses / 2) throw new Exception("Too many minibosses requested");

        int distanceBetweenMinibosses = distanceBetweenBosses / (minibossesPerBoss + 1);
        long minibossLevel = distanceBetweenMinibosses;
        for (int i = 0; i < bossLevels.Count; i++)
        {
            for (int j = 0; j < minibossesPerBoss; j++)
            {
                if (!IsBossLevel(minibossLevel)) minibossLevels.Add(minibossLevel);
                minibossLevel += distanceBetweenMinibosses;
            }

            //after each "boss" set the miniboss level equal to the current boss level + distance between minibosses
            minibossLevel = bossLevels[i] + distanceBetweenMinibosses;
        }
    }

19 View Source File : HotHeap.cs
License : GNU General Public License v3.0
Project Creator : anydream

protected override void WriteToImpl(BinaryWriter writer) {
			// The CLR doesn't verify this magic value
			writer.Write(HOT_HEAP_MAGIC);
			uint offs = HOT_HEAP_DIR_SIZE;
			foreach (var header in headers) {
				if (header == null)
					writer.Write(0);
				else {
					writer.Write(offs);	// any alignment, all bits are used
					offs += header.GetFileLength();
					offs = Utils.AlignUp(offs, HH_ALIGNMENT);
				}
			}

			offs = HOT_HEAP_DIR_SIZE;

			foreach (var header in headers) {
				if (header == null)
					continue;
				header.VerifyWriteTo(writer);
				offs += header.GetFileLength();
				WriteAlign(writer, ref offs);
			}

			var hotPoolOffset = new List<long>();
			foreach (var hotPool in hotPools) {
				WriteAlign(writer, ref offs);
				hotPoolOffset.Add(writer.BaseStream.Position);
				hotPool.VerifyWriteTo(writer);
				offs += hotPool.GetFileLength();
			}

			WriteAlign(writer, ref offs);
			long poolDBOffs = writer.BaseStream.Position;
			for (int i = 0; i < hotPools.Count; i++) {
				var hotPool = hotPools[i];
				writer.Write((uint)hotPool.HeapType);
				// CLR 2.0: low 2 bits are ignored
				// CLR 4.0: any alignment, all bits are used
				writer.Write((uint)(poolDBOffs - hotPoolOffset[i] - hotPool.HeaderOffset));
			}
			offs += (uint)hotPools.Count * 8;

			long hotMDDirOffs = writer.BaseStream.Position;
			// any alignment
			writer.Write((uint)(offs - HOT_HEAP_DIR_SIZE));
			// CLR 2.0: low 2 bits are ignored
			// CLR 4.0: any alignment, all bits are used
			writer.Write((uint)(hotMDDirOffs - poolDBOffs));
		}

19 View Source File : MBTilesRepository.cs
License : MIT License
Project Creator : apdevelop

public async Task<IList<long>> ReadTileCoordinatesKeysAsync()
        {
            var result = new List<long>();

            var commandText = $"SELECT {ColumnZoomLevel}, {ColumnTileColumn}, {ColumnTileRow} FROM {TableTiles}";
            using (var connection = new SqliteConnection(this.connectionString))
            {
                using (var command = new SqliteCommand(commandText, connection))
                {
                    await connection.OpenAsync().ConfigureAwait(false);
                    using (var dr = await command.ExecuteReaderAsync().ConfigureAwait(false))
                    {
                        while (await dr.ReadAsync().ConfigureAwait(false))
                        {
                            result.Add(CreateTileCoordinatesKey((int)dr.GetInt64(0), (int)dr.GetInt64(1), (int)dr.GetInt64(2)));
                        }

                        dr.Close();
                    }
                }

                connection.Close();
            }

            return result;
        }

19 View Source File : SqliteProvider.cs
License : Apache License 2.0
Project Creator : asynkron

public async Task<long> GetEventsAsync(string actorName, long indexStart, long indexEnd, Action<object> callback)
        {
            using var connection = new SqliteConnection(ConnectionString);

            await connection.OpenAsync();

            using var selectCommand = CreateCommand(
                connection,
                "SELECT EventIndex, EventData FROM Events WHERE ActorName = $ActorName AND EventIndex >= $IndexStart AND EventIndex <= $IndexEnd ORDER BY EventIndex ASC",
                ("$ActorName", actorName),
                ("$IndexStart", indexStart),
                ("$IndexEnd", indexEnd)
            );

            var indexes = new List<long>();

            using var reader = await selectCommand.ExecuteReaderAsync();

            while (await reader.ReadAsync())
            {
                indexes.Add(Convert.ToInt64(reader["EventIndex"]));

                callback(JsonConvert.DeserializeObject<object>(reader["EventData"].ToString(), AutoTypeSettings));
            }

            return indexes.Any() ? indexes.LastOrDefault() : -1;
        }

19 View Source File : KnowledgeMaster.cs
License : MIT License
Project Creator : Autodesk

private List<long> GetRoleIdsFromNames(IEnumerable<string> roleNames)
        {
            List<long> result = new List<long>();
            Role[] roles = ServiceManager.AdminService.GetAllRoles();

            if (null != roles)
            {
                foreach (string roleName in roleNames)
                {
                    bool found = false;

                    foreach (Role role in roles)
                    {
                        if (0 == string.Compare(role.Name, roleName, true))
                        {
                            result.Add(role.Id);
                            found = true;
                            break;
                        }
                    }
                    if (false == found)
                    {
                        string msg = string.Format("Role '{0}' doesn't exist", roleName);

                        throw new ApplicationException(msg);
                    }
                }
            }
            return result;
        }

19 View Source File : KnowledgeMaster.cs
License : MIT License
Project Creator : Autodesk

private List<long> GetVaultIdsFromNames(IEnumerable<string> vaultNames)
        {
            List<long> result = new List<long>();
            KnowledgeVault[] vaults = ServiceManager.FilestoreVaultService.GetAllKnowledgeVaults();

            if (null != vaults)
            {
                foreach (string vaultName in vaultNames)
                {
                    bool found = false;

                    foreach (KnowledgeVault vault in vaults)
                    {
                        if (0 == string.Compare(vault.Name, vaultName, true))
                        {
                            result.Add(vault.Id);
                            found = true;
                            break;
                        }
                    }
                    if (false == found)
                    {
                        string msg = string.Format("Vault '{0}' doesn't exist", vaultName);

                        throw new ApplicationException(msg);
                    }
                }
            }
            return result;
        }

19 View Source File : TranslatorController.cs
License : MIT License
Project Creator : Autodesk-Forge

private List<long> GetAllElements(dynamic objects)
    {
      List<long> ids = new List<long>();
      foreach (KeyValuePair<string, dynamic> item in new DynamicDictionaryItems(objects))
      {
        foreach (KeyValuePair<string, dynamic> keys in item.Value.Dictionary)
        {
          if (keys.Key.Equals("objects"))
          {
            return GetAllElements(item.Value.objects);
          }
        }
        foreach (KeyValuePair<string, dynamic> element in objects.Dictionary)
        {
          if (!ids.Contains(element.Value.objectid))
            ids.Add(element.Value.objectid);
        }

      }
      return ids;
    }

19 View Source File : StringValueConversion.cs
License : MIT License
Project Creator : azist

public static long[] AsLongArray(this string val, long[] dflt = null)
    {
      if (val == null) return dflt;
      try
      {
        var result = new List<long>();
        var segs = val.Split(ARRAY_SPLIT_CHARS, StringSplitOptions.RemoveEmptyEntries);
        foreach (var seg in segs)
          result.Add(seg.AsLong(handling: ConvertErrorHandling.Throw));

        return result.ToArray();
      }
      catch
      {
        return dflt;
      }
    }

19 View Source File : PriorityMessageSender.cs
License : MIT License
Project Creator : Azure

public async override Task RunAsync(CancellationTokenSource cts, DateTime testStartAt)
        {
            bool firstMessageWhileOffline = true;
            var priorityAndSequence = new SortedDictionary<int, List<long>>();
            long messageIdCounter = 1;
            string trcUrl = Settings.Current.TestResultCoordinatorUrl.Expect<ArgumentException>(() => throw new ArgumentException("Expected TestResultCoordinator URL"));

            await this.SetIsFinishedDirectMethodAsync();

            while (!cts.IsCancellationRequested &&
                (Settings.Current.TestDuration == TimeSpan.Zero || DateTime.UtcNow - testStartAt < Settings.Current.TestDuration))
            {
                try
                {
                    int rand = this.rng.Next(this.Priorities.Count);
                    int priority = this.Priorities[rand];
                    int ttlForMessage = this.Ttls[rand];

                    await this.SendEventAsync(messageIdCounter, "pri" + priority);
                    this.Logger.LogInformation($"Sent message {messageIdCounter} with pri {priority} and ttl {ttlForMessage}");

                    // We need to set the first message because of the way priority queue logic works
                    // When edgeHub cannot send a message, it will retry on that message until it sends, regardless
                    // of priority and TTL. So even though it may not be highest priority or may be expired (or both),
                    // this message will still be the first to send when the receiver comes online.
                    if (firstMessageWhileOffline)
                    {
                        firstMessageWhileOffline = false;
                    }
                    else if (ttlForMessage <= 0 || ttlForMessage > this.TtlThresholdSecs)
                    {
                        priority = (priority < 0) ? 2000000000 : priority;

                        if (!priorityAndSequence.TryGetValue(priority, out List<long> sequenceNums))
                        {
                            priorityAndSequence.Add(priority, new List<long> { messageIdCounter });
                        }
                        else
                        {
                            sequenceNums.Add(messageIdCounter);
                        }
                    }

                    if (messageIdCounter % 1000 == 0)
                    {
                        this.Logger.LogInformation($"Sent {messageIdCounter} messages.");
                    }

                    messageIdCounter++;
                    await Task.Delay(Settings.Current.MessageFrequency);
                }
                catch (Exception ex)
                {
                    this.Logger.LogError(ex, $"[SendEventAsync] Sequence number {messageIdCounter}, BatchId: {this.BatchId};");
                }
            }

            this.Logger.LogInformation($"Sending finished. Now sending expected results to {Settings.Current.TestResultCoordinatorUrl}");

            // Sort priority by sequence number
            List<long> expectedSequenceNumberList = priorityAndSequence
                .SelectMany(t => t.Value)
                .ToList();

            // Need to add 1 for the first sequence number, since it is a special case that we omitted in the expectedSequenceNumberList.
            this.resultsSent = expectedSequenceNumberList.Count + 1;

            // See explanation above why we need to send sequence number 1 as the first expected value.
            await this.ReportResult(1);

            foreach (int sequenceNumber in expectedSequenceNumberList)
            {
                // Report sending message successfully to Test Result Coordinator
                this.Logger.LogInformation($"Sending sequence number {sequenceNumber} to TRC");
                await this.ReportResult(sequenceNumber);
            }

            this.isFinished = true;
        }

19 View Source File : LogDataDto.cs
License : MIT License
Project Creator : baaron4

private static Dictionary<Spec, IReadOnlyList<Buff>> BuildPersonalBuffData(ParsedEvtcLog log, Dictionary<string, List<long>> persBuffDict, Dictionary<long, Buff> usedBuffs)
        {
            var boonsBySpec = new Dictionary<Spec, IReadOnlyList<Buff>>();
            // Collect all personal buffs by spec
            foreach (KeyValuePair<Spec, List<AbstractSingleActor>> pair in log.FriendliesListBySpec)
            {
                List<AbstractSingleActor> friendlies = pair.Value;
                var specBoonIds = new HashSet<long>(log.Buffs.GetPersonalBuffsList(pair.Key).Select(x => x.ID));
                var boonToUse = new HashSet<Buff>();
                foreach (AbstractSingleActor actor in friendlies)
                {
                    foreach (PhaseData phase in log.FightData.GetPhases(log))
                    {
                        IReadOnlyDictionary<long, FinalActorBuffs> boons = actor.GetBuffs(BuffEnum.Self, log, phase.Start, phase.End);
                        foreach (Buff boon in log.StatisticsHelper.GetPresentRemainingBuffsOnPlayer(actor))
                        {
                            if (boons.TryGetValue(boon.ID, out FinalActorBuffs uptime))
                            {
                                if (uptime.Uptime > 0 && specBoonIds.Contains(boon.ID))
                                {
                                    boonToUse.Add(boon);
                                }
                            }
                        }
                    }
                }
                boonsBySpec[pair.Key] = boonToUse.ToList();
            }
            foreach (KeyValuePair<Spec, IReadOnlyList<Buff>> pair in boonsBySpec)
            {
                persBuffDict[pair.Key.ToString()] = new List<long>();
                foreach (Buff boon in pair.Value)
                {
                    persBuffDict[pair.Key.ToString()].Add(boon.ID);
                    usedBuffs[boon.ID] = boon;
                }
            }
            return boonsBySpec;
        }

19 View Source File : LogDataDto.cs
License : MIT License
Project Creator : baaron4

private static Dictionary<Spec, IReadOnlyList<DamageModifier>> BuildPersonalDamageModData(ParsedEvtcLog log, Dictionary<string, List<long>> dgmModDict, HashSet<DamageModifier> usedDamageMods)
        {
            var damageModBySpecs = new Dictionary<Spec, IReadOnlyList<DamageModifier>>();
            // Collect all personal damage mods by spec
            foreach (KeyValuePair<Spec, List<AbstractSingleActor>> pair in log.FriendliesListBySpec)
            {
                var specDamageModsName = new HashSet<string>(log.DamageModifiers.GetModifiersPerSpec(pair.Key).Select(x => x.Name));
                var damageModsToUse = new HashSet<DamageModifier>();
                foreach (AbstractSingleActor actor in pair.Value)
                {
                    var presentDamageMods = new HashSet<string>(actor.GetPresentDamageModifier(log).Intersect(specDamageModsName));
                    foreach (string name in presentDamageMods)
                    {
                        damageModsToUse.Add(log.DamageModifiers.DamageModifiersByName[name]);
                    }
                }
                damageModBySpecs[pair.Key] = damageModsToUse.ToList();
            }
            foreach (KeyValuePair<Spec, IReadOnlyList<DamageModifier>> pair in damageModBySpecs)
            {
                dgmModDict[pair.Key.ToString()] = new List<long>();
                foreach (DamageModifier mod in pair.Value)
                {
                    dgmModDict[pair.Key.ToString()].Add(mod.ID);
                    usedDamageMods.Add(mod);
                }
            }
            return damageModBySpecs;
        }

19 View Source File : LogDataDto.cs
License : MIT License
Project Creator : baaron4

private static void BuildDictionaries(ParsedEvtcLog log, Dictionary<long, Buff> usedBuffs, HashSet<DamageModifier> usedDamageMods, LogDataDto logData, HashSet<string> allDamageMods, List<DamageModifier> commonDamageModifiers, List<DamageModifier> itemDamageModifiers)
        {
            foreach (AbstractSingleActor actor in log.Friendlies)
            {
                allDamageMods.UnionWith(actor.GetPresentDamageModifier(log));
            }
            if (log.DamageModifiers.DamageModifiersPerSource.TryGetValue(Source.Common, out IReadOnlyList<DamageModifier> list))
            {
                foreach (DamageModifier dMod in list)
                {
                    if (allDamageMods.Contains(dMod.Name))
                    {
                        commonDamageModifiers.Add(dMod);
                        logData.DmgModifiersCommon.Add(dMod.ID);
                        usedDamageMods.Add(dMod);
                    }
                }
            }
            if (log.DamageModifiers.DamageModifiersPerSource.TryGetValue(Source.FightSpecific, out list))
            {
                foreach (DamageModifier dMod in list)
                {
                    if (allDamageMods.Contains(dMod.Name))
                    {
                        commonDamageModifiers.Add(dMod);
                        logData.DmgModifiersCommon.Add(dMod.ID);
                        usedDamageMods.Add(dMod);
                    }
                }
            }
            if (log.DamageModifiers.DamageModifiersPerSource.TryGetValue(Source.Item, out list))
            {
                foreach (DamageModifier dMod in list)
                {
                    if (allDamageMods.Contains(dMod.Name))
                    {
                        itemDamageModifiers.Add(dMod);
                        logData.DmgModifiersItem.Add(dMod.ID);
                        usedDamageMods.Add(dMod);
                    }
                }
            }
            if (log.DamageModifiers.DamageModifiersPerSource.TryGetValue(Source.Gear, out list))
            {
                foreach (DamageModifier dMod in list)
                {
                    if (allDamageMods.Contains(dMod.Name))
                    {
                        itemDamageModifiers.Add(dMod);
                        logData.DmgModifiersItem.Add(dMod.ID);
                        usedDamageMods.Add(dMod);
                    }
                }
            }
            StatisticsHelper statistics = log.StatisticsHelper;
            foreach (Buff boon in statistics.PresentBoons)
            {
                logData.Boons.Add(boon.ID);
                usedBuffs[boon.ID] = boon;
            }
            foreach (Buff boon in statistics.PresentConditions)
            {
                logData.Conditions.Add(boon.ID);
                usedBuffs[boon.ID] = boon;
            }
            foreach (Buff boon in statistics.PresentOffbuffs)
            {
                logData.OffBuffs.Add(boon.ID);
                usedBuffs[boon.ID] = boon;
            }
            foreach (Buff boon in statistics.PresentSupbuffs)
            {
                logData.SupBuffs.Add(boon.ID);
                usedBuffs[boon.ID] = boon;
            }
            foreach (Buff boon in statistics.PresentDefbuffs)
            {
                logData.DefBuffs.Add(boon.ID);
                usedBuffs[boon.ID] = boon;
            }
            foreach (Buff boon in statistics.PresentGearbuffs)
            {
                logData.GearBuffs.Add(boon.ID);
                usedBuffs[boon.ID] = boon;
            }
            foreach (Buff boon in statistics.PresentFractalInstabilities)
            {
                logData.FractalInstabilities.Add(boon.ID);
                usedBuffs[boon.ID] = boon;
            }
        }

19 View Source File : JsonLogBuilder.cs
License : MIT License
Project Creator : baaron4

public static JsonLog BuildJsonLog(ParsedEvtcLog log, RawFormatSettings settings, Version parserVersion, string[] uploadLinks)
        {
            var jsonLog = new JsonLog();
            //
            log.UpdateProgressWithCancellationCheck("Raw Format: Building Meta Data");
            jsonLog.TriggerID = log.FightData.TriggerID;
            jsonLog.FightName = log.FightData.GetFightName(log);
            jsonLog.FightIcon = log.FightData.Logic.Icon;
            jsonLog.EliteInsightsVersion = parserVersion.ToString();
            jsonLog.ArcVersion = log.LogData.ArcVersion;
            jsonLog.RecordedBy = log.LogData.PoVName;
            jsonLog.TimeStart = log.LogData.LogStart;
            jsonLog.TimeEnd = log.LogData.LogEnd;
            jsonLog.TimeStartStd = log.LogData.LogStartStd;
            jsonLog.TimeEndStd = log.LogData.LogEndStd;
            jsonLog.Duration = log.FightData.DurationString;
            jsonLog.Success = log.FightData.Success;
            jsonLog.GW2Build = log.LogData.GW2Build;
            jsonLog.UploadLinks = uploadLinks;
            jsonLog.Language = log.LogData.Language;
            jsonLog.LanguageID = (byte)log.LogData.LanguageID;
            jsonLog.IsCM = log.FightData.IsCM;
            var personalBuffs = new Dictionary<string, HashSet<long>>();
            var skillMap = new Dictionary<string, SkillDesc>();
            var buffMap = new Dictionary<string, BuffDesc>();
            var damageModMap = new Dictionary<string, DamageModDesc>();

            if (log.StatisticsHelper.PresentFractalInstabilities.Any())
            {
                var presentFractalInstabilities = new List<long>();
                foreach (Buff fractalInstab in log.StatisticsHelper.PresentFractalInstabilities)
                {
                    presentFractalInstabilities.Add(fractalInstab.ID);
                    if (!buffMap.ContainsKey("b" + fractalInstab.ID))
                    {
                        buffMap["b" + fractalInstab.ID] = BuildBuffDesc(fractalInstab, log);
                    }
                }
                jsonLog.PresentFractalInstabilities = presentFractalInstabilities;
            }
            //
            log.UpdateProgressWithCancellationCheck("Raw Format: Building Mechanics");
            MechanicData mechanicData = log.MechanicData;
            var mechanicLogs = new List<MechanicEvent>();
            foreach (List<MechanicEvent> mLog in mechanicData.GetAllMechanics(log))
            {
                mechanicLogs.AddRange(mLog);
            }
            if (mechanicLogs.Any())
            {
                jsonLog.Mechanics = JsonMechanicsBuilder.GetJsonMechanicsList(mechanicLogs);
            }
            //
            log.UpdateProgressWithCancellationCheck("Raw Format: Building Phases");
            jsonLog.Phases = log.FightData.GetNonDummyPhases(log).Select(x => JsonPhaseBuilder.BuildJsonPhase(x, log)).ToList();
            //
            log.UpdateProgressWithCancellationCheck("Raw Format: Building Targets");
            jsonLog.Targets = log.FightData.Logic.Targets.Select(x => JsonNPCBuilder.BuildJsonNPC(x, log, settings, skillMap, buffMap)).ToList();
            //
            log.UpdateProgressWithCancellationCheck("Raw Format: Building Players");
            jsonLog.Players = log.Friendlies.Select(x => JsonPlayerBuilder.BuildJsonPlayer(x, log, settings, skillMap, buffMap, damageModMap, personalBuffs)).ToList();
            //
            if (log.LogData.LogErrors.Any())
            {
                jsonLog.LogErrors = new List<string>(log.LogData.LogErrors);
            }
            if (log.LogData.UsedExtensions.Any())
            {
                jsonLog.UsedExtensions = log.LogData.UsedExtensions.Select(x => {
                    return new ExtensionDesc()
                    {
                        Name = x.Name,
                        Version = x.Version,
                        Signature = x.Signature,
                        Revision = x.Revision
                    };
                }).ToList();
            }
            //
            jsonLog.PersonalBuffs = personalBuffs.ToDictionary(x => x.Key, x => (IReadOnlyCollection<long>) x.Value);
            jsonLog.SkillMap = skillMap;
            jsonLog.BuffMap = buffMap;
            jsonLog.DamageModMap = damageModMap;
            //
            if (log.CanCombatReplay)
            {
                jsonLog.CombatReplayMetaData = JsonCombatReplayMetaDataBuilder.BuildJsonCombatReplayMetaData(log, settings);
            }
            return jsonLog;
        }

19 View Source File : AbstractSingleActorCombatReplayDescription.cs
License : MIT License
Project Creator : baaron4

protected void SetStatus(ParsedEvtcLog log, AbstractSingleActor a)
        {
            var dead = new List<long>();
            Dead = dead;
            var down = new List<long>();
            Down = down;
            var dc = new List<long>();
            Dc = dc;
            (IReadOnlyList<(long start, long end)> deads, IReadOnlyList<(long start, long end)> downs, IReadOnlyList<(long start, long end)> dcs) = a.GetStatus(log);

            foreach ((long start, long end) in deads)
            {
                dead.Add(start);
                dead.Add(end);
            }
            foreach ((long start, long end) in downs)
            {
                down.Add(start);
                down.Add(end);
            }
            foreach ((long start, long end) in dcs)
            {
                dc.Add(start);
                dc.Add(end);
            }
        }

19 View Source File : Adina.cs
License : MIT License
Project Creator : baaron4

internal override List<PhaseData> GetPhases(ParsedEvtcLog log, bool requirePhases)
        {
            List<PhaseData> phases = GetInitialPhase(log);
            AbstractSingleActor mainTarget = Targets.FirstOrDefault(x => x.ID == (int)ArcDPSEnums.TargetID.Adina);
            if (mainTarget == null)
            {
                throw new MissingKeyActorsException("Adina not found");
            }
            phases[0].AddTarget(mainTarget);
            if (!requirePhases)
            {
                return phases;
            }
            // Split phases
            List<AbstractBuffEvent> invuls = GetFilteredList(log.CombatData, 762, mainTarget, true);
            long start = 0;
            var splitPhases = new List<PhaseData>();
            var splitPhaseEnds = new List<long>();
            for (int i = 0; i < invuls.Count; i++)
            {
                PhaseData splitPhase;
                AbstractBuffEvent be = invuls[i];
                if (be is BuffApplyEvent)
                {
                    start = be.Time;
                    if (i == invuls.Count - 1)
                    {
                        splitPhase = new PhaseData(start, log.FightData.FightEnd, "Split " + (i / 2 + 1));
                        splitPhaseEnds.Add(log.FightData.FightEnd);
                        AddTargetsToPhaseAndFit(splitPhase, new List<int> { (int)ArcDPSEnums.TrashID.HandOfErosion, (int)ArcDPSEnums.TrashID.HandOfEruption }, log);
                        splitPhases.Add(splitPhase);
                    }
                }
                else
                {
                    long end = be.Time;
                    splitPhase = new PhaseData(start, end, "Split " + (i / 2 + 1));
                    splitPhaseEnds.Add(end);
                    AddTargetsToPhaseAndFit(splitPhase, new List<int> { (int)ArcDPSEnums.TrashID.HandOfErosion, (int)ArcDPSEnums.TrashID.HandOfEruption }, log);
                    splitPhases.Add(splitPhase);
                }
            }
            // Main phases
            var mainPhases = new List<PhaseData>();
            var pillarApplies = log.CombatData.GetBuffData(56204).OfType<BuffApplyEvent>().Where(x => x.To == mainTarget.Agenreplacedem).ToList();
            Dictionary<long, List<BuffApplyEvent>> pillarAppliesGroupByTime = ParserHelper.GroupByTime(pillarApplies);
            var mainPhaseEnds = new List<long>();
            foreach (KeyValuePair<long, List<BuffApplyEvent>> pair in pillarAppliesGroupByTime)
            {
                if (pair.Value.Count == 6)
                {
                    mainPhaseEnds.Add(pair.Key);
                }
            }
            AbstractCastEvent boulderBarrage = mainTarget.GetCastEvents(log, 0, log.FightData.FightEnd).FirstOrDefault(x => x.SkillId == 56648 && x.Time < 6000);
            start = boulderBarrage == null ? 0 : boulderBarrage.EndTime;
            if (mainPhaseEnds.Any())
            {
                int phaseIndex = 1;
                foreach (long quantumQake in mainPhaseEnds)
                {
                    var curPhaseStart = splitPhaseEnds.LastOrDefault(x => x < quantumQake);
                    if (curPhaseStart == 0)
                    {
                        curPhaseStart = start;
                    }
                    long nextPhaseStart = splitPhaseEnds.FirstOrDefault(x => x > quantumQake);
                    if (nextPhaseStart != 0)
                    {
                        start = nextPhaseStart;
                        phaseIndex = splitPhaseEnds.IndexOf(start) + 1;
                    }
                    mainPhases.Add(new PhaseData(curPhaseStart, quantumQake, "Phase " + phaseIndex));
                }
                if (start != mainPhases.Last().Start)
                {
                    mainPhases.Add(new PhaseData(start, log.FightData.FightEnd, "Phase " + (phaseIndex + 1)));
                }
            } 
            else if (start > 0 && !invuls.Any())
            {
                // no split
                mainPhases.Add(new PhaseData(start, log.FightData.FightEnd, "Phase 1"));
            }

            foreach (PhaseData phase in mainPhases)
            {
                phase.AddTarget(mainTarget);
            }
            phases.AddRange(mainPhases);
            phases.AddRange(splitPhases);
            phases.Sort((x, y) => x.Start.CompareTo(y.Start));
            //
            try
            {
                var splitPhasesMap = new List<string>()
                {
                        "https://i.imgur.com/gJ55jKy.png",
                        "https://i.imgur.com/c2Oz5bj.png",
                        "https://i.imgur.com/P4SGbrc.png",
                };
                var mainPhasesMap = new List<string>()
                {
                        "https://i.imgur.com/IQn2RJV.png",
                        "https://i.imgur.com/3pO7eCB.png",
                        "https://i.imgur.com/ZFw590w.png",
                        "https://i.imgur.com/2P7UE8q.png"
                };
                var crMaps = new List<string>();
                int mainPhaseIndex = 0;
                int splitPhaseIndex = 0;
                for (int i = 1; i < phases.Count; i++)
                {
                    PhaseData phaseData = phases[i];
                    if (mainPhases.Contains(phaseData))
                    {
                        if (mainPhasesMap.Contains(crMaps.LastOrDefault()))
                        {
                            splitPhaseIndex++;
                        }
                        crMaps.Add(mainPhasesMap[mainPhaseIndex++]);
                    }
                    else
                    {
                        if (splitPhasesMap.Contains(crMaps.LastOrDefault()))
                        {
                            mainPhaseIndex++;
                        }
                        crMaps.Add(splitPhasesMap[splitPhaseIndex++]);
                    }
                }
                GetCombatReplayMap(log).MatchMapsToPhases(crMaps, phases, log.FightData.FightEnd);
            } 
            catch(Exception)
            {
                log.UpdateProgressWithCancellationCheck("Failed to replacedociate Adina Combat Replay maps");
            }
            
            //
            return phases;
        }

19 View Source File : PeerlessQadim.cs
License : MIT License
Project Creator : baaron4

internal override List<PhaseData> GetPhases(ParsedEvtcLog log, bool requirePhases)
        {
            List<PhaseData> phases = GetInitialPhase(log);
            AbstractSingleActor mainTarget = Targets.FirstOrDefault(x => x.ID == (int)ArcDPSEnums.TargetID.PeerlessQadim);
            if (mainTarget == null)
            {
                throw new MissingKeyActorsException("Peerless Qadim not found");
            }
            phases[0].AddTarget(mainTarget);
            if (!requirePhases)
            {
                return phases;
            }
            var phaseStarts = new List<long>();
            var phaseEnds = new List<long>();
            //
            var magmaDrops = log.CombatData.GetBuffData(56475).Where(x => x is BuffApplyEvent).ToList();
            foreach (AbstractBuffEvent magmaDrop in magmaDrops)
            {
                if (phaseEnds.Count > 0)
                {
                    if (Math.Abs(phaseEnds.Last() - magmaDrop.Time) > 1000)
                    {
                        phaseEnds.Add(magmaDrop.Time);
                    }
                }
                else
                {
                    phaseEnds.Add(magmaDrop.Time);
                }
            }
            IReadOnlyList<AnimatedCastEvent> pushes = log.CombatData.GetAnimatedCastData(56405);
            if (pushes.Count > 0)
            {
                AbstractCastEvent push = pushes[0];
                phaseStarts.Add(push.Time);
                foreach (long magmaDrop in phaseEnds)
                {
                    push = pushes.FirstOrDefault(x => x.Time >= magmaDrop);
                    if (push == null)
                    {
                        break;
                    }
                    phaseStarts.Add(push.Time);
                }
            }
            // rush to pylon
            phaseEnds.AddRange(log.CombatData.GetAnimatedCastData(56616).Select(x => x.Time).ToList());
            phaseEnds.Add(log.FightData.FightEnd);
            // tp to middle after pylon destruction
            phaseStarts.AddRange(log.CombatData.GetAnimatedCastData(56375).Select(x => x.EndTime));
            // There should be at least as many starts as ends, otherwise skip phases
            if (phaseEnds.Count < phaseStarts.Count)
            {
                return phases;
            }
            for (int i = 0; i < phaseStarts.Count; i++)
            {
                var phase = new PhaseData(phaseStarts[i], phaseEnds[i], "Phase " + (i + 1));
                phase.AddTarget(mainTarget);
                phases.Add(phase);
            }
            // intermission phase never finished, add a "dummy" log end
            if (phaseEnds.Count - 1 == phaseStarts.Count)
            {
                phaseStarts.Add(log.FightData.FightEnd);
            }
            // There should be as many ends as starts, otherwise anomaly, skip intermission phases
            if (phaseEnds.Count != phaseStarts.Count)
            {
                return phases;
            }
            string[] intermissionNames = { "Magma Drop 1", "Magma Drop 2", "North Pylon", "SouthWest Pylon", "SouthEast Pylon" };
            bool skipNames = intermissionNames.Length < phaseEnds.Count - 1;
            for (int i = 0; i < phaseEnds.Count - 1; i++)
            {
                var phase = new PhaseData(phaseEnds[i], Math.Min(phaseStarts[i + 1], log.FightData.FightEnd), skipNames ? "Intermission " + (i + 1) : intermissionNames[i]);
                phase.AddTarget(mainTarget);
                phases.Add(phase);
            }
            return phases;
        }

19 View Source File : Adina.cs
License : MIT License
Project Creator : baaron4

internal override List<PhaseData> GetPhases(ParsedEvtcLog log, bool requirePhases)
        {
            List<PhaseData> phases = GetInitialPhase(log);
            AbstractSingleActor mainTarget = Targets.FirstOrDefault(x => x.ID == (int)ArcDPSEnums.TargetID.Adina);
            if (mainTarget == null)
            {
                throw new MissingKeyActorsException("Adina not found");
            }
            phases[0].AddTarget(mainTarget);
            if (!requirePhases)
            {
                return phases;
            }
            // Split phases
            List<AbstractBuffEvent> invuls = GetFilteredList(log.CombatData, 762, mainTarget, true);
            long start = 0;
            var splitPhases = new List<PhaseData>();
            var splitPhaseEnds = new List<long>();
            for (int i = 0; i < invuls.Count; i++)
            {
                PhaseData splitPhase;
                AbstractBuffEvent be = invuls[i];
                if (be is BuffApplyEvent)
                {
                    start = be.Time;
                    if (i == invuls.Count - 1)
                    {
                        splitPhase = new PhaseData(start, log.FightData.FightEnd, "Split " + (i / 2 + 1));
                        splitPhaseEnds.Add(log.FightData.FightEnd);
                        AddTargetsToPhaseAndFit(splitPhase, new List<int> { (int)ArcDPSEnums.TrashID.HandOfErosion, (int)ArcDPSEnums.TrashID.HandOfEruption }, log);
                        splitPhases.Add(splitPhase);
                    }
                }
                else
                {
                    long end = be.Time;
                    splitPhase = new PhaseData(start, end, "Split " + (i / 2 + 1));
                    splitPhaseEnds.Add(end);
                    AddTargetsToPhaseAndFit(splitPhase, new List<int> { (int)ArcDPSEnums.TrashID.HandOfErosion, (int)ArcDPSEnums.TrashID.HandOfEruption }, log);
                    splitPhases.Add(splitPhase);
                }
            }
            // Main phases
            var mainPhases = new List<PhaseData>();
            var pillarApplies = log.CombatData.GetBuffData(56204).OfType<BuffApplyEvent>().Where(x => x.To == mainTarget.Agenreplacedem).ToList();
            Dictionary<long, List<BuffApplyEvent>> pillarAppliesGroupByTime = ParserHelper.GroupByTime(pillarApplies);
            var mainPhaseEnds = new List<long>();
            foreach (KeyValuePair<long, List<BuffApplyEvent>> pair in pillarAppliesGroupByTime)
            {
                if (pair.Value.Count == 6)
                {
                    mainPhaseEnds.Add(pair.Key);
                }
            }
            AbstractCastEvent boulderBarrage = mainTarget.GetCastEvents(log, 0, log.FightData.FightEnd).FirstOrDefault(x => x.SkillId == 56648 && x.Time < 6000);
            start = boulderBarrage == null ? 0 : boulderBarrage.EndTime;
            if (mainPhaseEnds.Any())
            {
                int phaseIndex = 1;
                foreach (long quantumQake in mainPhaseEnds)
                {
                    var curPhaseStart = splitPhaseEnds.LastOrDefault(x => x < quantumQake);
                    if (curPhaseStart == 0)
                    {
                        curPhaseStart = start;
                    }
                    long nextPhaseStart = splitPhaseEnds.FirstOrDefault(x => x > quantumQake);
                    if (nextPhaseStart != 0)
                    {
                        start = nextPhaseStart;
                        phaseIndex = splitPhaseEnds.IndexOf(start) + 1;
                    }
                    mainPhases.Add(new PhaseData(curPhaseStart, quantumQake, "Phase " + phaseIndex));
                }
                if (start != mainPhases.Last().Start)
                {
                    mainPhases.Add(new PhaseData(start, log.FightData.FightEnd, "Phase " + (phaseIndex + 1)));
                }
            } 
            else if (start > 0 && !invuls.Any())
            {
                // no split
                mainPhases.Add(new PhaseData(start, log.FightData.FightEnd, "Phase 1"));
            }

            foreach (PhaseData phase in mainPhases)
            {
                phase.AddTarget(mainTarget);
            }
            phases.AddRange(mainPhases);
            phases.AddRange(splitPhases);
            phases.Sort((x, y) => x.Start.CompareTo(y.Start));
            //
            try
            {
                var splitPhasesMap = new List<string>()
                {
                        "https://i.imgur.com/gJ55jKy.png",
                        "https://i.imgur.com/c2Oz5bj.png",
                        "https://i.imgur.com/P4SGbrc.png",
                };
                var mainPhasesMap = new List<string>()
                {
                        "https://i.imgur.com/IQn2RJV.png",
                        "https://i.imgur.com/3pO7eCB.png",
                        "https://i.imgur.com/ZFw590w.png",
                        "https://i.imgur.com/2P7UE8q.png"
                };
                var crMaps = new List<string>();
                int mainPhaseIndex = 0;
                int splitPhaseIndex = 0;
                for (int i = 1; i < phases.Count; i++)
                {
                    PhaseData phaseData = phases[i];
                    if (mainPhases.Contains(phaseData))
                    {
                        if (mainPhasesMap.Contains(crMaps.LastOrDefault()))
                        {
                            splitPhaseIndex++;
                        }
                        crMaps.Add(mainPhasesMap[mainPhaseIndex++]);
                    }
                    else
                    {
                        if (splitPhasesMap.Contains(crMaps.LastOrDefault()))
                        {
                            mainPhaseIndex++;
                        }
                        crMaps.Add(splitPhasesMap[splitPhaseIndex++]);
                    }
                }
                GetCombatReplayMap(log).MatchMapsToPhases(crMaps, phases, log.FightData.FightEnd);
            } 
            catch(Exception)
            {
                log.UpdateProgressWithCancellationCheck("Failed to replacedociate Adina Combat Replay maps");
            }
            
            //
            return phases;
        }

19 View Source File : ModelBindingContextExtension.cs
License : MIT License
Project Creator : baking-bad

public static bool TryGetInt64List(this ModelBindingContext bindingContext, string name, ref bool hasValue, out List<long> result)
        {
            result = null;
            var valueObject = bindingContext.ValueProvider.GetValue(name);

            if (valueObject != ValueProviderResult.None)
            {
                bindingContext.ModelState.SetModelValue(name, valueObject);
                if (!string.IsNullOrEmpty(valueObject.FirstValue))
                {
                    var rawValues = valueObject.FirstValue.Split(',', StringSplitOptions.RemoveEmptyEntries);

                    if (rawValues.Length == 0)
                    {
                        bindingContext.ModelState.TryAddModelError(name, "List should contain at least one item.");
                        return false;
                    }

                    hasValue = true;
                    result = new List<long>(rawValues.Length);

                    foreach (var rawValue in rawValues)
                    {
                        if (!long.TryParse(rawValue, out var value))
                        {
                            bindingContext.ModelState.TryAddModelError(name, "List contains invalid integer value.");
                            return false;
                        }
                        result.Add(value);
                    }
                }
            }

            return true;
        }

19 View Source File : Replay.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team

private static void VerifyEvents()
        {
            List<long?> diffTime = new List<long?>();

            foreach (ReplayEvent play in PlaybackEventList)
            {
                ReplayEvent rec =
                    RecordingEventList.FirstOrDefault(q => !q.applied && q.Equals(play));
                if (rec != null)
                {
                    // rec.time - CampaignTime of movement recorded in playback state (second step)
                    // play.time - CampaignTime of movement recorded in recording state (first step)
                    diffTime.Add((long) (rec.time - play.time).ToMilliseconds);
                    rec.applied = true;
                }
                else
                {
                    diffTime.Add(null);
                }
            }

            int skipped = diffTime.Count(q => q == null);
            int newEvents = RecordingEventList.Count(q => !q.applied);
            if (skipped > 0)
            {
                Logger.Info($"[REPLAY] Skipped {skipped} movements.");
            }

            if (newEvents > 0)
            {
                Logger.Info($"[REPLAY] There is {newEvents} new movements.");
            }

            string path = Path.Combine(logsDir, currentFilename + logFilename);
            ExportToFile(path, diffTime, skipped, newEvents);

            Logger.Info($"[REPLAY] Verifying has finished and exported into '{path}'.");
        }

19 View Source File : DOMAdapterExtensions.cs
License : MIT License
Project Creator : BaristaLabs

public long[] GetLong()
        {
            var result = new List<long>();

            foreach (var item in Path)
            {
                //Ignore the "M/L/Z" tokens for now..?
                if (long.TryParse(item, out long itemLong))
                {
                    result.Add(itemLong);
                }
            }

            return result.ToArray();
        }

19 View Source File : TestHelper.cs
License : GNU Affero General Public License v3.0
Project Creator : Barsonax

public static void LogNumericTestResult(object testFixture, string testName, long resultValue, string unit)
        {
            if (!string.IsNullOrEmpty(unit)) unit = " " + unit;

            List<long> lastValueList;
            if (!LocalTestMemory.GetValue(testFixture, testName, out lastValueList))
            {
                lastValueList = new List<long>();
            }
            lastValueList.Add(resultValue);
            if (lastValueList.Count > 10) lastValueList.RemoveAt(0);
            LocalTestMemory.SetValue(testFixture, testName, lastValueList);

            var localAverage = (long)lastValueList.Average();

            var nameStr = testFixture.GetType().Name + "." + testName;
            var newValueStr = $"{resultValue}{unit}";
            var lastValueStr = $"{localAverage}{unit}";

            var relativeChange = (resultValue - (double)localAverage) / localAverage;
            LogNumericTestResult(nameStr, newValueStr, lastValueStr, relativeChange);
        }

19 View Source File : DualityCollection.cs
License : GNU Lesser General Public License v3.0
Project Creator : Barsonax

public static void LogNumericTestResult(object testFixture, string testName, long resultValue, string unit)
		{
			if (!string.IsNullOrEmpty(unit)) unit = " " + unit;

		    if (!LocalTestMemory.GetValue(testFixture, testName, out List<long> lastValueList))
			{
				lastValueList = new List<long>();
			}
			lastValueList.Add(resultValue);
			if (lastValueList.Count > 10) lastValueList.RemoveAt(0);
			LocalTestMemory.SetValue(testFixture, testName, lastValueList);

			var localAverage = (long)lastValueList.Average();

			string nameStr = testFixture.GetType().Name + "." + testName;
			string newValueStr = $"{resultValue}{unit}";
			string lastValueStr = $"{localAverage}{unit}";

			double relativeChange = (resultValue - (double)localAverage) / localAverage;
			LogNumericTestResult(nameStr, newValueStr, lastValueStr, relativeChange);
		}

19 View Source File : GoogleTranslateEndpoint.cs
License : MIT License
Project Creator : bbepis

private string Tk( string r )
      {
         List<long> S = new List<long>();

         for( var v = 0 ; v < r.Length ; v++ )
         {
            long A = r[ v ];
            if( 128 > A )
               S.Add( A );
            else
            {
               if( 2048 > A )
                  S.Add( A >> 6 | 192 );
               else if( 55296 == ( 64512 & A ) && v + 1 < r.Length && 56320 == ( 64512 & r[ v + 1 ] ) )
               {
                  A = 65536 + ( ( 1023 & A ) << 10 ) + ( 1023 & r[ ++v ] );
                  S.Add( A >> 18 | 240 );
                  S.Add( A >> 12 & 63 | 128 );
               }
               else
               {
                  S.Add( A >> 12 | 224 );
                  S.Add( A >> 6 & 63 | 128 );
               }

               S.Add( 63 & A | 128 );
            }
         }

         const string F = "+-a^+6";
         const string D = "+-3^+b+-f";
         long p = m;

         for( var b = 0 ; b < S.Count ; b++ )
         {
            p += S[ b ];
            p = Vi( p, F );
         }

         p = Vi( p, D );
         p ^= s;
         if( 0 > p )
            p = ( 2147483647 & p ) + 2147483648;

         p %= (long)1e6;

         return p.ToString( CultureInfo.InvariantCulture ) + "." + ( p ^ m ).ToString( CultureInfo.InvariantCulture );
      }

19 View Source File : UnitTest.cs
License : Apache License 2.0
Project Creator : beetlex-io

public void AddDelayTime(long time)
		{
			lock (mdelayTimes)
			{
				mdelayTimes.Add(time);
			}
		}

19 View Source File : CodeStatistics.cs
License : Apache License 2.0
Project Creator : beetlex-io

public StatisticsData GetData()
        {
            StatisticsData result = new StatisticsData();
            result.Count = Count;
            result.Rps = Rps;
            result.MaxRps = MaxRps;
            result.AvgRps = AvgRps;

            result.Name = Name;
            result.Times.Add(Time10ms);
            result.Times.Add(Time20ms);
            result.Times.Add(Time50ms);
            result.Times.Add(Time100ms);
            result.Times.Add(Time200ms);
            result.Times.Add(Time500ms);
            result.Times.Add(Time1000ms);
            result.Times.Add(Time2000ms);
            result.Times.Add(Time5000ms);
            result.Times.Add(Time10000ms);
            result.Times.Add(TimeOtherms);
            double now = TimeWatch.GetTotalSeconds();
            double time = now - mLastRpsTime;

            int value = (int)((double)(ms10 - ms10LastCount) / time);
            ms10LastCount = ms10;
            result.TimesRps.Add(value);


            value = (int)((double)(ms20 - ms20LastCount) / time);
            ms20LastCount = ms20;
            result.TimesRps.Add(value);


            value = (int)((double)(ms50 - ms50LastCount) / time);
            ms50LastCount = ms50;
            result.TimesRps.Add(value);


            value = (int)((double)(ms100 - ms100LastCount) / time);
            ms100LastCount = ms100;
            result.TimesRps.Add(value);


            value = (int)((double)(ms200 - ms200LastCount) / time);
            ms200LastCount = ms200;
            result.TimesRps.Add(value);


            value = (int)((double)(ms500 - ms500LastCount) / time);
            ms500LastCount = ms500;
            result.TimesRps.Add(value);


            value = (int)((double)(ms1000 - ms1000LastCount) / time);
            ms1000LastCount = ms1000;
            result.TimesRps.Add(value);


            value = (int)((double)(ms2000 - ms2000LastCount) / time);
            ms2000LastCount = ms2000;
            result.TimesRps.Add(value);


            value = (int)((double)(ms5000 - ms5000LastCount) / time);
            ms5000LastCount = ms5000;
            result.TimesRps.Add(value);


            value = (int)((double)(ms10000 - ms10000LastCount) / time);
            ms10000LastCount = ms10000;
            result.TimesRps.Add(value);


            value = (int)((double)(msOther - msOtherLastCount) / time);
            msOtherLastCount = msOther;
            result.TimesRps.Add(value);


            mLastRpsTime = now;
            return result;
        }

19 View Source File : RemoveDuplicatedChunkRule.cs
License : GNU General Public License v3.0
Project Creator : Bililive

private IEnumerable<PipelineAction?> RunPerAction(FlvProcessingContext context, PipelineAction action)
        {
            if (action is PipelineDataAction data)
            {
                var feature = new List<long>(data.Tags.Count * 2 + 1)
                {
                    data.Tags.Count
                };

                unchecked
                {
                    // 计算一个特征码
                    // 此处并没有遵循什么特定的算法,只是随便取了一些代表性比较强的值,用简单又尽量可靠的方式糅合到一起而已
                    foreach (var tag in data.Tags)
                    {
                        var f = 0L;
                        f ^= tag.Type switch
                        {
                            TagType.Audio => 0b01,
                            TagType.Video => 0b10,
                            TagType.Script => 0b11,
                            _ => 0b00,
                        };
                        f <<= 3;
                        f ^= (int)tag.Flag & ((1 << 3) - 1);
                        f <<= 32;
                        f ^= tag.Timestamp;
                        f <<= 32 - 5;
                        f ^= tag.Size & ((1 << (32 - 5)) - 1);
                        feature.Add(f);

                        if (tag.Nalus == null)
                            feature.Add(long.MinValue);
                        else
                        {
                            long n = tag.Nalus.Count << 32;
                            foreach (var nalu in tag.Nalus)
                                n ^= (((int)nalu.Type) << 16) ^ ((int)nalu.FullSize);
                            feature.Add(n);
                        }
                    }
                }

                // 存储最近 MAX_HISTORY 个 Data Chunk 的特征的 Queue
                Queue<List<long>> history;
                if (context.SessionItems.TryGetValue(QUEUE_KEY, out var obj) && obj is Queue<List<long>> q)
                    history = q;
                else
                {
                    history = new Queue<List<long>>(MAX_HISTORY + 1);
                    context.SessionItems[QUEUE_KEY] = history;
                }

                // 对比历史特征
                if (history.ToStructEnumerable().Any(x => x.SequenceEqual(feature), x => x))
                {
                    context.AddComment(comment);
                }
                else
                {
                    history.Enqueue(feature);

                    while (history.Count > MAX_HISTORY)
                        history.Dequeue();

                    yield return action;
                }
            }

19 View Source File : RemoveDuplicatedChunkRule.cs
License : GNU General Public License v3.0
Project Creator : Bililive

private IEnumerable<PipelineAction?> RunPerAction(FlvProcessingContext context, PipelineAction action)
        {
            if (action is PipelineDataAction data)
            {
                var feature = new List<long>(data.Tags.Count * 2 + 1)
                {
                    data.Tags.Count
                };

                unchecked
                {
                    // 计算一个特征码
                    // 此处并没有遵循什么特定的算法,只是随便取了一些代表性比较强的值,用简单又尽量可靠的方式糅合到一起而已
                    foreach (var tag in data.Tags)
                    {
                        var f = 0L;
                        f ^= tag.Type switch
                        {
                            TagType.Audio => 0b01,
                            TagType.Video => 0b10,
                            TagType.Script => 0b11,
                            _ => 0b00,
                        };
                        f <<= 3;
                        f ^= (int)tag.Flag & ((1 << 3) - 1);
                        f <<= 32;
                        f ^= tag.Timestamp;
                        f <<= 32 - 5;
                        f ^= tag.Size & ((1 << (32 - 5)) - 1);
                        feature.Add(f);

                        if (tag.Nalus == null)
                            feature.Add(long.MinValue);
                        else
                        {
                            long n = tag.Nalus.Count << 32;
                            foreach (var nalu in tag.Nalus)
                                n ^= (((int)nalu.Type) << 16) ^ ((int)nalu.FullSize);
                            feature.Add(n);
                        }
                    }
                }

                // 存储最近 MAX_HISTORY 个 Data Chunk 的特征的 Queue
                Queue<List<long>> history;
                if (context.SessionItems.TryGetValue(QUEUE_KEY, out var obj) && obj is Queue<List<long>> q)
                    history = q;
                else
                {
                    history = new Queue<List<long>>(MAX_HISTORY + 1);
                    context.SessionItems[QUEUE_KEY] = history;
                }

                // 对比历史特征
                if (history.ToStructEnumerable().Any(x => x.SequenceEqual(feature), x => x))
                {
                    context.AddComment(comment);
                }
                else
                {
                    history.Enqueue(feature);

                    while (history.Count > MAX_HISTORY)
                        history.Dequeue();

                    yield return action;
                }
            }

19 View Source File : UtilTest.cs
License : MIT License
Project Creator : bitrinjani

private void MergePerf(IList<Quote> quotes)
        {
            var step = 5;
            var l = new List<long>(10);
            foreach (var i in Enumerable.Range(0, 10))
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                var r = quotes.Merge(step).ToList();
                stopwatch.Stop();
                var elapsed = stopwatch.ElapsedMilliseconds;
                Debug.WriteLine(elapsed);
                l.Add(elapsed);
            }

            var avg = l.Average();
            Debug.WriteLine($"AVG: {avg}");
        }

19 View Source File : UDPBase.cs
License : MIT License
Project Creator : BlazorPlus

protected void ProcessUDPPackage(UDPPackageType pt, byte[] data)
		{
			//UDPPackageType pt = UDPMeta.GetPackageType(data);
			long sid = BitConverter.ToInt64(data, 8);

			//Console.WriteLine("ProcessUDPPackage:" + sid + ":" + pt);

			if (pt == UDPPackageType.SessionError)
			{
				Close();
			}
			else if (pt == UDPPackageType.SessionClose)
			{
				Close();
			}

			if (pt == UDPPackageType.DataPost)
			{
				if (_closed)
				{
					SendToPeer(UDPMeta.CreateSessionError(SessionId, "closed"));
					return;
				}

				long peerminreadindex = BitConverter.ToInt64(data, 16);
				lock (_postmap)
				{
					OnGetPeerMinRead(peerminreadindex);
				}

				long dataindex = BitConverter.ToInt64(data, 24);

				//Console.WriteLine("DataPost:" + dataindex);

				if (dataindex == _readminindex + 1)
				{
					OnPost(data, 32, data.Length - 32);
					_readminindex = dataindex;
					byte[] buff;
					while (_buffmap.TryGetValue(_readminindex + 1, out buff))
					{
						_readminindex++;
						_buffmap.Remove(_readminindex);
						OnPost(buff);
					}
					SendToPeer(UDPMeta.CreateDataRead(SessionId, _readminindex, dataindex));
				}
				else
				{
					if (dataindex > _readmaxindex) _readmaxindex = dataindex;
					byte[] buff = new byte[data.Length - 32];
					Buffer.BlockCopy(data, 32, buff, 0, buff.Length);
					_buffmap[dataindex] = buff;
				}

			}
			if (pt == UDPPackageType.DataRead)
			{
				long peerminreadindex = BitConverter.ToInt64(data, 16);
				long dataindex = BitConverter.ToInt64(data, 24);
				lock (_postmap)
				{
					PostMapRemove(dataindex);
					OnGetPeerMinRead(peerminreadindex);
				}
			}
			if (pt == UDPPackageType.DataMiss)
			{
				long peerminreadindex = BitConverter.ToInt64(data, 16);
				lock (_postmap)
				{
					OnGetPeerMinRead(peerminreadindex);
				}

				int misscount = (data.Length - 24) / 8;
				List<DataItem> list = null;
				for (int missid = 0; missid < misscount; missid++)
				{
					long dataindex = BitConverter.ToInt64(data, 24 + missid * 8);
					DataItem item = null;
					lock (_postmap)
					{
						_postmap.TryGetValue(dataindex, out item);
					}
					if (item != null)
					{
						if (list == null) list = new List<DataItem>();
						list.Add(item);
					}
				}
				if (list != null)
				{
					list.Sort(delegate (DataItem d1, DataItem d2)
					{
						return d1.SendTime.CompareTo(d2.SendTime);
					});
					int maxsendagain = 65536;

					foreach (DataItem item in list)
					{
						if (DateTime.Now - item.SendTime < TimeSpan.FromMilliseconds(GetPackageLostMS()))
							break;
						if (maxsendagain < item.UDPData.Length)
							break;
						maxsendagain -= item.UDPData.Length;
						UDPMeta.UpdateDataRead(item.UDPData, _readminindex);
						item.SendTime = DateTime.Now;
						item.RetryCount++;
						SendToPeer(item.UDPData);
					}
				}
			}
			if (pt == UDPPackageType.DataPing)
			{
				long peerminreadindex = BitConverter.ToInt64(data, 16);
				lock (_postmap)
				{
					OnGetPeerMinRead(peerminreadindex);
				}

				long maxdataindex = BitConverter.ToInt64(data, 24);
				List<long> misslist = null;
				for (long index = _readminindex + 1; index <= maxdataindex; index++)
				{
					if (_buffmap.ContainsKey(index))
						continue;
					if (misslist == null)
						misslist = new List<long>();
					misslist.Add(index);
					if (misslist.Count * 8 + 40 > UDPMeta.BestUDPSize)
						break;
				}
				if (misslist != null)
				{
					SendToPeer(UDPMeta.CreateDataMiss(SessionId, _readminindex, misslist.ToArray()));
				}
				else
				{
					SendToPeer(UDPMeta.CreateDataRead(SessionId, _readminindex, _readminindex));
				}
			}
		}

19 View Source File : UDPBase.cs
License : MIT License
Project Creator : BlazorPlus

private void OnGetPeerMinRead(long peerminreadindex)
		{
			if (peerminreadindex < _peerminreadindex)
				return;
			if (_postmap.Count == 0)
				return;
			List<long> list = null;
			foreach (DataItem item in _postmap.Values)
			{
				if (item.DataIndex > peerminreadindex)
					continue;
				if (list == null) list = new List<long>();
				list.Add(item.DataIndex);
			}
			if (list != null)
			{
				foreach (long index in list)
					PostMapRemove(index);
			}
			_peerminreadindex = peerminreadindex;
		}

19 View Source File : STMHttpMeshReceiver.cs
License : MIT License
Project Creator : blkcatman

void OnStreamListReceived(string name, string list)
    {
      string[] lines = System.Text.RegularExpressions.Regex.Split(list, "\n");
      bool listUpdated = false;
      foreach (string line in lines)
      {
        StreamInfo info = JsonUtility.FromJson<StreamInfo>(line);
        if (info != null)
        {
          int index;
          if (int.TryParse(Path.GetFileNameWithoutExtension(info.video), out index))
          {
            if (m_streamBufferList.Contains(index) == false)
            {
              listUpdated = true;
              m_streamBufferList.Add(index);
              m_combineddBufferStartTicks.Add(info.startTicks);
              m_combinedBufferEndTicks.Add(info.endTicks);
              m_serializer.Request(info.video);
              break;
            }
          }
        }
      }
      if(listUpdated) {
        m_streamRefreshInterval = 1.0f;
      } else {
        m_streamRefreshInterval = m_frameInterval * m_combinedFrames * 2;
      }

      if (listUpdated || m_currentBufferIndex < m_bufferedStream.Count - m_combinedFrames)
      {
        remainPlayableStream = true;
      }
      else
      {
        remainPlayableStream = false;
      }

      // End of OnStreamListReceived()
    }

19 View Source File : NInvPacketExtensions.cs
License : GNU General Public License v3.0
Project Creator : BlowaXD

public static NInvPacket GenerateNInvPacket(this IPlayerEnreplacedy player, Shop shop, byte type)
        {
            int typeshop = 0;
            double percent = 1.0;

            switch (player.GetDignityIcon())
            {
                case CharacterDignity.BluffedNameOnly:
                    percent = 1.1;
                    typeshop = 110;
                    break;
                case CharacterDignity.NotQualifiedFor:
                    percent = 1.2;
                    typeshop = 120;
                    break;
                case CharacterDignity.Useless:
                case CharacterDignity.StupidMinded:
                    percent = 1.5;
                    typeshop = 150;
                    break;
            }


            if (typeshop == 0 && !shop.Skills.Any())
            {
                typeshop = 100;
            }

            List<long> skillIds = new List<long>();

            foreach (ShopSkillDto skill in shop.Skills.Where(s => s.Type == type))
            {
                if (skill.Type != 0)
                {
                    typeshop = 1;
                    if (skill.Skill.Clreplaced == (byte)player.Character.Clreplaced)
                    {
                        skillIds.Add(skill.SkillId);
                    }
                }
                else
                {
                    skillIds.Add(skill.SkillId);
                }
            }


            return new NInvPacket
            {
                VisualType = shop.Owner.Type,
                VisualId = shop.Owner.Id,
                ShopType = typeshop,
                Unknown = 0,
                ShopList = GetShopList(shop.Items.Where(s => s.Type == type), percent),
                ShopSkills = skillIds
            };
        }

19 View Source File : SkiPacketExtensions.cs
License : GNU General Public License v3.0
Project Creator : BlowaXD

public static SkiPacket GenerateSkiPacket(this IPlayerEnreplacedy player)
        {
            IEnumerable<SkillDto> skills = player.IsTransformedSp ? GetSpSkillsByCastIdAscending(player) : GetSkillsByCastIdAscending(player);

            List<long> ids = new List<long>();

            if (!player.IsTransformedSp)
            {
                ids.Add(200 + 20 * (byte)player.Character.Clreplaced);
                ids.Add(201 + 20 * (byte)player.Character.Clreplaced);
            }
            else
            {
                ids.Add(skills.ElementAt(0).Id);
                ids.Add(skills.ElementAt(0).Id);
            }

            ids.AddRange(skills.Select(s => s.Id));

            return new SkiPacket
            {
                SkillIds = ids
            };
        }

19 View Source File : MapMonsterGenerator.cs
License : GNU General Public License v3.0
Project Creator : BlowaXD

public void Generate(string filePath)
        {
            var mapMonsterService = ChickenContainer.Instance.Resolve<IMapMonsterService>();
            var npcMonsterService = ChickenContainer.Instance.Resolve<INpcMonsterService>();
            Dictionary<long, NpcMonsterDto> npcMonsters = npcMonsterService.Get().ToDictionary(s => s.Id, s => s);
            Dictionary<long, long> effPacketsDictionary = new Dictionary<long, long>();
            List<long> npcMvPacketsList = new List<long>();
            List<long> mapMonsterIds = new List<long>();

            string[] lines = File.ReadAllText(filePath, Encoding.UTF8).Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
            int counter = 0;
            short map = 0;

            foreach (string line in lines.Where(s => s.StartsWith("in") || s.StartsWith("mv") || s.StartsWith("eff") || s.StartsWith("at")))
            {
                try
                {
                    string[] currentPacket = line.Split('\t', ' ');
                    switch (currentPacket[0])
                    {
                        case "mv" when currentPacket[1].Equals("3") && !npcMvPacketsList.Contains(int.Parse(currentPacket[2])):
                            npcMvPacketsList.Add(int.Parse(currentPacket[2]));
                            break;

                        case "eff" when currentPacket[1].Equals("3") && !effPacketsDictionary.ContainsKey(int.Parse(currentPacket[2])):
                            effPacketsDictionary.Add(int.Parse(currentPacket[2]), long.Parse(currentPacket[3]));
                            break;

                        case "at":
                            map = short.Parse(currentPacket[2]);
                            break;

                        case "in" when currentPacket[1] == "3" && npcMonsters.ContainsKey(long.Parse(currentPacket[2])) && mapMonsterIds.All(id => id != long.Parse(currentPacket[3])):
                            _monsters.Add(new MapMonsterDto
                            {
                                MapX = short.Parse(currentPacket[4]),
                                MapY = short.Parse(currentPacket[5]),
                                MapId = map,
                                NpcMonsterId = long.Parse(currentPacket[2]),
                                Id = long.Parse(currentPacket[3]),
                                IsMoving = npcMvPacketsList.Contains(long.Parse(currentPacket[3])),
                                Position = (DirectionType)byte.Parse(currentPacket[6]),
                                IsDisabled = false
                            });
                            mapMonsterIds.Add(long.Parse(currentPacket[3]));
                            counter++;
                            break;
                    }
                }
                catch (Exception e)
                {
                    Log.Error("[PARSE]", e);
                    Log.Warn(line);
                }
            }

            mapMonsterService.Save(_monsters);
        }

19 View Source File : MapNpcGenerator.cs
License : GNU General Public License v3.0
Project Creator : BlowaXD

public void Generate(string filePath)
        {
            var mapNpcService = ChickenContainer.Instance.Resolve<IMapNpcService>();
            Dictionary<long, MapNpcDto> npcs = mapNpcService.Get().ToDictionary(dto => dto.Id, dto => dto);
            Dictionary<long, short> effPacketsDictionary = new Dictionary<long, short>();
            List<long> npcMvPacketsList = new List<long>();
            List<long> mapNpcIds = new List<long>();
            _npcs.Add(new MapNpcDto
            {
                MapX = 102,
                MapY = 154,
                MapId = 5,
                NpcMonsterId = 860,
                Position = DirectionType.South,
                IsMoving = false,
                EffectDelay = 4750,
                Dialog = 999
            });

            string[] lines = File.ReadAllText(filePath, Encoding.UTF8).Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
            int counter = 0;
            short map = 0;

            foreach (string line in lines.Where(s => s.StartsWith("eff")))
            {
                try
                {
                    string[] currentPacket = line.Split('\t', ' ');
                    switch (currentPacket[0])
                    {
                        case "eff" when currentPacket[1].Equals("2") && !effPacketsDictionary.ContainsKey(int.Parse(currentPacket[2])):
                            effPacketsDictionary.Add(int.Parse(currentPacket[2]), short.Parse(currentPacket[3]));
                            break;
                    }
                }
                catch (Exception e)
                {
                    Log.Error("[EFF]", e);
                    Log.Warn(line);
                }
            }

            foreach (string line in lines.Where(s => s.StartsWith("in") || s.StartsWith("mv") || s.StartsWith("eff") || s.StartsWith("at")))
            {
                try
                {
                    string[] currentPacket = line.Split('\t', ' ');
                    switch (currentPacket[0])
                    {
                        case "mv" when currentPacket[1].Equals("2") && !npcMvPacketsList.Contains(long.Parse(currentPacket[2])):
                            npcMvPacketsList.Add(long.Parse(currentPacket[2]));
                            break;


                        case "at":
                            map = short.Parse(currentPacket[2]);
                            break;

                        case "in" when currentPacket[1] == "2":
                            short npcId = short.Parse(currentPacket[2]);
                            long mapNpcId = long.Parse(currentPacket[3]);

                            if (mapNpcId > 20000 || npcs.ContainsKey(mapNpcId) || mapNpcIds.Any(id => id == mapNpcId))
                            {
                                continue;
                            }

                            _npcs.Add(new MapNpcDto
                            {
                                MapX = short.Parse(currentPacket[4]),
                                MapY = short.Parse(currentPacket[5]),
                                MapId = map,
                                NpcMonsterId = npcId,
                                Id = mapNpcId,
                                EffectDelay = 4750,
                                IsMoving = npcMvPacketsList.Contains(mapNpcId),
                                Position = (DirectionType)byte.Parse(currentPacket[6]),
                                Dialog = short.Parse(currentPacket[9]),
                                IsSitting = currentPacket[13] != "1",
                                IsDisabled = false,
                                Effect = (short)(effPacketsDictionary.ContainsKey(mapNpcId) ? (npcId == 453 /*Lod*/ ? 855 : effPacketsDictionary[mapNpcId]) : 0)
                            });
                            mapNpcIds.Add(mapNpcId);
                            counter++;
                            break;
                    }
                }
                catch (Exception e)
                {
                    Log.Error("[PARSE]", e);
                    Log.Warn(line);
                }
            }

            mapNpcService.Save(_npcs);
        }

19 View Source File : Launcher.cs
License : GNU General Public License v3.0
Project Creator : blueminder

public static int GuessDelay(string IP)
        {
            int delay = -1;
            long avgResponseTime;

            List<long> responseTimes = new List<long>();
            for (int i = 0; i < 10; i++) {
                try
                {
                    Ping ping = new Ping();
                    PingReply pingReply = ping.Send(IP, 1000);
                    if (pingReply.Status == 0)
                    {
                        long responseTime = pingReply.RoundtripTime;
                        responseTimes.Add(responseTime);
                        Console.WriteLine(responseTime);
                    }
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.Message);
                }
            }

            if (responseTimes.Count > 0)
            {
                avgResponseTime = (long)responseTimes.Average();

                var calcDelay = Math.Ceiling((double)avgResponseTime / 32.66);
                delay = Convert.ToInt32(calcDelay);
            }
            return delay;
        }

See More Examples