Here are the examples of the csharp api System.Collections.Generic.HashSet.UnionWith(System.Collections.Generic.IEnumerable) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
668 Examples
19
Source : TypedDurableActivityCallerGenerator.cs
with MIT License
from Azure
with MIT License
from Azure
private CompilationUnitSyntax Generate()
{
var modifiers = AsModifierList(SyntaxKind.PublicKeyword, SyntaxKind.PartialKeyword);
var baseTypes = AsBaseList(Names.ITypedDurableActivityCaller);
var memberList = new List<MemberDeclarationSyntax>();
memberList.Add(AsField(Names.IDurableOrchestrationContext, ContextFieldName));
memberList.Add(GenerateConstructor());
var requiredNamespaces = new HashSet<string>(requiredUsings);
foreach (var function in functions)
{
if (function.Kind != DurableFunctionKind.Activity)
continue;
memberList.Add(GenerateCallMethodWithRetry(function));
memberList.Add(GenerateCallMethodWithoutRetry(function));
requiredNamespaces.UnionWith(function.RequiredNamespaces);
}
var members = SyntaxFactory.List(memberList);
var @clreplaced = SyntaxFactory.ClreplacedDeclaration(Names.TypedDurableActivityCaller)
.WithModifiers(modifiers)
.WithBaseList(baseTypes)
.WithMembers(members);
var @namespace = GenerateNamespace().AddMembers(@clreplaced);
var usings = AsUsings(requiredNamespaces);
return SyntaxFactory.CompilationUnit().AddUsings(usings).AddMembers(@namespace).NormalizeWhitespace();
}
19
Source : TypedDurableOrchestrationCallerGenerator.cs
with MIT License
from Azure
with MIT License
from Azure
private CompilationUnitSyntax Generate()
{
var modifiers = AsModifierList(SyntaxKind.PublicKeyword, SyntaxKind.PartialKeyword);
var baseTypes = AsBaseList(Names.ITypedDurableOrchestrationCaller);
var memberList = new List<MemberDeclarationSyntax>();
memberList.Add(AsField(Names.IDurableOrchestrationContext, ContextFieldName));
memberList.Add(GenerateConstructor());
var requiredNamespaces = new HashSet<string>(requiredUsings);
foreach (var function in functions)
{
if (function.Kind != DurableFunctionKind.Orchestration)
continue;
memberList.Add(GenerateCallMethodWithRetry(function));
memberList.Add(GenerateCallMethodWithoutRetry(function));
memberList.Add(GenerateStartMethod(function));
requiredNamespaces.UnionWith(function.RequiredNamespaces);
}
var members = SyntaxFactory.List(memberList);
var @clreplaced = SyntaxFactory.ClreplacedDeclaration(Names.TypedDurableOrchestrationCaller)
.WithModifiers(modifiers)
.WithBaseList(baseTypes)
.WithMembers(members);
var @namespace = GenerateNamespace().AddMembers(@clreplaced);
var usings = AsUsings(requiredNamespaces);
return SyntaxFactory.CompilationUnit().AddUsings(usings).AddMembers(@namespace).NormalizeWhitespace();
}
19
Source : TypedDurableOrchestrationStarterGenerator.cs
with MIT License
from Azure
with MIT License
from Azure
private CompilationUnitSyntax Generate()
{
var modifiers = AsModifierList(SyntaxKind.PublicKeyword, SyntaxKind.PartialKeyword);
var baseTypes = AsBaseList(Names.ITypedDurableOrchestrationStarter);
var memberList = new List<MemberDeclarationSyntax>();
memberList.Add(AsField(Names.IDurableClient, ClientFieldName));
memberList.Add(GenerateConstructor());
var requiredNamespaces = new HashSet<string>(requiredUsings);
foreach (var function in functions)
{
if (function.Kind != DurableFunctionKind.Orchestration)
continue;
memberList.Add(GenerateStartMethod(function));
requiredNamespaces.UnionWith(function.RequiredNamespaces);
}
var members = SyntaxFactory.List(memberList);
var @clreplaced = SyntaxFactory.ClreplacedDeclaration(Names.TypedDurableOrchestrationStarter)
.WithModifiers(modifiers)
.WithBaseList(baseTypes)
.WithMembers(members);
var @namespace = GenerateNamespace().AddMembers(@clreplaced);
var usings = AsUsings(requiredNamespaces);
return SyntaxFactory.CompilationUnit().AddUsings(usings).AddMembers(@namespace).NormalizeWhitespace();
}
19
Source : DurableFunction.cs
with MIT License
from Azure
with MIT License
from Azure
public static bool TryParse(SemanticModel model, MethodDeclarationSyntax method, out DurableFunction function)
{
function = null;
if (!SyntaxNodeUtility.TryGetFunctionName(model, method, out string name))
return false;
if (!SyntaxNodeUtility.TryGetFunctionKind(method, out DurableFunctionKind kind))
return false;
if (!SyntaxNodeUtility.TryGetReturnType(method, out TypeSyntax returnType))
return false;
if (!SyntaxNodeUtility.TryGetParameters(model, method, out List<TypedParameter> parameters))
return false;
if (!SyntaxNodeUtility.TryGetQualifiedTypeName(model, method, out string fullTypeName))
return false;
var usedTypes = new List<TypeSyntax>();
usedTypes.Add(returnType);
usedTypes.AddRange(parameters.Select(p => p.Type));
if (!SyntaxNodeUtility.TryGetRequiredNamespaces(model, usedTypes, out HashSet<string> requiredNamespaces))
return false;
requiredNamespaces.UnionWith(GetRequiredGlobalNamespaces());
function = new DurableFunction(fullTypeName, name, kind, parameters, returnType, requiredNamespaces);
return true;
}
19
Source : HealthRestartPlanner.cs
with MIT License
from Azure
with MIT License
from Azure
public async Task<Plan> PlanAsync(
ModuleSet desired,
ModuleSet current,
IRuntimeInfo runtimeInfo,
IImmutableDictionary<string, IModuleIdenreplacedy> moduleIdenreplacedies)
{
Events.LogDesired(desired);
Events.LogCurrent(current);
List<ICommand> commands = new List<ICommand>();
// Create a grouping of desired and current modules based on their priority.
// We want to process all the modules in the deployment (desired modules) and also include the modules
// that are not specified in the deployment but are currently running on the device. This is so that
// their processing is done in the right priority order.
ILookup<uint, KeyValuePair<string, IModule>> desiredPriorityGroups = desired.Modules.ToLookup(x => x.Value.StartupOrder);
ILookup<uint, KeyValuePair<string, IModule>> currentPriorityGroups = current.Modules.ToLookup(x => x.Value.StartupOrder);
ImmutableSortedSet<uint> orderedPriorities = desiredPriorityGroups.Select(x => x.Key).Union(currentPriorityGroups.Select(x => x.Key)).ToImmutableSortedSet();
var processedDesiredMatchingCurrentModules = new HashSet<string>();
foreach (uint priority in orderedPriorities)
{
// The desired set is all the desired modules that have the priority of the current priority group being evaluated.
ModuleSet priorityBasedDesiredSet = ModuleSet.Create(desiredPriorityGroups[priority].Select(x => x.Value).ToArray());
// The current set is:
// - All the current modules that correspond to the desired modules present in the current priority group.
// - All the current modules that have the priority of the current priority group being evaluated which were not specified in the desired deployment config
// -and- have not already been processed yet.
// These are included so that they can be stopped and removed in the right priority order.
IEnumerable<KeyValuePair<string, IModule>> desiredMatchingCurrentModules = current.Modules.Where(x => priorityBasedDesiredSet.Modules.ContainsKey(x.Key));
ModuleSet priorityBasedCurrentSet = ModuleSet.Create(
desiredMatchingCurrentModules
.Union(currentPriorityGroups[priority].Where(x => !processedDesiredMatchingCurrentModules.Contains(x.Key)))
.Select(y => y.Value)
.ToArray());
processedDesiredMatchingCurrentModules.UnionWith(desiredMatchingCurrentModules.Select(x => x.Key));
commands.AddRange(await this.ProcessDesiredAndCurrentSets(priorityBasedDesiredSet, priorityBasedCurrentSet, runtimeInfo, moduleIdenreplacedies));
}
Events.PlanCreated(commands);
return new Plan(commands);
}
19
Source : RestartPlanner.cs
with MIT License
from Azure
with MIT License
from Azure
async Task<Plan> CreatePlan(ModuleSet desired, ModuleSet current, IRuntimeInfo runtimeInfo, IImmutableDictionary<string, IModuleIdenreplacedy> moduleIdenreplacedies)
{
var commands = new List<ICommand>();
// Create a grouping of desired and current modules based on their priority.
// We want to process all the modules in the deployment (desired modules) and also include the modules
// that are not specified in the deployment but are currently running on the device. This is so that
// their processing is done in the right priority order.
ILookup<uint, KeyValuePair<string, IModule>> desiredPriorityGroups = desired.Modules.ToLookup(x => x.Value.StartupOrder);
ILookup<uint, KeyValuePair<string, IModule>> currentPriorityGroups = current.Modules.ToLookup(x => x.Value.StartupOrder);
ImmutableSortedSet<uint> orderedPriorities = desiredPriorityGroups.Select(x => x.Key).Union(currentPriorityGroups.Select(x => x.Key)).ToImmutableSortedSet();
var processedDesiredMatchingCurrentModules = new HashSet<string>();
foreach (uint priority in orderedPriorities)
{
// The desired set is all the desired modules that have the priority of the current priority group being evaluated.
ModuleSet priorityBasedDesiredSet = ModuleSet.Create(desiredPriorityGroups[priority].Select(x => x.Value).ToArray());
// The current set is:
// - All the current modules that correspond to the desired modules present in the current priority group.
// - All the current modules that have the priority of the current priority group being evaluated which were not specified in the desired deployment config
// -and- have not already been processed yet.
// These are included so that they can be stopped and removed in the right priority order.
IEnumerable<KeyValuePair<string, IModule>> desiredMatchingCurrentModules = current.Modules.Where(x => priorityBasedDesiredSet.Modules.ContainsKey(x.Key));
ModuleSet priorityBasedCurrentSet = ModuleSet.Create(
desiredMatchingCurrentModules
.Union(currentPriorityGroups[priority].Where(x => !processedDesiredMatchingCurrentModules.Contains(x.Key)))
.Select(y => y.Value)
.ToArray());
processedDesiredMatchingCurrentModules.UnionWith(desiredMatchingCurrentModules.Select(x => x.Key));
commands.AddRange(await this.ProcessDesiredAndCurrentSets(priorityBasedDesiredSet, priorityBasedCurrentSet, runtimeInfo, moduleIdenreplacedies));
}
Events.PlanCreated(commands);
return new Plan(commands);
}
19
Source : Users.cs
with MIT License
from Azure
with MIT License
from Azure
public List<string> GetAllowedActions(IEnumerable<string> roles)
{
// ensure only unique values are added to the allowed actions list
// if duplicate actions are allowed in multiple roles
var allowedActions = new HashSet<string>();
foreach (var role in roles)
{
var policy = this.policies.GetByRole(role);
allowedActions.UnionWith(policy.AllowedActions);
}
return allowedActions.ToList();
}
19
Source : Messages.cs
with MIT License
from Azure
with MIT License
from Azure
private MessageList GetListFromCosmosDb(
DateTimeOffset? from,
DateTimeOffset? to,
string order,
int skip,
int limit,
string[] devices)
{
int dataPrefixLen = DATA_PREFIX.Length;
var sql = QueryBuilder.GetDoreplacedentsSql(
"d2cmessage",
null, null,
from, "device.msg.received",
to, "device.msg.received",
order, "device.msg.received",
skip,
limit,
devices, "device.id");
this.log.Debug("Created Message Query", () => new { sql });
FeedOptions queryOptions = new FeedOptions();
queryOptions.EnableCrossParreplacedionQuery = true;
queryOptions.EnableScanInQuery = true;
List<Doreplacedent> docs = this.storageClient.QueryDoreplacedents(
this.databaseName,
this.collectionId,
queryOptions,
sql,
skip,
limit);
// Messages to return
List<Message> messages = new List<Message>();
// Auto discovered telemetry types
HashSet<string> properties = new HashSet<string>();
foreach (Doreplacedent doc in docs)
{
// Doreplacedent fields to expose
JObject data = new JObject();
// Extract all the telemetry data and types
var jsonDoc = JObject.Parse(doc.ToString());
string dataSchema = jsonDoc.GetValue(DATA_SCHEMA_TYPE)?.ToString();
SchemaType schemaType;
Enum.TryParse(dataSchema, true, out schemaType);
switch (schemaType)
{
// Process messages output by streaming jobs
case SchemaType.StreamingJobs:
data = (JObject)jsonDoc.GetValue(DATA_PROPERTY_NAME);
if (data != null)
{
// Filter ParreplacedionId property sometimes generated by ASA query by default
properties.UnionWith(data.Properties()
.Where(p => !p.Name.Equals(DATA_PARreplacedION_ID, StringComparison.OrdinalIgnoreCase))
.Select(p => p.Name));
};
break;
// Process messages output by telemetry agent
default:
foreach (var item in jsonDoc)
{
// Ignore fields that don't start with "data."
if (item.Key.StartsWith(DATA_PREFIX))
{
// Remove the "data." prefix
string key = item.Key.ToString().Substring(dataPrefixLen);
data.Add(key, item.Value);
// Telemetry types auto-discovery magic through union of all keys
properties.Add(key);
}
}
break;
}
messages.Add(new Message(
doc.GetPropertyValue<string>("device.id"),
doc.GetPropertyValue<long>("device.msg.received"),
data));
}
return new MessageList(messages, new List<string>(properties));
}
19
Source : Messages.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
private MessageList GetListFromCosmosDb(
DateTimeOffset? from,
DateTimeOffset? to,
string order,
int skip,
int limit,
string[] devices)
{
int dataPrefixLen = DATA_PREFIX.Length;
var sql = QueryBuilder.GetDoreplacedentsSql(
"d2cmessage",
null, null,
from, "device.msg.received",
to, "device.msg.received",
order, "device.msg.received",
skip,
limit,
devices, "device.id");
this.log.Debug("Created Message Query", () => new { sql });
FeedOptions queryOptions = new FeedOptions();
queryOptions.EnableCrossParreplacedionQuery = true;
queryOptions.EnableScanInQuery = true;
List<Doreplacedent> docs = this.storageClient.QueryDoreplacedents(
this.databaseName,
this.collectionId,
queryOptions,
sql,
skip,
limit);
// Messages to return
List<Message> messages = new List<Message>();
// Auto discovered telemetry types
HashSet<string> properties = new HashSet<string>();
foreach (Doreplacedent doc in docs)
{
// Doreplacedent fields to expose
JObject data = new JObject();
// Extract all the telemetry data and types
var jsonDoc = JObject.Parse(doc.ToString());
string dataSchema = jsonDoc.GetValue(DATA_SCHEMA_TYPE)?.ToString();
SchemaType schemaType;
Enum.TryParse(dataSchema, true, out schemaType);
switch (schemaType)
{
// Process messages output by streaming jobs
case SchemaType.StreamingJobs:
data = (JObject)jsonDoc.GetValue(DATA_PROPERTY_NAME);
if (data != null)
{
// Filter ParreplacedionId property sometimes generated by ASA query by default
properties.UnionWith(data.Properties()
.Where(p => !p.Name.Equals(DATA_PARreplacedION_ID, StringComparison.OrdinalIgnoreCase))
.Select(p => p.Name));
};
break;
// Process messages output by telemetry agent
default:
foreach (var item in jsonDoc)
{
// Ignore fields that don't start with "data."
if (item.Key.StartsWith(DATA_PREFIX))
{
// Remove the "data." prefix
string key = item.Key.ToString().Substring(dataPrefixLen);
data.Add(key, item.Value);
// Telemetry types auto-discovery magic through union of all keys
properties.Add(key);
}
}
break;
}
messages.Add(new Message(
doc.GetPropertyValue<string>("device.id"),
null, // Getting message schema from Cosmos DB not yet implemented
doc.GetPropertyValue<long>("device.msg.received"),
data));
}
return new MessageList(messages, new List<string>(properties));
}
19
Source : IncrementalConsentAndConditionalAccessHelper.cs
with MIT License
from AzureAD
with MIT License
from AzureAD
public static AuthenticationProperties BuildAuthenticationProperties(
string[]? scopes,
MsalUiRequiredException ex,
ClaimsPrincipal user,
string? userflow = null)
{
if (ex == null)
{
throw new ArgumentNullException(nameof(ex));
}
scopes ??= new string[0];
var properties = new AuthenticationProperties();
// Set the scopes, including the scopes that MSAL.NET needs for the token cache
string[] additionalBuiltInScopes =
{
OidcConstants.ScopeOpenId,
OidcConstants.ScopeOfflineAccess,
OidcConstants.ScopeProfile,
};
HashSet<string> oidcParams = new HashSet<string>(scopes);
oidcParams.UnionWith(additionalBuiltInScopes);
properties.SetParameter(OpenIdConnectParameterNames.Scope, oidcParams.ToList());
// Attempts to set the login_hint to avoid the logged-in user to be presented with an account selection dialog
var loginHint = user.GetLoginHint();
if (!string.IsNullOrWhiteSpace(loginHint))
{
properties.SetParameter(OpenIdConnectParameterNames.LoginHint, loginHint);
var domainHint = user.GetDomainHint();
properties.SetParameter(OpenIdConnectParameterNames.DomainHint, domainHint);
}
// Additional claims required (for instance MFA)
if (!string.IsNullOrEmpty(ex.Claims))
{
properties.Items.Add(OidcConstants.AdditionalClaims, ex.Claims);
}
// Include current userflow for B2C
if (!string.IsNullOrEmpty(userflow))
{
properties.Items.Add(OidcConstants.PolicyKey, userflow);
}
return properties;
}
19
Source : ProjectPackageBuilder.cs
with MIT License
from b-editor
with MIT License
from b-editor
public ProjectPackageBuilder IncludeFonts(IEnumerable<Font> fonts)
{
Fonts.UnionWith(fonts);
return this;
}
19
Source : LogDataDto.cs
with MIT License
from baaron4
with MIT License
from 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
Source : BuffSourceFinder20210511.cs
with MIT License
from baaron4
with MIT License
from baaron4
protected override HashSet<long> GetIDs(ParsedEvtcLog log, long buffID, long extension)
{
BuffInfoEvent buffDescription = log.CombatData.GetBuffInfoEvent(buffID);
if (buffDescription != null && buffDescription.DurationCap == 0)
{
return base.GetIDs(log, buffID, extension);
}
var res = new HashSet<long>();
foreach (KeyValuePair<long, HashSet<long>> pair in DurationToIDs)
{
if (pair.Key >= extension)
{
res.UnionWith(pair.Value);
}
}
return res;
}
19
Source : ShatteredObservatory.cs
with MIT License
from baaron4
with MIT License
from baaron4
protected static HashSet<Agenreplacedem> GetParticipatingPlayerAgents(AbstractSingleActor target, CombatData combatData, IReadOnlyCollection<Agenreplacedem> playerAgents)
{
if (target == null)
{
return new HashSet<Agenreplacedem>();
}
var participatingPlayerAgents = new HashSet<Agenreplacedem>(combatData.GetDamageTakenData(target.Agenreplacedem).Where(x => playerAgents.Contains(x.From.GetFinalMaster())).Select(x => x.From.GetFinalMaster()));
participatingPlayerAgents.UnionWith(combatData.GetDamageData(target.Agenreplacedem).Where(x => playerAgents.Contains(x.To.GetFinalMaster())).Select(x => x.To.GetFinalMaster()));
return participatingPlayerAgents;
}
19
Source : EngineerHelper.cs
with MIT License
from baaron4
with MIT License
from baaron4
public static void AttachMasterToEngineerTurrets(IReadOnlyList<Player> players, CombatData combatData)
{
var playerAgents = new HashSet<Agenreplacedem>(players.Select(x => x.Agenreplacedem));
HashSet<Agenreplacedem> flameTurrets = ProfHelper.GetOffensiveGadgetAgents(combatData, 5903, playerAgents);
HashSet<Agenreplacedem> rifleTurrets = ProfHelper.GetOffensiveGadgetAgents(combatData, 5841, playerAgents);
rifleTurrets.UnionWith(ProfHelper.GetOffensiveGadgetAgents(combatData, 5875, playerAgents));
HashSet<Agenreplacedem> netTurrets = ProfHelper.GetOffensiveGadgetAgents(combatData, 5896, playerAgents);
netTurrets.UnionWith(ProfHelper.GetOffensiveGadgetAgents(combatData, 22137, playerAgents));
HashSet<Agenreplacedem> rocketTurrets = ProfHelper.GetOffensiveGadgetAgents(combatData, 6108, playerAgents);
rocketTurrets.UnionWith(ProfHelper.GetOffensiveGadgetAgents(combatData, 5914, playerAgents));
HashSet<Agenreplacedem> thumperTurrets = ProfHelper.GetOffensiveGadgetAgents(combatData, 5856, playerAgents);
thumperTurrets.UnionWith(ProfHelper.GetOffensiveGadgetAgents(combatData, 5890, playerAgents));
// TODO: need ID here
HashSet<Agenreplacedem> harpoonTurrets = ProfHelper.GetOffensiveGadgetAgents(combatData, -1, playerAgents);
HashSet<Agenreplacedem> healingTurrets = ProfHelper.GetOffensiveGadgetAgents(combatData, 5958, playerAgents);
healingTurrets.RemoveWhere(x => thumperTurrets.Contains(x) || rocketTurrets.Contains(x) || netTurrets.Contains(x) || rifleTurrets.Contains(x) || flameTurrets.Contains(x) || harpoonTurrets.Contains(x));
var engineers = players.Where(x => x.BaseSpec == Spec.Engineer).ToList();
// if only one engineer, could only be that one
if (engineers.Count == 1)
{
Player engineer = engineers[0];
ProfHelper.SetGadgetMaster(flameTurrets, engineer.Agenreplacedem);
ProfHelper.SetGadgetMaster(netTurrets, engineer.Agenreplacedem);
ProfHelper.SetGadgetMaster(rocketTurrets, engineer.Agenreplacedem);
ProfHelper.SetGadgetMaster(rifleTurrets, engineer.Agenreplacedem);
ProfHelper.SetGadgetMaster(thumperTurrets, engineer.Agenreplacedem);
ProfHelper.SetGadgetMaster(harpoonTurrets, engineer.Agenreplacedem);
ProfHelper.SetGadgetMaster(healingTurrets, engineer.Agenreplacedem);
}
else if (engineers.Count > 1)
{
ProfHelper.AttachMasterToGadgetByCastData(combatData, flameTurrets, new List<long> { 5836, 5868 }, 1000);
ProfHelper.AttachMasterToGadgetByCastData(combatData, rifleTurrets, new List<long> { 5818 }, 1000);
ProfHelper.AttachMasterToGadgetByCastData(combatData, netTurrets, new List<long> { 5837, 5868, 6183 }, 1000);
ProfHelper.AttachMasterToGadgetByCastData(combatData, rocketTurrets, new List<long> { 5912, 22574, 6183 }, 1000);
ProfHelper.AttachMasterToGadgetByCastData(combatData, thumperTurrets, new List<long> { 5838 }, 1000);
//AttachMasterToGadgetByCastData(castData, harpoonTurrets, new List<long> { 6093, 6183 }, 1000);
//AttachMasterToGadgetByCastData(castData, healingTurrets, new List<long> { 5857, 5868 }, 1000);
}
}
19
Source : Definition.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
public bool LoadDefinition(string path)
{
if (loading)
return true;
try
{
XmlSerializer deser = new(typeof(Definition));
using (FileStream fs = new FileStream(path, FileMode.Open))
{
Definition def = (Definition)deser.Deserialize(fs);
var newtables = def.Tables.Where(x => Tables.Count(y => x.Build == y.Build && x.Name == y.Name) == 0).ToList();
newtables.ForEach(x => x.Load());
Tables.UnionWith(newtables.Where(x => x.Key != null));
return true;
}
}
catch
{
return false;
}
}
19
Source : Set.cs
with MIT License
from bleroy
with MIT License
from bleroy
public ISet<T> Union(ISet<T> other)
{
if (other is EmptySet<T>) return this;
if (other is CompleteSet<T>) return Complete;
if (other is Set<T> otherSet)
{
var result = new HashSet<T>(_innerSet);
result.UnionWith(otherSet._innerSet);
return new Set<T>(result);
}
return other.Union(this);
}
19
Source : SettingsWindow.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
private void SubmitButton_Click(object sender, RoutedEventArgs e)
{
beSet.UnionWith(BindingOperations.GetSourceUpdatingBindings(this));
foreach (var be in beSet)
{
be.UpdateSource();
}
this.DialogResult = true;
this.Close();
}
19
Source : SettingsWindow.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
beSet.UnionWith(BindingOperations.GetSourceUpdatingBindings(this));
}
19
Source : SettingsWindow.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
private async void SubmitButton_Click(object sender, RoutedEventArgs e)
{
beSet.UnionWith(BindingOperations.GetSourceUpdatingBindings(this));
foreach (var be in beSet)
{
be.UpdateSource();
}
await vm.ApplySettings();
this.DialogResult = true;
this.Close();
}
19
Source : SettingsWindow.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
private void TabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
beSet.UnionWith(BindingOperations.GetSourceUpdatingBindings(this));
}
19
Source : PackageManager.cs
with MIT License
from bonsai-rx
with MIT License
from bonsai-rx
static void GetTransitiveDependents(
PackageIdenreplacedy package,
HashSet<PackageIdenreplacedy> transitiveDependents,
IDictionary<PackageIdenreplacedy, HashSet<PackageIdenreplacedy>> dependentPackages)
{
if (dependentPackages.TryGetValue(package, out HashSet<PackageIdenreplacedy> dependents))
{
transitiveDependents.UnionWith(dependents);
foreach (var dependent in dependents)
{
GetTransitiveDependents(dependent, transitiveDependents, dependentPackages);
}
}
}
19
Source : ClientWatchManager.cs
with MIT License
from brucehu123
with MIT License
from brucehu123
private HashSet<Watcher> Materialize()
{
HashSet<Watcher> result = new HashSet<Watcher>();
lock (dataWatches)
{
foreach (var wa in dataWatches.Values)
{
result.UnionWith(wa);
}
}
return result;
}
19
Source : Map.cs
with GNU General Public License v3.0
from caioavidal
with GNU General Public License v3.0
from caioavidal
public HashSet<ICreature> GetSpectators(Location fromLocation, Location toLocation, bool onlyPlayer = false)
{
if (fromLocation.Z == toLocation.Z)
{
var minRangeX = (int) MapViewPort.ViewPortX;
var maxRangeX = (int) MapViewPort.ViewPortX;
var minRangeY = (int) MapViewPort.ViewPortY;
var maxRangeY = (int) MapViewPort.ViewPortY;
if (fromLocation.Y > toLocation.Y) ++minRangeY;
else if (fromLocation.Y < toLocation.Y) ++maxRangeY;
if (fromLocation.X < toLocation.X) ++maxRangeX;
else if (fromLocation.X > toLocation.X) ++minRangeX;
var search = new SpectatorSearch(ref fromLocation, true, minRangeX, minRangeY: minRangeY,
maxRangeX: maxRangeX, maxRangeY: maxRangeY, onlyPlayers: onlyPlayer);
return world.GetSpectators(ref search).ToHashSet();
}
var oldSpecs = GetSpectators(fromLocation);
var newSpecs = GetSpectators(toLocation);
oldSpecs.UnionWith(newSpecs);
return oldSpecs;
}
19
Source : UserDefinedUniverse.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security,
DateTime currentTimeUtc,
DateTime maximumEndTimeUtc,
ISubscriptionDataConfigService subscriptionService)
{
var result = _subscriptionDataConfigs.Where(x => x.Symbol == security.Symbol).ToList();
if (!result.Any())
{
result = _pendingRemovedConfigs.Where(x => x.Symbol == security.Symbol).ToList();
if (result.Any())
{
_pendingRemovedConfigs.RemoveWhere(x => x.Symbol == security.Symbol);
}
else
{
result = base.GetSubscriptionRequests(security, currentTimeUtc, maximumEndTimeUtc, subscriptionService).Select(x => x.Configuration).ToList();
// we create subscription data configs ourselves, add the configs
_subscriptionDataConfigs.UnionWith(result);
}
}
return result.Select(config => new SubscriptionRequest(isUniverseSubscription: false,
universe: this,
security: security,
configuration: config,
startTimeUtc: currentTimeUtc,
endTimeUtc: maximumEndTimeUtc));
}
19
Source : UserDefinedUniverse.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private bool RemoveAndKeepTrack(Symbol symbol)
{
var toBeRemoved = _subscriptionDataConfigs.Where(x => x.Symbol == symbol).ToList();
var removedSymbol = _symbols.Remove(symbol);
if (removedSymbol || toBeRemoved.Any())
{
_subscriptionDataConfigs.RemoveWhere(x => x.Symbol == symbol);
_pendingRemovedConfigs.UnionWith(toBeRemoved);
return true;
}
return false;
}
19
Source : DbSplitObjectsOperate.cs
with GNU Lesser General Public License v3.0
from CarefreeXT
with GNU Lesser General Public License v3.0
from CarefreeXT
internal void Add(IEnumerable<T> items)
{
lock (_Items) { _Items.UnionWith(items); }
}
19
Source : RPCClientExtensions.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public static async Task<ISet<uint256>> GetAllDependentsAsync(this IRPCClient rpc, IEnumerable<uint256> transactionHashes, bool includingProvided, bool likelyProvidedManyConfirmedOnes)
{
IEnumerable<uint256> workingTxHashes = likelyProvidedManyConfirmedOnes // If confirmed txIds are provided, then do a big check first.
? await rpc.GetUnconfirmedAsync(transactionHashes)
: transactionHashes;
var hashSet = new HashSet<uint256>();
foreach (var txId in workingTxHashes)
{
// Go through all the txIds provided and getmempoolentry to get the dependents and the confirmation status.
var entry = await rpc.GetMempoolEntryAsync(txId, throwIfNotFound: false);
if (entry != null)
{
// If we asked to include the provided transaction hashes into the result then check which ones are confirmed and do so.
if (includingProvided)
{
hashSet.Add(txId);
}
// Get all the dependents of all the dependents except the ones we already know of.
var except = entry.Depends.Except(hashSet);
var dependentsOfDependents = await rpc.GetAllDependentsAsync(except, includingProvided: true, likelyProvidedManyConfirmedOnes: false);
// Add them to the hashset.
hashSet.UnionWith(dependentsOfDependents);
}
}
return hashSet;
}
19
Source : ChaumianCoinJoinController.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
[HttpPost("inputs")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(404)]
public async Task<IActionResult> PostInputsAsync([FromBody, Required]InputsRequest request)
{
// Validate request.
if (request.RoundId < 0 || !ModelState.IsValid)
{
return BadRequest("Invalid request.");
}
if (request.Inputs.Count() > 7)
{
return BadRequest("Maximum 7 inputs can be registered.");
}
using (await InputsLock.LockAsync())
{
CoordinatorRound round = Coordinator.TryGetRound(request.RoundId);
if (round is null || round.Phase != RoundPhase.InputRegistration)
{
return NotFound("No such running round in InputRegistration. Try another round.");
}
// Do more checks.
try
{
uint256[] blindedOutputs = request.BlindedOutputScripts.ToArray();
int blindedOutputCount = blindedOutputs.Length;
int maxBlindedOutputCount = round.MixingLevels.Count();
if (blindedOutputCount > maxBlindedOutputCount)
{
return BadRequest($"Too many blinded output was provided: {blindedOutputCount}, maximum: {maxBlindedOutputCount}.");
}
if (blindedOutputs.Distinct().Count() < blindedOutputs.Length)
{
return BadRequest("Duplicate blinded output found.");
}
if (round.ContainsAnyBlindedOutputScript(blindedOutputs))
{
return BadRequest("Blinded output has already been registered.");
}
if (request.ChangeOutputAddress.Network != Network)
{
// RegTest and TestNet address formats are sometimes the same.
if (Network == Network.Main)
{
return BadRequest($"Invalid ChangeOutputAddress Network.");
}
}
var uniqueInputs = new HashSet<OutPoint>();
foreach (InputProofModel inputProof in request.Inputs)
{
var outpoint = inputProof.Input;
if (uniqueInputs.Contains(outpoint))
{
return BadRequest("Cannot register an input twice.");
}
uniqueInputs.Add(outpoint);
}
var alicesToRemove = new HashSet<Guid>();
var getTxOutResponses = new List<(InputProofModel inputModel, Task<GetTxOutResponse> getTxOutTask)>();
var batch = RpcClient.PrepareBatch();
foreach (InputProofModel inputProof in request.Inputs)
{
if (round.ContainsInput(inputProof.Input, out List<Alice> tr))
{
alicesToRemove.UnionWith(tr.Select(x => x.UniqueId)); // Input is already registered by this alice, remove it later if all the checks are completed fine.
}
if (Coordinator.AnyRunningRoundContainsInput(inputProof.Input, out List<Alice> tnr))
{
if (tr.Union(tnr).Count() > tr.Count)
{
return BadRequest("Input is already registered in another round.");
}
}
OutPoint outpoint = inputProof.Input;
var bannedElem = await Coordinator.UtxoReferee.TryGetBannedAsync(outpoint, notedToo: false);
if (bannedElem != null)
{
return BadRequest($"Input is banned from participation for {(int)bannedElem.BannedRemaining.TotalMinutes} minutes: {inputProof.Input.N}:{inputProof.Input.Hash}.");
}
var txOutResponseTask = batch.GetTxOutAsync(inputProof.Input.Hash, (int)inputProof.Input.N, includeMempool: true);
getTxOutResponses.Add((inputProof, txOutResponseTask));
}
// Perform all RPC request at once
await batch.SendBatchAsync();
byte[] blindedOutputScriptHashesByte = ByteHelpers.Combine(blindedOutputs.Select(x => x.ToBytes()));
uint256 blindedOutputScriptsHash = new uint256(Hashes.SHA256(blindedOutputScriptHashesByte));
var inputs = new HashSet<Coin>();
var allInputsConfirmed = true;
foreach (var responses in getTxOutResponses)
{
var (inputProof, getTxOutResponseTask) = responses;
var getTxOutResponse = await getTxOutResponseTask;
// Check if inputs are unspent.
if (getTxOutResponse is null)
{
return BadRequest($"Provided input is not unspent: {inputProof.Input.N}:{inputProof.Input.Hash}.");
}
// Check if unconfirmed.
if (getTxOutResponse.Confirmations <= 0)
{
// If it spends a CJ then it may be acceptable to register.
if (!await Coordinator.ContainsUnconfirmedCoinJoinAsync(inputProof.Input.Hash))
{
return BadRequest("Provided input is neither confirmed, nor is from an unconfirmed coinjoin.");
}
allInputsConfirmed = false;
}
// Check if immature.
if (getTxOutResponse.IsCoinBase && getTxOutResponse.Confirmations <= 100)
{
return BadRequest("Provided input is immature.");
}
// Check if inputs are native segwit.
if (getTxOutResponse.ScriptPubKeyType != "witness_v0_keyhash")
{
return BadRequest("Provided input must be witness_v0_keyhash.");
}
TxOut txOut = getTxOutResponse.TxOut;
var address = (BitcoinWitPubKeyAddress)txOut.ScriptPubKey.GetDestinationAddress(Network);
// Check if proofs are valid.
if (!address.VerifyMessage(blindedOutputScriptsHash, inputProof.Proof))
{
return BadRequest("Provided proof is invalid.");
}
inputs.Add(new Coin(inputProof.Input, txOut));
}
if (!allInputsConfirmed)
{
// Check if mempool would accept a fake transaction created with the registered inputs.
// Fake outputs: mixlevels + 1 maximum, +1 because there can be a change.
var result = await RpcClient.TestMempoolAcceptAsync(inputs, fakeOutputCount: round.MixingLevels.Count() + 1, round.FeePerInputs, round.FeePerOutputs);
if (!result.accept)
{
return BadRequest($"Provided input is from an unconfirmed coinjoin, but a limit is reached: {result.rejectReason}");
}
}
var acceptedBlindedOutputScripts = new List<uint256>();
// Calculate expected networkfee to pay after base denomination.
int inputCount = inputs.Count;
Money networkFeeToPayAfterBaseDenomination = (inputCount * round.FeePerInputs) + (2 * round.FeePerOutputs);
// Check if inputs have enough coins.
Money inputSum = inputs.Sum(x => x.Amount);
Money changeAmount = (inputSum - (round.MixingLevels.GetBaseDenomination() + networkFeeToPayAfterBaseDenomination));
if (changeAmount < Money.Zero)
{
return BadRequest($"Not enough inputs are provided. Fee to pay: {networkFeeToPayAfterBaseDenomination.ToString(false, true)} BTC. Round denomination: {round.MixingLevels.GetBaseDenomination().ToString(false, true)} BTC. Only provided: {inputSum.ToString(false, true)} BTC.");
}
acceptedBlindedOutputScripts.Add(blindedOutputs.First());
Money networkFeeToPay = networkFeeToPayAfterBaseDenomination;
// Make sure we sign the proper number of additional blinded outputs.
var moneySoFar = Money.Zero;
for (int i = 1; i < blindedOutputCount; i++)
{
if (!round.MixingLevels.TryGetDenomination(i, out Money denomination))
{
break;
}
Money coordinatorFee = denomination.Percentage(round.CoordinatorFeePercent * round.AnonymitySet); // It should be the number of bobs, but we must make sure they'd have money to pay all.
changeAmount -= (denomination + round.FeePerOutputs + coordinatorFee);
networkFeeToPay += round.FeePerOutputs;
if (changeAmount < Money.Zero)
{
break;
}
acceptedBlindedOutputScripts.Add(blindedOutputs[i]);
}
// Make sure Alice checks work.
var alice = new Alice(inputs, networkFeeToPayAfterBaseDenomination, request.ChangeOutputAddress, acceptedBlindedOutputScripts);
foreach (Guid aliceToRemove in alicesToRemove)
{
round.RemoveAlicesBy(aliceToRemove);
}
// if alice is counted in queued count already, remove it
round.DequeueAnyFamiliarAlice(request.Inputs);
round.AddAlice(alice);
// All checks are good. Sign.
var blindSignatures = new List<uint256>();
for (int i = 0; i < acceptedBlindedOutputScripts.Count; i++)
{
var blindedOutput = acceptedBlindedOutputScripts[i];
var signer = round.MixingLevels.GetLevel(i).Signer;
uint256 blindSignature = signer.Sign(blindedOutput);
blindSignatures.Add(blindSignature);
}
alice.BlindedOutputSignatures = blindSignatures.ToArray();
// Check if phase changed since.
if (round.Status != CoordinatorRoundStatus.Running || round.Phase != RoundPhase.InputRegistration)
{
return StatusCode(StatusCodes.Status503ServiceUnavailable, "The state of the round changed while handling the request. Try again.");
}
// Progress round if needed.
if (round.CountAlices() >= round.AnonymitySet)
{
await round.RemoveAlicesIfAnInputRefusedByMempoolAsync();
if (round.CountAlices() >= round.AnonymitySet)
{
await round.ExecuteNextPhaseAsync(RoundPhase.ConnectionConfirmation);
}
}
var resp = new InputsResponse
{
UniqueId = alice.UniqueId,
RoundId = round.RoundId
};
return Ok(resp);
}
catch (Exception ex)
{
Logger.LogDebug(ex);
return BadRequest(ex.Message);
}
}
}
19
Source : ExpressionCompiler.cs
with MIT License
from chaowlert
with MIT License
from chaowlert
public replacedembly Createreplacedembly()
{
var references = new HashSet<replacedembly>();
references.UnionWith(from t in Translators
from n in t.TypeNames
select n.Key.replacedembly);
if (_options?.References != null)
references.UnionWith(_options.References);
references.Add(typeof(object).replacedembly);
#if NETSTANDARD2_0
references.Add(replacedembly.Load(new replacedemblyName("netstandard")));
references.Add(replacedembly.Load(new replacedemblyName("System.Runtime")));
references.Add(replacedembly.Load(new replacedemblyName("System.Collections")));
#endif
var replacedemblyName = Path.GetRandomFileName();
var symbolsName = Path.ChangeExtension(replacedemblyName, "pdb");
var metadataReferences = references.Select(it => MetadataReference.CreateFromFile(it.Location));
var isRelease = _options?.IsRelease ?? !Debugger.IsAttached;
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
_codes,
metadataReferences,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: new[] { "System" })
.WithOptimizationLevel(isRelease ? OptimizationLevel.Release : OptimizationLevel.Debug)
.WithPlatform(Platform.AnyCpu)
);
using var replacedemblyStream = new MemoryStream();
using var symbolsStream = new MemoryStream();
var emitOptions = new EmitOptions(
debugInformationFormat: DebugInformationFormat.PortablePdb,
pdbFilePath: symbolsName);
var embeddedTexts = _codes.Select(it => EmbeddedText.FromSource(it.FilePath, it.GetText()));
EmitResult result = compilation.Emit(
peStream: replacedemblyStream,
pdbStream: symbolsStream,
embeddedTexts: embeddedTexts,
options: emitOptions);
if (!result.Success)
{
var errors = new List<string>();
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
errors.Add($"{diagnostic.Id}: {diagnostic.GetMessage()}");
throw new InvalidOperationException(string.Join("\n", errors));
}
replacedemblyStream.Seek(0, SeekOrigin.Begin);
symbolsStream.Seek(0, SeekOrigin.Begin);
#if NETSTANDARD2_0
return System.Runtime.Loader.replacedemblyLoadContext.Default.LoadFromStream(replacedemblyStream, symbolsStream);
#else
return replacedembly.Load(replacedemblyStream.ToArray(), symbolsStream.ToArray());
#endif
}
19
Source : IOperator.cs
with GNU General Public License v3.0
from CheezLang
with GNU General Public License v3.0
from CheezLang
public object Execute(object left, object right)
{
var l = left as EnumValue;
var r = right as EnumValue;
if (l == null || r == null)
throw new ArgumentException($"'{nameof(left)}' and '{nameof(right)}' must be enum values, but are '{left}' and '{right}'");
if (l.Type != r.Type)
throw new ArgumentException($"'{nameof(left)}' and '{nameof(right)}' must have the same type, but have {l.Type} and {r.Type}");
var members = new HashSet<AstEnumMemberNew>();
members.UnionWith(l.Members);
members.UnionWith(r.Members);
return new EnumValue(l.Type, members.ToArray());
}
19
Source : PassResolveDeclatarions.cs
with GNU General Public License v3.0
from CheezLang
with GNU General Public License v3.0
from CheezLang
private void ResolveMissingTypesOfDeclarations(IEnumerable<AstDecl> declarations)
{
var whiteSet = new HashSet<AstDecl>();
var greySet = new HashSet<AstDecl>();
var chain = new Dictionary<AstDecl, AstDecl>();
whiteSet.UnionWith(declarations);
while (whiteSet.Count > 0)
{
var x = whiteSet.First();
ResolveMissingTypesOfDeclarationsHelper(x, whiteSet, greySet, chain);
}
}
19
Source : Molecule.cs
with Apache License 2.0
from Chem4Word
with Apache License 2.0
from Chem4Word
private static Ring GetRing(Atom startAtom)
{
// Only returns the first ring.
//
// Uses the Figueras algorithm
// Figueras, J, J. Chem. Inf. Comput. Sci., 1996,36, 96, 986-991
// The algorithm goes as follows:
//1. Remove node frontNode and its Source from the front of the queue.
//2. For each node m attached to frontNode, and not equal to Source:
//If path[m] is null, compute path[m] ) path[frontNode] +[m]
//and put node m(with its Source, frontNode) on the back of the queue.
//If path[m] is not null then
// 1) Compute the intersection path[frontNode]*path[m].
// 2) If the intersection is a singleton, compute the ring set path[m]+path[frontNode] and exit.
//3. Return to step 1.
//set up the data structures
Queue<AtomData> atomsSoFar; //needed for BFS
Dictionary<Atom, HashSet<Atom>> path = new Dictionary<Atom, HashSet<Atom>>();
//initialise all the paths to empty
foreach (var atom in startAtom.Parent.Atoms)
{
path[atom] = new HashSet<Atom>();
}
//set up a new queue
atomsSoFar = new Queue<AtomData>();
//set up a front node and shove it onto the queue
AtomData frontNode;
//shove the neigbours onto the queue to prime it
foreach (Atom initialAtom in startAtom.Neighbours)
{
var node = new AtomData() { Source = startAtom, CurrentAtom = initialAtom };
path[initialAtom] = new HashSet<Atom>() { startAtom, initialAtom };
atomsSoFar.Enqueue(node);
}
//now scan the Molecule and detect all rings
while (atomsSoFar.Any())
{
frontNode = atomsSoFar.Dequeue();
foreach (Atom m in frontNode.CurrentAtom.Neighbours)
{
if (m != frontNode.Source) //ignore an atom that we've visited
{
if ((!path.ContainsKey(m)) || (path[m].Count == 0)) //null path
{
var temp = new HashSet<Atom>();
temp.Add(m);
temp.UnionWith(path[frontNode.CurrentAtom]);
path[m] = temp; //add on the path built up so far
AtomData newItem = new AtomData() { Source = frontNode.CurrentAtom, CurrentAtom = m };
atomsSoFar.Enqueue(newItem);
}
else //we've got a collision - is it a ring closure
{
HashSet<Atom> overlap = new HashSet<Atom>();
overlap.UnionWith(path[frontNode.CurrentAtom]); //clone this set
overlap.IntersectWith(path[m]);
if (overlap.Count == 1) //we've had a singleton overlap : ring closure
{
var ringAtoms = new HashSet<Atom>();
ringAtoms.UnionWith(path[m]);
ringAtoms.UnionWith(path[frontNode.CurrentAtom]);
return new Ring(ringAtoms);
}
}
}
}
}
//no collisions therefore no rings detected
return null;
}
19
Source : VisualTreeHelpers.cs
with Apache License 2.0
from Chem4Word
with Apache License 2.0
from Chem4Word
public static HashSet<T> FindAllChildren<T>(DependencyObject parent)
where T : DependencyObject
{
HashSet<T> allChildren = new HashSet<T>();
// Confirm parent is valid.
if (parent == null) return allChildren;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
allChildren.UnionWith(FindAllChildren<T>(child));
}
else
{
// child element found.
allChildren.Add(childType);
}
}
return allChildren;
}
19
Source : VisualTreeHelpers.cs
with Apache License 2.0
from Chem4Word
with Apache License 2.0
from Chem4Word
public static HashSet<T> FindAllChildren<T>(DependencyObject parent)
where T : DependencyObject
{
HashSet<T> allChildren = new HashSet<T>();
// Confirm parent is valid.
if (parent == null)
{
return allChildren;
}
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
allChildren.UnionWith(FindAllChildren<T>(child));
}
else
{
// child element found.
allChildren.Add(childType);
}
}
return allChildren;
}
19
Source : TypeInitializer.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
private IEnumerable<RegisteredType> GetNextBatch(
ISet<ITypeReference> processed)
{
foreach (RegisteredType type in _next)
{
if (TryNormalizeDependencies(type.Conditionals, out IReadOnlyList<ITypeReference>? normalized) &&
processed.IsSupersetOf(GetTypeRefsExceptSelfRefs(type, normalized)))
{
yield return type;
}
else
{
_temp.Add(type);
}
}
_next.Clear();
if (_temp.Count > 0)
{
_next.AddRange(_temp);
_temp.Clear();
}
List<ITypeReference> GetTypeRefsExceptSelfRefs(
RegisteredType type,
IReadOnlyList<ITypeReference> normalizedTypeReferences)
{
_typeRefs.Clear();
_typeRefSet.Clear();
_typeRefSet.UnionWith(type.References);
foreach (ITypeReference? typeRef in normalizedTypeReferences)
{
if (_typeRefSet.Add(typeRef))
{
_typeRefs.Add(typeRef);
}
}
return _typeRefs;
}
}
19
Source : TimelineRecording.cs
with MIT License
from chstetco
with MIT License
from chstetco
static HashSet<double> GetKeyTimes(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state)
{
var keyTimes = new HashSet<double>();
AnimationClip animationClip;
double keyTime;
bool inRange;
GetClipAndRelativeTime(target, state, out animationClip, out keyTime, out inRange);
if (animationClip == null)
return keyTimes;
var component = target as Component;
var playablereplacedet = target as IPlayablereplacedet;
var info = AnimationClipCurveCache.Instance.GetCurveInfo(animationClip);
TimelineClip clip = null;
if (component != null)
{
GetTrackForGameObject(component.gameObject, state).FindRecordingClipAtTime(state.editSequence.time, out clip);
}
else if (playablereplacedet != null)
{
clip = FindClipWithreplacedet(state.editSequence.replacedet, playablereplacedet);
}
foreach (var mod in modifications)
{
EditorCurveBinding temp;
if (HasBinding(target, mod, animationClip, out temp))
{
IEnumerable<double> keys = new HashSet<double>();
if (temp.isPPtrCurve)
{
var curve = info.GetObjectCurveForBinding(temp);
if (curve != null)
{
keys = curve.Select(x => (double)x.time);
}
}
else
{
var curve = info.GetCurveForBinding(temp);
if (curve != null)
{
keys = curve.keys.Select(x => (double)x.time);
}
}
// Transform the times in to 'global' space using the clip
if (clip != null)
{
foreach (var k in keys)
{
var time = clip.FromLocalTimeUnbound(k);
const double eps = 1e-5;
if (time >= clip.start - eps && time <= clip.end + eps)
{
keyTimes.Add(time);
}
}
}
// infinite clip mode, global == local space
else
{
keyTimes.UnionWith(keys);
}
}
}
return keyTimes;
}
19
Source : TransferDialog.cs
with MIT License
from CityOfZion
with MIT License
from CityOfZion
public Transaction GetTransaction()
{
var cOutputs = txOutListBox1.Items.Where(p => p.replacedetId is UInt160).GroupBy(p => new
{
replacedetId = (UInt160)p.replacedetId,
Account = p.ScriptHash
}, (k, g) => new
{
replacedetId = k.replacedetId,
Value = g.Aggregate(BigInteger.Zero, (x, y) => x + y.Value.Value),
Account = k.Account
}).ToArray();
Transaction tx;
List<TransactionAttribute> attributes = new List<TransactionAttribute>();
if (cOutputs.Length == 0)
{
tx = new ContractTransaction();
}
else
{
UInt160[] addresses = Program.CurrentWallet.GetAccounts().Select(p => p.ScriptHash).ToArray();
HashSet<UInt160> sAttributes = new HashSet<UInt160>();
using (ScriptBuilder sb = new ScriptBuilder())
{
foreach (var output in cOutputs)
{
byte[] script;
using (ScriptBuilder sb2 = new ScriptBuilder())
{
foreach (UInt160 address in addresses)
sb2.EmitAppCall(output.replacedetId, "balanceOf", address);
sb2.Emit(OpCode.DEPTH, OpCode.PACK);
script = sb2.ToArray();
}
ApplicationEngine engine = ApplicationEngine.Run(script);
if (engine.State.HasFlag(VMState.FAULT)) return null;
var balances = engine.EvaluationStack.Pop().GetArray().Reverse().Zip(addresses, (i, a) => new
{
Account = a,
Value = i.GetBigInteger()
}).ToArray();
BigInteger sum = balances.Aggregate(BigInteger.Zero, (x, y) => x + y.Value);
if (sum < output.Value) return null;
if (sum != output.Value)
{
balances = balances.OrderByDescending(p => p.Value).ToArray();
BigInteger amount = output.Value;
int i = 0;
while (balances[i].Value <= amount)
amount -= balances[i++].Value;
if (amount == BigInteger.Zero)
balances = balances.Take(i).ToArray();
else
balances = balances.Take(i).Concat(new[] { balances.Last(p => p.Value >= amount) }).ToArray();
sum = balances.Aggregate(BigInteger.Zero, (x, y) => x + y.Value);
}
sAttributes.UnionWith(balances.Select(p => p.Account));
for (int i = 0; i < balances.Length; i++)
{
BigInteger value = balances[i].Value;
if (i == 0)
{
BigInteger change = sum - output.Value;
if (change > 0) value -= change;
}
sb.EmitAppCall(output.replacedetId, "transfer", balances[i].Account, output.Account, value);
sb.Emit(OpCode.THROWIFNOT);
}
}
tx = new InvocationTransaction
{
Version = 1,
Script = sb.ToArray()
};
}
attributes.AddRange(sAttributes.Select(p => new TransactionAttribute
{
Usage = TransactionAttributeUsage.Script,
Data = p.ToArray()
}));
}
if (!string.IsNullOrEmpty(remark))
attributes.Add(new TransactionAttribute
{
Usage = TransactionAttributeUsage.Remark,
Data = Encoding.UTF8.GetBytes(remark)
});
tx.Attributes = attributes.ToArray();
tx.Outputs = txOutListBox1.Items.Where(p => p.replacedetId is UInt256).Select(p => p.ToTxOutput()).ToArray();
if (tx is ContractTransaction ctx)
tx = Program.CurrentWallet.MakeTransaction(ctx, change_address: ChangeAddress, fee: Fee);
return tx;
}
19
Source : TransactionOperationManager.cs
with MIT License
from CityOfZion
with MIT License
from CityOfZion
public async Task<UInt160[]> GetScriptHashes(Transaction transaction)
{
var references = await GetReferences(transaction);
var hashes = new HashSet<UInt160>(transaction.Inputs.Select(p => references[p].ScriptHash));
hashes.UnionWith(
transaction.Attributes
.Where(p => p.Usage == TransactionAttributeUsage.Script)
.Select(p => new UInt160(p.Data)));
foreach (var group in transaction.Outputs.GroupBy(p => p.replacedetId))
{
var replacedet = await _replacedetRepository.Getreplacedet(group.Key);
if (replacedet == null)
{
throw new InvalidOperationException();
}
if (replacedet.replacedetType.HasFlag(replacedetType.DutyFlag))
{
hashes.UnionWith(group.Select(p => p.ScriptHash));
}
}
return hashes.OrderBy(p => p).ToArray();
}
19
Source : Compiler.cs
with GNU General Public License v3.0
from cobbr
with GNU General Public License v3.0
from cobbr
private static HashSet<ITypeSymbol> GetUsedTypesRecursively(CSharpCompilation compilation, SyntaxTree sourceTree, ref HashSet<ITypeSymbol> currentUsedTypes, ref List<SourceSyntaxTree> sourceSyntaxTrees)
{
HashSet<string> copyCurrentUsedTypes = currentUsedTypes.Select(CT => GetFullyQualifiedTypeName(CT)).ToHashSet();
HashSet<ITypeSymbol> usedTypes = GetUsedTypes(compilation, sourceTree);
currentUsedTypes.UnionWith(usedTypes);
HashSet<SyntaxTree> searchTrees = new HashSet<SyntaxTree>();
foreach (ITypeSymbol symbol in usedTypes)
{
SyntaxReference sr = symbol.DeclaringSyntaxReferences.FirstOrDefault();
if (sr != null)
{
SourceSyntaxTree sst = sourceSyntaxTrees.FirstOrDefault(SST => SST.SyntaxTree == sr.SyntaxTree);
if (sst != null) { sst.UsedTypes.Add(symbol); }
string fullyQualifiedTypeName = GetFullyQualifiedTypeName(symbol);
searchTrees.Add(sr.SyntaxTree);
}
}
searchTrees.Remove(sourceTree);
foreach (SyntaxTree tree in searchTrees)
{
HashSet<ITypeSymbol> newTypes = GetUsedTypesRecursively(compilation, tree, ref currentUsedTypes, ref sourceSyntaxTrees);
currentUsedTypes.UnionWith(newTypes);
}
return currentUsedTypes;
}
19
Source : Textures.cs
with MIT License
from colinator27
with MIT License
from colinator27
public void FindTextureGroups()
{
// Attempts to find a group ID with a page; makes a new group when necessary
int findGroupWithPage(int page)
{
int i;
for (i = 0; i < TextureGroups.Count; i++)
{
if (TextureGroups[i].Pages.Contains(page))
return i;
}
TextureGroups.Add(new Group(page));
return i;
}
// Function to create and merge groups based on texture entries known to be on the same group
void iterateEntries(IList<GMTextureItem> entries)
{
if (entries == null || entries.Count == 0 || entries[0] == null)
return;
int group = findGroupWithPage(entries[0].TexturePageID);
foreach (var item in entries.Skip(1))
{
if (item == null)
continue;
for (int i = 0; i < TextureGroups.Count; i++)
{
if (i == group)
{
TextureGroups[i].Pages.Add(item.TexturePageID);
continue;
}
if (TextureGroups[i].Pages.Contains(item.TexturePageID))
{
TextureGroups[group].Pages.UnionWith(TextureGroups[i].Pages);
if (group > i)
group--;
TextureGroups.RemoveAt(i);
break;
}
}
}
}
// Iterate over all replacedets to find groups (using above functions)
foreach (GMSprite spr in Project.DataHandle.GetChunk<GMChunkSPRT>().List)
iterateEntries(spr.TextureItems);
foreach (GMBackground bg in Project.DataHandle.GetChunk<GMChunkBGND>().List)
{
if (bg.TextureItem != null)
{
bg.TextureItem._HasExtraBorder = true;
findGroupWithPage(bg.TextureItem.TexturePageID);
}
}
foreach (GMFont fnt in Project.DataHandle.GetChunk<GMChunkFONT>().List)
{
if (fnt.TextureItem != null)
{
fnt.TextureItem._EmptyBorder = true;
findGroupWithPage(fnt.TextureItem.TexturePageID);
}
}
var embi = Project.DataHandle.GetChunk<GMChunkEMBI>();
if (embi != null)
{
foreach (var img in embi.List)
{
if (img.TextureItem != null)
findGroupWithPage(img.TextureItem.TexturePageID);
}
}
// Now quickly sort texture groups in case this algorithm gets adjusted
TextureGroups = TextureGroups.OrderBy(x => x.Pages.Min()).ToList();
// replacedemble dictionary from page IDs to group IDs for convenience
for (int i = 0; i < TextureGroups.Count; i++)
{
foreach (int page in TextureGroups[i].Pages)
PageToGroup[page] = i;
}
// Find any others that haven't been made yet (happens with unreferenced textures/modded games)
var tpagList = Project.DataHandle.GetChunk<GMChunkTPAG>().List;
if (PageToGroup.Count != tpagList.Count)
{
for (int i = 0; i < tpagList.Count; i++)
{
if (!PageToGroup.ContainsKey(tpagList[i].TexturePageID))
PageToGroup[i] = findGroupWithPage(tpagList[i].TexturePageID);
}
}
// replacedign all texture entries to groups for further processing
foreach (GMTextureItem entry in Project.DataHandle.GetChunk<GMChunkTPAG>().List)
{
if (entry.TexturePageID == -1)
continue;
if (PageToGroup.TryGetValue(entry.TexturePageID, out int groupId))
TextureGroups[groupId].Items.Add(entry);
else
{
// This is an unreferenced entry
int group = findGroupWithPage(entry.TexturePageID);
PageToGroup[entry.TexturePageID] = group;
TextureGroups[group].Items.Add(entry);
}
}
}
19
Source : LocalTransportThreadModelTest.cs
with MIT License
from cuteant
with MIT License
from cuteant
[Fact]
public async Task TestStagedExecution()
{
IEventLoopGroup l = new DefaultEventLoopGroup(4, new DefaultThreadFactory("l"));
IEventExecutorGroup e1 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e1"));
IEventExecutorGroup e2 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e2"));
ThreadNameAuditor h1 = new ThreadNameAuditor();
ThreadNameAuditor h2 = new ThreadNameAuditor();
ThreadNameAuditor h3 = new ThreadNameAuditor(true);
IChannel ch = new LocalChannel();
// With no EventExecutor specified, h1 will be always invoked by EventLoop 'l'.
ch.Pipeline.AddLast(h1);
// h2 will be always invoked by EventExecutor 'e1'.
ch.Pipeline.AddLast(e1, h2);
// h3 will be always invoked by EventExecutor 'e2'.
ch.Pipeline.AddLast(e2, h3);
await l.RegisterAsync(ch);
await ch.ConnectAsync(_localAddr);
// Fire inbound events from all possible starting points.
ch.Pipeline.FireChannelRead("1");
ch.Pipeline.Context(h1).FireChannelRead("2");
ch.Pipeline.Context(h2).FireChannelRead("3");
ch.Pipeline.Context(h3).FireChannelRead("4");
// Fire outbound events from all possible starting points.
ch.Pipeline.WriteAsync("5").Ignore();
ch.Pipeline.Context(h3).WriteAsync("6").Ignore();
ch.Pipeline.Context(h2).WriteAsync("7").Ignore();
await ch.Pipeline.Context(h1).WriteAndFlushAsync("8");
await ch.CloseAsync();
// Wait until all events are handled completely.
while (h1._outboundThreadNames.Count < 3 || h3._inboundThreadNames.Count < 3 ||
h1._removalThreadNames.Count < 1)
{
if (h1._exception.Value != null)
{
throw h1._exception.Value;
}
if (h2._exception.Value != null)
{
throw h2._exception.Value;
}
if (h3._exception.Value != null)
{
throw h3._exception.Value;
}
Thread.Sleep(10);
}
string currentName = Thread.CurrentThread.Name;
try
{
// Events should never be handled from the current thread.
replacedert.DoesNotContain(currentName, h1._inboundThreadNames);
replacedert.DoesNotContain(currentName, h2._inboundThreadNames);
replacedert.DoesNotContain(currentName, h3._inboundThreadNames);
replacedert.DoesNotContain(currentName, h1._outboundThreadNames);
replacedert.DoesNotContain(currentName, h2._outboundThreadNames);
replacedert.DoesNotContain(currentName, h3._outboundThreadNames);
replacedert.DoesNotContain(currentName, h1._removalThreadNames);
replacedert.DoesNotContain(currentName, h2._removalThreadNames);
replacedert.DoesNotContain(currentName, h3._removalThreadNames);
// replacedert that events were handled by the correct executor.
foreach (string name in h1._inboundThreadNames)
{
replacedert.StartsWith("l-", name);
}
foreach (string name in h2._inboundThreadNames)
{
replacedert.StartsWith("e1-", name);
}
foreach (string name in h3._inboundThreadNames)
{
replacedert.StartsWith("e2-", name);
}
foreach (string name in h1._outboundThreadNames)
{
replacedert.StartsWith("l-", name);
}
foreach (string name in h2._outboundThreadNames)
{
replacedert.StartsWith("e1-", name);
}
foreach (string name in h3._outboundThreadNames)
{
replacedert.StartsWith("e2-", name);
}
foreach (string name in h1._removalThreadNames)
{
replacedert.StartsWith("l-", name);
}
foreach (string name in h2._removalThreadNames)
{
replacedert.StartsWith("e1-", name);
}
foreach (string name in h3._removalThreadNames)
{
replacedert.StartsWith("e2-", name);
}
// replacedert that the events for the same handler were handled by the same thread.
HashSet<string> names = new HashSet<string>();
names.UnionWith(h1._inboundThreadNames);
names.UnionWith(h1._outboundThreadNames);
names.UnionWith(h1._removalThreadNames);
replacedert.Single(names);
names.Clear();
names.UnionWith(h2._inboundThreadNames);
names.UnionWith(h2._outboundThreadNames);
names.UnionWith(h2._removalThreadNames);
replacedert.Single(names);
names.Clear();
names.UnionWith(h3._inboundThreadNames);
names.UnionWith(h3._outboundThreadNames);
names.UnionWith(h3._removalThreadNames);
replacedert.Single(names);
// Count the number of events
replacedert.Single(h1._inboundThreadNames);
replacedert.Equal(2, h2._inboundThreadNames.Count);
replacedert.Equal(3, h3._inboundThreadNames.Count);
replacedert.Equal(3, h1._outboundThreadNames.Count);
replacedert.Equal(2, h2._outboundThreadNames.Count);
replacedert.Single(h3._outboundThreadNames);
replacedert.Single(h1._removalThreadNames);
replacedert.Single(h2._removalThreadNames);
replacedert.Single(h3._removalThreadNames);
}
catch (Exception)
{
//System.out.println("H1I: " + h1.inboundThreadNames);
//System.out.println("H2I: " + h2.inboundThreadNames);
//System.out.println("H3I: " + h3.inboundThreadNames);
//System.out.println("H1O: " + h1.outboundThreadNames);
//System.out.println("H2O: " + h2.outboundThreadNames);
//System.out.println("H3O: " + h3.outboundThreadNames);
//System.out.println("H1R: " + h1.removalThreadNames);
//System.out.println("H2R: " + h2.removalThreadNames);
//System.out.println("H3R: " + h3.removalThreadNames);
throw;
}
finally
{
Task.WaitAll(
l.ShutdownGracefullyAsync(),
e1.ShutdownGracefullyAsync(),
e2.ShutdownGracefullyAsync());
}
}
19
Source : LoggingHandler.cs
with MIT License
from cuteant
with MIT License
from cuteant
public void SetInterest(params Event[] events)
{
_interest.Clear();
_interest.UnionWith(events);
}
19
Source : PackagesFileService.cs
with Apache License 2.0
from CycloneDX
with Apache License 2.0
from CycloneDX
public async Task<HashSet<NugetPackage>> RecursivelyGetNugetPackagesAsync(string directoryPath)
{
var packages = new HashSet<NugetPackage>();
var packageFiles = _fileDiscoveryService.GetPackagesConfigFiles(directoryPath);
foreach (var packageFile in packageFiles)
{
var newPackages = await GetNugetPackagesAsync(packageFile).ConfigureAwait(false);
packages.UnionWith(newPackages);
}
return packages;
}
19
Source : ProjectFileService.cs
with Apache License 2.0
from CycloneDX
with Apache License 2.0
from CycloneDX
public async Task<HashSet<NugetPackage>> GetProjectNugetPackagesAsync(string projectFilePath, string baseIntermediateOutputPath, bool excludeTestProjects)
{
if (!_fileSystem.File.Exists(projectFilePath))
{
Console.Error.WriteLine($"Project file \"{projectFilePath}\" does not exist");
return new HashSet<NugetPackage>();
}
var isTestProject = IsTestProject(projectFilePath);
var packages = new HashSet<NugetPackage>();
Console.WriteLine();
Console.WriteLine($"» replacedyzing: {projectFilePath}");
if (excludeTestProjects && isTestProject)
{
Console.WriteLine($"Skipping: {projectFilePath}");
return new HashSet<NugetPackage>();
}
if (!DisablePackageRestore) {
Console.WriteLine(" Attempting to restore packages");
var restoreResult = _dotnetUtilsService.Restore(projectFilePath);
if (restoreResult.Success)
{
Console.WriteLine(" Packages restored");
}
else
{
Console.WriteLine("Dotnet restore failed:");
Console.WriteLine(restoreResult.ErrorMessage);
throw new DotnetRestoreException($"Dotnet restore failed with message: {restoreResult.ErrorMessage}");
}
}
var replacedetsFilename = _fileSystem.Path.Combine(GetProjectProperty(projectFilePath, baseIntermediateOutputPath), "project.replacedets.json");
if (!File.Exists(replacedetsFilename))
{
Console.WriteLine($"File not found: \"{replacedetsFilename}\", \"{projectFilePath}\" ");
}
packages.UnionWith(_projectreplacedetsFileService.GetNugetPackages(replacedetsFilename, isTestProject));
// if there are no project file package references look for a packages.config
if (!packages.Any())
{
Console.WriteLine(" No packages found");
var directoryPath = _fileSystem.Path.GetDirectoryName(projectFilePath);
var packagesPath = _fileSystem.Path.Combine(directoryPath, "packages.config");
if (_fileSystem.File.Exists(packagesPath))
{
Console.WriteLine(" Found packages.config. Will attempt to process");
packages = await _packagesFileService.GetNugetPackagesAsync(packagesPath).ConfigureAwait(false);
}
}
return packages;
}
19
Source : ProjectFileService.cs
with Apache License 2.0
from CycloneDX
with Apache License 2.0
from CycloneDX
public async Task<HashSet<NugetPackage>> RecursivelyGetProjectNugetPackagesAsync(string projectFilePath, string baseIntermediateOutputPath, bool excludeTestProjects)
{
var nugetPackages = await GetProjectNugetPackagesAsync(projectFilePath, baseIntermediateOutputPath, excludeTestProjects).ConfigureAwait(false);
var projectReferences = await RecursivelyGetProjectReferencesAsync(projectFilePath).ConfigureAwait(false);
foreach (var project in projectReferences)
{
var projectNugetPackages = await GetProjectNugetPackagesAsync(project, baseIntermediateOutputPath, excludeTestProjects).ConfigureAwait(false);
nugetPackages.UnionWith(projectNugetPackages);
}
return nugetPackages;
}
19
Source : SolutionFileService.cs
with Apache License 2.0
from CycloneDX
with Apache License 2.0
from CycloneDX
public async Task<HashSet<string>> GetSolutionProjectReferencesAsync(string solutionFilePath)
{
var solutionFolder = _fileSystem.Path.GetDirectoryName(solutionFilePath);
var projects = new HashSet<string>();
using (var reader = _fileSystem.File.OpenText(solutionFilePath))
{
string line;
while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
{
if (!line.StartsWith("Project", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var regex = new Regex("(.*) = \"(.*?)\", \"(.*?)\"");
var match = regex.Match(line);
if (match.Success)
{
var relativeProjectPath = match.Groups[3].Value.Replace('\\', _fileSystem.Path.DirectorySeparatorChar);
var projectFile = _fileSystem.Path.GetFullPath(_fileSystem.Path.Combine(solutionFolder, relativeProjectPath));
if (Utils.IsSupportedProjectType(projectFile)) projects.Add(projectFile);
}
}
}
var projectList = new List<string>(projects);
foreach (var project in projectList)
{
var projectReferences = await _projectFileService.RecursivelyGetProjectReferencesAsync(project).ConfigureAwait(false);
projects.UnionWith(projectReferences);
}
return projects;
}
19
Source : SolutionFileService.cs
with Apache License 2.0
from CycloneDX
with Apache License 2.0
from CycloneDX
public async Task<HashSet<NugetPackage>> GetSolutionNugetPackages(string solutionFilePath, string baseIntermediateOutputPath, bool excludeTestProjects)
{
if (!_fileSystem.File.Exists(solutionFilePath))
{
Console.Error.WriteLine($"Solution file \"{solutionFilePath}\" does not exist");
return new HashSet<NugetPackage>();
}
Console.WriteLine();
Console.WriteLine($"» Solution: {solutionFilePath}");
Console.WriteLine(" Getting projects");
var packages = new HashSet<NugetPackage>();
var projectPaths = await GetSolutionProjectReferencesAsync(solutionFilePath).ConfigureAwait(false);
if (projectPaths.Count == 0)
{
Console.Error.WriteLine(" No projects found");
}
else
{
Console.WriteLine($" {projectPaths.Count} project(s) found");
}
// Process first all productive projects, then test projects (scope order)
var projectQuery = from p in projectPaths orderby ProjectFileService.IsTestProject(p) select p;
foreach (var projectFilePath in projectQuery)
{
Console.WriteLine();
var projectPackages = await _projectFileService.GetProjectNugetPackagesAsync(projectFilePath, baseIntermediateOutputPath, excludeTestProjects).ConfigureAwait(false);
packages.UnionWith(projectPackages);
}
return packages;
}
19
Source : AddrParser.cs
with BSD 3-Clause "New" or "Revised" License
from dabi0ne
with BSD 3-Clause "New" or "Revised" License
from dabi0ne
public static HashSet<string> ParseTargets(string input)
{
HashSet<string> result = new HashSet<string>();
string[] targets = input.Split(' ');
int cidr_count = 0;
foreach (string target in targets)
{
// check if target contains letter then consider it as hostname
if (target.Count(char.IsLetter) > 1)
{
result.Add(target);
}
else
{
cidr_count = target.Count(c => c == '/');
if (cidr_count > 1)
{
throw new Exception("Invalid target syntax : " + target);
}
else if (cidr_count == 1)
{
result.UnionWith(ParseCIDR(target));
}
else
{
result.UnionWith(ParseRange(target));
}
}
}
return result;
}
19
Source : HashSet2.0Tests.cs
with MIT License
from dahall
with MIT License
from dahall
[Test]
public void UnionWithTest()
{
var s1 = new HashSet<string>();
replacedert.That(() => s1.UnionWith(null), Throws.Exception);
var e1 = NumGen(0, 2, 5).ToArray();
s1.UnionWith(e1);
replacedert.That(s1, Is.EquivalentTo(e1));
s1.UnionWith(s1);
replacedert.That(s1, Is.EquivalentTo(e1));
s1.UnionWith(e1);
replacedert.That(s1, Is.EquivalentTo(e1));
var s2 = new HashSet<string>(NumGen(10, 2, 5));
s1.UnionWith(s2);
replacedert.That(s1.Count, Is.EqualTo(10));
s1.UnionWith(s2);
replacedert.That(s1.Count, Is.EqualTo(10));
var s3 = new HashSet<string>(NumGen(16, 2, 5));
s1.UnionWith(s3);
replacedert.That(s1.Count, Is.EqualTo(13));
}
See More Examples