Here are the examples of the csharp api System.Collections.Generic.HashSet.Add(uint) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
150 Examples
19
Source : CryptoSystem.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool Search(uint x)
{
if (CurrentKey == x)
{
return true;
}
if (xors.Contains(x))
{
return true;
}
int g = xors.Count;
for (int i = 0; i < MaximumEffortLevel - g; i++)
{
xors.Add(CurrentKey);
ConsumeKey(CurrentKey);
if (CurrentKey == x)
return true;
}
return false;
}
19
Source : Fellowship.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public Dictionary<uint, Player> GetFellowshipMembers()
{
var results = new Dictionary<uint, Player>();
var dropped = new HashSet<uint>();
foreach (var kvp in FellowshipMembers)
{
var playerGuid = kvp.Key;
var playerRef = kvp.Value;
playerRef.TryGetTarget(out var player);
if (player != null && player.Session != null && player.Session.Player != null && player.Fellowship != null)
results.Add(playerGuid, player);
else
dropped.Add(playerGuid);
}
// TODO: process dropped list
if (dropped.Count > 0)
ProcessDropList(FellowshipMembers, dropped);
return results;
}
19
Source : HouseList.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static HashSet<uint> GetHousesOwned()
{
// select * from biota where weenie_Type=53;
var housesOwned = DatabaseManager.Shard.BaseDatabase.GetHousesOwned();
Console.WriteLine($"Owned houses: {housesOwned.Count}");
// build owned hashset
var owned = new HashSet<uint>();
foreach (var house in housesOwned)
{
if (owned.Contains(house.Id))
{
Console.WriteLine($"HouseList.GetOwned(): duplicate owned house id {house.Id}");
continue;
}
owned.Add(house.Id);
}
return owned;
}
19
Source : LandblockGroup.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool Remove(Landblock landblock)
{
if (landblocks.Remove(landblock))
{
landblock.CurrentLandblockGroup = null;
// Empty landblock groups will be discarded immediately
if (landblocks.Count == 0)
return true;
uniqueLandblockIdsRemoved.Add(landblock.Id.Raw);
// If this landblock is on the perimeter of the group, recalculate the boundaries (they may end up the same)
if (landblock.Id.LandblockX == xMin || landblock.Id.LandblockX == xMax ||
landblock.Id.LandblockY == yMin || landblock.Id.LandblockY == yMax)
{
RecalculateBoundaries();
}
return true;
}
return false;
}
19
Source : Corpse.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool HasPermission(Player player)
{
// players can loot their own corpses
if (VictimId == null || player.Guid.Full == VictimId)
return true;
// players can loot corpses of creatures they killed or corpses that have previously been looted by killer
if (KillerId != null && player.Guid.Full == KillerId || IsLooted)
return true;
var victimGuid = new ObjectGuid(VictimId.Value);
// players can /permit other players to loot their corpse if not killed by another player killer.
if (player.HasLootPermission(victimGuid) && PkLevel != PKLevel.PK)
{
if (!PropertyManager.GetBool("permit_corpse_all").Item)
{
// this is the retail default. see the comments for 'permitteeOpened' for an explanation of why this table is needed
if (permitteeOpened == null)
permitteeOpened = new HashSet<uint>();
// these are technically side effects, and HasPermission() is not the best place for this logic to mutate state,
// however with the current lone calling pattern for corpse ActOnUse -> TryOpen -> HasPermission -> Open
// if HasPermission returns true, the corpse is always opened, ie. there's no chance of 'the corpse is already in use' or any other failure cases,
// as those pre-verifications have already happened before this function is called
permitteeOpened.Add(player.Guid.Full);
player.LootPermission.Remove(victimGuid);
}
return true;
}
if (permitteeOpened != null && permitteeOpened.Contains(player.Guid.Full))
return true;
// all players can loot monster corpses after 1/2 decay time except if corpse generates a rare
if (TimeToRot != null && TimeToRot < HalfLife && !new ObjectGuid(VictimId.Value).IsPlayer() && !CorpseGeneratedRare)
return true;
// players in the same fellowship as the killer w/ loot sharing enabled except if corpse generates a rare
if (player.Fellowship != null && player.Fellowship.ShareLoot)
{
var onlinePlayer = PlayerManager.GetOnlinePlayer(KillerId ?? 0);
if (onlinePlayer != null && onlinePlayer.Fellowship != null && player.Fellowship == onlinePlayer.Fellowship && !CorpseGeneratedRare && PkLevel != PKLevel.PK)
return true;
}
return false;
}
19
Source : WorldObject_Set.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static List<Spell> GetSpellSetAll(EquipmentSet equipmentSet)
{
var spells = new List<Spell>();
if (!DatManager.PortalDat.SpellTable.SpellSet.TryGetValue((uint)equipmentSet, out var spellSet))
return spells;
var spellIds = new HashSet<uint>();
foreach (var level in spellSet.SpellSetTiers.Values)
{
foreach (var spell in level.Spells)
spellIds.Add(spell);
}
foreach (var spellId in spellIds)
spells.Add(new Spell(spellId, false));
return spells;
}
19
Source : EditorHandsInput.cs
with MIT License
from anderm
with MIT License
from anderm
private void UpdateHandData()
{
float time;
float deltaTime;
if (manualHandControl.UseUnscaledTime)
{
time = Time.unscaledTime;
deltaTime = Time.unscaledDeltaTime;
}
else
{
time = Time.time;
deltaTime = Time.deltaTime;
}
if (manualHandControl.LeftHandInView)
{
GetOrAddHandData(0);
currentHands.Add(0);
UpdateHandState(manualHandControl.LeftHandSourceState, editorHandsData[0], deltaTime, time);
}
if (manualHandControl.RightHandInView)
{
GetOrAddHandData(1);
currentHands.Add(1);
UpdateHandState(manualHandControl.RightHandSourceState, editorHandsData[1], deltaTime, time);
}
}
19
Source : EditorHandsInput.cs
with MIT License
from anderm
with MIT License
from anderm
private EditorHandData GetOrAddHandData(uint sourceId)
{
EditorHandData handData;
if (!handIdToData.TryGetValue(sourceId, out handData))
{
handData = new EditorHandData(sourceId);
handIdToData.Add(handData.HandId, handData);
newHands.Add(handData.HandId);
}
return handData;
}
19
Source : GLSLLinkProgram.cs
with GNU Lesser General Public License v2.1
from axiom3d
with GNU Lesser General Public License v2.1
from axiom3d
private void ExtractAttributes()
{
foreach (var a in this.sCustomAttributes)
{
var attrib = Gl.glGetAttribLocationARB(this.glHandle, a.name);
if (attrib != -1)
{
this.validAttributes.Add(a.attrib);
}
}
}
19
Source : DistinctMap.UnorderedDistinctMap.cs
with MIT License
from Azure
with MIT License
from Azure
public static TryCatch<DistinctMap> TryCreate(CosmosElement continuationToken)
{
HashSet<Number64> numbers = new HashSet<Number64>();
HashSet<uint> stringsLength4 = new HashSet<uint>();
HashSet<ulong> stringsLength8 = new HashSet<ulong>();
HashSet<UInt128> stringsLength16 = new HashSet<UInt128>();
HashSet<UInt128> stringsLength16Plus = new HashSet<UInt128>();
HashSet<UInt128> arrays = new HashSet<UInt128>();
HashSet<UInt128> objects = new HashSet<UInt128>();
SimpleValues simpleValues = SimpleValues.None;
if (continuationToken != null)
{
if (!(continuationToken is CosmosObject hashDictionary))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
// Numbers
if (!hashDictionary.TryGetValue(UnorderdDistinctMap.PropertyNames.Numbers, out CosmosArray numbersArray))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
foreach (CosmosElement rawNumber in numbersArray)
{
if (!(rawNumber is CosmosNumber64 number))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
numbers.Add(number.GetValue());
}
// Strings Length 4
if (!hashDictionary.TryGetValue(UnorderdDistinctMap.PropertyNames.StringsLength4, out CosmosArray stringsLength4Array))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
foreach (CosmosElement rawStringLength4 in stringsLength4Array)
{
if (!(rawStringLength4 is CosmosUInt32 stringlength4))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
stringsLength4.Add(stringlength4.GetValue());
}
// Strings Length 8
if (!hashDictionary.TryGetValue(UnorderdDistinctMap.PropertyNames.StringsLength8, out CosmosArray stringsLength8Array))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
foreach (CosmosElement rawStringLength8 in stringsLength8Array)
{
if (!(rawStringLength8 is CosmosInt64 stringlength8))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
stringsLength8.Add((ulong)stringlength8.GetValue());
}
// Strings Length 16
stringsLength16 = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.PropertyNames.StringsLength16);
// Strings Length 24
stringsLength16Plus = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.PropertyNames.StringsLength16Plus);
// Array
arrays = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.PropertyNames.Arrays);
// Object
objects = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.PropertyNames.Object);
// Simple Values
CosmosElement rawSimpleValues = hashDictionary[UnorderdDistinctMap.PropertyNames.SimpleValues];
if (!(rawSimpleValues is CosmosString simpleValuesString))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
if (!Enum.TryParse<SimpleValues>(simpleValuesString.Value, out simpleValues))
{
return TryCatch<DistinctMap>.FromException(
new MalformedContinuationTokenException(
$"{nameof(UnorderdDistinctMap)} continuation token was malformed."));
}
}
return TryCatch<DistinctMap>.FromResult(new UnorderdDistinctMap(
numbers,
stringsLength4,
stringsLength8,
stringsLength16,
stringsLength16Plus,
arrays,
objects,
simpleValues));
}
19
Source : MultiRowDbTableEditorViewModel.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
private void EnsureKey(uint enreplacedy)
{
if (keys.Add(enreplacedy))
{
byEntryGroups[enreplacedy] = new DatabaseEnreplacediesGroupViewModel(enreplacedy, GenerateName(enreplacedy));
Rows.Add(byEntryGroups[enreplacedy]);
}
}
19
Source : DatabaseTableModelGenerator.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
public IDatabaseTableData? CreateDatabaseTable(DatabaseTableDefinitionJson tableDefinition,
uint[] keys,
IList<Dictionary<string, (System.Type type, object value)>> fieldsFromDb)
{
HashSet<uint> providedKeys = new();
IList<IConditionLine>? conditions = null;
List<DatabaseEnreplacedy> rows = new();
foreach (var enreplacedy in fieldsFromDb)
{
uint? key = null;
Dictionary<string, IDatabaseField> columns = new();
foreach (var column in enreplacedy)
{
IValueHolder valueHolder = null!;
if (column.Value.type == typeof(string))
{
string? val = column.Value.value as string ?? null;
valueHolder = new ValueHolder<string>(val, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(float))
{
valueHolder = new ValueHolder<float>(column.Value.value as float? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(uint))
{
valueHolder = new ValueHolder<long>(column.Value.value as uint? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(int))
{
valueHolder = new ValueHolder<long>(column.Value.value as int? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(long))
{
valueHolder = new ValueHolder<long>(column.Value.value as long? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(ulong))
{
valueHolder = new ValueHolder<long>((long)(column.Value.value as ulong? ?? 0), column.Value.value is DBNull);
}
else if (column.Value.type == typeof(byte))
{
valueHolder = new ValueHolder<long>(column.Value.value as byte? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(sbyte))
{
valueHolder = new ValueHolder<long>(column.Value.value as sbyte? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(ushort))
{
valueHolder = new ValueHolder<long>(column.Value.value as ushort? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(short))
{
valueHolder = new ValueHolder<long>(column.Value.value as short? ?? 0, column.Value.value is DBNull);
}
else if (column.Value.type == typeof(bool))
{
valueHolder = new ValueHolder<long>(column.Value.value is DBNull ? 0 : ((bool)column.Value.value ? 1 : 0), column.Value.value is DBNull);
}
else if (column.Value.type == typeof(IList<IConditionLine>))
{
conditions = ((IList<IConditionLine>)column.Value.value);
continue;
}
else
{
throw new NotImplementedException("Unknown column type " + column.Value.type);
}
if (column.Key == tableDefinition.TablePrimaryKeyColumnName)
{
if (valueHolder is ValueHolder<long> longKey)
{
key = (uint)longKey.Value;
providedKeys.Add(key.Value);
}
}
columns[column.Key] = databaseFieldFactory.CreateField(column.Key, valueHolder);
}
if (key.HasValue)
rows.Add(new DatabaseEnreplacedy(true, key.Value, columns, conditions?.ToList<ICondition>()));
}
if (!tableDefinition.IsMultiRecord)
{
foreach (var key in keys)
{
if (!providedKeys.Contains(key))
rows.Add(CreateEmptyEnreplacedy(tableDefinition, key));
}
}
try
{
return new DatabaseTableData(tableDefinition, rows);
}
catch (Exception e)
{
// in case of throw from DbTableFieldFactory
ShowLoadingError(e.Message);
}
return null;
}
19
Source : CreatureTextProcessor.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
Process(PacketBase basePacket, PacketChat packet)
{
if (packet.Sender.Entry == 0)
return null;
keys.Add(packet.Sender.Entry);
return new object[]
{
(uint)packet.Sender.Entry,
packet.Text,
(long)packet.Type,
(long)packet.Language,
(long)(databaseProvider.GetBroadcastTextByText(packet.Text)?.Id ?? 0)
};
}
19
Source : GossipExtractProcessor.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
public void AddTextId(uint textId)
{
TextsId.Add(textId);
}
19
Source : GossipExtractProcessor.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
private async Task DeleteExisting()
{
await ResolvePointsOfInterest();
foreach (var entry in gossiperToFirstMenuId.Keys.ToList())
{
var template = databaseProvider.GetCreatureTemplate(entry);
if (template != null)
{
if (template.GossipMenuId == gossiperToFirstMenuId[entry])
gossiperToFirstMenuId.Remove(entry);
else if (template.GossipMenuId != 0)
overridenDatabaseGossipMenu.Add(entry, template.GossipMenuId);
}
else
templatesNotExistingInDb.Add(entry);
}
var databaseMenus = await databaseProvider.GetGossipMenusAsync();
var databaseGossipMenus = databaseMenus.ToDictionary(o => o.MenuId);
foreach (var menu in menus)
{
if (!databaseGossipMenus.TryGetValue(menu.Key, out var dbMenu))
{
menuMissingInDb.Add(menu.Key);
continue;
}
foreach (var dbText in dbMenu.Text)
{
if (!menu.Value.TextsId.Contains(dbText.Id))
menu.Value.DatabaseOnlyTextsId.Add(dbText.Id);
}
if (menu.Value.DatabaseOnlyTextsId.Count == 0 &&
menu.Value.TextsId.All(text => dbMenu.Text.Any(f => f.Id == text)))
menusAlreadyInDb.Add(menu.Key);
}
foreach (var menu in menus)
{
if (menu.Value.Options.Count == 0)
continue;
var existingOptions = await databaseProvider.GetGossipMenuOptionsAsync(menu.Key);
if (existingOptions.Count == 0)
{
menuOptionsMissingInDb.Add(menu.Key);
continue;
}
bool allInDb = true;
foreach (var option in menu.Value.Options)
{
var isInDb = existingOptions.Any(db => IsSameOption(option, db));
if (!isInDb)
allInDb = false;
}
foreach (var option in existingOptions)
{
var isInSniff = menu.Value.Options.Any(sniff => IsSameOption(option, sniff));
if (!isInSniff)
{
allInDb = false;
menu.Value.AddDatabaseOption(new GossipMenuOption(option));
}
}
if (allInDb)
{
menuOptionsAlreadyInDb.Add(menu.Key);
}
}
}
19
Source : GossipExtractProcessor.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
private async Task DeleteExisting()
{
await ResolvePointsOfInterest();
foreach (var entry in gossiperToFirstMenuId.Keys.ToList())
{
var template = databaseProvider.GetCreatureTemplate(entry);
if (template != null)
{
if (template.GossipMenuId == gossiperToFirstMenuId[entry])
gossiperToFirstMenuId.Remove(entry);
else if (template.GossipMenuId != 0)
overridenDatabaseGossipMenu.Add(entry, template.GossipMenuId);
}
else
templatesNotExistingInDb.Add(entry);
}
var databaseMenus = await databaseProvider.GetGossipMenusAsync();
var databaseGossipMenus = databaseMenus.ToDictionary(o => o.MenuId);
foreach (var menu in menus)
{
if (!databaseGossipMenus.TryGetValue(menu.Key, out var dbMenu))
{
menuMissingInDb.Add(menu.Key);
continue;
}
foreach (var dbText in dbMenu.Text)
{
if (!menu.Value.TextsId.Contains(dbText.Id))
menu.Value.DatabaseOnlyTextsId.Add(dbText.Id);
}
if (menu.Value.DatabaseOnlyTextsId.Count == 0 &&
menu.Value.TextsId.All(text => dbMenu.Text.Any(f => f.Id == text)))
menusAlreadyInDb.Add(menu.Key);
}
foreach (var menu in menus)
{
if (menu.Value.Options.Count == 0)
continue;
var existingOptions = await databaseProvider.GetGossipMenuOptionsAsync(menu.Key);
if (existingOptions.Count == 0)
{
menuOptionsMissingInDb.Add(menu.Key);
continue;
}
bool allInDb = true;
foreach (var option in menu.Value.Options)
{
var isInDb = existingOptions.Any(db => IsSameOption(option, db));
if (!isInDb)
allInDb = false;
}
foreach (var option in existingOptions)
{
var isInSniff = menu.Value.Options.Any(sniff => IsSameOption(option, sniff));
if (!isInSniff)
{
allInDb = false;
menu.Value.AddDatabaseOption(new GossipMenuOption(option));
}
}
if (allInDb)
{
menuOptionsAlreadyInDb.Add(menu.Key);
}
}
}
19
Source : NameAsEnumDumper.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
public bool Process(PacketHolder packet)
{
var results = inner.Process(packet);
if (results == null)
return false;
foreach (var result in results)
{
if (!existing.Add(result.entry))
continue;
if (!entries.TryGetValue(result.prefix, out var list))
list = entries[result.prefix] = new();
var name = (result.prefix + " " + result.name).ToEnumName();
list.Add($"{name,-40} = {result.entry}");
}
return true;
}
19
Source : EventManagerTests.cs
with Apache License 2.0
from bnoazx005
with Apache License 2.0
from bnoazx005
[Test]
public void TestSubscribe_MultipleSubscriptionsCreatesNewListener_ReturnsListenerIdentifier()
{
replacedert.DoesNotThrow(() =>
{
HashSet<uint> createdListenersIds = new HashSet<uint>();
IEventListener eventListener = Subsreplacedute.For<IEventListener>();
uint registeredListenerId = 0;
for (int i = 0; i < 4; ++i)
{
registeredListenerId = mEventManager.Subscribe<TSimpleEvent>(eventListener);
// all registered listeners have unique identifiers
replacedert.IsFalse(createdListenersIds.Contains(registeredListenerId));
createdListenersIds.Add(registeredListenerId);
}
});
}
19
Source : MemoryDebugger.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
private static void AddSection(uint b, uint e, string n, bool isMmio)
{
s_NamedPSections.Add(new NamedMemorySection(b, e, n));
if (isMmio) {
s_RegTable.Add(b);
}
}
19
Source : MipsDebugger.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
public void AppendInstBreakpointByCode(String asm)
{
uint inst = N64replacedembler.replacedembleSingleInstruction(asm);
if (!m_InstByCodeBreakpoints.Contains(inst))
{
m_InstByCodeBreakpoints.Add(inst);
}
}
19
Source : MipsDebugger.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
public void AppendInstBreakpointByAddr(uint address)
{
if (!m_InstByAddressBreakpoints.Contains(address))
{
m_InstByAddressBreakpoints.Add(address);
}
}
19
Source : Party.cs
with GNU General Public License v3.0
from caioavidal
with GNU General Public License v3.0
from caioavidal
public Result Invite(IPlayer by, IPlayer invitedPlayer)
{
if (invitedPlayer.PlayerParty.IsInParty) return new Result(InvalidOperation.CannotInvite);
if (!IsLeader(by)) return new Result(InvalidOperation.CannotInvite);
invites.Add(invitedPlayer.CreatureId);
return Result.Success;
}
19
Source : Vip.cs
with GNU General Public License v3.0
from caioavidal
with GNU General Public License v3.0
from caioavidal
public void LoadVipList(IEnumerable<(uint, string)> vips)
{
if (Guard.AnyNull(vips)) return;
var vipList = new HashSet<(uint, string)>();
foreach (var vip in vips)
{
if (string.IsNullOrWhiteSpace(vip.Item2)) continue;
VipList.Add(vip.Item1);
vipList.Add(vip);
}
OnLoadedVipList?.Invoke(_owner, vipList);
}
19
Source : Vip.cs
with GNU General Public License v3.0
from caioavidal
with GNU General Public License v3.0
from caioavidal
public bool AddToVip(IPlayer player)
{
if (Guard.AnyNull(player)) return false;
if (string.IsNullOrWhiteSpace(player.Name)) return false;
VipList ??= new HashSet<uint>();
if (VipList.Count >= 200)
{
OperationFailService.Display(_owner.CreatureId, "You cannot add more buddies.");
return false;
}
if (player.FlagIsEnabled(PlayerFlag.SpecialVip))
if (!_owner.FlagIsEnabled(PlayerFlag.SpecialVip))
{
OperationFailService.Display(_owner.CreatureId, TextConstants.CANNOT_ADD_PLAYER_TO_VIP_LIST);
return false;
}
if (!VipList.Add(player.Id))
{
OperationFailService.Display(_owner.CreatureId, "This player is already in your list.");
return false;
}
OnAddedToVipList?.Invoke(_owner, player.Id, player.Name);
return true;
}
19
Source : Texture.cs
with MIT License
from ChevyRay
with MIT License
from ChevyRay
internal static void MarkAllForUnbinding()
{
for (int i = 0; i < binded.Length; ++i)
if (binded[i].ID != 0)
unbind.Add(binded[i].ID);
}
19
Source : MqttClientSubscriptionsManager.cs
with MIT License
from chkr1011
with MIT License
from chkr1011
public CheckSubscriptionsResult CheckSubscriptions(string topic, MqttQualityOfServiceLevel qosLevel, string senderClientId)
{
List<Subscription> subscriptions;
_subscriptionsLock.EnterReadLock();
try
{
subscriptions = _subscriptions.Values.ToList();
}
finally
{
_subscriptionsLock.ExitReadLock();
}
var senderIsReceiver = string.Equals(senderClientId, _clientSession.ClientId);
var qosLevels = new HashSet<MqttQualityOfServiceLevel>();
var subscriptionIdentifiers = new HashSet<uint>();
var retainAsPublished = false;
foreach (var subscription in subscriptions)
{
if (subscription.NoLocal && senderIsReceiver)
{
// This is a MQTTv5 feature!
continue;
}
if (subscription.RetainAsPublished)
{
// This is a MQTTv5 feature!
retainAsPublished = true;
}
if (!MqttTopicFilterComparer.IsMatch(topic, subscription.Topic))
{
continue;
}
qosLevels.Add(subscription.QualityOfServiceLevel);
if (subscription.Identifier > 0)
{
subscriptionIdentifiers.Add(subscription.Identifier);
}
}
if (qosLevels.Count == 0)
{
return CheckSubscriptionsResult.NotSubscribed;
}
return new CheckSubscriptionsResult
{
IsSubscribed = true,
RetainAsPublished = retainAsPublished,
SubscriptionIdentifiers = subscriptionIdentifiers.ToList(),
QualityOfServiceLevel = GetEffectiveQoS(qosLevel, qosLevels)
};
}
19
Source : CollectionService.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public void Drop(CollectionPage col)
{
// add all pages to delete
var pages = new HashSet<uint>();
// search for all data page and index page
foreach (var index in col.GetIndexes(true))
{
// get all nodes from index
var nodes = _indexer.FindAll(index, Query.Ascending);
foreach (var node in nodes)
{
// if is PK index, add dataPages
if (index.Slot == 0)
{
pages.Add(node.DataBlock.PageID);
// read datablock to check if there is any extended page
var block = _data.GetBlock(node.DataBlock);
if (block.ExtendPageID != uint.MaxValue)
{
_pager.DeletePage(block.ExtendPageID, true);
}
}
// memory checkpoint
_trans.CheckPoint();
// add index page to delete list page
pages.Add(node.Position.PageID);
}
// remove head+tail nodes in all indexes
pages.Add(index.HeadNode.PageID);
pages.Add(index.TailNode.PageID);
}
// and now, lets delete all this pages
foreach (var pageID in pages)
{
// delete page
_pager.DeletePage(pageID);
// memory checkpoint
_trans.CheckPoint();
}
// get header page to remove from collection list links
var header = _pager.GetPage<HeaderPage>(0);
header.CollectionPages.Remove(col.CollectionName);
// set header as dirty after remove
_pager.SetDirty(header);
_pager.DeletePage(col.PageID);
}
19
Source : IndexService.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public void DropIndex(CollectionIndex index)
{
var pages = new HashSet<uint>();
var nodes = this.FindAll(index, Query.Ascending);
// get reference for pageID from all index nodes
foreach (var node in nodes)
{
pages.Add(node.Position.PageID);
// for each node I need remove from node list datablock reference
var prevNode = this.GetNode(node.PrevNode);
var nextNode = this.GetNode(node.NextNode);
if (prevNode != null)
{
prevNode.NextNode = node.NextNode;
_pager.SetDirty(prevNode.Page);
}
if (nextNode != null)
{
nextNode.PrevNode = node.PrevNode;
_pager.SetDirty(nextNode.Page);
}
}
// now delete all pages
foreach (var pageID in pages)
{
_pager.DeletePage(pageID);
}
}
19
Source : Recovery.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
private static HashSet<uint> RecoveryDetectCollectionByIndexPages(UltraLiteEngine engine, HashSet<uint> initialPagesID, StringBuilder log)
{
var indexPages = new Dictionary<uint, bool>();
var dataPages = new HashSet<uint>();
foreach(var pageID in initialPagesID)
{
indexPages.Add(pageID, false);
}
// discover all indexes pages related with this current indexPage (all of them are in same collection)
while (indexPages.Count(x => x.Value == false) > 0)
{
var item = indexPages.First(x => x.Value == false);
// mark page as readed
indexPages[item.Key] = true;
IndexPage indexPage = null;
try
{
// try read page from disk and deserialize as IndexPage
var buffer = engine._disk.ReadPage(item.Key);
var page = BasePage.ReadPage(buffer);
if (page.PageType != PageType.Index) continue;
indexPage = page as IndexPage;
}
catch(Exception ex)
{
log.AppendLine($"Page {item.Key} (Collection) Error: {ex.Message}");
continue;
}
// now, check for all nodes to get dataPages
foreach (var node in indexPage.Nodes.Values)
{
if (node.DataBlock.PageID != uint.MaxValue)
{
dataPages.Add(node.DataBlock.PageID);
}
// add into indexPages all possible indexPages
if (!indexPages.ContainsKey(node.PrevNode.PageID) && node.PrevNode.PageID != uint.MaxValue)
{
indexPages.Add(node.PrevNode.PageID, false);
}
if (!indexPages.ContainsKey(node.NextNode.PageID) && node.NextNode.PageID != uint.MaxValue)
{
indexPages.Add(node.NextNode.PageID, false);
}
foreach (var pos in node.Prev.Where(x => !x.IsEmpty && x.PageID != uint.MaxValue))
{
if (!indexPages.ContainsKey(pos.PageID)) indexPages.Add(pos.PageID, false);
}
foreach (var pos in node.Next.Where(x => !x.IsEmpty && x.PageID != uint.MaxValue))
{
if (!indexPages.ContainsKey(pos.PageID)) indexPages.Add(pos.PageID, false);
}
}
}
return dataPages;
}
19
Source : AlbionPalette.cs
with MIT License
from csinkers
with MIT License
from csinkers
public uint[] GetUnambiguousPalette()
{
if (_unambiguous == null)
{
_unambiguous = new uint[256];
var used = new HashSet<uint>();
for (int i = 0; i < 256; i++)
{
uint entry = Entries[i];
// Always set full alpha when it's not index 0 so things like item graphics
// that should just use the common palette still round-trip correctly if
// they accidentally contain some indices < 192
if (i > 0)
entry |= 0xff000000;
if (used.Contains(entry))
entry = Search(entry, used);
_unambiguous[i] = entry;
used.Add(entry);
}
}
return _unambiguous;
}
19
Source : BattlePetManager.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public uint GetPetUniqueSpeciesCount()
{
HashSet<uint> speciesIds = new();
foreach (var pair in _pets)
speciesIds.Add(pair.Value.PacketInfo.Species);
return (uint)speciesIds.Count;
}
19
Source : QueryHandler.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
[WorldPacketHandler(ClientOpcodes.QuestPoiQuery, Processing = PacketProcessing.Inplace)]
void HandleQuestPOIQuery(QuestPOIQuery packet)
{
if (packet.MissingQuestCount >= SharedConst.MaxQuestLogSize)
return;
// Read quest ids and add the in a unordered_set so we don't send POIs for the same quest multiple times
HashSet<uint> questIds = new();
for (int i = 0; i < packet.MissingQuestCount; ++i)
questIds.Add(packet.MissingQuestPOIs[i]); // QuestID
QuestPOIQueryResponse response = new();
foreach (uint questId in questIds)
{
if (_player.FindQuestSlot(questId) != SharedConst.MaxQuestLogSize)
{
QuestPOIData poiData = Global.ObjectMgr.GetQuestPOIData(questId);
if (poiData != null)
response.QuestPOIDataStats.Add(poiData);
}
}
SendPacket(response);
}
19
Source : FileReaderV7.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
private HashSet<uint> VisitIndexPages(uint startPageID)
{
var toVisit = new HashSet<uint>(new uint[] { startPageID });
var visited = new HashSet<uint>();
while(toVisit.Count > 0)
{
var indexPageID = toVisit.First();
toVisit.Remove(indexPageID);
var indexPage = this.ReadPage(indexPageID);
if (indexPage == null || indexPage["pageType"] != 3) continue;
visited.Add(indexPageID);
foreach(var node in indexPage["nodes"].AsArray)
{
var prev = (uint)node["prev"]["pageID"].AsInt32;
var next = (uint)node["next"]["pageID"].AsInt32;
if (!visited.Contains(prev)) toVisit.Add(prev);
if (!visited.Contains(next)) toVisit.Add(next);
}
}
return visited;
}
19
Source : SnapShot.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void DropCollection(Action safePoint)
{
var indexer = new IndexService(this, _header.Pragmas.Collation);
// CollectionPage will be last deleted page (there is no NextPageID from CollectionPage)
_transPages.FirstDeletedPageID = _collectionPage.PageID;
_transPages.LastDeletedPageID = _collectionPage.PageID;
// mark collection page as empty
_collectionPage.MarkAsEmtpy();
_transPages.DeletedPages = 1;
var indexPages = new HashSet<uint>();
// getting all indexes pages from all indexes
foreach(var index in _collectionPage.GetCollectionIndexes())
{
// add head/tail (same page) to be deleted
indexPages.Add(index.Head.PageID);
foreach (var node in indexer.FindAll(index, Query.Ascending))
{
indexPages.Add(node.Page.PageID);
safePoint();
}
}
// now, mark all pages as deleted
foreach (var pageID in indexPages)
{
var page = this.GetPage<IndexPage>(pageID);
// mark page as delete and fix deleted page list
page.MarkAsEmtpy();
page.NextPageID = _transPages.FirstDeletedPageID;
_transPages.FirstDeletedPageID = page.PageID;
_transPages.DeletedPages++;
safePoint();
}
// adding all data pages
foreach (var startPageID in _collectionPage.FreeDataPageList)
{
var next = startPageID;
while(next != uint.MaxValue)
{
var page = this.GetPage<DataPage>(next);
next = page.NextPageID;
// mark page as delete and fix deleted page list
page.MarkAsEmtpy();
page.NextPageID = _transPages.FirstDeletedPageID;
_transPages.FirstDeletedPageID = page.PageID;
_transPages.DeletedPages++;
safePoint();
}
}
// remove collection name (in header) at commit time
_transPages.Commit += (h) => h.DeleteCollection(_collectionName);
}
19
Source : WalIndexService.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void ConfirmTransaction(uint transactionID, ICollection<PagePosition> pagePositions)
{
// must lock commit operation to update WAL-Index (memory only operation)
_indexLock.TryEnterWriteLock(-1);
try
{
// increment current version
_currentReadVersion++;
// update wal-index
foreach (var pos in pagePositions)
{
if (_index.TryGetValue(pos.PageID, out var slot) == false)
{
slot = new List<KeyValuePair<int, long>>();
_index.Add(pos.PageID, slot);
}
// add version/position into pageID slot
slot.Add(new KeyValuePair<int, long>(_currentReadVersion, pos.Position));
}
// add transaction as confirmed
_confirmTransactions.Add(transactionID);
}
finally
{
_indexLock.ExitWriteLock();
}
}
19
Source : GestureManager.cs
with MIT License
from dag10
with MIT License
from dag10
private void InteractionManager_SourceDetected(InteractionSourceState state)
{
trackedInteractionSource.Add(state.source.id);
}
19
Source : GestureManager.cs
with MIT License
from dag10
with MIT License
from dag10
private void InteractionManager_SourcePressed(InteractionSourceState state)
{
// Make sure we're using a tracked interaction source.
if (trackedInteractionSource.Contains(state.source.id))
{
// Add it to the list of pressed states.
if (!pressedInteractionSource.Contains(state.source.id))
{
pressedInteractionSource.Add(state.source.id);
}
// Don't start another manipulation gesture if one is already underway.
if (!ManipulationInProgress)
{
// Cache our current source state for use later.
currentInteractionSourceState = state;
// Gesture Support for Controllers: (i.e. Clicker, Xbox Controller, etc.)
if (state.source.kind == InteractionSourceKind.Controller)
{
OnManipulation(inProgress: true, offset: ManipulationPosition);
if (OnManipulationStarted != null)
{
OnManipulationStarted(state.source.kind);
}
}
}
}
}
19
Source : HandsManager.cs
with MIT License
from dag10
with MIT License
from dag10
private void InteractionManager_SourceDetected(InteractionSourceState state)
{
// Check to see that the source is a hand.
if (state.source.kind == InteractionSourceKind.Hand)
{
trackedHands.Add(state.source.id);
if (HandInView != null)
{
HandInView(HandDetected);
}
}
}
19
Source : HandsManager.cs
with MIT License
from dag10
with MIT License
from dag10
private void InteractionManager_SourcePressed(InteractionSourceState state)
{
if (state.source.kind == InteractionSourceKind.Hand)
{
if (trackedHands.Contains(state.source.id))
{
currentHandState = state;
if(!pressedHands.Contains(state.source.id))
{
pressedHands.Add(state.source.id);
}
}
}
}
19
Source : TabEditLevelTextures.cs
with MIT License
from DavidSM64
with MIT License
from DavidSM64
private void loadModelsOnlyButtonSet()
{
HashSet<uint> addresses = new HashSet<uint>();
List<RadioButtonWithInfo> buttons = new List<RadioButtonWithInfo>();
foreach (KeyValuePair<ushort, Model3D> entry in level.ModelIDs)
{
for (int i = 0; i < entry.Value.builder.TextureImages.Count; i++)
{
uint address = entry.Value.builder.TextureAddresses[i];
if (address == 0)
continue;
if (!addresses.Contains(address))
{
AddNewImage(ref buttons, entry.Value.builder.TextureImages[i], address, RadioButtonWithInfo_Click);
addresses.Add(address);
}
}
}
lt_modelButtons = buttons.ToArray();
}
19
Source : TabEditLevelTextures.cs
with MIT License
from DavidSM64
with MIT License
from DavidSM64
private void loadLevelOnlyButtonSet()
{
List<RadioButtonWithInfo> buttons = new List<RadioButtonWithInfo>();
HashSet<uint> addresses = new HashSet<uint>();
foreach (Area area in level.Areas)
{
for (int i = 0; i < area.AreaModel.builder.TextureImages.Count; i++)
{
uint address = area.AreaModel.builder.TextureAddresses[i];
if (address == 0)
continue;
if (!addresses.Contains(address))
{
AddNewImage(ref buttons, area.AreaModel.builder.TextureImages[i], address, RadioButtonWithInfo_Click);
addresses.Add(address);
}
}
}
lt_levelButtons = buttons.ToArray();
}
19
Source : TabEditLevelTextures.cs
with MIT License
from DavidSM64
with MIT License
from DavidSM64
private void loadObjectsOnlyButtonSet()
{
List<RadioButtonWithInfo> buttons = new List<RadioButtonWithInfo>();
HashSet<uint> addresses = new HashSet<uint>();
HashSet<ushort> modelIDs = level.getModelIDsUsedByObjects();
foreach (ushort modelID in modelIDs)
{
if (level.ModelIDs.ContainsKey(modelID))
{
for (int i = 0; i < level.ModelIDs[modelID].builder.TextureImages.Count; i++)
{
uint address = level.ModelIDs[modelID].builder.TextureAddresses[i];
if (address == 0)
continue;
if (!addresses.Contains(address))
{
AddNewImage(ref buttons, level.ModelIDs[modelID].builder.TextureImages[i], address, RadioButtonWithInfo_Click);
addresses.Add(address);
}
}
}
}
lt_objectButtons = buttons.ToArray();
}
19
Source : Program.cs
with MIT License
from DebugST
with MIT License
from DebugST
static void m_scanner_Completed(object sender, ScanEventArgs e) {
if (e.CanConnect) {
lock (m_obj_sync) {
m_nResult++;
if (ScannerConfiger.StopProto.Contains(e.Protocol)) {
uint u = BitConverter.ToUInt32(((IPEndPoint)e.EndPoint).Address.GetAddressBytes(), 0);
m_hs_stop_host.Add(u);
}
}
string strProto = e.Protocol;
string strIP = ((IPEndPoint)e.EndPoint).Address.ToString();
int nPort = ((IPEndPoint)e.EndPoint).Port;
if (string.IsNullOrEmpty(strProto)) {
if (m_pc.DefaultProtocol.ContainsKey(nPort))
strProto = m_pc.DefaultProtocol[nPort] + "?";
}
Program.OutResult(strIP, nPort.ToString(), ScannerConfiger.ProtocolType, strProto, e.Banner, e.RegexLine, e.Data, e.Length);
}
//if()
m_se.Release();
lock (m_obj_sync) {
m_nRuned++;
m_nRunning--;
}
}
19
Source : DeadlockMonitor.cs
with MIT License
from dinazil
with MIT License
from dinazil
private void FindDeadlockStartingFrom(ClrThread thread, HashSet<uint> visitedThreadIds, Stack<string> chain)
{
if (thread == null)
return;
if (visitedThreadIds.Contains(thread.OSThreadId))
{
WriteTraceLine("Deadlock found between the following threads:");
foreach (var entry in chain.Reverse())
{
WriteTraceLine($" {entry} -->");
}
WriteTraceLine($" Thread {thread.OSThreadId}, DEADLOCK!");
return;
}
visitedThreadIds.Add(thread.OSThreadId);
string topStackTrace = String.Join("\n ",
thread.StackTrace.Where(f => f.Kind == ClrStackFrameType.ManagedMethod)
.Select(f => f.DisplayString)
.Take(5));
chain.Push($"Thread {thread.OSThreadId} at {topStackTrace}");
foreach (var blockingObject in thread.BlockingObjects)
{
chain.Push($"{blockingObject.Reason} at {blockingObject.Object:X}");
foreach (var owner in blockingObject.Owners)
{
FindDeadlockStartingFrom(owner, visitedThreadIds, chain);
}
chain.Pop();
}
chain.Pop();
visitedThreadIds.Remove(thread.OSThreadId);
}
19
Source : Plugin.cs
with GNU Affero General Public License v3.0
from djkaty
with GNU Affero General Public License v3.0
from djkaty
public void PreProcessBinary(Il2CppBinary binary, PluginPreProcessBinaryEventInfo data) {
// Enable surrogate properties
Binary = binary;
// We can only perform this re-ordering if we can refer to a loaded global-Metadata.dat
if (Metadata == null)
return;
// Do nothing if binary metadata appears to be valid
if (MetadataRegistration.typesCount >= MetadataRegistration.typeDefinitionsSizesCount
&& MetadataRegistration.genericMethodTableCount >= MetadataRegistration.genericInstsCount
&& CodeRegistration.reversePInvokeWrapperCount <= 0x4000
&& CodeRegistration.unresolvedVirtualCallCount <= 0x4000 // >= 22
&& CodeRegistration.interopDataCount <= 0x1000 // >= 23
&& (Image.Version > 24.1 || CodeRegistration.invokerPointersCount <= CodeRegistration.methodPointersCount))
return;
// Don't cause corruption in unsupported versions
if (Image.Version < 19 || Image.Version > 24.1)
return;
// If the section table is not available, give up and do nothing
if (!Image.TryGetSections(out var sections))
return;
// Get relevant image sections
var codeSections = sections.Where(s => s.IsExec).ToList();
var dataSections = sections.Where(s => s.IsData && !s.IsBSS).ToList();
var bssSections = sections.Where(s => s.IsBSS).ToList();
// For PE files, data sections in memory can be larger than in the image
// The unmapped portion is BSS data so create fake sections for this and shrink the existing ones
foreach (var section in dataSections) {
var virtualSize = section.VirtualEnd - section.VirtualStart;
var imageSize = section.ImageEnd - section.ImageStart;
if (imageSize < virtualSize) {
var bssEnd = section.VirtualEnd;
section.VirtualEnd = section.VirtualStart + imageSize;
bssSections.Add(new Section {
VirtualStart = section.VirtualStart + imageSize + 1,
VirtualEnd = bssEnd,
ImageStart = 0,
ImageEnd = 0,
IsExec = false,
IsData = false,
IsBSS = true,
Name = ".bss"
});
}
}
// Fetch and sanitize our pointer and count lists
var (codePtrsOrdered, codeCountLimits, codeCounts)
= preparePointerList(typeof(Il2CppCodeRegistration), binary.CodeRegistrationPointer, dataSections, true);
var (metaPtrsOrdered, metaCountLimits, metaCounts)
= preparePointerList(typeof(Il2CppMetadataRegistration), binary.MetadataRegistrationPointer, dataSections);
// Progress updater
var maxProgress = codeCounts.Sum() + metaCounts.Sum();
var currentProgress = 0;
var lastUpdate = string.Empty;
void UpdateProgress(int workDone) {
currentProgress += workDone;
var thisUpdate = $"Reconstructing obfuscated registration metadata ({currentProgress * 100 / maxProgress:F0}%)";
if (thisUpdate != lastUpdate) {
lastUpdate = thisUpdate;
PluginServices.For(this).StatusUpdate(thisUpdate);
}
}
UpdateProgress(0);
// Counts from minimal compiles
// v21 test project:
// genericMethodPointers - 0x07B5, customAttributeGenerators - 0x0747, invokerPointers - 0x04DB, methodPointers - 0x226A
// v24.1 empty Unity project:
// genericMethodPointers - 0x0C15, customAttributeGenerators - 0x0A21, invokerPointers - 0x0646, methodPointers - 0x268B
// v24.2 without Unity:
// genericMethodPointers - 0x2EC2, customAttributeGenerators - 0x15EC, invokerPointers - 0x0B65
// v21 test project:
// genericInsts - 0x0150, genericMethodTable - 0x0805, types - 0x1509, methodSpecs - 0x08D8, fieldOffsets - 0x0569, metadataUsages - 0x1370
// v24.1 empty Unity project:
// genericInsts - 0x025E, genericMethodTable - 0x0E3F, types - 0x2632, methodSpecs - 0x0FD4, fieldOffsets - 0x0839, metadataUsages - 0x1850
// v24.2 without Unity:
// genericInsts - 0x06D4, genericMethodTable - 0x31E8, types - 0x318A, methodSpecs - 0x3AD8, fieldOffsets - 0x0B3D, metadataUsages - 0x3BA8
// Some heuristic constants
// The maximum address gap in a sequential list of pointers before the sequence is considered to be 'broken'
const int MAX_SEQUENCE_GAP = 0x10000;
// The minimum number of Il2CppTypes we expect
const int MIN_TYPES = 0x1400;
// The maximum number of generic type parameters we expect for any clreplaced or method
const int MAX_GENERIC_TYPE_PARAMETERS = 32;
// The minimum number of Il2CppGenericInsts we expect
const int MIN_GENERIC_INSTANCES = 0x140;
// The maximum number of generic methods in generic clreplacedes we expect to find in a single sequence of Il2CppMethodSpec
// The highest we have seen in a production app is 3414; the next highest 2013, the next highest 1380
// 300-600 is typical
const int MAX_SEQUENTIAL_GENERIC_CLreplaced_METHODS = 5000;
// The minimum number of Il2CppMethodSpecs we expect
const int MIN_METHOD_SPECS = 0x0800;
// The minimum number of Il2CppGenericMethodFunctionsDefinitions we expect
const int MIN_GENERIC_METHOD_TABLE = 0x600;
// The minimum spread of values in an instance of Il2CppGenericMethodFunctionsDefinitions under which the threshold counter is incremented
const int MIN_GENERIC_METHOD_TABLE_SPREAD = 100;
// The maximum number of instances in a row with a spread under the minimum we expect to find in a single sequence
const int MAX_SEQUENTIAL_GENERIC_METHOD_TABLE_LOW_SPREAD_INSTANCES = 100;
// The minimum number of field offsets we expect
const int MIN_FIELD_OFFSETS = 0x400;
// The maximum value for a field offset
const int MAX_FIELD_OFFSET = 0x100000;
// The minimum and maximum proportions of inversions we expect in a non-pointer field offset list
// Example values: 0.385, 0.415, 0.468
const double MIN_FIELD_OFFSET_INVERSION = 0.3;
const double MAX_FIELD_OFFSET_INVERSION = 0.6;
// The minimum and maximum proportions of zeroes we expect in a non-pointer field offset list
// Example values: 0.116, 0.179, 0.303, 0.321, 0.385
// The main thing is to force enough zeroes to prevent it being confused with a list with no zeroes (eg. genericClreplacedes)
const double MIN_FIELD_OFFSET_ZEROES = 0.10;
const double MAX_FIELD_OFFSET_ZEROES = 0.5;
// The maximum allowed gap between two field offsets
const int MAX_FIELD_OFFSET_GAP = 0x10000;
// Things we need from Il2CppCodeRegistration
// methodPointers (<=24.1) -> list of function pointers (1st count) (non-sequential)
// genericMethodPointers -> list of function pointers (first IS zero) (2nd count) (not sequential)
// customAttributeGenerators (<27) -> list of function pointers (first MAY be zero) (2nd count) (sequential)
// invokerPointers -> list of function pointers (3rd count) (sequential)
// codeGenModules (>=24.2) -> list of Il2CppCodeGenModule* // TODO: We only support <=24.1 currently
// (interopData will probably have 6 sequential pointers since Il2CppInteropData starts with 5 function pointers and a GUID)
// Let's see how many valid pointers and sequential valid pointers we actually find at each address
// Scan each pointer address for valid list of function pointers and sort into size order
// Consider the sequence to be broken if there is a gap over a certain threshold
var fnPtrs = new SortedDictionary<ulong, int>();
var seqFnPtrs = new SortedDictionary<ulong, int>();
for (var i = 0; i < codePtrsOrdered.Count; i++) {
// Non-sequential valid pointers
var ptrs = Image.ReadMappedArray<ulong>(codePtrsOrdered[i], codeCountLimits[i]);
var foundCount = ptrs.TakeWhile(p => codeSections.Any(s => p >= s.VirtualStart && p <= s.VirtualEnd || p == 0)).Count();
// Prune count of trailing zero pointers
while (foundCount > 0 && ptrs[foundCount - 1] == 0ul)
foundCount--;
fnPtrs.Add(codePtrsOrdered[i], foundCount);
// Binaries compiled with MSVC (generally PE files) use /OPT:ICF by default (enable ICF) so this won't work.
// For these binaries, we'll use a different selection strategy below
if (Image is PEReader)
continue;
// Sequential valid pointers (a subset of non-sequential valid pointers)
if (foundCount > 0) {
foundCount = ptrs.Take(foundCount)
.Zip(ptrs.Take(foundCount).Skip(1), (a, b) => (a, b))
.TakeWhile(t => ((long) t.b - (long) t.a >= 0 || t.b == 0)
&& ((long) t.b - (long) t.a < MAX_SEQUENCE_GAP || t.a == 0)
// Disallow two zero pointers in a row
&& (t.a != 0 || t.b != 0))
.Count() + 1;
// Prune count of trailing zero pointers
while (foundCount > 0 && ptrs[foundCount - 1] == 0ul)
foundCount--;
}
seqFnPtrs.Add(codePtrsOrdered[i], foundCount);
UpdateProgress(foundCount);
}
KeyValuePair<ulong, int> methodPointers, genericMethodPointers, customAttributeGenerators, invokerPointers;
// Solution without ICF
if (!(Image is PEReader)) {
// The two largest sequential groups are customAttributeGenerators and invokerPointers
var seqLongest = seqFnPtrs.OrderByDescending(kv => kv.Value).Take(2).ToList();
(customAttributeGenerators, invokerPointers) = (seqLongest[0], seqLongest[1]);
// For >=27, customAttributeGenerators is zero and so the largest group is invokerPointers
if (Image.Version >= 27) {
invokerPointers = customAttributeGenerators;
customAttributeGenerators = new KeyValuePair<ulong, int>(0ul, 0);
}
// After removing these from the non-sequential list, the largest groups are methodPointers and genericMethodPointers
var longest = fnPtrs.Except(seqLongest).OrderByDescending(kv => kv.Value).Take(2).ToList();
(methodPointers, genericMethodPointers) = (longest[0], longest[1]);
// For >=24.2, methodPointers is zero and so the largest group is genericMethodPointers
if (Image.Version >= 24.2) {
genericMethodPointers = methodPointers;
methodPointers = new KeyValuePair<ulong, int>(0ul, 0);
}
// Prune genericMethodPointers at 2nd zero (first pointer is always zero)
var gmPtr = Image.ReadMappedArray<ulong>(genericMethodPointers.Key, genericMethodPointers.Value);
var gmZero = Array.IndexOf(gmPtr, 0ul, 1);
if (gmZero != -1)
genericMethodPointers = new KeyValuePair<ulong, int>(genericMethodPointers.Key, gmZero);
}
// Solution with ICF
else {
// Take and remove the first item and replacedume it's methodPointers for <=24.1, otherwise set to zero
var orderedPtrs = fnPtrs.OrderByDescending(kv => kv.Value).ToList();
if (Image.Version <= 24.1) {
methodPointers = orderedPtrs[0];
orderedPtrs.RemoveAt(0);
} else
methodPointers = new KeyValuePair<ulong, int>(0ul, 0);
// replacedume this order is right most of the time
// TODO: generic and custom attribute might be the wrong way round (eg. #102)
(genericMethodPointers, customAttributeGenerators, invokerPointers) = (orderedPtrs[0], orderedPtrs[1], orderedPtrs[2]);
// customAttributeGenerators is removed in metadata >=27
if (Image.Version >= 27) {
invokerPointers = customAttributeGenerators;
customAttributeGenerators = new KeyValuePair<ulong, int>(0ul, 0);
}
}
#region Debugging validation checks
#if false
// Used on non-obfuscated binaries during development to confirm the output is correct
if (methodPointers.Key != CodeRegistration.pmethodPointers)
throw new Exception("Method Pointers incorrect");
if (invokerPointers.Key != CodeRegistration.invokerPointers)
throw new Exception("Invoker Pointers incorrect");
if (customAttributeGenerators.Key != CodeRegistration.customAttributeGenerators)
throw new Exception("Custom attribute generators incorrect");
if (genericMethodPointers.Key != CodeRegistration.genericMethodPointers)
throw new Exception("Generic method pointers incorrect");
if (methodPointers.Value != (int) CodeRegistration.methodPointersCount)
throw new Exception("Count of Method Pointers incorrect");
if (invokerPointers.Value != (int) CodeRegistration.invokerPointersCount)
throw new Exception("Count of Invoker Pointers incorrect");
if (customAttributeGenerators.Value != (int) CodeRegistration.customAttributeCount)
throw new Exception("Count of Custom attribute generators incorrect");
if (genericMethodPointers.Value != (int) CodeRegistration.genericMethodPointersCount)
throw new Exception("Count of Generic method pointers incorrect");
#endif
#endregion
// Things we need from Il2CppMetadataRegistration
// genericInsts -> list of Il2CppGenericInst* (argc is count of Il2CppType* at data pointer argv; datapoint = GenericParameterIndex)
// genericMethodTable -> list of Il2CppGenericMethodFunctionsDefinitions (genericMethodIndex, methodIndex, invokerIndex)
// types -> list of Il2CppType*
// methodSpecs -> list of Il2CppMethodSpec
// methodReferences (<=16) -> list of uint (ignored, we don't support <=16 here)
// fieldOffsets (fieldOffsetsArePointers) -> either a list of data pointers (some zero, some VAs not mappable) to list of uints, or a list of uints
// metadataUsages (>=19, <27) -> list of unmappable data pointers
// Read in all the required data once since we'll be using nested loops
var metaPtrData = new List<(ulong, int, ulong[], int)>();
for (var i = 0; i < metaPtrsOrdered.Count; i++) {
// Pointers in this list
var ptrs = Image.ReadMappedArray<ulong>(metaPtrsOrdered[i], metaCountLimits[i] / (Image.Bits / 8));
// First set of pointers that point to a data section virtual address
var foundDataPtrsCount = ptrs.TakeWhile(p => dataSections.Any(s => p >= s.VirtualStart && p <= s.VirtualEnd)).Count();
// First set of pointers that can be mapped anywhere into the image
var foundImageMappablePtrsCount = ptrs.TakeWhile(p => Image.TryMapVATR(p, out _)).Count();
#if DEBUG
// First set of pointers that can be mapped into a data section in the image
var mappableDataPtrs = ptrs.Take(foundImageMappablePtrsCount)
.TakeWhile(p => dataSections.Any(s => Image.MapVATR(p) >= s.ImageStart && Image.MapVATR(p) <= s.ImageEnd))
.ToArray();
var foundNonBSSDataPtrsCount = mappableDataPtrs.Length;
if (foundDataPtrsCount != foundNonBSSDataPtrsCount)
throw new Exception($"Pointer count mismatch: {foundDataPtrsCount:x8} / {foundNonBSSDataPtrsCount:x8}");
#endif
metaPtrData.Add((metaPtrsOrdered[i], metaCountLimits[i], ptrs, foundDataPtrsCount));
}
// Items we need to search for
var types = (ptr: 0ul, count: -1);
var genericInsts = (ptr: 0ul, count: -1);
var methodSpecs = (ptr: 0ul, count: -1);
var genericMethodTable = (ptr: 0ul, count: -1);
var metadataUsages = (ptr: 0ul, count: -1);
var fieldOffsets = (ptr: 0ul, count: -1);
var NOT_FOUND = (ptr: 0xfffffffful, count: -1);
// Intermediary items
var typesPtrs = new List<ulong>();
Il2CppMethodSpec[] methodSpec = null;
// IL2CPP doesn't calculate metadataUsagesCount correctly so we do it here
// Adapted from Il2CppInspector.buildMetadataUsages()
var usages = new HashSet<uint>();
// Only on supported metadata versions (>=19, <27)
if (Metadata.MetadataUsageLists != null)
foreach (var metadataUsageList in Metadata.MetadataUsageLists)
for (var i = 0; i < metadataUsageList.count; i++)
usages.Add(Metadata.MetadataUsagePairs[metadataUsageList.start + i].destinationindex);
// Determine what each pointer is
// We need to do this in a certain order because validating some items relies on earlier items
while (metaPtrData.Any()) {
ref var foundItem = ref NOT_FOUND;
(ulong ptr, int count) foundData = (0ul, -1);
// We loop repeatedly through every set of data looking for our next target item,
// remove the matching set from the list and then repeat the outer while loop
// until there is nothing left to find
foreach (var (ptr, limit, ptrs, dataPtrsCount) in metaPtrData) {
foundData = (ptr, 0);
// Test for Il2CppType**
// ---------------------
if (types.count == -1) {
// We don't ever expect there to be less than MIN_TYPES types
if (dataPtrsCount >= MIN_TYPES) {
var tesreplacedems = Image.ReadMappedObjectPointerArray<Il2CppType>(ptr, dataPtrsCount);
foreach (var item in tesreplacedems) {
// TODO: v27 will fail this because of the bit shifting in Il2CppType.bits
if (item.num_mods != 0)
break;
if (!Enum.IsDefined(typeof(Il2CppTypeEnum), item.type))
break;
if (item.type == Il2CppTypeEnum.IL2CPP_TYPE_END)
break;
// Test datapoint
if (item.type switch {
var t when (t is Il2CppTypeEnum.IL2CPP_TYPE_VALUETYPE || t is Il2CppTypeEnum.IL2CPP_TYPE_CLreplaced)
&& item.datapoint >= (ulong) Metadata.Types.Length => false,
var t when (t is Il2CppTypeEnum.IL2CPP_TYPE_VAR || t is Il2CppTypeEnum.IL2CPP_TYPE_MVAR)
&& item.datapoint >= (ulong) Metadata.GenericParameters.Length => false,
var t when (t is Il2CppTypeEnum.IL2CPP_TYPE_PTR || t is Il2CppTypeEnum.IL2CPP_TYPE_SZARRAY)
&& !ptrs.Take(dataPtrsCount).Contains(item.datapoint) => false,
// Untested cases, we could add more here (IL2CPP_TYPE_ARRAY, IL2CPP_TYPE_GENERICINST)
_ => true
})
foundData.count++;
else
break;
}
if (foundData.count >= MIN_TYPES) {
foundItem = ref types;
typesPtrs = ptrs.ToList();
break;
}
}
}
// Test for Il2CppGenericInst**
// ----------------------------
else if (genericInsts.count == -1) {
if (dataPtrsCount >= MIN_GENERIC_INSTANCES) {
var tesreplacedems = Image.ReadMappedObjectPointerArray<Il2CppGenericInst>(ptr, dataPtrsCount);
foreach (var item in tesreplacedems) {
// Let's pray no generic type has more than this many type parameters
if (item.type_argc > MAX_GENERIC_TYPE_PARAMETERS)
break;
// All the generic type paramters must be in the total list of types,
// ie. typePtrs must be a subset of typesData.Keys
try {
var typePtrs = Image.ReadMappedArray<ulong>(item.type_argv, (int) item.type_argc);
if (typePtrs.Any(p => !typePtrs.Contains(p)))
break;
// Pointers were invalid
}
catch (InvalidOperationException) {
break;
}
foundData.count++;
}
if (foundData.count >= MIN_GENERIC_INSTANCES) {
foundItem = ref genericInsts;
break;
}
}
}
// Test for Il2CppMethodSpec*
// --------------------------
else if (methodSpecs.count == -1) {
var max = limit / Metadata.Sizeof(typeof(Il2CppMethodSpec));
if (max >= MIN_METHOD_SPECS) {
var tesreplacedems = Image.ReadMappedArray<Il2CppMethodSpec>(ptr, max);
var nonNegativePairs = 0;
foreach (var item in tesreplacedems) {
if (item.methodDefinitionIndex < 0 || item.methodDefinitionIndex >= Metadata.Methods.Length)
break;
if (item.clreplacedIndexIndex < -1 || item.clreplacedIndexIndex >= genericInsts.count)
break;
if (item.methodIndexIndex < -1 || item.methodIndexIndex >= genericInsts.count)
break;
// Non-negative pairs shouldn't appear in large groups
nonNegativePairs = item.clreplacedIndexIndex != -1 && item.methodIndexIndex != -1 ? nonNegativePairs + 1 : 0;
if (nonNegativePairs > MAX_SEQUENTIAL_GENERIC_CLreplaced_METHODS)
break;
foundData.count++;
}
// replacedumes last methods are not generic methods in generic clreplacedes
foundData.count -= nonNegativePairs;
if (foundData.count >= MIN_METHOD_SPECS) {
foundItem = ref methodSpecs;
methodSpec = tesreplacedems;
break;
}
}
}
// Test for Il2CppGenericMethodFunctionsDefinitions*
// -------------------------------------------------
else if (genericMethodTable.count == -1) {
var max = limit / Metadata.Sizeof(typeof(Il2CppGenericMethodFunctionsDefinitions));
if (max >= MIN_GENERIC_METHOD_TABLE) {
var tesreplacedems = Image.ReadMappedArray<Il2CppGenericMethodFunctionsDefinitions>(ptr, max);
var lowSpreadCount = 0;
foreach (var item in tesreplacedems) {
if (item.genericMethodIndex < 0 || item.genericMethodIndex >= methodSpecs.count)
break;
if (item.indices.methodIndex < 0 || item.indices.methodIndex >= genericMethodPointers.Value)
break;
if (item.indices.invokerIndex < 0 || item.indices.invokerIndex >= invokerPointers.Value)
break;
// methodIndex is an index into the method pointer table
// For generic type definitions, there is no concrete function so this must be 0xffffffff
// TODO: For >=24.2, we need to use the method token to look up the value in an Il2CppCodeGenModule, not currently implemented
if (Image.Version <= 24.1)
if (Metadata.Methods[methodSpec[item.genericMethodIndex].methodDefinitionIndex].methodIndex != -1)
break;
foundData.count++;
// Instances where all the values are clustered should be rare
var spread = Math.Max(Math.Max(item.indices.methodIndex, item.indices.invokerIndex), item.genericMethodIndex)
- Math.Min(Math.Min(item.indices.methodIndex, item.indices.invokerIndex), item.genericMethodIndex);
lowSpreadCount = spread < MIN_GENERIC_METHOD_TABLE_SPREAD ? lowSpreadCount + 1 : 0;
if (lowSpreadCount > MAX_SEQUENTIAL_GENERIC_METHOD_TABLE_LOW_SPREAD_INSTANCES)
break;
}
// replacedumes the last instances don't have clustered values
foundData.count -= lowSpreadCount;
if (foundData.count >= MIN_GENERIC_METHOD_TABLE) {
foundItem = ref genericMethodTable;
break;
}
}
}
// Test for metadata usages
// ------------------------
else if (metadataUsages.count == -1) {
// No metadata usages for these versions
if (Image.Version < 19 || Image.Version >= 27) {
foundData.ptr = 0ul;
foundItem = ref metadataUsages;
break;
}
// Metadata usages always map to BSS sections (dataPtrsCount == 0)
// For images dumped from memory, metadata usages must always map to data sections
if ((dataPtrsCount == 0 && limit / (Image.Bits / 8) >= usages.Count)
|| dataPtrsCount >= usages.Count) {
// No null pointers allowed (this test only applies to non-dumped images)
if (ptrs.Take(usages.Count).All(p => p != 0ul)) {
// For normal images, all the pointers must map to a BSS section
// For PE files this relies on our section modding above
// For dumped images, BSS sections are also data sections so we can use the same test
var bssMappableCount = ptrs.Take(usages.Count).Count(p => bssSections.Any(s => p >= s.VirtualStart && p <= s.VirtualEnd));
foundData.count = bssMappableCount;
foundItem = ref metadataUsages;
break;
}
}
}
// Test for field offsets
// ----------------------
else if (fieldOffsets.count == -1) {
// This could be a list of pointers to locally incrementing sequences of uints,
// or it could be a sequence of uints
// Some uints may be zero, but must otherwise never be less than the minimum heap offset of the first parameter
// for the binary's function calling convention, and never greater than the maximum heap offset of the last parameter
// Try as sequence of uints
if (Metadata.Version <= 21) {
var max = limit / sizeof(uint);
if (max >= MIN_FIELD_OFFSETS) {
var tesreplacedems = Image.ReadMappedArray<uint>(ptr, max);
var previousItem = 0u;
var inversions = 0;
var zeroes = 0;
foreach (var item in tesreplacedems) {
if (item > MAX_FIELD_OFFSET && item != 0xffffffff)
break;
if (item > previousItem + MAX_FIELD_OFFSET_GAP && item != 0xffffffff)
break;
// Count zeroes and inversions (equality counts as inversion here since two arguments can't share a heap offset)
if (item <= previousItem)
inversions++;
if (item == 0)
zeroes++;
previousItem = item;
foundData.count++;
}
if (foundData.count >= MIN_FIELD_OFFSETS) {
var inversionsPc = (double) inversions / foundData.count;
var zeroesPc = (double) zeroes / foundData.count;
if (inversionsPc >= MIN_FIELD_OFFSET_INVERSION && inversionsPc <= MAX_FIELD_OFFSET_INVERSION
&& zeroesPc >= MIN_FIELD_OFFSET_ZEROES && zeroesPc <= MAX_FIELD_OFFSET_ZEROES) {
foundItem = ref fieldOffsets;
break;
}
}
}
}
// Try as a sequence of pointers to sets of uints
if (Metadata.Version >= 21) {
foundData.count = 0;
var max = limit / (Image.Bits / 8);
if (max >= MIN_FIELD_OFFSETS) {
var tesreplacedems = Image.ReadMappedArray<ulong>(ptr, max);
var zeroes = 0;
foreach (var item in tesreplacedems) {
// Every pointer must either be zero or mappable into a data or BSS section
if (item != 0ul && !dataSections.Any(s => item >= s.VirtualStart && item < s.VirtualEnd)
&& !bssSections.Any(s => item >= s.VirtualStart && item < s.VirtualEnd))
break;
// Count zeroes
if (item == 0ul)
zeroes++;
// Every valid pointer must point to a series of incrementing offsets until an inversion or a large gap
else if (dataSections.Any(s => item >= s.VirtualStart && item < s.VirtualEnd)) {
Image.Position = Image.MapVATR(item);
var previous = 0u;
var offset = 0u;
var valid = true;
while (offset != 0xffffffff && offset > previous && valid) {
previous = offset;
offset = Image.ReadUInt32();
// Consider a large gap as the end of the sequence
if (offset > previous + MAX_FIELD_OFFSET_GAP && offset != 0xffffffff)
break;
// A few offsets seem to have the top bit set for some reason
if (offset >= previous && (offset & 0x7fffffff) > MAX_FIELD_OFFSET && offset != 0xffffffff)
valid = false;
}
if (!valid)
break;
}
foundData.count++;
}
if (foundData.count >= MIN_FIELD_OFFSETS) {
var zeroesPc = (double) zeroes / foundData.count;
if (zeroesPc >= MIN_FIELD_OFFSET_ZEROES && zeroesPc <= MAX_FIELD_OFFSET_ZEROES) {
foundItem = ref fieldOffsets;
break;
}
}
}
}
}
foundData = (0ul, -1);
}
// We didn't find anything - break to avoid an infinite loop
if (foundItem == NOT_FOUND)
break;
// Remove pointer from list of remaining pointers to test
metaPtrData = metaPtrData.Where(m => foundData.ptr != m.Item1).ToList();
// Select the highest count in the original data that is lower or equal to our found count
// Skip items not implemented by the specific metadata version we are replacedyzing (ptr == 0, count == 0)
// Skip metadataUsages because it is calculated incorrectly by IL2CPP and the count is wrong
if (foundData.count > 0 && foundData.count != usages.Count) {
// Aggregate uses the first value for 'next' as the seed for 'nearest' unless we specify a starting seed
foundData.count = metaCounts.Aggregate(0, (nearest, next) => next - foundData.count > nearest - foundData.count && next - foundData.count <= 0 ? next : nearest);
metaCounts = metaCounts.Where(c => c != foundData.count).ToList();
}
// Set item via ref
foundItem = foundData;
// If we just found the Il2CppTypes data, prune the pointer list to the correct length
if (foundItem == types && typesPtrs.Count != foundData.count)
typesPtrs = typesPtrs.Take(foundData.count).ToList();
UpdateProgress(foundData.count);
}
19
Source : ClusteringTests.cs
with MIT License
from dotnet
with MIT License
from dotnet
[Fact]
public void PredictClusters()
{
int n = 1000;
int k = 4;
var rand = new Random(1);
var clusters = new ClusteringData[k];
var data = new ClusteringData[n];
for (int i = 0; i < k; i++)
{
//pick clusters as points on circle with angle to axis X equal to 360*i/k
clusters[i] = new ClusteringData { Points = new float[2] { (float)Math.Cos(Math.PI * i * 2 / k), (float)Math.Sin(Math.PI * i * 2 / k) } };
}
// create data points by randomly picking cluster and shifting point slightly away from it.
for (int i = 0; i < n; i++)
{
var index = rand.Next(0, k);
var shift = (rand.NextDouble() - 0.5) / 10;
data[i] = new ClusteringData
{
Points = new float[2]
{
(float)(clusters[index].Points[0] + shift),
(float)(clusters[index].Points[1] + shift)
}
};
}
var mlContext = new MLContext(seed: 1);
// Turn the data into the ML.NET data view.
// We can use CreateDataView or ReadFromEnumerable, depending on whether 'churnData' is an IList,
// or merely an IEnumerable.
var trainData = mlContext.Data.LoadFromEnumerable(data);
var testData = mlContext.Data.LoadFromEnumerable(clusters);
// Create Estimator
var pipe = mlContext.Clustering.Trainers.KMeans("Features", numberOfClusters: k);
// Train the pipeline
var trainedModel = pipe.Fit(trainData);
// Validate that initial points we pick up as centers of cluster during data generation belong to different clusters.
var labels = new HashSet<uint>();
var predictFunction = mlContext.Model.CreatePredictionEngine<ClusteringData, ClusteringPrediction>(trainedModel);
for (int i = 0; i < k; i++)
{
var scores = predictFunction.Predict(clusters[i]);
replacedert.True(!labels.Contains(scores.SelectedClusterId));
labels.Add(scores.SelectedClusterId);
}
// Evaluate the trained pipeline
var predicted = trainedModel.Transform(testData);
var metrics = mlContext.Clustering.Evaluate(predicted);
//Label is not specified, so NMI would be equal to NaN
replacedert.Equal(metrics.NormalizedMutualInformation, double.NaN);
//Calculate dbi is false by default so Dbi would be 0
replacedert.Equal(metrics.DaviesBouldinIndex, (double)0.0);
replacedert.Equal(metrics.AverageDistance, (double)0.0, 5);
}
19
Source : MpqArchive.cs
with MIT License
from Drake53
with MIT License
from Drake53
public int AddFileName(string fileName)
{
if (fileName is null)
{
throw new ArgumentNullException(nameof(fileName));
}
var hashes = GetHashEntries(fileName);
var fileIndicesFound = new HashSet<uint>();
foreach (var hash in hashes)
{
if (fileIndicesFound.Add(hash.BlockIndex))
{
_blockTable[hash.BlockIndex].FileName = fileName;
}
}
return fileIndicesFound.Count;
}
19
Source : GhostNetRaceManager.cs
with MIT License
from EverestAPI
with MIT License
from EverestAPI
public void Start() {
if (Areas.Count == 0)
throw new Exception("Can't start a race with no areas!");
if (Hreplacedtarted)
throw new Exception("The race has already started!");
Hreplacedtarted = true;
Send(null,
@"The race will start soon!
You will be sent to the menu. Please wait there.
The server will teleport you when the race starts."
);
Thread.Sleep(5000);
lock (Players) {
foreach (uint playerID in Players) {
WaitingForStart.Add(playerID);
Move(playerID, -1);
}
}
while (WaitingForStart.Count > 0)
Thread.Sleep(0);
Send(null, "Starting the race in 3...");
Thread.Sleep(1000);
Send(null, "2...");
Thread.Sleep(1000);
Send(null, "1...");
Thread.Sleep(1000);
Time.Start();
lock (Players) {
// Note: Even though we're locked, Players can change if the local client (running in same thread!) doesn't have the map.
foreach (uint playerID in new List<uint>(Players)) {
Progress(playerID);
}
}
Send(null, "GO!");
}
19
Source : DispelManager.cs
with GNU General Public License v3.0
from Exmortem
with GNU General Public License v3.0
from Exmortem
public static void Reset()
{
if (!Core.Me.IsHealer() && Core.Me.CurrentJob != ClreplacedJobType.Bard)
return;
if (Dispelling.Instance == null)
return;
if (Dispelling.Instance.StatusList == null || Dispelling.Instance.StatusList.Count == 0)
return;
HighPriorityDispels.Clear();
NormalDispels.Clear();
foreach (var dispel in Dispelling.Instance.StatusList)
{
// ReSharper disable once SwitchStatementMissingSomeCases
switch (RotationManager.CurrentRotation)
{
case ClreplacedJobType.Conjurer: if (dispel.WhiteMage) { AddDispel(dispel.Id, dispel.HighPriority); } continue;
case ClreplacedJobType.Bard: if (dispel.Bard) { AddDispel(dispel.Id, dispel.HighPriority); } continue;
case ClreplacedJobType.WhiteMage: if (dispel.WhiteMage) { AddDispel(dispel.Id, dispel.HighPriority); } continue;
case ClreplacedJobType.Scholar: if (dispel.Scholar) { AddDispel(dispel.Id, dispel.HighPriority); } continue;
case ClreplacedJobType.Astrologian: if (dispel.Astrologian) { AddDispel(dispel.Id, dispel.HighPriority); } continue;
default: continue;
}
}
Logger.Write("Dispel List Reset");
void AddDispel(uint dispel, bool highPriority)
{
if (highPriority) { HighPriorityDispels.Add(dispel); } else { NormalDispels.Add(dispel); }
}
}
19
Source : InterruptsAndStunsManager.cs
with GNU General Public License v3.0
from Exmortem
with GNU General Public License v3.0
from Exmortem
public static void Reset()
{
if (InterruptsAndStuns.Instance == null)
return;
if (InterruptsAndStuns.Instance.ActionList == null || InterruptsAndStuns.Instance.ActionList.Count == 0)
return;
HighPriorityInterrupts.Clear();
NormalInterrupts.Clear();
HighPriorityStuns.Clear();
NormalStuns.Clear();
foreach (var action in InterruptsAndStuns.Instance.ActionList)
{
// ReSharper disable once SwitchStatementMissingSomeCases
switch (RotationManager.CurrentRotation)
{
case ClreplacedJobType.Bard:
if (action.Bard) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
case ClreplacedJobType.Machinist:
if (action.Machinist) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
case ClreplacedJobType.Scholar:
if (action.Scholar) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
case ClreplacedJobType.Dragoon:
if (action.Dragoon) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
case ClreplacedJobType.Lancer:
if (action.Dragoon) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
case ClreplacedJobType.Paladin:
if (action.Paladin) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
case ClreplacedJobType.Warrior:
if (action.Warrior) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
case ClreplacedJobType.DarkKnight:
if (action.DarkKnight) { AddAction(action.Id, action.Stun, action.Interrupt, action.HighPriority); }
continue;
default: continue;
}
}
Logger.Write("Interrupts And Stuns List Reset");
void AddAction(uint action, bool stun, bool interrupt, bool highPriority)
{
if (stun)
{
if (highPriority) { HighPriorityStuns.Add(action); } else { NormalStuns.Add(action); }
}
if (!interrupt)
return;
if (highPriority) { HighPriorityInterrupts.Add(action); } else { NormalInterrupts.Add(action); }
}
}
See More Examples