content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using Ultraviolet.Presentation.Animations;
namespace Ultraviolet.Presentation.Styles
{
/// <summary>
/// Represents an Ultraviolet Style Sheet document's representation of a storyboard animation.
/// </summary>
public sealed class UvssStoryboard
{
/// <summary>
/// Initializes a new instance of the <see cref="UvssStoryboard"/> class.
/// </summary>
/// <param name="name">The storyboard's name.</param>
/// <param name="loopBehavior">The storyboard's loop behavior.</param>
/// <param name="targets">The storyboard's collection of targets.</param>
internal UvssStoryboard(String name, LoopBehavior loopBehavior, UvssStoryboardTargetCollection targets)
{
this.name = name;
this.loopBehavior = loopBehavior;
this.targets = targets;
}
/// <summary>
/// Gets the storyboard's name.
/// </summary>
public String Name
{
get { return name; }
}
/// <summary>
/// Gets the storyboard's loop behavior.
/// </summary>
public LoopBehavior LoopBehavior
{
get { return loopBehavior; }
}
/// <summary>
/// Gets the storyboard's collection of targets.
/// </summary>
public UvssStoryboardTargetCollection Targets
{
get { return targets; }
}
// Property values.
private readonly String name;
private readonly LoopBehavior loopBehavior;
private readonly UvssStoryboardTargetCollection targets;
}
}
| 30.481481 | 111 | 0.589915 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet.Presentation/Shared/Styles/UvssStoryboard.cs | 1,648 | C# |
namespace SFundR.SharedKernel.Interfaces;
// Apply this marker interface only to aggregate root entities
// Repositories will only work with aggregate roots, not their children
public interface IAggregateRoot
{
}
| 26.875 | 71 | 0.813953 | [
"MIT"
] | plipowczan/SFundR | src/SFundR.SharedKernel/Interfaces/IAggregateRoot.cs | 217 | C# |
namespace CarPartsManager.App.Base
{
using System.Windows.Forms;
public interface IValidationRule
{
string ErrorMessage { get; }
bool Validate(Control control);
}
}
| 16.666667 | 39 | 0.655 | [
"MIT"
] | andre197/CarPartsManager | CarPartsManager/CarPartsManager.App/Base/IValidationRule.cs | 202 | C# |
#nullable enable
using System.Threading.Tasks;
using Content.Server.NodeContainer;
using Content.Server.NodeContainer.Nodes;
using Content.Server.Power.Components;
using Content.Server.Power.EntitySystems;
using Content.Server.Power.Nodes;
using Content.Shared.Coordinates;
using NUnit.Framework;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Timing;
namespace Content.IntegrationTests.Tests.Power
{
[Parallelizable(ParallelScope.Fixtures)]
[TestFixture]
public sealed class PowerTest : ContentIntegrationTest
{
private const string Prototypes = @"
- type: entity
id: GeneratorDummy
components:
- type: NodeContainer
nodes:
output:
!type:CableDeviceNode
nodeGroupID: HVPower
- type: PowerSupplier
- type: Transform
anchored: true
- type: entity
id: ConsumerDummy
components:
- type: Transform
anchored: true
- type: NodeContainer
nodes:
input:
!type:CableDeviceNode
nodeGroupID: HVPower
- type: PowerConsumer
- type: entity
id: ChargingBatteryDummy
components:
- type: Transform
anchored: true
- type: NodeContainer
nodes:
output:
!type:CableDeviceNode
nodeGroupID: HVPower
- type: PowerNetworkBattery
- type: Battery
- type: BatteryCharger
- type: entity
id: DischargingBatteryDummy
components:
- type: Transform
anchored: true
- type: NodeContainer
nodes:
output:
!type:CableDeviceNode
nodeGroupID: HVPower
- type: PowerNetworkBattery
- type: Battery
- type: BatteryDischarger
- type: entity
id: FullBatteryDummy
components:
- type: Transform
anchored: true
- type: NodeContainer
nodes:
output:
!type:CableDeviceNode
nodeGroupID: HVPower
input:
!type:CableTerminalPortNode
nodeGroupID: HVPower
- type: PowerNetworkBattery
- type: Battery
- type: BatteryDischarger
node: output
- type: BatteryCharger
node: input
- type: entity
id: SubstationDummy
components:
- type: NodeContainer
nodes:
input:
!type:CableDeviceNode
nodeGroupID: HVPower
output:
!type:CableDeviceNode
nodeGroupID: MVPower
- type: BatteryCharger
voltage: High
- type: BatteryDischarger
voltage: Medium
- type: PowerNetworkBattery
maxChargeRate: 1000
maxSupply: 1000
supplyRampTolerance: 1000
- type: Battery
maxCharge: 1000
startingCharge: 1000
- type: Transform
anchored: true
- type: entity
id: ApcDummy
components:
- type: Battery
maxCharge: 10000
startingCharge: 10000
- type: PowerNetworkBattery
maxChargeRate: 1000
maxSupply: 1000
supplyRampTolerance: 1000
- type: BatteryCharger
voltage: Medium
- type: BatteryDischarger
voltage: Apc
- type: Apc
voltage: Apc
- type: NodeContainer
nodes:
input:
!type:CableDeviceNode
nodeGroupID: MVPower
output:
!type:CableDeviceNode
nodeGroupID: Apc
- type: Transform
anchored: true
- type: UserInterface
interfaces:
- key: enum.ApcUiKey.Key
type: ApcBoundUserInterface
- type: AccessReader
access: [['Engineering']]
- type: entity
id: ApcPowerReceiverDummy
components:
- type: ApcPowerReceiver
- type: ExtensionCableReceiver
- type: Transform
anchored: true
";
private ServerIntegrationInstance _server = default!;
private IMapManager _mapManager = default!;
private IEntityManager _entityManager = default!;
private IGameTiming _gameTiming = default!;
private ExtensionCableSystem _extensionCableSystem = default!;
[OneTimeSetUp]
public async Task Setup()
{
var options = new ServerIntegrationOptions {ExtraPrototypes = Prototypes};
_server = StartServer(options);
await _server.WaitIdleAsync();
_mapManager = _server.ResolveDependency<IMapManager>();
_entityManager = _server.ResolveDependency<IEntityManager>();
_gameTiming = _server.ResolveDependency<IGameTiming>();
_extensionCableSystem = _entityManager.EntitySysManager.GetEntitySystem<ExtensionCableSystem>();
}
/// <summary>
/// Test small power net with a simple surplus of power over the loads.
/// </summary>
[Test]
public async Task TestSimpleSurplus()
{
const float loadPower = 200;
PowerSupplierComponent supplier = default!;
PowerConsumerComponent consumer1 = default!;
PowerConsumerComponent consumer2 = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 3; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var generatorEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates());
var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 1));
var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2));
supplier = _entityManager.GetComponent<PowerSupplierComponent>(generatorEnt);
consumer1 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt1);
consumer2 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt2);
// Plenty of surplus and tolerance
supplier.MaxSupply = loadPower * 4;
supplier.SupplyRampTolerance = loadPower * 4;
consumer1.DrawRate = loadPower;
consumer2.DrawRate = loadPower;
});
_server.RunTicks(1); //let run a tick for PowerNet to process power
_server.Assert(() =>
{
// Assert both consumers fully powered
Assert.That(consumer1.ReceivedPower, Is.EqualTo(consumer1.DrawRate).Within(0.1));
Assert.That(consumer2.ReceivedPower, Is.EqualTo(consumer2.DrawRate).Within(0.1));
// Assert that load adds up on supply.
Assert.That(supplier.CurrentSupply, Is.EqualTo(loadPower * 2).Within(0.1));
});
await _server.WaitIdleAsync();
}
/// <summary>
/// Test small power net with a simple deficit of power over the loads.
/// </summary>
[Test]
public async Task TestSimpleDeficit()
{
const float loadPower = 200;
PowerSupplierComponent supplier = default!;
PowerConsumerComponent consumer1 = default!;
PowerConsumerComponent consumer2 = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 3; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var generatorEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates());
var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 1));
var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2));
supplier = _entityManager.GetComponent<PowerSupplierComponent>(generatorEnt);
consumer1 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt1);
consumer2 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt2);
// Too little supply, both consumers should get 33% power.
supplier.MaxSupply = loadPower;
supplier.SupplyRampTolerance = loadPower;
consumer1.DrawRate = loadPower;
consumer2.DrawRate = loadPower * 2;
});
_server.RunTicks(1); //let run a tick for PowerNet to process power
_server.Assert(() =>
{
// Assert both consumers get 33% power.
Assert.That(consumer1.ReceivedPower, Is.EqualTo(consumer1.DrawRate / 3).Within(0.1));
Assert.That(consumer2.ReceivedPower, Is.EqualTo(consumer2.DrawRate / 3).Within(0.1));
// Supply should be maxed out
Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task TestSupplyRamp()
{
PowerSupplierComponent supplier = default!;
PowerConsumerComponent consumer = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 3; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var generatorEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates());
var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2));
supplier = _entityManager.GetComponent<PowerSupplierComponent>(generatorEnt);
consumer = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt);
// Supply has enough total power but needs to ramp up to match.
supplier.MaxSupply = 400;
supplier.SupplyRampRate = 400;
supplier.SupplyRampTolerance = 100;
consumer.DrawRate = 400;
});
// Exact values can/will be off by a tick, add tolerance for that.
var tickRate = (float) _gameTiming.TickPeriod.TotalSeconds;
var tickDev = 400 * tickRate * 1.1f;
_server.RunTicks(1);
_server.Assert(() =>
{
// First tick, supply should be delivering 100 W (max tolerance) and start ramping up.
Assert.That(supplier.CurrentSupply, Is.EqualTo(100).Within(0.1));
Assert.That(consumer.ReceivedPower, Is.EqualTo(100).Within(0.1));
});
_server.RunTicks(14);
_server.Assert(() =>
{
// After 15 ticks (0.25 seconds), supply ramp pos should be at 100 W and supply at 100, approx.
Assert.That(supplier.CurrentSupply, Is.EqualTo(200).Within(tickDev));
Assert.That(supplier.SupplyRampPosition, Is.EqualTo(100).Within(tickDev));
Assert.That(consumer.ReceivedPower, Is.EqualTo(200).Within(tickDev));
});
_server.RunTicks(45);
_server.Assert(() =>
{
// After 1 second total, ramp should be at 400 and supply should be at 400, everybody happy.
Assert.That(supplier.CurrentSupply, Is.EqualTo(400).Within(tickDev));
Assert.That(supplier.SupplyRampPosition, Is.EqualTo(400).Within(tickDev));
Assert.That(consumer.ReceivedPower, Is.EqualTo(400).Within(tickDev));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task TestBatteryRamp()
{
const float startingCharge = 100_000;
PowerNetworkBatteryComponent netBattery = default!;
BatteryComponent battery = default!;
PowerConsumerComponent consumer = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 3; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var generatorEnt = _entityManager.SpawnEntity("DischargingBatteryDummy", grid.ToCoordinates());
var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2));
netBattery = _entityManager.GetComponent<PowerNetworkBatteryComponent>(generatorEnt);
battery = _entityManager.GetComponent<BatteryComponent>(generatorEnt);
consumer = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt);
battery.MaxCharge = startingCharge;
battery.CurrentCharge = startingCharge;
netBattery.MaxSupply = 400;
netBattery.SupplyRampRate = 400;
netBattery.SupplyRampTolerance = 100;
consumer.DrawRate = 400;
});
// Exact values can/will be off by a tick, add tolerance for that.
var tickRate = (float) _gameTiming.TickPeriod.TotalSeconds;
var tickDev = 400 * tickRate * 1.1f;
_server.RunTicks(1);
_server.Assert(() =>
{
// First tick, supply should be delivering 100 W (max tolerance) and start ramping up.
Assert.That(netBattery.CurrentSupply, Is.EqualTo(100).Within(0.1));
Assert.That(consumer.ReceivedPower, Is.EqualTo(100).Within(0.1));
});
_server.RunTicks(14);
_server.Assert(() =>
{
// After 15 ticks (0.25 seconds), supply ramp pos should be at 100 W and supply at 100, approx.
Assert.That(netBattery.CurrentSupply, Is.EqualTo(200).Within(tickDev));
Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(100).Within(tickDev));
Assert.That(consumer.ReceivedPower, Is.EqualTo(200).Within(tickDev));
// Trivial integral to calculate expected power spent.
const double spentExpected = (200 + 100) / 2.0 * 0.25;
Assert.That(battery.CurrentCharge, Is.EqualTo(startingCharge - spentExpected).Within(tickDev));
});
_server.RunTicks(45);
_server.Assert(() =>
{
// After 1 second total, ramp should be at 400 and supply should be at 400, everybody happy.
Assert.That(netBattery.CurrentSupply, Is.EqualTo(400).Within(tickDev));
Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(400).Within(tickDev));
Assert.That(consumer.ReceivedPower, Is.EqualTo(400).Within(tickDev));
// Trivial integral to calculate expected power spent.
const double spentExpected = (400 + 100) / 2.0 * 0.75 + 400 * 0.25;
Assert.That(battery.CurrentCharge, Is.EqualTo(startingCharge - spentExpected).Within(tickDev));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task TestSimpleBatteryChargeDeficit()
{
PowerSupplierComponent supplier = default!;
BatteryComponent battery = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 3; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var generatorEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates());
var batteryEnt = _entityManager.SpawnEntity("ChargingBatteryDummy", grid.ToCoordinates(0, 2));
supplier = _entityManager.GetComponent<PowerSupplierComponent>(generatorEnt);
var netBattery = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt);
battery = _entityManager.GetComponent<BatteryComponent>(batteryEnt);
supplier.MaxSupply = 500;
supplier.SupplyRampTolerance = 500;
battery.MaxCharge = 100000;
netBattery.MaxChargeRate = 1000;
netBattery.Efficiency = 0.5f;
});
_server.RunTicks(30); // 60 TPS, 0.5 seconds
_server.Assert(() =>
{
// half a second @ 500 W = 250
// 50% efficiency, so 125 J stored total.
Assert.That(battery.CurrentCharge, Is.EqualTo(125).Within(0.1));
Assert.That(supplier.CurrentSupply, Is.EqualTo(500).Within(0.1));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task TestFullBattery()
{
PowerConsumerComponent consumer = default!;
PowerSupplierComponent supplier = default!;
PowerNetworkBatteryComponent netBattery = default!;
BatteryComponent battery = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 4; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1));
_entityManager.GetComponent<TransformComponent>(terminal).LocalRotation = Angle.FromDegrees(180);
var batteryEnt = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2));
var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 0));
var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 3));
consumer = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt);
supplier = _entityManager.GetComponent<PowerSupplierComponent>(supplyEnt);
netBattery = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt);
battery = _entityManager.GetComponent<BatteryComponent>(batteryEnt);
// Consumer needs 1000 W, supplier can only provide 800, battery fills in the remaining 200.
consumer.DrawRate = 1000;
supplier.MaxSupply = 800;
supplier.SupplyRampTolerance = 800;
netBattery.MaxSupply = 400;
netBattery.SupplyRampTolerance = 400;
netBattery.SupplyRampRate = 100_000;
battery.MaxCharge = 100_000;
battery.CurrentCharge = 100_000;
});
// Run some ticks so everything is stable.
_server.RunTicks(60);
// Exact values can/will be off by a tick, add tolerance for that.
var tickRate = (float) _gameTiming.TickPeriod.TotalSeconds;
var tickDev = 400 * tickRate * 1.1f;
_server.Assert(() =>
{
Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.1));
Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1));
// Battery's current supply includes passed-through power from the supply.
// Assert ramp position is correct to make sure it's only supplying 200 W for real.
Assert.That(netBattery.CurrentSupply, Is.EqualTo(1000).Within(0.1));
Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(200).Within(0.1));
const int expectedSpent = 200;
Assert.That(battery.CurrentCharge, Is.EqualTo(battery.MaxCharge - expectedSpent).Within(tickDev));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task TestFullBatteryEfficiencyPassThrough()
{
PowerConsumerComponent consumer = default!;
PowerSupplierComponent supplier = default!;
PowerNetworkBatteryComponent netBattery = default!;
BatteryComponent battery = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 4; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1));
_entityManager.GetComponent<TransformComponent>(terminal).LocalRotation = Angle.FromDegrees(180);
var batteryEnt = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2));
var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 0));
var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 3));
consumer = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt);
supplier = _entityManager.GetComponent<PowerSupplierComponent>(supplyEnt);
netBattery = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt);
battery = _entityManager.GetComponent<BatteryComponent>(batteryEnt);
// Consumer needs 1000 W, supply and battery can only provide 400 each.
// BUT the battery has 50% input efficiency, so 50% of the power of the supply gets lost.
consumer.DrawRate = 1000;
supplier.MaxSupply = 400;
supplier.SupplyRampTolerance = 400;
netBattery.MaxSupply = 400;
netBattery.SupplyRampTolerance = 400;
netBattery.SupplyRampRate = 100_000;
netBattery.Efficiency = 0.5f;
battery.MaxCharge = 1_000_000;
battery.CurrentCharge = 1_000_000;
});
// Run some ticks so everything is stable.
_server.RunTicks(60);
// Exact values can/will be off by a tick, add tolerance for that.
var tickRate = (float) _gameTiming.TickPeriod.TotalSeconds;
var tickDev = 400 * tickRate * 1.1f;
_server.Assert(() =>
{
Assert.That(consumer.ReceivedPower, Is.EqualTo(600).Within(0.1));
Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1));
Assert.That(netBattery.CurrentSupply, Is.EqualTo(600).Within(0.1));
Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(400).Within(0.1));
const int expectedSpent = 400;
Assert.That(battery.CurrentCharge, Is.EqualTo(battery.MaxCharge - expectedSpent).Within(tickDev));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task TestFullBatteryEfficiencyDemandPassThrough()
{
PowerConsumerComponent consumer1 = default!;
PowerConsumerComponent consumer2 = default!;
PowerSupplierComponent supplier = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Map layout here is
// C - consumer
// B - battery
// G - generator
// B - battery
// C - consumer
// Connected in the only way that makes sense.
// Power only works when anchored
for (var i = 0; i < 5; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
_entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2));
var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2));
_entityManager.GetComponent<TransformComponent>(terminal).LocalRotation = Angle.FromDegrees(180);
var batteryEnt1 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 1));
var batteryEnt2 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 3));
var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 2));
var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 0));
var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 4));
consumer1 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt1);
consumer2 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt2);
supplier = _entityManager.GetComponent<PowerSupplierComponent>(supplyEnt);
var netBattery1 = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt1);
var netBattery2 = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt2);
var battery1 = _entityManager.GetComponent<BatteryComponent>(batteryEnt1);
var battery2 = _entityManager.GetComponent<BatteryComponent>(batteryEnt2);
// There are two loads, 500 W and 1000 W respectively.
// The 500 W load is behind a 50% efficient battery,
// so *effectively* it needs 2x as much power from the supply to run.
// Assert that both are getting 50% power.
// Batteries are empty and only a bridge.
consumer1.DrawRate = 500;
consumer2.DrawRate = 1000;
supplier.MaxSupply = 1000;
supplier.SupplyRampTolerance = 1000;
battery1.MaxCharge = 1_000_000;
battery2.MaxCharge = 1_000_000;
netBattery1.MaxChargeRate = 1_000;
netBattery2.MaxChargeRate = 1_000;
netBattery1.Efficiency = 0.5f;
netBattery1.MaxSupply = 1_000_000;
netBattery2.MaxSupply = 1_000_000;
netBattery1.SupplyRampTolerance = 1_000_000;
netBattery2.SupplyRampTolerance = 1_000_000;
});
// Run some ticks so everything is stable.
_server.RunTicks(10);
_server.Assert(() =>
{
Assert.That(consumer1.ReceivedPower, Is.EqualTo(250).Within(0.1));
Assert.That(consumer2.ReceivedPower, Is.EqualTo(500).Within(0.1));
Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1));
});
await _server.WaitIdleAsync();
}
/// <summary>
/// Test that power is distributed proportionally, even through batteries.
/// </summary>
[Test]
public async Task TestBatteriesProportional()
{
PowerConsumerComponent consumer1 = default!;
PowerConsumerComponent consumer2 = default!;
PowerSupplierComponent supplier = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Map layout here is
// C - consumer
// B - battery
// G - generator
// B - battery
// C - consumer
// Connected in the only way that makes sense.
// Power only works when anchored
for (var i = 0; i < 5; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
_entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2));
var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2));
_entityManager.GetComponent<TransformComponent>(terminal).LocalRotation = Angle.FromDegrees(180);
var batteryEnt1 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 1));
var batteryEnt2 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 3));
var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 2));
var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 0));
var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 4));
consumer1 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt1);
consumer2 = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt2);
supplier = _entityManager.GetComponent<PowerSupplierComponent>(supplyEnt);
var netBattery1 = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt1);
var netBattery2 = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt2);
var battery1 = _entityManager.GetComponent<BatteryComponent>(batteryEnt1);
var battery2 = _entityManager.GetComponent<BatteryComponent>(batteryEnt2);
consumer1.DrawRate = 500;
consumer2.DrawRate = 1000;
supplier.MaxSupply = 1000;
supplier.SupplyRampTolerance = 1000;
battery1.MaxCharge = 1_000_000;
battery2.MaxCharge = 1_000_000;
netBattery1.MaxChargeRate = 20;
netBattery2.MaxChargeRate = 20;
netBattery1.MaxSupply = 1_000_000;
netBattery2.MaxSupply = 1_000_000;
netBattery1.SupplyRampTolerance = 1_000_000;
netBattery2.SupplyRampTolerance = 1_000_000;
});
// Run some ticks so everything is stable.
_server.RunTicks(60);
_server.Assert(() =>
{
// NOTE: MaxChargeRate on batteries actually skews the demand.
// So that's why the tolerance is so high, the charge rate is so *low*,
// and we run so many ticks to stabilize.
Assert.That(consumer1.ReceivedPower, Is.EqualTo(333.333).Within(10));
Assert.That(consumer2.ReceivedPower, Is.EqualTo(666.666).Within(10));
Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task TestBatteryEngineCut()
{
PowerConsumerComponent consumer = default!;
PowerSupplierComponent supplier = default!;
PowerNetworkBatteryComponent netBattery = default!;
_server.Post(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 4; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, i));
}
var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1));
_entityManager.GetComponent<TransformComponent>(terminal).LocalRotation = Angle.FromDegrees(180);
var batteryEnt = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2));
var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 0));
var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 3));
consumer = _entityManager.GetComponent<PowerConsumerComponent>(consumerEnt);
supplier = _entityManager.GetComponent<PowerSupplierComponent>(supplyEnt);
netBattery = _entityManager.GetComponent<PowerNetworkBatteryComponent>(batteryEnt);
var battery = _entityManager.GetComponent<BatteryComponent>(batteryEnt);
// Consumer needs 1000 W, supplier can only provide 800, battery fills in the remaining 200.
consumer.DrawRate = 1000;
supplier.MaxSupply = 1000;
supplier.SupplyRampTolerance = 1000;
netBattery.MaxSupply = 1000;
netBattery.SupplyRampTolerance = 200;
netBattery.SupplyRampRate = 10;
battery.MaxCharge = 100_000;
battery.CurrentCharge = 100_000;
});
// Run some ticks so everything is stable.
_server.RunTicks(5);
_server.Assert(() =>
{
// Supply and consumer are fully loaded/supplied.
Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.5));
Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.5));
// Cut off the supplier
supplier.Enabled = false;
// Remove tolerance on battery too.
netBattery.SupplyRampTolerance = 5;
});
_server.RunTicks(3);
_server.Assert(() =>
{
// Assert that network drops to 0 power and starts ramping up
Assert.That(consumer.ReceivedPower, Is.LessThan(50).And.GreaterThan(0));
Assert.That(netBattery.CurrentReceiving, Is.EqualTo(0));
Assert.That(netBattery.CurrentSupply, Is.GreaterThan(0));
});
await _server.WaitIdleAsync();
}
/// <summary>
/// Test that <see cref="CableTerminalNode"/> correctly isolates two networks.
/// </summary>
[Test]
public async Task TestTerminalNodeGroups()
{
CableNode leftNode = default!;
CableNode rightNode = default!;
Node batteryInput = default!;
Node batteryOutput = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 4; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
}
var leftEnt = _entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, 0));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, 1));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, 2));
var rightEnt = _entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, 3));
var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1));
_entityManager.GetComponent<TransformComponent>(terminal).LocalRotation = Angle.FromDegrees(180);
var battery = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2));
var batteryNodeContainer = _entityManager.GetComponent<NodeContainerComponent>(battery);
leftNode = _entityManager.GetComponent<NodeContainerComponent>(leftEnt).GetNode<CableNode>("power");
rightNode = _entityManager.GetComponent<NodeContainerComponent>(rightEnt).GetNode<CableNode>("power");
batteryInput = batteryNodeContainer.GetNode<Node>("input");
batteryOutput = batteryNodeContainer.GetNode<Node>("output");
});
// Run ticks to allow node groups to update.
_server.RunTicks(1);
_server.Assert(() =>
{
Assert.That(batteryInput.NodeGroup, Is.EqualTo(leftNode.NodeGroup));
Assert.That(batteryOutput.NodeGroup, Is.EqualTo(rightNode.NodeGroup));
Assert.That(leftNode.NodeGroup, Is.Not.EqualTo(rightNode.NodeGroup));
});
await _server.WaitIdleAsync();
}
[Test]
public async Task ApcChargingTest()
{
PowerNetworkBatteryComponent substationNetBattery = default!;
BatteryComponent apcBattery = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 3; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
}
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, 0));
_entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, 1));
_entityManager.SpawnEntity("CableMV", grid.ToCoordinates(0, 1));
_entityManager.SpawnEntity("CableMV", grid.ToCoordinates(0, 2));
var generatorEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 0));
var substationEnt = _entityManager.SpawnEntity("SubstationDummy", grid.ToCoordinates(0, 1));
var apcEnt = _entityManager.SpawnEntity("ApcDummy", grid.ToCoordinates(0, 2));
var generatorSupplier = _entityManager.GetComponent<PowerSupplierComponent>(generatorEnt);
substationNetBattery = _entityManager.GetComponent<PowerNetworkBatteryComponent>(substationEnt);
apcBattery = _entityManager.GetComponent<BatteryComponent>(apcEnt);
generatorSupplier.MaxSupply = 1000;
generatorSupplier.SupplyRampTolerance = 1000;
apcBattery.CurrentCharge = 0;
});
_server.RunTicks(5); //let run a few ticks for PowerNets to reevaluate and start charging apc
_server.Assert(() =>
{
Assert.That(substationNetBattery.CurrentSupply, Is.GreaterThan(0)); //substation should be providing power
Assert.That(apcBattery.CurrentCharge, Is.GreaterThan(0)); //apc battery should have gained charge
});
await _server.WaitIdleAsync();
}
[Test]
public async Task ApcNetTest()
{
PowerNetworkBatteryComponent apcNetBattery = default!;
ApcPowerReceiverComponent receiver = default!;
_server.Assert(() =>
{
var map = _mapManager.CreateMap();
var grid = _mapManager.CreateGrid(map);
// Power only works when anchored
for (var i = 0; i < 3; i++)
{
grid.SetTile(new Vector2i(0, i), new Tile(1));
}
var apcEnt = _entityManager.SpawnEntity("ApcDummy", grid.ToCoordinates(0, 0));
var apcExtensionEnt = _entityManager.SpawnEntity("CableApcExtension", grid.ToCoordinates(0, 0));
var powerReceiverEnt = _entityManager.SpawnEntity("ApcPowerReceiverDummy", grid.ToCoordinates(0, 2));
receiver = _entityManager.GetComponent<ApcPowerReceiverComponent>(powerReceiverEnt);
var battery = _entityManager.GetComponent<BatteryComponent>(apcEnt);
apcNetBattery = _entityManager.GetComponent<PowerNetworkBatteryComponent>(apcEnt);
_extensionCableSystem.SetProviderTransferRange(apcExtensionEnt, 5);
_extensionCableSystem.SetReceiverReceptionRange(powerReceiverEnt, 5);
battery.MaxCharge = 10000; //arbitrary nonzero amount of charge
battery.CurrentCharge = battery.MaxCharge; //fill battery
receiver.Load = 1; //arbitrary small amount of power
});
_server.RunTicks(1); //let run a tick for ApcNet to process power
_server.Assert(() =>
{
Assert.That(receiver.Powered);
Assert.That(apcNetBattery.CurrentSupply, Is.EqualTo(1).Within(0.1));
});
await _server.WaitIdleAsync();
}
}
}
| 41.274725 | 122 | 0.592652 | [
"MIT"
] | Alainx277/space-station-14 | Content.IntegrationTests/Tests/Power/PowerTest.cs | 41,316 | C# |
using EventAggregator.Interfaces;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using WPF.Basics.MVVM;
using WPF.DashboardLibrary.Events.Dashboard;
using WPF.DashboardLibrary.Events.Login;
using WPF.DashboardStarter.Content;
using WPF.DashboardStarter.Configuration;
using WPF.DashboardStarter.Localization;
using WPF.DashboardStarter.EventArgs;
namespace WPF.DashboardStarter.Dashboard
{
/// <summary>
/// Interaction logic for Dashboard.xaml
/// </summary>
public partial class Dashboard : Window, INotifyPropertyChanged
{
protected IEventAggregator EventAggregator;
#region Dependency Properties
public int SidebarButtonLength
{
get { return (int)GetValue(SidebarButtonLengthProperty); }
set { SetValue(SidebarButtonLengthProperty, value); }
}
public static readonly DependencyProperty SidebarButtonLengthProperty =
DependencyProperty.Register(nameof(SidebarButtonLength), typeof(int), typeof(Dashboard), new PropertyMetadata(50));
public Thickness DashboardContentMargin
{
get { return (Thickness)GetValue(DashboardContentMarginProperty); }
set { SetValue(DashboardContentMarginProperty, value); }
}
public static readonly DependencyProperty DashboardContentMarginProperty =
DependencyProperty.Register(nameof(DashboardContentMargin), typeof(Thickness), typeof(Dashboard), new PropertyMetadata(default(Thickness)));
#endregion
#region Properties
/// <summary>
/// Determine which View is currently visible in the inner Drawer
/// </summary>
private string innerDrawerContent;
public string InnerDrawerContent
{
get { return innerDrawerContent; }
set
{
if (innerDrawerContent != value)
{
innerDrawerContent = value;
InnerDrawerExpanded = true;
}
else
{
InnerDrawerExpanded = !InnerDrawerExpanded;
}
}
}
/// <summary>
/// OuterDrawer expanded or retracted
/// </summary>
private bool outerDrawerExpanded = false;
public bool OuterDrawerExpanded
{
get { return outerDrawerExpanded; }
set
{
if (outerDrawerExpanded != value)
{
outerDrawerExpanded = value;
OnOuterDrawerExpandedChanged();
OnPropertyChanged();
}
}
}
/// <summary>
/// Width of a Button
/// </summary>
private int sidebarsRetractedWidth = 50;
public int SidebarsRetractedWidth
{
get { return sidebarsRetractedWidth; }
set { sidebarsRetractedWidth = value; }
}
/// <summary>
/// InnerDrawer expanded or retracted
/// </summary>
private bool innerDrawerExpanded = false;
public bool InnerDrawerExpanded
{
get { return innerDrawerExpanded; }
set
{
if (innerDrawerExpanded != value)
{
innerDrawerExpanded = value;
OnInnerDrawerExpandedChanged();
}
}
}
/// <summary>
/// Both Drawers are hidden
/// </summary>
private bool bothDrawersCompletelyHidden = true;
public bool BothDrawersCompletelyHidden
{
get { return bothDrawersCompletelyHidden; }
set
{
if (bothDrawersCompletelyHidden != value)
{
bothDrawersCompletelyHidden = value;
if (bothDrawersCompletelyHidden)
{
if (OuterDrawerExpanded)
{
OuterDrawerExpanded = false;
}
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
HideSidebars(500, 1000);
ChangeDashboardContentMargin(DashboardContentMargin_BothDrawersCompletelyHidden);
}));
}
else
{
if (InnerDrawerExpanded)
{
InnerDrawerExpanded = false;
}
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
ShowSidebars(500, 500);
ChangeDashboardContentMargin(DashboardContentMargin_OuterDrawerRetracted);
}));
}
}
}
}
/// <summary>
/// https://stackoverflow.com/questions/10181245/how-can-i-animate-the-margin-of-a-stackpanel-with-a-storyboard
/// </summary>
/// <param name="newMargin"></param>
private void ChangeDashboardContentMargin(Thickness newMargin)
{
var sb = new Storyboard();
var ta = new ThicknessAnimation();
ta.BeginTime = new TimeSpan(0);
ta.SetValue(Storyboard.TargetNameProperty, "DashboardHost");
Storyboard.SetTargetProperty(ta, new PropertyPath(MarginProperty));
ta.From = DashboardContentMargin;
ta.To = newMargin;
ta.Duration = new Duration(TimeSpan.FromMilliseconds(500));
sb.Children.Add(ta);
sb.Begin(this);
DashboardContentMargin = newMargin;
}
private string _ExpandSidebarButtonText;
public string ExpandSidebarButtonText
{
get { return _ExpandSidebarButtonText; }
set
{
_ExpandSidebarButtonText = value;
OnPropertyChanged();
}
}
public string ArrowIconPath
{
get { return Paths.ToggleSidebarIcon; }
}
public string SettingsIconPath
{
get { return Paths.SettingsIcon; }
}
public string BurgerIconPath
{
get { return Paths.BurgerIcon; }
}
public string LaunchIconPath
{
get { return Paths.LaunchProgramsIcon; }
}
private string messageIconPath = Paths.MessageIcon;
public string MessageIconPath
{
get { return messageIconPath; }
set
{
messageIconPath = value;
OnPropertyChanged();
}
}
private bool isLoggedIn = false;
public bool IsLoggedIn
{
get { return isLoggedIn; }
set
{
if (isLoggedIn != value)
{
isLoggedIn = value;
OnPropertyChanged();
BothDrawersCompletelyHidden = !IsLoggedIn;
if (IsLoggedIn)
{
OuterDrawerExpanded = Properties.Dashboard.Default.ShowSidebar;
}
}
}
}
#endregion
#region Variables
private readonly int SidebarsHiddenWidth = 0;
private readonly int SidebarExpandedWidth = 250;
private readonly int InnerDrawerExpandedWidth = 500;
private readonly Thickness DashboardContentMargin_BothDrawersCompletelyHidden;
private readonly Thickness DashboardContentMargin_OuterDrawerRetracted;
private readonly Thickness DashboardContentMargin_OuterDrawerExpanded;
#endregion
#region Commands
private ICommand _ToggleSidebar;
public ICommand ToggleSidebarCommand
{
get
{
if (_ToggleSidebar == null)
{
_ToggleSidebar = new RelayCommand(
p => (IsLoggedIn),
p => OuterDrawerExpanded = !OuterDrawerExpanded);
}
return _ToggleSidebar;
}
}
#endregion
#region Ctor
public Dashboard()
{
InitializeComponent();
if (DataContext is BaseViewModel viewModel)
{
EventAggregator = viewModel.GetEventAggregator;
if (viewModel is DashboardViewModel dashboardViewModel)
{
DashboardViewModel.ContentChanged += DashboardViewModel_ContentChanged;
}
}
InitializeEvents();
DashboardContentMargin_BothDrawersCompletelyHidden = new Thickness(0, 0, 0, 0);
DashboardContentMargin_OuterDrawerRetracted = new Thickness(0, 0, SidebarButtonLength, 0);
DashboardContentMargin_OuterDrawerExpanded = new Thickness(0, 0, SidebarExpandedWidth, 0);
}
private void DashboardViewModel_ContentChanged(object sender, System.EventArgs ea)
{
try
{
if (ea is ContentChangedEventArgs ccea)
{
switch (ccea.userControlLocation)
{
case DashboardLibrary.Enums.UserControlLocation.Unknown:
break;
case DashboardLibrary.Enums.UserControlLocation.Dashboard:
break;
case DashboardLibrary.Enums.UserControlLocation.OuterDrawer:
break;
case DashboardLibrary.Enums.UserControlLocation.InnerDrawer:
InnerDrawerContent = ccea.userControlName;
break;
case DashboardLibrary.Enums.UserControlLocation.Popup:
break;
default:
break;
}
}
}
catch (Exception)
{
}
}
#endregion
#region Init
private void InitializeEvents()
{
EventAggregator?.Subscribe<LoginResponseEvent>(OnLoginResponse);
EventAggregator?.Subscribe<LogoutEvent>(OnLogout);
Titlebar.MouseDown += Titlebar_MouseDown;
Titlebar.MinimizeButton.Click += MinimizeButton_Click;
Titlebar.MaximizeButton.Click += MaximizeButton_Click;
Titlebar.CloseButton.Click += CloseButton_Click;
}
#endregion
#region IEvents
private void OnLogout(LogoutEvent e)
{
IsLoggedIn = false;
}
private void OnLoginResponse(LoginResponseEvent e)
{
if (e.IsValid)
{
IsLoggedIn = true;
}
}
#endregion
#region OuterDrawer Animations
private void OnOuterDrawerExpandedChanged()
{
if (InnerDrawerExpanded && !outerDrawerExpanded)
{
InnerDrawerExpanded = false;
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
RetractInnerDrawer(500);
}));
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
RetractOuterDrawer(500);
RotateArrow(180, 0);
ExpandSidebarButtonText = Strings.HoverText_ExpandSidebar;
}));
}
if (outerDrawerExpanded)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
ExpandSidebar(500);
RotateArrow(0, 180);
ExpandSidebarButtonText = Strings.HoverText_RetractSidebar;
ChangeDashboardContentMargin(DashboardContentMargin_OuterDrawerExpanded);
}));
}
else
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
RetractOuterDrawer(500);
RotateArrow(180, 0);
ExpandSidebarButtonText = Strings.HoverText_ExpandSidebar;
ChangeDashboardContentMargin(DashboardContentMargin_OuterDrawerRetracted);
}));
}
}
private void OnInnerDrawerExpandedChanged()
{
if (InnerDrawerExpanded)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
ExpandInnerDrawer(500);
}));
}
else
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
{
RetractInnerDrawer(1000);
}));
}
}
private void RotateArrow(int from, int to)
{
var da = new DoubleAnimation(from, to, new Duration(TimeSpan.FromMilliseconds(500)));
var rt = new RotateTransform();
Arrow.RenderTransform = rt;
Arrow.RenderTransformOrigin = new Point(0.5, 0.5);
rt.BeginAnimation(RotateTransform.AngleProperty, da);
}
private void RotateSettingsIcon(int from, int to)
{
var da = new DoubleAnimation(from, to, new Duration(TimeSpan.FromMilliseconds(500)));
var rt = new RotateTransform();
SettingsIcon.RenderTransform = rt;
SettingsIcon.RenderTransformOrigin = new Point(0.5, 0.5);
rt.BeginAnimation(RotateTransform.AngleProperty, da);
}
private void HideSidebars(int durationInnerSidebarMs, int durationOuterSidebarMs)
{
ChangeGridWidth(InnerDrawer,
(int)InnerDrawer.Width,
SidebarsHiddenWidth,
TimeSpan.FromMilliseconds(durationInnerSidebarMs));
ChangeGridWidth(OuterDrawer,
(int)OuterDrawer.Width,
SidebarsHiddenWidth,
TimeSpan.FromMilliseconds(durationOuterSidebarMs));
}
private void ShowSidebars(int durationInnerSidebarMs, int durationOuterSidebarMs)
{
ChangeGridWidth(InnerDrawer,
(int)InnerDrawer.Width,
SidebarsRetractedWidth,
TimeSpan.FromMilliseconds(durationInnerSidebarMs));
ChangeGridWidth(OuterDrawer,
(int)OuterDrawer.Width,
SidebarsRetractedWidth,
TimeSpan.FromMilliseconds(durationOuterSidebarMs));
}
private void ExpandSidebar(int durationInMs)
{
ChangeGridWidth(OuterDrawer,
SidebarsRetractedWidth,
SidebarExpandedWidth,
TimeSpan.FromMilliseconds(durationInMs));
}
private void RetractOuterDrawer(int durationInMs)
{
ChangeGridWidth(OuterDrawer,
(int)OuterDrawer.Width,
SidebarsRetractedWidth,
TimeSpan.FromMilliseconds(durationInMs));
}
private void ExpandInnerDrawer(int durationInMs)
{
ChangeGridWidth(InnerDrawer,
SidebarExpandedWidth,
InnerDrawerExpandedWidth,
TimeSpan.FromMilliseconds(durationInMs));
}
private void RetractInnerDrawer(int durationInMs)
{
ChangeGridWidth(InnerDrawer,
(int)InnerDrawer.Width,
SidebarsRetractedWidth,
TimeSpan.FromMilliseconds(durationInMs));
}
private void ChangeGridWidth(Grid grid, int oldWidth, int newWidth, TimeSpan duration)
{
DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames();
LinearDoubleKeyFrame start = new LinearDoubleKeyFrame(oldWidth);
animation.KeyFrames.Add(start);
LinearDoubleKeyFrame end = new LinearDoubleKeyFrame(newWidth, duration);
animation.KeyFrames.Add(end);
grid.BeginAnimation(Grid.WidthProperty, animation);
}
private void Titlebar_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
if (this.WindowState == WindowState.Maximized)
{
this.WindowState = WindowState.Normal;
}
this.DragMove();
}
}
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
{
if (this.WindowState == WindowState.Maximized)
{
this.WindowState = WindowState.Normal;
}
else if (this.WindowState == WindowState.Normal)
{
this.WindowState = WindowState.Maximized;
}
}
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
EventAggregator?.Publish(new DashboardShutdownRequestedEvent());
}
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
| 33.068468 | 152 | 0.543344 | [
"MIT"
] | Architect0711/WPF.Dashboard | WPF.DashboardStarter/Dashboard/Dashboard.xaml.cs | 18,355 | C# |
using System;
using System.IO;
using System.Text;
using ProtoBuf.Meta;
namespace ProtoBuf
{
/// <summary>
/// <para>Represents an output stream for writing protobuf data.</para>
/// <para>
/// Why is the API backwards (static methods with writer arguments)?
/// See: http://marcgravell.blogspot.com/2010/03/last-will-be-first-and-first-will-be.html
/// </para>
/// </summary>
public abstract partial class ProtoWriter : IDisposable
{
internal const string UseStateAPI = ProtoReader.UseStateAPI;
private TypeModel model;
private int packedFieldNumber;
void IDisposable.Dispose()
{
Dispose();
}
/// <summary>
/// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type).
/// </summary>
/// <param name="value">The object to write.</param>
/// <param name="key">The key that uniquely identifies the type within the model.</param>
/// <param name="writer">The destination.</param>
[Obsolete(ProtoWriter.UseStateAPI, false)]
public static void WriteObject(object value, int key, ProtoWriter writer)
{
State state = default;
WriteObject(value, key, writer, ref state);
}
/// <summary>
/// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type).
/// </summary>
/// <param name="value">The object to write.</param>
/// <param name="key">The key that uniquely identifies the type within the model.</param>
/// <param name="writer">The destination.</param>
/// <param name="state">Writer state</param>
public static void WriteObject(object value, int key, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
if (writer.model == null)
{
throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided");
}
SubItemToken token = StartSubItem(value, writer, ref state);
if (key >= 0)
{
writer.model.Serialize(writer, ref state, key, value);
}
else if (writer.model != null && writer.model.TrySerializeAuxiliaryType(writer, ref state, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null))
{
// all ok
}
else
{
TypeModel.ThrowUnexpectedType(value.GetType());
}
EndSubItem(token, writer, ref state);
}
/// <summary>
/// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type) - but the
/// caller is asserting that this relationship is non-recursive; no recursion check will be
/// performed.
/// </summary>
/// <param name="value">The object to write.</param>
/// <param name="key">The key that uniquely identifies the type within the model.</param>
/// <param name="writer">The destination.</param>
[Obsolete(UseStateAPI, false)]
public static void WriteRecursionSafeObject(object value, int key, ProtoWriter writer)
{
State state = default;
WriteRecursionSafeObject(value, key, writer, ref state);
}
/// <summary>
/// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type) - but the
/// caller is asserting that this relationship is non-recursive; no recursion check will be
/// performed.
/// </summary>
/// <param name="value">The object to write.</param>
/// <param name="key">The key that uniquely identifies the type within the model.</param>
/// <param name="writer">The destination.</param>
/// <param name="state">Writer state</param>
public static void WriteRecursionSafeObject(object value, int key, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
if (writer.model == null)
{
throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided");
}
SubItemToken token = StartSubItem(null, writer, ref state);
writer.model.Serialize(writer, ref state, key, value);
EndSubItem(token, writer, ref state);
}
internal static void WriteObject(ProtoWriter writer, ref State state, object value, int key, PrefixStyle style, int fieldNumber)
{
if (writer.model == null)
{
throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided");
}
if (writer.WireType != WireType.None) throw ProtoWriter.CreateException(writer);
switch (style)
{
case PrefixStyle.Base128:
writer.WireType = WireType.String;
writer.fieldNumber = fieldNumber;
if (fieldNumber > 0) WriteHeaderCore(fieldNumber, WireType.String, writer, ref state);
break;
case PrefixStyle.Fixed32:
case PrefixStyle.Fixed32BigEndian:
writer.fieldNumber = 0;
writer.WireType = WireType.Fixed32;
break;
default:
throw new ArgumentOutOfRangeException(nameof(style));
}
SubItemToken token = writer.StartSubItem(ref state, value, style);
if (key < 0)
{
if (!writer.model.TrySerializeAuxiliaryType(writer, ref state, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null))
{
TypeModel.ThrowUnexpectedType(value.GetType());
}
}
else
{
writer.model.Serialize(writer, ref state, key, value);
}
writer.EndSubItem(ref state, token, style);
}
internal int GetTypeKey(ref Type type)
{
return model.GetKey(ref type);
}
internal NetObjectCache NetCache { get; } = new NetObjectCache();
private int fieldNumber;
internal WireType WireType { get; set; }
/// <summary>
/// Writes a field-header, indicating the format of the next data we plan to write.
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer)
{
State state = default;
WriteFieldHeader(fieldNumber, wireType, writer, ref state);
}
/// <summary>
/// Writes a field-header, indicating the format of the next data we plan to write.
/// </summary>
public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
if (writer.WireType != WireType.None)
{
throw new InvalidOperationException("Cannot write a " + wireType.ToString()
+ " header until the " + writer.WireType.ToString() + " data has been written");
}
if (fieldNumber < 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber));
#if DEBUG
switch (wireType)
{ // validate requested header-type
case WireType.Fixed32:
case WireType.Fixed64:
case WireType.String:
case WireType.StartGroup:
case WireType.SignedVariant:
case WireType.Variant:
break; // fine
case WireType.None:
case WireType.EndGroup:
default:
throw new ArgumentException("Invalid wire-type: " + wireType.ToString(), nameof(wireType));
}
#endif
writer._needFlush = true;
if (writer.packedFieldNumber == 0)
{
writer.fieldNumber = fieldNumber;
writer.WireType = wireType;
WriteHeaderCore(fieldNumber, wireType, writer, ref state);
}
else if (writer.packedFieldNumber == fieldNumber)
{ // we'll set things up, but note we *don't* actually write the header here
switch (wireType)
{
case WireType.Fixed32:
case WireType.Fixed64:
case WireType.Variant:
case WireType.SignedVariant:
break; // fine
default:
throw new InvalidOperationException("Wire-type cannot be encoded as packed: " + wireType.ToString());
}
writer.fieldNumber = fieldNumber;
writer.WireType = wireType;
}
else
{
throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString());
}
}
internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer, ref State state)
{
uint header = (((uint)fieldNumber) << 3)
| (((uint)wireType) & 7);
int bytes = writer.ImplWriteVarint32(ref state, header);
writer.Advance(bytes);
}
/// <summary>
/// Writes a byte-array to the stream; supported wire-types: String
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteBytes(byte[] data, ProtoWriter writer)
{
State state = default;
WriteBytes(data, writer, ref state);
}
/// <summary>
/// Writes a byte-array to the stream; supported wire-types: String
/// </summary>
public static void WriteBytes(byte[] data, ProtoWriter writer, ref State state)
{
if (data == null) throw new ArgumentNullException(nameof(data));
WriteBytes(data, 0, data.Length, writer, ref state);
}
/// <summary>
/// Writes a byte-array to the stream; supported wire-types: String
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteBytes(byte[] data, int offset, int length, ProtoWriter writer)
{
State state = default;
WriteBytes(data, offset, length, writer, ref state);
}
/// <summary>
/// Writes a byte-array to the stream; supported wire-types: String
/// </summary>
public static void WriteBytes(byte[] data, int offset, int length, ProtoWriter writer, ref State state)
{
switch (writer.WireType)
{
case WireType.Fixed32:
if (length != 4) throw new ArgumentException(nameof(length));
writer.ImplWriteBytes(ref state, data, offset, 4);
writer.AdvanceAndReset(4);
return;
case WireType.Fixed64:
if (length != 8) throw new ArgumentException(nameof(length));
writer.ImplWriteBytes(ref state, data, offset, 8);
writer.AdvanceAndReset(8);
return;
case WireType.String:
writer.AdvanceAndReset(writer.ImplWriteVarint32(ref state, (uint)length) + length);
if (length == 0) return;
writer.ImplWriteBytes(ref state, data, offset, length);
break;
default:
ThrowException(writer);
break;
}
}
private int depth = 0;
private const int RecursionCheckDepth = 25;
/// <summary>
/// Indicates the start of a nested record.
/// </summary>
/// <param name="instance">The instance to write.</param>
/// <param name="writer">The destination.</param>
/// <returns>A token representing the state of the stream; this token is given to EndSubItem.</returns>
[Obsolete(UseStateAPI, false)]
public static SubItemToken StartSubItem(object instance, ProtoWriter writer)
{
State state = default;
return writer.StartSubItem(ref state, instance, PrefixStyle.Base128);
}
/// <summary>
/// Indicates the start of a nested record.
/// </summary>
/// <param name="instance">The instance to write.</param>
/// <param name="writer">The destination.</param>
/// <param name="state">Writer state</param>
/// <returns>A token representing the state of the stream; this token is given to EndSubItem.</returns>
public static SubItemToken StartSubItem(object instance, ProtoWriter writer, ref State state)
=> writer.StartSubItem(ref state, instance, PrefixStyle.Base128);
private SubItemToken StartSubItem(ref State state, object instance, PrefixStyle style)
{
if (++depth > RecursionCheckDepth)
{
CheckRecursionStackAndPush(instance);
}
if (packedFieldNumber != 0) throw new InvalidOperationException("Cannot begin a sub-item while performing packed encoding");
switch (WireType)
{
case WireType.StartGroup:
WireType = WireType.None;
return new SubItemToken((long)(-fieldNumber));
case WireType.Fixed32:
switch (style)
{
case PrefixStyle.Fixed32:
case PrefixStyle.Fixed32BigEndian:
break; // OK
default:
throw CreateException(this);
}
goto case WireType.String;
case WireType.String:
#if DEBUG
if (model != null && model.ForwardsOnly)
{
throw new ProtoException("Should not be buffering data: " + instance ?? "(null)");
}
#endif
return ImplStartLengthPrefixedSubItem(ref state, instance, style);
default:
throw CreateException(this);
}
}
private MutableList recursionStack;
private void CheckRecursionStackAndPush(object instance)
{
int hitLevel;
if (recursionStack == null) { recursionStack = new MutableList(); }
else if (instance != null && (hitLevel = recursionStack.IndexOfReference(instance)) >= 0)
{
#if DEBUG
Helpers.DebugWriteLine("Stack:");
foreach (object obj in recursionStack)
{
Helpers.DebugWriteLine(obj == null ? "<null>" : obj.ToString());
}
Helpers.DebugWriteLine(instance == null ? "<null>" : instance.ToString());
#endif
#pragma warning disable RCS1097 // Remove redundant 'ToString' call.
throw new ProtoException("Possible recursion detected (offset: " + (recursionStack.Count - hitLevel).ToString() + " level(s)): " + instance.ToString());
#pragma warning restore RCS1097 // Remove redundant 'ToString' call.
}
recursionStack.Add(instance);
}
private void PopRecursionStack() { recursionStack.RemoveLast(); }
/// <summary>
/// Indicates the end of a nested record.
/// </summary>
/// <param name="token">The token obtained from StartubItem.</param>
/// <param name="writer">The destination.</param>
[Obsolete(UseStateAPI, false)]
public static void EndSubItem(SubItemToken token, ProtoWriter writer)
{
State state = default;
writer.EndSubItem(ref state, token, PrefixStyle.Base128);
}
/// <summary>
/// Indicates the end of a nested record.
/// </summary>
/// <param name="token">The token obtained from StartubItem.</param>
/// <param name="writer">The destination.</param>
/// <param name="state">Writer state</param>
public static void EndSubItem(SubItemToken token, ProtoWriter writer, ref State state)
=> writer.EndSubItem(ref state, token, PrefixStyle.Base128);
private void EndSubItem(ref State state, SubItemToken token, PrefixStyle style)
{
if (WireType != WireType.None) { throw CreateException(this); }
int value = (int)token.value64;
if (depth <= 0) throw CreateException(this);
if (depth-- > RecursionCheckDepth)
{
PopRecursionStack();
}
packedFieldNumber = 0; // ending the sub-item always wipes packed encoding
if (value < 0)
{ // group - very simple append
WriteHeaderCore(-value, WireType.EndGroup, this, ref state);
WireType = WireType.None;
return;
}
ImplEndLengthPrefixedSubItem(ref state, token, style);
}
/// <summary>
/// Creates a new writer against a stream
/// </summary>
/// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects</param>
/// <param name="context">Additional context about this serialization operation</param>
protected private ProtoWriter(TypeModel model, SerializationContext context)
{
this.model = model;
WireType = WireType.None;
if (context == null) { context = SerializationContext.Default; }
else { context.Freeze(); }
Context = context;
}
/// <summary>
/// Addition information about this serialization operation.
/// </summary>
public SerializationContext Context { get; }
protected private virtual void Dispose()
{
if (depth == 0 && _needFlush && ImplDemandFlushOnDispose)
{
throw new InvalidOperationException("Writer was diposed without being flushed; data may be lost - you should ensure that Flush (or Abandon) is called");
}
model = null;
}
/// <summary>
/// Abandon any pending unflushed data
/// </summary>
public void Abandon() { _needFlush = false; }
private bool _needFlush;
// note that this is used by some of the unit tests and should not be removed
#pragma warning disable RCS1163 // Unused parameter.
internal static long GetLongPosition(ProtoWriter writer, ref State state) { return writer._position64; }
#pragma warning restore RCS1163 // Unused parameter.
private long _position64;
protected private void Advance(long count) => _position64 += count;
protected private void AdvanceAndReset(int count)
{
_position64 += count;
WireType = WireType.None;
}
protected private void AdvanceAndReset(long count)
{
_position64 += count;
WireType = WireType.None;
}
/// <summary>
/// Flushes data to the underlying stream, and releases any resources. The underlying stream is *not* disposed
/// by this operation.
/// </summary>
[Obsolete(UseStateAPI, false)]
public void Close()
{
State state = default;
Close(ref state);
}
/// <summary>
/// Flushes data to the underlying stream, and releases any resources. The underlying stream is *not* disposed
/// by this operation.
/// </summary>
public void Close(ref State state)
{
CheckClear(ref state);
Dispose();
}
internal void CheckClear(ref State state)
{
if (depth != 0 || !TryFlush(ref state)) throw new InvalidOperationException("The writer is in an incomplete state");
_needFlush = false; // because we ^^^ *JUST DID*
}
/// <summary>
/// Get the TypeModel associated with this writer
/// </summary>
public TypeModel Model => model;
#if COREFX
private protected static readonly Encoding UTF8 = Encoding.UTF8;
#else
private protected static readonly UTF8Encoding UTF8 = new UTF8Encoding();
#endif
private static uint Zig(int value)
{
return (uint)((value << 1) ^ (value >> 31));
}
private static ulong Zig(long value)
{
return (ulong)((value << 1) ^ (value >> 63));
}
/// <summary>
/// Writes a string to the stream; supported wire-types: String
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteString(string value, ProtoWriter writer)
{
State state = default;
WriteString(value, writer, ref state);
}
/// <summary>
/// Writes a string to the stream; supported wire-types: String
/// </summary>
public static void WriteString(string value, ProtoWriter writer, ref State state)
{
switch (writer.WireType)
{
case WireType.String:
if (string.IsNullOrEmpty(value))
{
writer.AdvanceAndReset(writer.ImplWriteVarint32(ref state, 0));
}
else
{
var len = UTF8.GetByteCount(value);
writer.AdvanceAndReset(writer.ImplWriteVarint32(ref state, (uint)len) + len);
writer.ImplWriteString(ref state, value, len);
}
break;
default:
ThrowException(writer);
break;
}
}
protected private abstract void ImplWriteString(ref State state, string value, int expectedBytes);
protected private abstract int ImplWriteVarint32(ref State state, uint value);
protected private abstract int ImplWriteVarint64(ref State state, ulong value);
protected private abstract void ImplWriteFixed32(ref State state, uint value);
protected private abstract void ImplWriteFixed64(ref State state, ulong value);
protected private abstract void ImplWriteBytes(ref State state, byte[] data, int offset, int length);
protected private abstract void ImplCopyRawFromStream(ref State state, Stream source);
private protected abstract SubItemToken ImplStartLengthPrefixedSubItem(ref State state, object instance, PrefixStyle style);
protected private abstract void ImplEndLengthPrefixedSubItem(ref State state, SubItemToken token, PrefixStyle style);
protected private abstract bool ImplDemandFlushOnDispose { get; }
/// <summary>
/// Writes any uncommitted data to the output
/// </summary>
public void Flush(ref State state)
{
if (TryFlush(ref state))
{
_needFlush = false;
}
}
/// <summary>
/// Writes any buffered data (if possible) to the underlying stream.
/// </summary>
/// <param name="state">Wwriter state</param>
/// <remarks>It is not always possible to fully flush, since some sequences
/// may require values to be back-filled into the byte-stream.</remarks>
private protected abstract bool TryFlush(ref State state);
/// <summary>
/// Writes an unsigned 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteUInt64(ulong value, ProtoWriter writer)
{
State state = default;
WriteUInt64(value, writer, ref state);
}
/// <summary>
/// Writes an unsigned 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
public static void WriteUInt64(ulong value, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
switch (writer.WireType)
{
case WireType.Fixed64:
writer.ImplWriteFixed64(ref state, value);
writer.AdvanceAndReset(8);
return;
case WireType.Variant:
int bytes = writer.ImplWriteVarint64(ref state, value);
writer.AdvanceAndReset(bytes);
return;
case WireType.Fixed32:
writer.ImplWriteFixed32(ref state, checked((uint)value));
writer.AdvanceAndReset(4);
return;
default:
ThrowException(writer);
break;
}
}
/// <summary>
/// Writes a signed 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteInt64(long value, ProtoWriter writer)
{
State state = default;
WriteInt64(value, writer, ref state);
}
/// <summary>
/// Writes a signed 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
public static void WriteInt64(long value, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
switch (writer.WireType)
{
case WireType.Fixed64:
writer.ImplWriteFixed64(ref state, (ulong)value);
writer.AdvanceAndReset(8);
return;
case WireType.Variant:
writer.AdvanceAndReset(writer.ImplWriteVarint64(ref state, (ulong)value));
return;
case WireType.SignedVariant:
writer.AdvanceAndReset(writer.ImplWriteVarint64(ref state, Zig(value)));
return;
case WireType.Fixed32:
writer.ImplWriteFixed32(ref state, checked((uint)(int)value));
writer.AdvanceAndReset(4);
return;
default:
ThrowException(writer);
break;
}
}
/// <summary>
/// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteUInt32(uint value, ProtoWriter writer)
{
State state = default;
WriteUInt32(value, writer, ref state);
}
/// <summary>
/// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
public static void WriteUInt32(uint value, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
switch (writer.WireType)
{
case WireType.Fixed32:
writer.ImplWriteFixed32(ref state, value);
writer.AdvanceAndReset(4);
return;
case WireType.Fixed64:
writer.ImplWriteFixed64(ref state, value);
writer.AdvanceAndReset(8);
return;
case WireType.Variant:
int bytes = writer.ImplWriteVarint32(ref state, value);
writer.AdvanceAndReset(bytes);
return;
default:
ThrowException(writer);
break;
}
}
/// <summary>
/// Writes a signed 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteInt16(short value, ProtoWriter writer)
{
State state = default;
WriteInt32(value, writer, ref state);
}
/// <summary>
/// Writes a signed 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
public static void WriteInt16(short value, ProtoWriter writer, ref State state)
=> WriteInt32(value, writer, ref state);
/// <summary>
/// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteUInt16(ushort value, ProtoWriter writer)
{
State state = default;
WriteUInt32(value, writer, ref state);
}
/// <summary>
/// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
public static void WriteUInt16(ushort value, ProtoWriter writer, ref State state)
=> WriteUInt32(value, writer, ref state);
/// <summary>
/// Writes an unsigned 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteByte(byte value, ProtoWriter writer)
{
State state = default;
WriteUInt32(value, writer, ref state);
}
/// <summary>
/// Writes an unsigned 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
public static void WriteByte(byte value, ProtoWriter writer, ref State state)
=> WriteUInt32(value, writer, ref state);
/// <summary>
/// Writes a signed 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteSByte(sbyte value, ProtoWriter writer)
{
State state = default;
WriteInt32(value, writer, ref state);
}
/// <summary>
/// Writes a signed 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
public static void WriteSByte(sbyte value, ProtoWriter writer, ref State state)
=> WriteInt32(value, writer, ref state);
/// <summary>
/// Writes a signed 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteInt32(int value, ProtoWriter writer)
{
State state = default;
WriteInt32(value, writer, ref state);
}
/// <summary>
/// Writes a signed 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
/// </summary>
public static void WriteInt32(int value, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
switch (writer.WireType)
{
case WireType.Fixed32:
writer.ImplWriteFixed32(ref state, (uint)value);
writer.AdvanceAndReset(4);
return;
case WireType.Fixed64:
writer.ImplWriteFixed64(ref state, (ulong)(long)value);
writer.AdvanceAndReset(8);
return;
case WireType.Variant:
if (value >= 0)
{
writer.AdvanceAndReset(writer.ImplWriteVarint32(ref state, (uint)value));
}
else
{
writer.AdvanceAndReset(writer.ImplWriteVarint64(ref state, (ulong)(long)value));
}
return;
case WireType.SignedVariant:
writer.AdvanceAndReset(writer.ImplWriteVarint32(ref state, Zig(value)));
return;
default:
ThrowException(writer);
break;
}
}
/// <summary>
/// Writes a double-precision number to the stream; supported wire-types: Fixed32, Fixed64
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteDouble(double value, ProtoWriter writer)
{
State state = default;
WriteDouble(value, writer, ref state);
}
/// <summary>
/// Writes a double-precision number to the stream; supported wire-types: Fixed32, Fixed64
/// </summary>
public static void WriteDouble(double value, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
switch (writer.WireType)
{
case WireType.Fixed32:
float f = (float)value;
if (float.IsInfinity(f) && !double.IsInfinity(value))
{
throw new OverflowException();
}
WriteSingle(f, writer, ref state);
return;
case WireType.Fixed64:
#if FEAT_SAFE
writer.ImplWriteFixed64(ref state, (ulong)BitConverter.DoubleToInt64Bits(value));
#else
unsafe { writer.ImplWriteFixed64(ref state, *(ulong*)&value); }
#endif
writer.AdvanceAndReset(8);
return;
default:
ThrowException(writer);
return;
}
}
/// <summary>
/// Writes a single-precision number to the stream; supported wire-types: Fixed32, Fixed64
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteSingle(float value, ProtoWriter writer)
{
State state = default;
WriteSingle(value, writer, ref state);
}
/// <summary>
/// Writes a single-precision number to the stream; supported wire-types: Fixed32, Fixed64
/// </summary>
public static void WriteSingle(float value, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
switch (writer.WireType)
{
case WireType.Fixed32:
#if FEAT_SAFE
writer.ImplWriteFixed32(ref state, BitConverter.ToUInt32(BitConverter.GetBytes(value), 0));
#else
unsafe { writer.ImplWriteFixed32(ref state, *(uint*)&value); }
#endif
writer.AdvanceAndReset(4);
return;
case WireType.Fixed64:
WriteDouble(value, writer, ref state);
return;
default:
ThrowException(writer);
break;
}
}
/// <summary>
/// Throws an exception indicating that the given enum cannot be mapped to a serialized value.
/// </summary>
public static void ThrowEnumException(ProtoWriter writer, object enumValue)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
#pragma warning disable RCS1097 // Remove redundant 'ToString' call.
string rhs = enumValue == null ? "<null>" : (enumValue.GetType().FullName + "." + enumValue.ToString());
#pragma warning restore RCS1097 // Remove redundant 'ToString' call.
throw new ProtoException("No wire-value is mapped to the enum " + rhs + " at position " + writer._position64.ToString());
}
// general purpose serialization exception message
internal static Exception CreateException(ProtoWriter writer)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
return new ProtoException("Invalid serialization operation with wire-type " + writer.WireType.ToString() + " at position " + writer._position64.ToString());
}
internal static void ThrowException(ProtoWriter writer)
=> throw CreateException(writer);
/// <summary>
/// Writes a boolean to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteBoolean(bool value, ProtoWriter writer)
{
State state = default;
WriteBoolean(value, writer, ref state);
}
/// <summary>
/// Writes a boolean to the stream; supported wire-types: Variant, Fixed32, Fixed64
/// </summary>
public static void WriteBoolean(bool value, ProtoWriter writer, ref State state)
{
ProtoWriter.WriteUInt32(value ? (uint)1 : (uint)0, writer, ref state);
}
/// <summary>
/// Copies any extension data stored for the instance to the underlying stream
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void AppendExtensionData(IExtensible instance, ProtoWriter writer)
{
State state = default;
AppendExtensionData(instance, writer, ref state);
}
/// <summary>
/// Copies any extension data stored for the instance to the underlying stream
/// </summary>
public static void AppendExtensionData(IExtensible instance, ProtoWriter writer, ref State state)
{
if (instance == null) throw new ArgumentNullException(nameof(instance));
if (writer == null) throw new ArgumentNullException(nameof(writer));
// we expect the writer to be raw here; the extension data will have the
// header detail, so we'll copy it implicitly
if (writer.WireType != WireType.None) throw CreateException(writer);
IExtension extn = instance.GetExtensionObject(false);
if (extn != null)
{
// unusually we *don't* want "using" here; the "finally" does that, with
// the extension object being responsible for disposal etc
Stream source = extn.BeginQuery();
try
{
if (ProtoReader.TryConsumeSegmentRespectingPosition(source, out var data, ProtoReader.TO_EOF))
{
writer.ImplWriteBytes(ref state, data.Array, data.Offset, data.Count);
writer.Advance(data.Count);
}
else
{
writer.ImplCopyRawFromStream(ref state, source);
}
}
finally { extn.EndQuery(source); }
}
}
/// <summary>
/// Used for packed encoding; indicates that the next field should be skipped rather than
/// a field header written. Note that the field number must match, else an exception is thrown
/// when the attempt is made to write the (incorrect) field. The wire-type is taken from the
/// subsequent call to WriteFieldHeader. Only primitive types can be packed.
/// </summary>
public static void SetPackedField(int fieldNumber, ProtoWriter writer)
{
if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber));
if (writer == null) throw new ArgumentNullException(nameof(writer));
writer.packedFieldNumber = fieldNumber;
}
/// <summary>
/// Used for packed encoding; explicitly reset the packed field marker; this is not required
/// if using StartSubItem/EndSubItem
/// </summary>
public static void ClearPackedField(int fieldNumber, ProtoWriter writer)
{
if (fieldNumber != writer.packedFieldNumber)
throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString());
writer.packedFieldNumber = 0;
}
/// <summary>
/// Used for packed encoding; writes the length prefix using fixed sizes rather than using
/// buffering. Only valid for fixed-32 and fixed-64 encoding.
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WritePackedPrefix(int elementCount, WireType wireType, ProtoWriter writer)
{
State state = default;
WritePackedPrefix(elementCount, wireType, writer, ref state);
}
/// <summary>
/// Used for packed encoding; writes the length prefix using fixed sizes rather than using
/// buffering. Only valid for fixed-32 and fixed-64 encoding.
/// </summary>
public static void WritePackedPrefix(int elementCount, WireType wireType, ProtoWriter writer, ref State state)
{
if (writer.WireType != WireType.String) throw new InvalidOperationException("Invalid wire-type: " + writer.WireType);
if (elementCount < 0) throw new ArgumentOutOfRangeException(nameof(elementCount));
ulong bytes;
switch (wireType)
{
// use long in case very large arrays are enabled
case WireType.Fixed32: bytes = ((ulong)elementCount) << 2; break; // x4
case WireType.Fixed64: bytes = ((ulong)elementCount) << 3; break; // x8
default:
throw new ArgumentOutOfRangeException(nameof(wireType), "Invalid wire-type: " + wireType);
}
int prefixLength = writer.ImplWriteVarint64(ref state, bytes);
writer.AdvanceAndReset(prefixLength);
}
internal string SerializeType(Type type)
{
return TypeModel.SerializeType(model, type);
}
/// <summary>
/// Specifies a known root object to use during reference-tracked serialization
/// </summary>
public void SetRootObject(object value)
{
NetCache.SetKeyedObject(NetObjectCache.Root, value);
}
/// <summary>
/// Writes a Type to the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String
/// </summary>
[Obsolete(UseStateAPI, false)]
public static void WriteType(Type value, ProtoWriter writer)
{
State state = default;
WriteType(value, writer, ref state);
}
/// <summary>
/// Writes a Type to the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String
/// </summary>
public static void WriteType(Type value, ProtoWriter writer, ref State state)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
WriteString(writer.SerializeType(value), writer, ref state);
}
}
}
| 43.707364 | 187 | 0.555203 | [
"Apache-2.0"
] | James-xin/protobuf-net | src/protobuf-net/ProtoWriter.cs | 45,108 | C# |
using ASOPC.Application.Features.Components.Commands.Create;
using ASOPC.Application.Features.Components.Commands.Delete;
using ASOPC.Application.Features.Components.Commands.Update;
using ASOPC.Application.Features.Components.Queries;
using ASOPC.Application.Features.Components.Queries.Get;
using ASOPC.Application.Features.Components.Queries.GetAll;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using IResult = ASCOPC.Domain.Contracts.IResult;
namespace ASCOPC.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "Admin, Editor")]
public class ComponentController : ControllerBase
{
private readonly IMediator _mediator;
public ComponentController(IMediator mediator)
{
_mediator = mediator;
}
[HttpDelete("{id}")]
public async Task<ActionResult<IResult>> Delete(int id) =>
Ok(await _mediator.Send(new DeleteComponentCommand { Id = id }));
[HttpPost]
public async Task<ActionResult<IResult>> Create([FromBody] CreateComponentCommand request) =>
Ok(await _mediator.Send(request));
[HttpPut]
public async Task<ActionResult<IResult>> Put([FromBody] UpdateComponentCommand request) =>
Ok(await _mediator.Send(request));
[HttpGet]
public async Task<ActionResult<IResult>> GetAll() =>
Ok(await _mediator.Send(new GetAllComponentCommand()));
[Authorize(Roles = "User")]
[HttpGet("{id}")]
public async Task<ActionResult<IResult>> GetById(int id) =>
Ok(await _mediator.Send(new GetComponentCommand() { Id = id }));
[Authorize(Roles = "User")]
[HttpGet, Route("filter/")]
public async Task<ActionResult<IResult>> GetFiltered([FromBody] GetFilteredComponentCommand components) =>
Ok(await _mediator.Send(components));
}
}
| 39.150943 | 114 | 0.695904 | [
"MIT"
] | FectourSu/ASCOPC | src/ASCOPC/Server/Controllers/ComponentController.cs | 2,077 | C# |
//
// Unit tests for AvoidDeclaringCustomDelegatesRule
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Cecil;
using Gendarme.Rules.Design.Generic;
using NUnit.Framework;
using Test.Rules.Definitions;
using Test.Rules.Fixtures;
using Test.Rules.Helpers;
namespace Test.Rules.Design.Generic {
[TestFixture]
public class AvoidDeclaringCustomDelegatesTest : TypeRuleTestFixture<AvoidDeclaringCustomDelegatesRule> {
[Test]
public void NotApplicableBefore2_0 ()
{
// ensure that the rule does not apply for types defined in 1.x assemblies
TypeDefinition violator = DefinitionLoader.GetTypeDefinition<AvoidDeclaringCustomDelegatesRule> ();
TargetRuntime realRuntime = violator.Module.Runtime;
try {
// fake assembly runtime version and do the check
violator.Module.Runtime = TargetRuntime.Net_1_1;
Rule.Active = true;
Rule.Initialize (Runner);
Assert.IsFalse (Rule.Active, "Active");
}
catch {
// rollback
violator.Module.Runtime = realRuntime;
Rule.Active = true;
}
}
[Test]
public void NotApplicable ()
{
AssertRuleDoesNotApply (SimpleTypes.Class);
AssertRuleDoesNotApply (SimpleTypes.Enum);
AssertRuleDoesNotApply (SimpleTypes.Interface);
AssertRuleDoesNotApply (SimpleTypes.Structure);
}
delegate void VoidNoParameter ();
delegate void VoidOneParameter (int a);
delegate void VoidTwoParameters (int a, string b);
delegate void VoidThreeParameters (int a, string b, object c);
delegate void VoidFourParameters (int a, string b, object c, float d);
delegate void Void17Parameters (int a, string b, object c, float d, double e, short f, byte g, long h,
int i, string j, object k, float l, double m, short n, byte o, long p, DateTime q);
[Test]
public void ReplaceWithAction ()
{
AssertRuleFailure<VoidNoParameter> ();
AssertRuleFailure<VoidOneParameter> ();
AssertRuleFailure<VoidTwoParameters> ();
AssertRuleFailure<VoidThreeParameters> ();
AssertRuleFailure<VoidFourParameters> ();
// we don't test 5-16 since they will be valid for NET_4_0
// having more than 16 parameters is another issue (unrelated to this rule)
AssertRuleFailure<Void17Parameters> ();
}
delegate int NonVoidNoParameter ();
delegate int NonVoidOneParameter (int a);
delegate int NonVoidTwoParameters (int a, string b);
delegate int NonVoidThreeParameters (int a, string b, object c);
delegate int NonVoidFourParameters (int a, string b, object c, float d);
delegate long NonVoid17Parameters (int a, string b, object c, float d, double e, short f, byte g, long h,
int i, string j, object k, float l, double m, short n, byte o, long p, DateTime q);
[Test]
public void ReplaceWithFunc ()
{
AssertRuleFailure<NonVoidNoParameter> ();
AssertRuleFailure<NonVoidOneParameter> ();
AssertRuleFailure<NonVoidTwoParameters> ();
AssertRuleFailure<NonVoidThreeParameters> ();
AssertRuleFailure<NonVoidFourParameters> ();
// we don't test 5-16 since they will be valid for NET_4_0
// having more than 16 parameters is another issue (unrelated to this rule)
AssertRuleFailure<NonVoid17Parameters> ();
}
delegate int RefDelegate (ref int a);
delegate void OutDelegate (out int a);
delegate void ParamsDelegate (params object[] args);
[Test]
public void SpecialCases ()
{
AssertRuleSuccess<RefDelegate> ();
AssertRuleSuccess<OutDelegate> ();
AssertRuleSuccess<ParamsDelegate> ();
}
}
}
| 35.623077 | 107 | 0.740877 | [
"MIT"
] | JAD-SVK/Gendarme | rules/Gendarme.Rules.Design.Generic/Test/AvoidDeclaringCustomDelegatesTest.cs | 4,631 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace PlayLibrary
{
public class User_DAL
{
SqlConnection sqlConn;
string connStr = ConfigurationManager.ConnectionStrings["dbSOFT703ConnectionString"].ConnectionString;
//for registration
public void RegisterUser(string userID, string name, string password)
{
try
{
sqlConn = new SqlConnection(connStr);
sqlConn.Open();
string query_save = "insert into tblUser values ('"
//+ userID + "', '"
+ getHashed(userID, password) + "', '"
+ userID + "', '"
+ name + "', '"
+ "" + "', "
+ "0"
+ ")";
SqlCommand sqlCmd = new SqlCommand(query_save, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
catch (Exception)
{
throw;
}
}
//for login
public Boolean LoginUser(string userID, string password)
{
try
{
sqlConn = new SqlConnection(connStr);
sqlConn.Open();
string query_select = "select * from tblUser where email = '"
+ userID + "' and password = '"
+ getHashed(userID, password) + "'";
SqlCommand sqlCmd = new SqlCommand(query_select, sqlConn);
SqlDataReader reader = sqlCmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read()) {
LoginCounter(reader.GetInt32(0), reader.GetInt32(5) + 1);
}
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
public void LoginCounter(int userID, int num)
{
try
{
sqlConn = new SqlConnection(connStr);
sqlConn.Open();
string query_save = "update tblUser " +
"SET logintime = "
+ num + "" +
" WHERE userID = '" + userID + "'";
SqlCommand sqlCmd = new SqlCommand(query_save, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
catch (Exception)
{
throw;
}
}
public string ResetPassword(string userID, string userName)
{
try
{
sqlConn = new SqlConnection(connStr);
sqlConn.Open();
var password = "tLibrary" + new Random(999);
string query_save = "update tblAPM_user " +
"SET password = '"
+ getHashed(userID, password) + "'" +
" WHERE userID = '" + userID + "'";
SqlCommand sqlCmd = new SqlCommand(query_save, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
return password;
}
catch (Exception)
{
throw;
}
}
private string getHashed(string str, string strSalt)
{
byte[] strByte = ASCIIEncoding.ASCII.GetBytes(str + strSalt + "AIS");
byte[] hashByte = SHA256.Create().ComputeHash(strByte);
return Convert.ToBase64String(hashByte);
}
}
} | 29.666667 | 110 | 0.450483 | [
"MIT"
] | Shaw6157/PlayLibrary | PlayLibrary/User_DAL.cs | 3,829 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoT.Model
{
/// <summary>
/// Container for the parameters to the DetachPrincipalPolicy operation.
/// Removes the specified policy from the specified certificate.
///
/// <note>
/// <para>
/// This action is deprecated. Please use <a>DetachPolicy</a> instead.
/// </para>
/// </note>
/// <para>
/// Requires permission to access the <a href="https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions">DetachPrincipalPolicy</a>
/// action.
/// </para>
/// </summary>
public partial class DetachPrincipalPolicyRequest : AmazonIoTRequest
{
private string _policyName;
private string _principal;
/// <summary>
/// Gets and sets the property PolicyName.
/// <para>
/// The name of the policy to detach.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=128)]
public string PolicyName
{
get { return this._policyName; }
set { this._policyName = value; }
}
// Check to see if PolicyName property is set
internal bool IsSetPolicyName()
{
return this._policyName != null;
}
/// <summary>
/// Gets and sets the property Principal.
/// <para>
/// The principal.
/// </para>
///
/// <para>
/// Valid principals are CertificateArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:cert/<i>certificateId</i>),
/// thingGroupArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:thinggroup/<i>groupName</i>)
/// and CognitoId (<i>region</i>:<i>id</i>).
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Principal
{
get { return this._principal; }
set { this._principal = value; }
}
// Check to see if Principal property is set
internal bool IsSetPrincipal()
{
return this._principal != null;
}
}
} | 31.568421 | 191 | 0.608536 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/DetachPrincipalPolicyRequest.cs | 2,999 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Foundation.Collections
{
#if false || false || false || false || false || false || false
#if false || false || false || false || false || false || false
[global::Uno.NotImplemented]
#endif
public enum CollectionChange
{
// Skipping already declared field Windows.Foundation.Collections.CollectionChange.Reset
// Skipping already declared field Windows.Foundation.Collections.CollectionChange.ItemInserted
// Skipping already declared field Windows.Foundation.Collections.CollectionChange.ItemRemoved
// Skipping already declared field Windows.Foundation.Collections.CollectionChange.ItemChanged
}
#endif
}
| 41.277778 | 97 | 0.77389 | [
"Apache-2.0"
] | Abhishek-Sharma-Msft/uno | src/Uno.Foundation/Generated/2.0.0.0/Windows.Foundation.Collections/CollectionChange.cs | 743 | C# |
using Nixxis.Client.Controls;
using Nixxis.ClientV2;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Controls.WpfPropertyGrid;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Nixxis.Client.Supervisor
{
/// <summary>
/// Interaction logic for Dashboard.xaml
/// </summary>
public partial class DashboardWidgetDatasourceDialog : Window, INotifyPropertyChanged
{
private string m_ObjType;
public string ObjType
{
get { return m_ObjType; }
set
{
m_ObjType = value;
ObjectDescriptionProperty = new DescriptionSelector().Convert(new Object[] { DataContext, ObjType }, null, null, null) as string;
FirePropertyChanged("ObjType");
}
}
public List<string> ObjIds
{
get
{
if (chkAll.IsChecked.GetValueOrDefault())
return new List<string>();
else
return new List<string>(Objects.Select((obj) => (obj.GetType().GetProperty("Id").GetValue(obj, null) as string)));
}
set
{
if (!String.IsNullOrEmpty(ObjType))
{
if (value.Count == 0)
{
chkAll.IsChecked = true;
}
else
{
IEnumerable ienum = new ObjectSelector().Convert(new object[] { DataContext, ObjType }, null, null, null) as IEnumerable;
foreach (string strVal in value)
{
foreach (object o in ienum)
if (o.GetType().GetProperty("Id").GetValue(o, null).Equals(strVal))
Objects.Add(o);
}
}
}
FirePropertyChanged("Objects");
}
}
public List<string> ObjProperties
{
get
{
return new List<string>(Properties.Select((obj) => (obj.GetType().GetProperty("Id").GetValue(obj, null) as string)));
}
set
{
if (!String.IsNullOrEmpty(ObjType))
{
IEnumerable ienum = new PropertySelector().Convert(new object[] { DataContext, ObjType }, null, null, null) as IEnumerable;
foreach (string strVal in value)
{
foreach (object o in ienum)
if (o.GetType().GetProperty("Id").GetValue(o, null).Equals(strVal))
Properties.Add(o);
}
}
FirePropertyChanged("Properties");
}
}
private ObservableCollection<object> m_Objects = new ObservableCollection<object>();
public ObservableCollection<object> Objects { get { return m_Objects; } set { m_Objects = value; } }
private ObservableCollection<object> m_Properties = new ObservableCollection<object>();
public ObservableCollection<object> Properties { get { return m_Properties; } set { m_Properties = value; } }
private string m_ObjectDescriptionProperty;
public string ObjectDescriptionProperty
{
get { return m_ObjectDescriptionProperty; }
set
{
m_ObjectDescriptionProperty = value;
FirePropertyChanged("ObjectDescriptionProperty");
}
}
public DashboardWidgetDatasourceDialog()
{
if (System.Globalization.CultureInfo.CurrentCulture.TextInfo.IsRightToLeft)
FlowDirection = System.Windows.FlowDirection.RightToLeft;
else
FlowDirection = System.Windows.FlowDirection.LeftToRight;
InitializeComponent();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void AddObject(object sender, RoutedEventArgs e)
{
DashboardWidgetObjectSelectorDialog dlg = new DashboardWidgetObjectSelectorDialog();
dlg.DataContext = this.DataContext;
dlg.Owner = this;
dlg.ObjType = ObjType;
if (dlg.ShowDialog().GetValueOrDefault())
{
ObjectDescriptionProperty = new DescriptionSelector().Convert(new Object[] { DataContext, ObjType }, null, null, null) as string;
foreach(object obj in dlg.lbObjects.SelectedItems)
Objects.Add(obj);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void FirePropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
private void RemoveObject(object sender, RoutedEventArgs e)
{
int backup = lbObjects.SelectedIndex;
Objects.RemoveAt(lbObjects.SelectedIndex);
if (Objects.Count != 0)
{
if (backup >= Objects.Count)
lbObjects.SelectedIndex = Objects.Count - 1;
else
lbObjects.SelectedIndex = backup;
}
}
private void ObjectMoveUp(object sender, RoutedEventArgs e)
{
if (lbObjects.SelectedIndex < 0)
return;
int toInsert = lbObjects.SelectedIndex - 1;
if (toInsert < 0)
return;
object obj = Objects[lbObjects.SelectedIndex];
Objects.RemoveAt(lbObjects.SelectedIndex);
Objects.Insert(toInsert, obj);
lbObjects.SelectedIndex = toInsert;
}
private void ObjectMoveDown(object sender, RoutedEventArgs e)
{
if (lbObjects.SelectedIndex < 0)
return;
int toInsert = lbObjects.SelectedIndex + 1;
if (toInsert >= Objects.Count)
return;
object obj = Objects[lbObjects.SelectedIndex];
Objects.RemoveAt(lbObjects.SelectedIndex);
Objects.Insert(toInsert, obj);
lbObjects.SelectedIndex = toInsert;
}
private void chkAll_Checked(object sender, RoutedEventArgs e)
{
lbObjects.SelectedIndex = -1;
}
private void PropertyAdd(object sender, RoutedEventArgs e)
{
DashboardWidgetPropertySelectorDialog dlg = new DashboardWidgetPropertySelectorDialog();
dlg.DataContext = this.DataContext;
dlg.Owner = this;
dlg.ObjType = ObjType;
if (dlg.ShowDialog().GetValueOrDefault())
{
foreach (object obj in dlg.lbProperties.SelectedItems)
Properties.Add(obj);
}
}
private void PropertyRemove(object sender, RoutedEventArgs e)
{
int backup = lbProperties.SelectedIndex;
Properties.RemoveAt(lbProperties.SelectedIndex);
if (Properties.Count != 0)
{
if (backup >= Properties.Count)
lbProperties.SelectedIndex = Properties.Count - 1;
else
lbProperties.SelectedIndex = backup;
}
}
private void PropertyMoveUp(object sender, RoutedEventArgs e)
{
if (lbProperties.SelectedIndex < 0)
return;
int toInsert = lbProperties.SelectedIndex - 1;
if (toInsert < 0)
return;
object obj = Properties[lbProperties.SelectedIndex];
Properties.RemoveAt(lbProperties.SelectedIndex);
Properties.Insert(toInsert, obj);
lbProperties.SelectedIndex = toInsert;
}
private void PropertyMoveDown(object sender, RoutedEventArgs e)
{
if (lbProperties.SelectedIndex < 0)
return;
int toInsert = lbProperties.SelectedIndex + 1;
if (toInsert >= Properties.Count)
return;
object obj = Properties[lbProperties.SelectedIndex];
Properties.RemoveAt(lbProperties.SelectedIndex);
Properties.Insert(toInsert, obj);
lbProperties.SelectedIndex = toInsert;
}
}
}
| 32.915441 | 145 | 0.553669 | [
"MIT"
] | Nixxis/ncs-client | NixxisSupControls/DashboardWidgetDataSourceDialog.xaml.cs | 8,955 | C# |
namespace Dynatrace.Net.Environment.Deployment.Models
{
public enum OneAgentInstallerTypes
{
Default,
DefaultUnattended,
Paas,
PaasSh
}
}
| 14.545455 | 55 | 0.7125 | [
"MIT"
] | lvermeulen/Dynatrace.Net | src/Dynatrace.Net/Environment/Deployment/Models/OneAgentInstallerTypes.cs | 162 | C# |
namespace SharpPdb.Windows.TypeRecords
{
/// <summary>
/// Represents CV_ptrtype_e.
/// </summary>
public enum PointerKind : byte
{
/// <summary>
/// 16 bit pointer
/// </summary>
Near16 = 0x00,
/// <summary>
/// 16:16 far pointer
/// </summary>
Far16 = 0x01,
/// <summary>
/// 16:16 huge pointer
/// </summary>
Huge16 = 0x02,
/// <summary>
/// based on segment
/// </summary>
BasedOnSegment = 0x03,
/// <summary>
/// based on value of base
/// </summary>
BasedOnValue = 0x04,
/// <summary>
/// based on segment value of base
/// </summary>
BasedOnSegmentValue = 0x05,
/// <summary>
/// based on address of base
/// </summary>
BasedOnAddress = 0x06,
/// <summary>
/// based on segment address of base
/// </summary>
BasedOnSegmentAddress = 0x07,
/// <summary>
/// based on type
/// </summary>
BasedOnType = 0x08,
/// <summary>
/// based on self
/// </summary>
BasedOnSelf = 0x09,
/// <summary>
/// 32 bit pointer
/// </summary>
Near32 = 0x0a,
/// <summary>
/// 16:32 pointer
/// </summary>
Far32 = 0x0b,
/// <summary>
/// 64 bit pointer
/// </summary>
Near64 = 0x0c,
}
}
| 20.594595 | 44 | 0.43832 | [
"MIT"
] | codehz/SharpPdb | Source/Windows/TypeRecords/PointerKind.cs | 1,526 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace raiden_mail_reader.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class VN {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal VN() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("raiden_mail_reader.Properties.VN", typeof(VN).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.3125 | 170 | 0.611472 | [
"MIT"
] | raidengates/raiden_send_mail | Properties/VN.Designer.cs | 2,774 | C# |
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
#nullable enable
// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236
namespace PrivateWiki.UWP.UI.UI.Controls
{
public sealed partial class SettingsHeader : UserControl
{
public SettingsHeader()
{
this.InitializeComponent();
}
public IconElement Icon
{
get => (IconElement) GetValue(IconProperty);
set
{
SetValue(IconProperty, value);
SettingsHeaderIcon.Children.Add(value);
}
}
public static readonly DependencyProperty IconProperty = DependencyProperty.Register("IconProperty", typeof(IconElement), typeof(SettingsHeader), null);
public string Title
{
get => (string) GetValue(TitleProperty);
set => SetValue(TitleProperty, value);
}
// Using a DependencyProperty as the backing store for TitleProperty.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("TitleProperty",
typeof(string), typeof(SettingsHeader), null);
public string Subtitle
{
get => (string) GetValue(SubtitleProperty);
set => SetValue(SubtitleProperty, value);
}
// Using a DependencyProperty as the backing store for TitleProperty.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty SubtitleProperty = DependencyProperty.Register("SubtitleProperty",
typeof(string), typeof(SettingsHeader), null);
public event RoutedEventHandler? ApplyClick;
protected void Apply_Click(object sender, RoutedEventArgs e)
{
//bubble the event up to the parent
ApplyClick?.Invoke(this, e);
}
public event RoutedEventHandler? ResetClick;
protected void Reset_Click(object sender, RoutedEventArgs e)
{
//bubble the event up to the parent
ResetClick?.Invoke(this, e);
}
}
} | 28.014925 | 154 | 0.742142 | [
"MIT"
] | lampenlampen/PrivateWiki | PrivateWiki.UWP.UI/UI/Controls/SettingsHeader.xaml.cs | 1,879 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace SceneSkope.PowerBI
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Imports operations.
/// </summary>
public partial interface IImports
{
/// <summary>
/// Returns a list of imports
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<ODataResponseListImport>> GetImportsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new import using the specified import info
/// </summary>
/// <param name='datasetDisplayName'>
/// The display name of the dataset
/// </param>
/// <param name='importInfo'>
/// The import to post
/// </param>
/// <param name='nameConflict'>
/// Determines what to do if a dataset with the same name already
/// exists. Possible values include: 'Ignore', 'Abort', 'Overwrite'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Import>> PostImportWithHttpMessagesAsync(string datasetDisplayName, ImportInfo importInfo, string nameConflict = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the import metadata for the specifed import id
/// </summary>
/// <param name='importId'>
/// The import id
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Import>> GetImportByIdWithHttpMessagesAsync(string importId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a temporary upload location for large files
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<TemporaryUploadLocation>> CreateTemporaryUploadLocationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns a list of imports for the specified group
/// </summary>
/// <param name='groupId'>
/// The group id
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<ODataResponseListImport>> GetImportsInGroupWithHttpMessagesAsync(string groupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new import using the specified import info
/// </summary>
/// <param name='groupId'>
/// The group id
/// </param>
/// <param name='datasetDisplayName'>
/// The display name of the dataset
/// </param>
/// <param name='importInfo'>
/// The import to post
/// </param>
/// <param name='nameConflict'>
/// Determines what to do if a dataset with the same name already
/// exists
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Import>> PostImportInGroupWithHttpMessagesAsync(string groupId, string datasetDisplayName, ImportInfo importInfo, string nameConflict = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the import metadata for the specifed import id
/// </summary>
/// <param name='groupId'>
/// The group id
/// </param>
/// <param name='importId'>
/// The import id
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Import>> GetImportByIdInGroupWithHttpMessagesAsync(string groupId, string importId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a temporary upload location for large files
/// </summary>
/// <param name='groupId'>
/// The group id
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<TemporaryUploadLocation>> CreateTemporaryUploadLocationInGroupWithHttpMessagesAsync(string groupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 47.188406 | 309 | 0.624283 | [
"MIT"
] | sceneskope/powerbi | SceneSkope.PowerBI/IImports.cs | 9,768 | C# |
using System;
using Android.Content;
using AndroidX.RecyclerView.Widget;
namespace Xamarin.Forms.Platform.Android.CollectionView
{
public class CarouselViewAdapter<TItemsView, TItemsViewSource> : ItemsViewAdapter<TItemsView, TItemsViewSource>
where TItemsView : ItemsView
where TItemsViewSource : IItemsViewSource
{
protected readonly CarouselView CarouselView;
internal CarouselViewAdapter(CarouselView itemsView, Func<View, Context, ItemContentView> createItemContentView = null) : base(itemsView as TItemsView, createItemContentView)
{
CarouselView = itemsView;
}
public override int ItemCount => CarouselView.Loop && !(ItemsSource is EmptySource) && ItemsSource.Count > 0 ? int.MaxValue : ItemsSource.Count;
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (CarouselView == null || ItemsSource == null)
return;
bool hasItems = ItemsSource != null && ItemsSource.Count > 0;
if (!hasItems)
return;
int positionInList = (CarouselView.Loop && hasItems) ? position % ItemsSource.Count : position;
switch (holder)
{
case TextViewHolder textViewHolder:
textViewHolder.TextView.Text = ItemsSource.GetItem(positionInList).ToString();
break;
case TemplatedItemViewHolder templatedItemViewHolder:
BindTemplatedItemViewHolder(templatedItemViewHolder, ItemsSource.GetItem(positionInList));
break;
}
}
}
}
| 33.186047 | 176 | 0.762439 | [
"MIT"
] | BenLampson/maui | src/Platform.Renderers/src/Xamarin.Forms.Platform.Android/CollectionView/CarouselViewAdapter.cs | 1,429 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using PS.Web.API.Data;
namespace PS.Web.API.Migrations
{
[DbContext(typeof(PolysenseContext))]
partial class PolysenseContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0");
modelBuilder.Entity("PS.Shared.Models.Bill", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("CongressionalCommitteId")
.HasColumnType("int");
b.Property<int?>("HouseOfRepresentativesId")
.HasColumnType("int");
b.Property<DateTime>("IntroductionDatetime")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<int?>("SenateId")
.HasColumnType("int");
b.Property<int?>("SponsorId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CongressionalCommitteId");
b.HasIndex("HouseOfRepresentativesId");
b.HasIndex("SenateId");
b.HasIndex("SponsorId");
b.ToTable("Bill");
});
modelBuilder.Entity("PS.Shared.Models.BillStatus", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("BillId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<DateTime>("TransitionDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("BillId");
b.ToTable("BillStatus");
});
modelBuilder.Entity("PS.Shared.Models.BillVotes", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("CongressId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CongressId");
b.ToTable("BillVotes");
});
modelBuilder.Entity("PS.Shared.Models.Congress", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("CurrentCongress")
.HasColumnType("int");
b.Property<int?>("HouseId")
.HasColumnType("int");
b.Property<int?>("SenateId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("HouseId");
b.HasIndex("SenateId");
b.ToTable("Congress");
});
modelBuilder.Entity("PS.Shared.Models.CongressionalCommitte", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("ChairId")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ChairId");
b.ToTable("CongressionalCommitte");
});
modelBuilder.Entity("PS.Shared.Models.HouseOfRepresentatives", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("SpeakerOfTheHouseId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("SpeakerOfTheHouseId");
b.ToTable("HouseOfRepresentatives");
});
modelBuilder.Entity("PS.Shared.Models.Judge", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<DateTime>("BirthDateTime")
.HasColumnType("datetime2");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Judge");
b.HasDiscriminator<string>("Discriminator").HasValue("Judge");
});
modelBuilder.Entity("PS.Shared.Models.Politician", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("BillId")
.HasColumnType("int");
b.Property<DateTime>("BirthDateTime")
.HasColumnType("datetime2");
b.Property<int?>("CongressionalCommitteId")
.HasColumnType("int");
b.Property<int>("CurrentOffice")
.HasColumnType("int");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<int?>("HouseOfRepresentativesId")
.HasColumnType("int");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<int?>("SenateId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BillId");
b.HasIndex("CongressionalCommitteId");
b.HasIndex("HouseOfRepresentativesId");
b.HasIndex("SenateId");
b.ToTable("Politician");
});
modelBuilder.Entity("PS.Shared.Models.ScraperText", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("CategoryId")
.HasColumnType("int");
b.Property<string>("Text")
.HasColumnType("nvarchar(max)");
b.Property<string>("Website")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("ScraperText");
});
modelBuilder.Entity("PS.Shared.Models.Senate", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("PresidentOfTheSenateId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PresidentOfTheSenateId");
b.ToTable("Senate");
});
modelBuilder.Entity("PS.Shared.Models.SupremeCourt", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("ChiefJusticeId")
.HasColumnType("int");
b.Property<DateTime>("TransitionDate")
.HasColumnType("datetime2");
b.Property<int>("TransitionType")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ChiefJusticeId");
b.ToTable("SupremeCourt");
});
modelBuilder.Entity("PS.Shared.Models.TextCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("TextCategory");
});
modelBuilder.Entity("PS.Shared.Models.Justice", b =>
{
b.HasBaseType("PS.Shared.Models.Judge");
b.Property<int?>("AppointedById")
.HasColumnType("int");
b.Property<DateTime?>("EndDateTime")
.HasColumnType("datetime2");
b.Property<DateTime>("StartDateTime")
.HasColumnType("datetime2");
b.Property<int?>("SupremeCourtId")
.HasColumnType("int");
b.HasIndex("AppointedById");
b.HasIndex("SupremeCourtId");
b.HasDiscriminator().HasValue("Justice");
});
modelBuilder.Entity("PS.Shared.Models.Bill", b =>
{
b.HasOne("PS.Shared.Models.CongressionalCommitte", null)
.WithMany("ProposedBills")
.HasForeignKey("CongressionalCommitteId");
b.HasOne("PS.Shared.Models.HouseOfRepresentatives", null)
.WithMany("Bills")
.HasForeignKey("HouseOfRepresentativesId");
b.HasOne("PS.Shared.Models.Senate", null)
.WithMany("Bills")
.HasForeignKey("SenateId");
b.HasOne("PS.Shared.Models.Politician", "Sponsor")
.WithMany()
.HasForeignKey("SponsorId");
b.Navigation("Sponsor");
});
modelBuilder.Entity("PS.Shared.Models.BillStatus", b =>
{
b.HasOne("PS.Shared.Models.Bill", "Bill")
.WithMany("HistoricalStatuses")
.HasForeignKey("BillId");
b.Navigation("Bill");
});
modelBuilder.Entity("PS.Shared.Models.BillVotes", b =>
{
b.HasOne("PS.Shared.Models.Congress", "Congress")
.WithMany()
.HasForeignKey("CongressId");
b.Navigation("Congress");
});
modelBuilder.Entity("PS.Shared.Models.Congress", b =>
{
b.HasOne("PS.Shared.Models.HouseOfRepresentatives", "House")
.WithMany()
.HasForeignKey("HouseId");
b.HasOne("PS.Shared.Models.Senate", "Senate")
.WithMany()
.HasForeignKey("SenateId");
b.Navigation("House");
b.Navigation("Senate");
});
modelBuilder.Entity("PS.Shared.Models.CongressionalCommitte", b =>
{
b.HasOne("PS.Shared.Models.Politician", "Chair")
.WithMany()
.HasForeignKey("ChairId");
b.Navigation("Chair");
});
modelBuilder.Entity("PS.Shared.Models.HouseOfRepresentatives", b =>
{
b.HasOne("PS.Shared.Models.Politician", "SpeakerOfTheHouse")
.WithMany()
.HasForeignKey("SpeakerOfTheHouseId");
b.Navigation("SpeakerOfTheHouse");
});
modelBuilder.Entity("PS.Shared.Models.Politician", b =>
{
b.HasOne("PS.Shared.Models.Bill", null)
.WithMany("Cosponsors")
.HasForeignKey("BillId");
b.HasOne("PS.Shared.Models.CongressionalCommitte", null)
.WithMany("Members")
.HasForeignKey("CongressionalCommitteId");
b.HasOne("PS.Shared.Models.HouseOfRepresentatives", null)
.WithMany("CongressMen")
.HasForeignKey("HouseOfRepresentativesId");
b.HasOne("PS.Shared.Models.Senate", null)
.WithMany("Senators")
.HasForeignKey("SenateId");
});
modelBuilder.Entity("PS.Shared.Models.ScraperText", b =>
{
b.HasOne("PS.Shared.Models.TextCategory", "Category")
.WithMany()
.HasForeignKey("CategoryId");
b.Navigation("Category");
});
modelBuilder.Entity("PS.Shared.Models.Senate", b =>
{
b.HasOne("PS.Shared.Models.Politician", "PresidentOfTheSenate")
.WithMany()
.HasForeignKey("PresidentOfTheSenateId");
b.Navigation("PresidentOfTheSenate");
});
modelBuilder.Entity("PS.Shared.Models.SupremeCourt", b =>
{
b.HasOne("PS.Shared.Models.Justice", "ChiefJustice")
.WithMany()
.HasForeignKey("ChiefJusticeId");
b.Navigation("ChiefJustice");
});
modelBuilder.Entity("PS.Shared.Models.Justice", b =>
{
b.HasOne("PS.Shared.Models.Politician", "AppointedBy")
.WithMany()
.HasForeignKey("AppointedById");
b.HasOne("PS.Shared.Models.SupremeCourt", null)
.WithMany("Justices")
.HasForeignKey("SupremeCourtId");
b.Navigation("AppointedBy");
});
modelBuilder.Entity("PS.Shared.Models.Bill", b =>
{
b.Navigation("Cosponsors");
b.Navigation("HistoricalStatuses");
});
modelBuilder.Entity("PS.Shared.Models.CongressionalCommitte", b =>
{
b.Navigation("Members");
b.Navigation("ProposedBills");
});
modelBuilder.Entity("PS.Shared.Models.HouseOfRepresentatives", b =>
{
b.Navigation("Bills");
b.Navigation("CongressMen");
});
modelBuilder.Entity("PS.Shared.Models.Senate", b =>
{
b.Navigation("Bills");
b.Navigation("Senators");
});
modelBuilder.Entity("PS.Shared.Models.SupremeCourt", b =>
{
b.Navigation("Justices");
});
#pragma warning restore 612, 618
}
}
}
| 33.403162 | 83 | 0.428884 | [
"Apache-2.0"
] | Unskilledcrab/Polysense | PS.Web.API/Migrations/PolysenseContextModelSnapshot.cs | 16,904 | C# |
namespace KoheiUtils
{
using System;
using UnityEngine;
#if ODIN_INSPECTOR
using Sirenix.OdinInspector;
#endif
public class PoolElement : MonoBehaviour
{
public bool isRent { get; private set; }
// Object Pool で使用される.
private Action<PoolElement> onReturn;
public void Setup(Action<PoolElement> onReturn)
{
this.onReturn = onReturn;
}
public void Rent()
{
isRent = true;
RentInner();
}
protected virtual void RentInner()
{
}
#if ODIN_INSPECTOR
[Button]
#endif
public void Return()
{
onReturn?.Invoke(this);
isRent = false;
ReturnInner();
}
protected virtual void ReturnInner()
{
}
}
} | 18.26087 | 55 | 0.52381 | [
"MIT"
] | akagik/KoheiUtils | Runtime/Utils/PoolElement.cs | 854 | C# |
using Avalonia;
using Avalonia.Controls;
using Avalonia.Diagnostics;
using AvalonStudio.Commands;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using WalletWasabi.Gui.Tabs;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class HelpCommands
{
public Global Global { get; }
[ImportingConstructor]
public HelpCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
AboutCommand = new CommandDefinition(
"About",
commandIconService.GetCompletionKindImage("About"),
ReactiveCommand.Create(() =>
{
IoC.Get<IShell>().AddOrSelectDocument(() => new AboutViewModel(Global));
}));
CustomerSupportCommand = new CommandDefinition(
"Customer Support",
commandIconService.GetCompletionKindImage("CustomerSupport"),
ReactiveCommand.Create(() =>
{
try
{
IoHelpers.OpenBrowser("https://www.reddit.com/r/WasabiWallet/");
}
catch (Exception ex)
{
Logging.Logger.LogWarning<HelpCommands>(ex);
IoC.Get<IShell>().AddOrSelectDocument(() => new AboutViewModel(Global));
}
}));
ReportBugCommand = new CommandDefinition(
"Report Bug",
commandIconService.GetCompletionKindImage("ReportBug"),
ReactiveCommand.Create(() =>
{
try
{
IoHelpers.OpenBrowser("https://github.com/zkSNACKs/WalletWasabi/issues");
}
catch (Exception ex)
{
Logging.Logger.LogWarning<HelpCommands>(ex);
IoC.Get<IShell>().AddOrSelectDocument(() => new AboutViewModel(Global));
}
}));
FaqCommand = new CommandDefinition(
"FAQ",
commandIconService.GetCompletionKindImage("Faq"),
ReactiveCommand.Create(() =>
{
try
{
IoHelpers.OpenBrowser("https://github.com/zkSNACKs/WalletWasabi/blob/master/WalletWasabi.Documentation/FAQ.md");
}
catch (Exception ex)
{
Logging.Logger.LogWarning<HelpCommands>(ex);
IoC.Get<IShell>().AddOrSelectDocument(() => new AboutViewModel(Global));
}
}));
PrivacyPolicyCommand = new CommandDefinition(
"Privacy Policy",
commandIconService.GetCompletionKindImage("PrivacyPolicy"),
ReactiveCommand.Create(() =>
{
IoC.Get<IShell>().AddOrSelectDocument(() => new PrivacyPolicyViewModel(Global));
}));
TermsAndConditionsCommand = new CommandDefinition(
"Terms and Conditions",
commandIconService.GetCompletionKindImage("TermsAndConditions"),
ReactiveCommand.Create(() =>
{
IoC.Get<IShell>().AddOrSelectDocument(() => new TermsAndConditionsViewModel(Global));
}));
LegalIssuesCommand = new CommandDefinition(
"Legal Issues",
commandIconService.GetCompletionKindImage("LegalIssues"),
ReactiveCommand.Create(() =>
{
IoC.Get<IShell>().AddOrSelectDocument(() => new LegalIssuesViewModel(Global));
}));
#if DEBUG
DevToolsCommand = new CommandDefinition(
"Dev Tools",
commandIconService.GetCompletionKindImage("DevTools"),
ReactiveCommand.Create(() =>
{
var devTools = new DevTools(Application.Current.Windows.FirstOrDefault());
var devToolsWindow = new Window
{
Width = 1024,
Height = 512,
Content = devTools,
DataTemplates =
{
new ViewLocator<Avalonia.Diagnostics.ViewModels.ViewModelBase>()
}
};
devToolsWindow.Show();
}));
#endif
}
[ExportCommandDefinition("Help.About")]
public CommandDefinition AboutCommand { get; }
[ExportCommandDefinition("Help.CustomerSupport")]
public CommandDefinition CustomerSupportCommand { get; }
[ExportCommandDefinition("Help.ReportBug")]
public CommandDefinition ReportBugCommand { get; }
[ExportCommandDefinition("Help.Faq")]
public CommandDefinition FaqCommand { get; }
[ExportCommandDefinition("Help.PrivacyPolicy")]
public CommandDefinition PrivacyPolicyCommand { get; }
[ExportCommandDefinition("Help.TermsAndConditions")]
public CommandDefinition TermsAndConditionsCommand { get; }
[ExportCommandDefinition("Help.LegalIssues")]
public CommandDefinition LegalIssuesCommand { get; }
#if DEBUG
[ExportCommandDefinition("Help.DevTools")]
public CommandDefinition DevToolsCommand { get; }
#endif
}
}
| 27.613924 | 118 | 0.702269 | [
"MIT"
] | SeppPenner/WalletWasabi | WalletWasabi.Gui/Shell/Commands/HelpCommands.cs | 4,363 | C# |
namespace GTVariable
{
[System.Serializable]
public class ReadOnlyBoolVariable : ReadOnlyVariable<BoolVariable, bool>
{
public ReadOnlyBoolVariable(BoolVariable variable) : base(variable)
{
}
}
} | 22.454545 | 77 | 0.639676 | [
"MIT"
] | GhooTS/GTScriptableVariable | Runtime/Variables/Vars/ReadOnly/ReadOnlyBoolVariable.cs | 249 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noobot.Core.MessagingPipeline.Middleware.ValidHandles;
using Noobot.Core.MessagingPipeline.Request;
using Noobot.Core.MessagingPipeline.Response;
namespace Noobot.Core.MessagingPipeline.Middleware.StandardMiddleware
{
internal class HelpMiddleware : MiddlewareBase
{
private readonly INoobotCore _noobotCore;
public HelpMiddleware(IMiddleware next, INoobotCore noobotCore) : base(next)
{
_noobotCore = noobotCore;
HandlerMappings = new[]
{
new HandlerMapping
{
ValidHandles = new IValidHandle[]
{
new StartsWithHandle("help")
},
Description = "Returns supported commands and descriptions of how to use them",
EvaluatorFunc = HelpHandler
}
};
}
private IEnumerable<ResponseMessage> HelpHandler(IncomingMessage message, IValidHandle matchedHandle)
{
var builder = new StringBuilder();
builder.Append(">>>");
IEnumerable<CommandDescription> supportedCommands = GetSupportedCommands().OrderBy(x => x.Command);
foreach (CommandDescription commandDescription in supportedCommands)
{
string description = commandDescription.Description.Replace("@{bot}", $"@{_noobotCore.GetBotUserName()}");
builder.AppendFormat("{0}\t- {1}\n", commandDescription.Command, description);
}
yield return message.ReplyToChannel(builder.ToString());
}
}
}
| 35.061224 | 122 | 0.612922 | [
"MIT"
] | Julian-mostert/noobot | src/Noobot.Core/MessagingPipeline/Middleware/StandardMiddleware/HelpMiddleware.cs | 1,720 | C# |
/*
* Copyright (c) 2017-2018 Håkan Edling
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* http://github.com/piranhacms/piranha
*
*/
using System;
using System.Collections.Generic;
namespace Piranha.Data
{
public sealed class Media : IModel, ICreated, IModified
{
/// <summary>
/// Gets/sets the unique id.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets/sets the optional folder id.
/// </summary>
public Guid? FolderId { get; set; }
/// <summary>
/// Gets/sets the media type.
/// </summary>
public Models.MediaType Type { get; set; }
/// <summary>
/// Gets/sets the filename.
/// </summary>
public string Filename { get; set; }
/// <summary>
/// Gets/sets the content type.
/// </summary>
/// <returns></returns>
public string ContentType { get; set; }
/// <summary>
/// Gets/sets the file size in bytes.
/// </summary>
public long Size { get; set; }
/// <summary>
/// Gets/sets the public url.
/// </summary>
public string PublicUrl { get; set; }
/// <summary>
/// Gets/sets the optional width. This only applies
/// if the media asset is an image.
/// </summary>
public int? Width { get; set; }
/// <summary>
/// Gets/sets the optional height. This only applies
/// if the media asset is an image.
/// </summary>
public int? Height { get; set; }
/// <summary>
/// Gets/sets the created date.
/// </summary>
public DateTime Created { get; set; }
/// <summary>
/// Gets/sets the last modification date.
/// </summary>
public DateTime LastModified { get; set; }
/// <summary>
/// Gets/sets the optional folder.
/// </summary>
public MediaFolder Folder { get; set; }
/// <summary>
/// Gets/sets the available versions.
/// </summary>
public IList<MediaVersion> Versions { get; set; }
/// <summary>
/// Default constructor.
/// </summary>
public Media()
{
Versions = new List<MediaVersion>();
}
}
} | 25.914894 | 64 | 0.513547 | [
"MIT"
] | CMSCollection/piranha.core | core/Piranha/Data/Media.cs | 2,437 | C# |
namespace HPSocket.Udp
{
public class UdpArqClient : UdpClient, IUdpArqClient
{
public UdpArqClient()
: base(Sdk.Udp.Create_HP_UdpArqClientListener,
Sdk.Udp.Create_HP_UdpArqClient,
Sdk.Udp.Destroy_HP_UdpArqClient,
Sdk.Udp.Destroy_HP_UdpArqClientListener)
{
}
protected UdpArqClient(Sdk.CreateListenerDelegate createListenerFunction, Sdk.CreateServiceDelegate createServiceFunction, Sdk.DestroyListenerDelegate destroyServiceFunction, Sdk.DestroyListenerDelegate destroyListenerFunction)
: base(createListenerFunction, createServiceFunction, destroyServiceFunction, destroyListenerFunction)
{
}
/// <inheritdoc />
public bool IsNoDelay
{
get => Sdk.Udp.HP_UdpArqClient_IsNoDelay(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetNoDelay(SenderPtr, value);
}
/// <inheritdoc />
public bool IsTurnoffCongestCtrl
{
get => Sdk.Udp.HP_UdpArqClient_IsTurnoffCongestCtrl(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetTurnoffCongestCtrl(SenderPtr, value);
}
/// <inheritdoc />
public uint FlushInterval
{
get => Sdk.Udp.HP_UdpArqClient_GetFlushInterval(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetFlushInterval(SenderPtr, value);
}
/// <inheritdoc />
public uint ResendByAcks
{
get => Sdk.Udp.HP_UdpArqClient_GetResendByAcks(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetResendByAcks(SenderPtr, value);
}
/// <inheritdoc />
public uint SendWndSize
{
get => Sdk.Udp.HP_UdpArqClient_GetSendWndSize(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetSendWndSize(SenderPtr, value);
}
/// <inheritdoc />
public uint RecvWndSize
{
get => Sdk.Udp.HP_UdpArqClient_GetRecvWndSize(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetRecvWndSize(SenderPtr, value);
}
/// <inheritdoc />
public uint MinRto
{
get => Sdk.Udp.HP_UdpArqClient_GetMinRto(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetMinRto(SenderPtr, value);
}
/// <inheritdoc />
public uint MaxTransUnit
{
get => Sdk.Udp.HP_UdpArqClient_GetMaxTransUnit(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetMaxTransUnit(SenderPtr, value);
}
/// <inheritdoc />
public uint MaxMessageSize
{
get => Sdk.Udp.HP_UdpArqClient_GetMaxMessageSize(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetMaxMessageSize(SenderPtr, value);
}
/// <inheritdoc />
public uint HandShakeTimeout
{
get => Sdk.Udp.HP_UdpArqClient_GetHandShakeTimeout(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetHandShakeTimeout(SenderPtr, value);
}
/// <inheritdoc />
public uint FastLimit
{
get => Sdk.Udp.HP_UdpArqClient_GetFastLimit(SenderPtr);
set => Sdk.Udp.HP_UdpArqClient_SetFastLimit(SenderPtr, value);
}
/// <inheritdoc />
public bool GetWaitingSendMessageCount(out int count)
{
count = 0;
return Sdk.Udp.HP_UdpArqClient_GetWaitingSendMessageCount(SenderPtr, ref count);
}
}
}
| 33.796117 | 235 | 0.61218 | [
"Apache-2.0"
] | Gao996/HPSocket.Net | src/HPSocket.Net/Udp/UdpArqClient.cs | 3,483 | C# |
namespace Xpand.Extensions.ObjectExtensions{
public static partial class ObjectExtensions{
public static bool IsDefaultValue<TSource>(this TSource source){
var def = default(TSource);
return def != null ? def.Equals(source) : source == null;
}
}
} | 32.5 | 66 | 0.738462 | [
"Apache-2.0"
] | mbogaerts/DevExpress.XAF | src/Extensions/Xpand.Extensions/ObjectExtensions/IsDefaultValue.cs | 262 | C# |
// Copyright (C) 2014 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alena Mikshina
// Created: 2014.05.06
using System;
using Xtensive.Core;
namespace Xtensive.Sql.Dml
{
[Serializable]
public sealed class SqlCustomFunctionType : IEquatable<SqlCustomFunctionType>
{
public string Name { get; private set; }
#region Equality members
public bool Equals(SqlCustomFunctionType other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return string.Equals(Name, other.Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
return Equals((SqlCustomFunctionType) obj);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public static bool operator ==(SqlCustomFunctionType left, SqlCustomFunctionType right)
{
return Equals(left, right);
}
public static bool operator !=(SqlCustomFunctionType left, SqlCustomFunctionType right)
{
return !Equals(left, right);
}
#endregion
// Constructors
public SqlCustomFunctionType(string name)
{
ArgumentValidator.EnsureArgumentNotNull(name, "name");
Name = name;
}
}
}
| 23.1875 | 92 | 0.634097 | [
"MIT"
] | SergeiPavlov/dataobjects-net | DataObjects/Sql/Dml/SqlCustomFunctionType.cs | 1,486 | C# |
using Microsoft.AspNetCore.Components;
namespace Leeax.Web.Components
{
public interface IContext
{
void AddChild(ComponentBase component);
void RemoveChild(ComponentBase component);
}
} | 19.727273 | 50 | 0.714286 | [
"Apache-2.0"
] | Ieeax/web | src/Leeax.Web.Components/IContext.cs | 219 | C# |
using J2N;
using J2N.Text;
namespace ICU4N.Impl.Coll
{
/// <summary>
/// UTF-16 collation element and character iterator.
/// Handles normalized UTF-16 text, with length or NUL-terminated.
/// Unnormalized text is handled by a subclass.
/// </summary>
public class UTF16CollationIterator : CollationIterator
{
/// <summary>
/// Partial constructor, see <see cref="CollationIterator.CollationIterator(CollationData)"/>
/// </summary>
public UTF16CollationIterator(CollationData d)
: base(d)
{
}
public UTF16CollationIterator(CollationData d, bool numeric, ICharSequence s, int p)
: base(d, numeric)
{
seq = s;
start = 0;
pos = p;
limit = s.Length;
}
public override bool Equals(object other)
{
if (!base.Equals(other)) { return false; }
if (other is UTF16CollationIterator o)
{
// Compare the iterator state but not the text: Assume that the caller does that.
return (pos - start) == (o.pos - o.start);
}
return false;
}
public override int GetHashCode()
{
// ICU4N specific - implemented hash code
return (pos - start).GetHashCode();
}
public override void ResetToOffset(int newOffset)
{
Reset();
pos = start + newOffset;
}
public override int Offset => pos - start;
public virtual void SetText(bool numeric, ICharSequence s, int p)
{
Reset(numeric);
seq = s;
start = 0;
pos = p;
limit = s.Length;
}
public override int NextCodePoint()
{
if (pos == limit)
{
return Collation.SentinelCodePoint;
}
char c = seq[pos++];
char trail;
if (char.IsHighSurrogate(c) && pos != limit &&
char.IsLowSurrogate(trail = seq[pos]))
{
++pos;
return Character.ToCodePoint(c, trail);
}
else
{
return c;
}
}
public override int PreviousCodePoint()
{
if (pos == start)
{
return Collation.SentinelCodePoint;
}
char c = seq[--pos];
char lead;
if (char.IsLowSurrogate(c) && pos != start &&
char.IsHighSurrogate(lead = seq[pos - 1]))
{
--pos;
return Character.ToCodePoint(lead, c);
}
else
{
return c;
}
}
protected override long HandleNextCE32()
{
if (pos == limit)
{
return NoCodePointAndCE32;
}
char c = seq[pos++];
return MakeCodePointAndCE32Pair(c, trie.GetFromU16SingleLead(c));
}
protected override char HandleGetTrailSurrogate()
{
if (pos == limit) { return (char)0; }
char trail;
if (char.IsLowSurrogate(trail = seq[pos])) { ++pos; }
return trail;
}
/* bool foundNULTerminator(); */
protected override void ForwardNumCodePoints(int num)
{
while (num > 0 && pos != limit)
{
char c = seq[pos++];
--num;
if (char.IsHighSurrogate(c) && pos != limit &&
char.IsLowSurrogate(seq[pos]))
{
++pos;
}
}
}
protected override void BackwardNumCodePoints(int num)
{
while (num > 0 && pos != start)
{
char c = seq[--pos];
--num;
if (char.IsLowSurrogate(c) && pos != start &&
char.IsHighSurrogate(seq[pos - 1]))
{
--pos;
}
}
}
protected ICharSequence seq;
protected int start;
protected int pos;
protected int limit;
}
}
| 27.481013 | 101 | 0.452096 | [
"Apache-2.0"
] | NightOwl888/ICU4N | src/ICU4N.Collation/Impl/Coll/UTF16CollationIterator.cs | 4,344 | C# |
using System;
using UnityEditor;
using UnityEditor.Tilemaps;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Buriola.Utilities.Editor.Brushes
{
/// <summary>
/// Helper class to paint prefabs on the tilemap
/// </summary>
[CreateAssetMenu(fileName = "Prefab Brush", menuName = "Brushes/Prefab Brush")]
[CustomGridBrush(false, true, false, "Prefab Brush")]
public class PrefabBrush : GridBrush
{
private const float k_PerlinOffset = 100000f;
public GameObject[] m_Prefabs;
public float m_PerlinScale = 0.5f;
public Vector3 m_Anchor = new Vector3(0.5f, 0.5f, 0.5f);
private GameObject prev_brushTarget;
private Vector3Int prev_Position = Vector3Int.one * Int32.MaxValue;
public override void Paint(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
{
if (position == prev_Position)
return;
prev_Position = position;
if (brushTarget)
prev_brushTarget = brushTarget;
brushTarget = prev_brushTarget;
if (brushTarget.layer == 31)
return;
int index = Mathf.Clamp(Mathf.FloorToInt(GetPerlinValue(position, m_PerlinScale, k_PerlinOffset) * m_Prefabs.Length),
0, m_Prefabs.Length - 1);
GameObject prefab = m_Prefabs[index];
GameObject instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
if(instance != null)
{
Erase(gridLayout, brushTarget, position);
Undo.MoveGameObjectToScene(instance, brushTarget.scene, "Paint Prefabs");
Undo.RegisterCreatedObjectUndo((Object)instance, "Paint Prefabs");
instance.transform.SetParent(brushTarget.transform);
instance.transform.position = gridLayout.LocalToWorld(gridLayout.CellToLocalInterpolated(position + m_Anchor));
}
}
public override void Erase(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
{
if (brushTarget)
prev_brushTarget = brushTarget;
brushTarget = prev_brushTarget;
if (brushTarget.layer == 31)
return;
Transform erased = GetObjectInCell(gridLayout, brushTarget.transform, position);
if (erased != null)
Undo.DestroyObjectImmediate(erased.gameObject);
}
private static Transform GetObjectInCell(GridLayout grid, Transform parent, Vector3Int position)
{
int childCount = parent.childCount;
Vector3 min = grid.LocalToWorld(grid.CellToLocalInterpolated(position));
Vector3 max = grid.LocalToWorld(grid.CellToLocalInterpolated(position + Vector3Int.one));
Bounds bounds = new Bounds((max + min) * .5f, max - min);
for (int i = 0; i < childCount; i++)
{
Transform child = parent.GetChild(i);
if (bounds.Contains(child.position))
return child;
}
return null;
}
private static float GetPerlinValue(Vector3Int position, float scale, float offset)
{
return Mathf.PerlinNoise((position.x + offset) * scale, (position.y + offset) * scale);
}
}
}
| 36.376344 | 129 | 0.616317 | [
"MIT"
] | Buriola/pacman-remake | Assets/Scripts/Buriola/Utilities/Editor/Brushes/PrefabBrush.cs | 3,385 | C# |
using NUnit.Framework;
namespace Whois.Domains
{
[TestFixture]
public class DomainTests
{
private WhoisLookup lookup;
[SetUp]
public void SetUp()
{
lookup = new WhoisLookup();
}
[Test]
public void TestLookupCom()
{
var result = lookup.Lookup("001hosting.com.br");
Assert.AreEqual(@"
% Copyright (c) Nic.br
% The use of the data below is only permitted as described in
% full by the terms of use at https://registro.br/termo/en.html ,
% being prohibited its distribution, commercialization or
% reproduction, in particular, to use it for advertising or
% any similar purpose.
% 2019-04-30T07:03:56-03:00
domain: 001hosting.com.br
owner: Ultra Provedor
ownerid: 350.562.738-05
country: BR
owner-c: ULPRO5
admin-c: ULPRO5
tech-c: ULPRO5
billing-c: ULPRO5
nserver: ns1.ultraprovedor.com.br
nsstat: 20190425 AA
nslastaa: 20190425
nserver: ns2.ultraprovedor.com.br
nsstat: 20190425 AA
nslastaa: 20190425
nserver: ns3.ultraprovedor.com.br
nsstat: 20190425 AA
nslastaa: 20190425
created: 20010919 #645178
changed: 20190406
expires: 20200919
status: published
nic-hdl-br: ULPRO5
person: Ultra Provedor
e-mail: registro@ultraprovedor.com.br
country: BR
created: 20180226
changed: 20180226
% Security and mail abuse issues should also be addressed to
% cert.br, http://www.cert.br/ , respectivelly to cert@cert.br
% and mail-abuse@cert.br
%
% whois.registro.br accepts only direct match queries. Types
% of queries are: domain (.br), registrant (tax ID), ticket,
% provider, contact handle (ID), CIDR block, IP and ASN.", result.Content);
}
}
}
| 25.826087 | 75 | 0.65881 | [
"MIT"
] | SonicGD/whois | Whois.Tests.Integration/Domains/DomainTests.cs | 1,784 | C# |
using System.Diagnostics.CodeAnalysis;
using HotChocolate.Language;
namespace HotChocolate.Types.NodaTime
{
public abstract class StringToClassBaseType<TRuntimeType> : ScalarType<TRuntimeType, StringValueNode>
where TRuntimeType : class
{
public StringToClassBaseType(string name) : base(name, bind: BindingBehavior.Implicit)
{
}
protected abstract string Serialize(TRuntimeType baseValue);
protected abstract bool TryDeserialize(string str, [NotNullWhen(true)] out TRuntimeType? output);
protected override TRuntimeType ParseLiteral(StringValueNode literal)
{
if (TryDeserialize(literal.Value, out TRuntimeType? value))
{
return value;
}
throw new SerializationException(
$"Unable to deserialize string to {this.Name}",
this);
}
protected override StringValueNode ParseValue(TRuntimeType value)
{
return new(Serialize(value));
}
public override IValueNode ParseResult(object? resultValue)
{
if (resultValue is null)
{
return NullValueNode.Default;
}
if (resultValue is string s)
{
return new StringValueNode(s);
}
if (resultValue is TRuntimeType v)
{
return ParseValue(v);
}
throw new SerializationException(
$"Unable to deserialize string to {this.Name}",
this);
}
public override bool TrySerialize(object? runtimeValue, out object? resultValue)
{
if (runtimeValue is null)
{
resultValue = null;
return true;
}
if (runtimeValue is TRuntimeType dt)
{
resultValue = Serialize(dt);
return true;
}
resultValue = null;
return false;
}
public override bool TryDeserialize(object? resultValue, out object? runtimeValue)
{
if (resultValue is null)
{
runtimeValue = null;
return true;
}
if (resultValue is string str && TryDeserialize(str, out TRuntimeType? val))
{
runtimeValue = val;
return true;
}
runtimeValue = null;
return false;
}
}
} | 28.10989 | 105 | 0.534402 | [
"MIT"
] | Sheldrybox/hotchocolate-nodatime | HotChocolate.Types.NodaTime/Helpers/StringToClassBaseType.cs | 2,558 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.PostgreSQL.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Performance tier properties
/// </summary>
public partial class PerformanceTierProperties
{
/// <summary>
/// Initializes a new instance of the PerformanceTierProperties class.
/// </summary>
public PerformanceTierProperties()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the PerformanceTierProperties class.
/// </summary>
/// <param name="id">ID of the performance tier.</param>
/// <param name="maxBackupRetentionDays">Maximum Backup retention in
/// days for the performance tier edition</param>
/// <param name="minBackupRetentionDays">Minimum Backup retention in
/// days for the performance tier edition</param>
/// <param name="maxStorageMB">Max storage allowed for a
/// server.</param>
/// <param name="minLargeStorageMB">Max storage allowed for a
/// server.</param>
/// <param name="maxLargeStorageMB">Max storage allowed for a
/// server.</param>
/// <param name="minStorageMB">Max storage allowed for a
/// server.</param>
/// <param name="serviceLevelObjectives">Service level objectives
/// associated with the performance tier</param>
public PerformanceTierProperties(string id = default(string), int? maxBackupRetentionDays = default(int?), int? minBackupRetentionDays = default(int?), int? maxStorageMB = default(int?), int? minLargeStorageMB = default(int?), int? maxLargeStorageMB = default(int?), int? minStorageMB = default(int?), IList<PerformanceTierServiceLevelObjectives> serviceLevelObjectives = default(IList<PerformanceTierServiceLevelObjectives>))
{
Id = id;
MaxBackupRetentionDays = maxBackupRetentionDays;
MinBackupRetentionDays = minBackupRetentionDays;
MaxStorageMB = maxStorageMB;
MinLargeStorageMB = minLargeStorageMB;
MaxLargeStorageMB = maxLargeStorageMB;
MinStorageMB = minStorageMB;
ServiceLevelObjectives = serviceLevelObjectives;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets ID of the performance tier.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets maximum Backup retention in days for the performance
/// tier edition
/// </summary>
[JsonProperty(PropertyName = "maxBackupRetentionDays")]
public int? MaxBackupRetentionDays { get; set; }
/// <summary>
/// Gets or sets minimum Backup retention in days for the performance
/// tier edition
/// </summary>
[JsonProperty(PropertyName = "minBackupRetentionDays")]
public int? MinBackupRetentionDays { get; set; }
/// <summary>
/// Gets or sets max storage allowed for a server.
/// </summary>
[JsonProperty(PropertyName = "maxStorageMB")]
public int? MaxStorageMB { get; set; }
/// <summary>
/// Gets or sets max storage allowed for a server.
/// </summary>
[JsonProperty(PropertyName = "minLargeStorageMB")]
public int? MinLargeStorageMB { get; set; }
/// <summary>
/// Gets or sets max storage allowed for a server.
/// </summary>
[JsonProperty(PropertyName = "maxLargeStorageMB")]
public int? MaxLargeStorageMB { get; set; }
/// <summary>
/// Gets or sets max storage allowed for a server.
/// </summary>
[JsonProperty(PropertyName = "minStorageMB")]
public int? MinStorageMB { get; set; }
/// <summary>
/// Gets or sets service level objectives associated with the
/// performance tier
/// </summary>
[JsonProperty(PropertyName = "serviceLevelObjectives")]
public IList<PerformanceTierServiceLevelObjectives> ServiceLevelObjectives { get; set; }
}
}
| 39.725 | 434 | 0.629746 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/postgresql/Microsoft.Azure.Management.PostgreSQL/src/postgresql/Generated/Models/PerformanceTierProperties.cs | 4,767 | C# |
using Owin;
namespace TrashGuy
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 14.230769 | 50 | 0.562162 | [
"MIT"
] | jtpete/TrashCollection | TrashGuy/Startup.cs | 187 | C# |
using Neptuo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Neptuo.Observables.Commands
{
/// <summary>
/// An implementation of <see cref="System.Windows.Input.ICommand"/> that takes delegates for 'execute' and 'can execute' methods.
/// </summary>
public class DelegateCommand : Command
{
private readonly Action execute;
private readonly Func<bool> canExecute;
/// <summary>
/// Creates new instance where <paramref name="execute"/> and <paramref name="canExecute"/> can't be <c>null</c>.
/// </summary>
/// <param name="execute">A delegate to be executed when the command is executed.</param>
/// <param name="canExecute">A delegate to be execute when the 'can execute' is executed.</param>
public DelegateCommand(Action execute, Func<bool> canExecute)
{
Ensure.NotNull(execute, "execute");
Ensure.NotNull(canExecute, "canExecute");
this.execute = execute;
this.canExecute = canExecute;
}
/// <summary>
/// Creates new instance where 'can execute' returns always <c>true</c> and <paramref name="execute"/> can't be <c>null</c>.
/// </summary>
/// <param name="execute">A delegate to be executed when the command is executed.</param>
public DelegateCommand(Action execute)
: this(execute, () => true)
{ }
public override bool CanExecute()
{
return canExecute();
}
public override void Execute()
{
execute();
}
}
/// <summary>
/// An implementation of <see cref="System.Windows.Input.ICommand"/> with parameter of type <typeparam name="T" />
/// that takes delegates for 'execute' and 'can execute' methods.
/// </summary>
/// <typeparam name="T">A type of the parameter.</typeparam>
public class DelegateCommand<T> : Command<T>
{
private readonly Action<T> execute;
private readonly Func<T, bool> canExecute;
/// <summary>
/// Creates new instance where <paramref name="execute"/> and <paramref name="canExecute"/> can't be <c>null</c>.
/// </summary>
/// <param name="execute">A delegate to be executed when the command is executed.</param>
/// <param name="canExecute">A delegate to be execute when the 'can execute' is executed.</param>
public DelegateCommand(Action<T> execute, Func<T, bool> canExecute)
{
Ensure.NotNull(execute, "execute");
Ensure.NotNull(canExecute, "canExecute");
this.execute = execute;
this.canExecute = canExecute;
}
/// <summary>
/// Creates new instance where 'can execute' returns always <c>true</c> and <paramref name="execute"/> can't be <c>null</c>.
/// </summary>
/// <param name="execute">A delegate to be executed when the command is executed.</param>
public DelegateCommand(Action<T> execute)
: this(execute, parameter => true)
{ }
public override bool CanExecute(T parameter)
{
return canExecute(parameter);
}
public override void Execute(T parameter)
{
execute(parameter);
}
}
} | 37.230769 | 134 | 0.600059 | [
"Apache-2.0"
] | ScriptBox21/Money | src/Neptuo/Observables/Commands/DelegateCommand.cs | 3,390 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SimulacaoCompra.Models
{
public class Compra
{
[Key]
public int Idcompra { get; set; }
[Required(ErrorMessage = "Este campo é obrigatorio")]
[Display(Name = "Nome da compra")]
[StringLength(100, ErrorMessage = "Informe no campo até 100 caracteres")]
public string NomeDaCompra { get; set; }
[Required(ErrorMessage = "Este campo é obrigatorio")]
[Range(1, 10000000000, ErrorMessage = "O minimo para a simulação, é o valor de R$1,00 e o maximo é R$ 1.00000000,00.")]
[DataType(DataType.Currency)]
[Display(Name = "Valor da compra")]
[Column(TypeName = "decimal(10, 2)")]
[DisplayFormat(DataFormatString = "R$ {0:f}")]
public decimal Valortotal { get; set; }
[Required(ErrorMessage = "Informe o percentual de juros, pois este campo não pode ser nulo ou zerado.")]
[Display(Name = "% Juros")]
[Column(TypeName = "decimal(10, 4)")]
[DisplayFormat(DataFormatString = "{0:g} %")]
public decimal Valorjuros { get; set; }
[Required(ErrorMessage = "Este campo é obrigatorio")]
[Display(Name = "Qtd Parcelas")]
[Range(1, 10000000000, ErrorMessage = "Informe no minimo 01 parcela")]
[Column(TypeName = "Decimal(10,5)")]
[DisplayFormat(DataFormatString = "{0:0}")]
public decimal Qtdparcelas { get; set; }
[Required(ErrorMessage = "Este campo é obrigatorio, selecione uma data atual ou posterior")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Data da compra")]
public DateTime Datacompra { get; set; }
[Required(ErrorMessage = "Este campo é obrigatorio, selecione pelo menos 1 das opções")]
[Display(Name = "Tipo de Calculo")]
public string TipoCalculo { get; set; }
[Required(ErrorMessage = "É necessário preencher este campo!")]
[Display(Name = "Valor da parcela")]
[DataType(DataType.Currency)]
[Column(TypeName = "decimal(10, 2)")]
[DisplayFormat(DataFormatString = "R$ {0:f}")]
public decimal Valorparcela { get; set; }
[Required(ErrorMessage = "É necessário preencher este campo!")]
public string Categoria { get; set; }
}
}
| 41.066667 | 127 | 0.62987 | [
"Apache-2.0"
] | TARGINO0110/SimulacaoCompra | SimulacaoCompra/Models/Compra.cs | 2,483 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Domain
{
/// <summary>
/// AlipayUserMpointAuthbasePayModel Data Structure.
/// </summary>
public class AlipayUserMpointAuthbasePayModel : AlipayObject
{
/// <summary>
/// 业务子类型,由会员方面分配
/// </summary>
[JsonPropertyName("biz_sub_type")]
public string BizSubType { get; set; }
/// <summary>
/// 业务类型,由会员方面分配
/// </summary>
[JsonPropertyName("biz_type")]
public string BizType { get; set; }
/// <summary>
/// 外部业务号
/// </summary>
[JsonPropertyName("out_biz_no")]
public string OutBizNo { get; set; }
/// <summary>
/// 目标扣减积分数
/// </summary>
[JsonPropertyName("point")]
public string Point { get; set; }
/// <summary>
/// 蚂蚁统一会员ID
/// </summary>
[JsonPropertyName("user_id")]
public string UserId { get; set; }
}
}
| 24.682927 | 64 | 0.535573 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Domain/AlipayUserMpointAuthbasePayModel.cs | 1,100 | C# |
using System;
using System.Collections.Generic;
namespace COMInteraction.Misc
{
public class NonNullImmutableList<T> : IEnumerable<T> where T : class
{
private List<T> _data;
public NonNullImmutableList()
{
_data = new List<T>();
}
public NonNullImmutableList(IEnumerable<T> values)
{
if (values == null)
throw new ArgumentNullException("values");
var data = new List<T>();
foreach (var value in values)
{
if (value == null)
throw new ArgumentException("Null entry encountered in values");
data.Add(value);
}
_data = data;
}
public NonNullImmutableList<T> Add(T value)
{
if (value == null)
throw new ArgumentNullException("value");
var dataNew = new List<T>(_data);
dataNew.Add(value);
return new NonNullImmutableList<T>()
{
_data = dataNew
};
}
public NonNullImmutableList<T> RemoveAt(int index)
{
if ((index < 0) || (index >= _data.Count))
throw new ArgumentOutOfRangeException("index");
var dataNew = new List<T>(_data);
dataNew.RemoveAt(index);
return new NonNullImmutableList<T>()
{
_data = dataNew
};
}
public bool Contains(T value)
{
if (value == null)
throw new ArgumentNullException("value");
return _data.Contains(value);
}
public IEnumerator<T> GetEnumerator()
{
return _data.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| 28.043478 | 85 | 0.50646 | [
"MIT"
] | ProductiveRage/ComInteraction | COMInteraction/Misc/NonNullImmutableList.cs | 1,937 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Web.Http.Internal;
namespace System.Web.Http.Dispatcher
{
/// <summary>
/// Provides an implementation of <see cref="IHttpControllerTypeResolver"/> with no external dependencies.
/// </summary>
public class DefaultHttpControllerTypeResolver : IHttpControllerTypeResolver
{
private readonly Predicate<Type> _isControllerTypePredicate;
public DefaultHttpControllerTypeResolver() : this(IsControllerType)
{
}
/// <summary>
/// Creates a new <see cref="DefaultHttpControllerTypeResolver"/> instance using a predicate to filter controller types.
/// </summary>
/// <param name="predicate">The predicate.</param>
public DefaultHttpControllerTypeResolver(Predicate<Type> predicate)
{
Contract.Assert(predicate != null);
_isControllerTypePredicate = predicate;
}
protected Predicate<Type> IsControllerTypePredicate
{
get { return _isControllerTypePredicate; }
}
private static bool IsControllerType(Type t)
{
return
t != null &&
t.IsClass &&
t.IsPublic &&
t.Name.EndsWith(DefaultHttpControllerSelector.ControllerSuffix, StringComparison.OrdinalIgnoreCase) &&
!t.IsAbstract &&
TypeHelper.HttpControllerType.IsAssignableFrom(t);
}
/// <summary>
/// Returns a list of controllers available for the application.
/// </summary>
/// <returns>An <see cref="ICollection{Type}"/> of controllers.</returns>
public virtual ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)
{
// Go through all assemblies referenced by the application and search for types matching a predicate
IEnumerable<Type> typesSoFar = Type.EmptyTypes;
ICollection<Assembly> assemblies = assembliesResolver.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (assembly.IsDynamic)
{
// can't call GetExportedTypes on a dynamic assembly
continue;
}
typesSoFar = typesSoFar.Concat(assembly.GetExportedTypes());
}
return typesSoFar.Where(x => IsControllerTypePredicate(x)).ToList();
}
}
}
| 36.297297 | 128 | 0.628444 | [
"Apache-2.0"
] | Distrotech/mono | external/aspnetwebstack/src/System.Web.Http/Dispatcher/DefaultHttpControllerTypeResolver.cs | 2,688 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace BorderControl.Contracts
{
public interface IIdentifiable
{
public string Id { get; }
}
}
| 15.666667 | 34 | 0.696809 | [
"MIT"
] | MirelaMileva/C-Sharp-OOP | InterfacesAndAbstraction/BorderControl/Contracts/IIdentifiable.cs | 190 | C# |
using NUnit.Framework;
using WordCounter.Words;
namespace WordCounter.Tests.Words
{
[TestFixture]
class WordManagerTests
{
[Test]
public void Add_IncreaseCounter()
{
var wordManager = new WordManager();
Assert.That(wordManager.PrettyPrint, Is.Empty);
var word = "abs";
var count = 1;
AssertCount(wordManager, word, count);
AssertCount(wordManager, word, ++count);
}
static void AssertCount(WordManager wordManager, string wordToAdd, int count)
{
var word1 = new Word(wordToAdd);
wordManager.Add(word1);
Assert.That(wordManager.PrettyPrint, Contains.Substring($"{word1.PrettyPrint} {count}"));
}
}
}
| 23.133333 | 95 | 0.665706 | [
"MIT"
] | pdebesc/WordCounter | Tests/Words/WordManagerTests.cs | 696 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Utilities;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// Relational database specific extension methods for <see cref="PropertyBuilder" />.
/// </summary>
public static class PropertiesConfigurationBuilderExtensions
{
/// <summary>
/// Configures the data type of the column that the property maps to when targeting a relational database.
/// This should be the complete type name, including precision, scale, length, etc.
/// </summary>
/// <param name="propertyBuilder"> The builder for the property being configured. </param>
/// <param name="typeName"> The name of the data type of the column. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static PropertiesConfigurationBuilder HaveColumnType(
this PropertiesConfigurationBuilder propertyBuilder,
string typeName)
{
Check.NotNull(propertyBuilder, nameof(propertyBuilder));
Check.NotEmpty(typeName, nameof(typeName));
propertyBuilder.HaveAnnotation(RelationalAnnotationNames.ColumnType, typeName);
return propertyBuilder;
}
/// <summary>
/// Configures the data type of the column that the property maps to when targeting a relational database.
/// This should be the complete type name, including precision, scale, length, etc.
/// </summary>
/// <typeparam name="TProperty"> The type of the property being configured. </typeparam>
/// <param name="propertyBuilder"> The builder for the property being configured. </param>
/// <param name="typeName"> The name of the data type of the column. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static PropertiesConfigurationBuilder<TProperty> HaveColumnType<TProperty>(
this PropertiesConfigurationBuilder<TProperty> propertyBuilder,
string typeName)
=> (PropertiesConfigurationBuilder<TProperty>)HaveColumnType((PropertiesConfigurationBuilder)propertyBuilder, typeName);
/// <summary>
/// Configures the property as capable of storing only fixed-length data, such as strings.
/// </summary>
/// <param name="propertyBuilder"> The builder for the property being configured. </param>
/// <param name="fixedLength"> A value indicating whether the property is constrained to fixed length values. </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public static PropertiesConfigurationBuilder AreFixedLength(
this PropertiesConfigurationBuilder propertyBuilder,
bool fixedLength = true)
{
Check.NotNull(propertyBuilder, nameof(propertyBuilder));
propertyBuilder.HaveAnnotation(RelationalAnnotationNames.IsFixedLength, fixedLength);
return propertyBuilder;
}
/// <summary>
/// Configures the property as capable of storing only fixed-length data, such as strings.
/// </summary>
/// <typeparam name="TProperty"> The type of the property being configured. </typeparam>
/// <param name="propertyBuilder"> The builder for the property being configured. </param>
/// <param name="fixedLength"> A value indicating whether the property is constrained to fixed length values. </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public static PropertiesConfigurationBuilder<TProperty> AreFixedLength<TProperty>(
this PropertiesConfigurationBuilder<TProperty> propertyBuilder,
bool fixedLength = true)
=> (PropertiesConfigurationBuilder<TProperty>)AreFixedLength((PropertiesConfigurationBuilder)propertyBuilder, fixedLength);
/// <summary>
/// Configures the property to use the given collation. The database column will be created with the given
/// collation, and it will be used implicitly in all collation-sensitive operations.
/// </summary>
/// <param name="propertyBuilder"> The builder for the property being configured. </param>
/// <param name="collation"> The collation for the column. </param>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static PropertiesConfigurationBuilder UseCollation(this PropertiesConfigurationBuilder propertyBuilder, string collation)
{
Check.NotNull(propertyBuilder, nameof(propertyBuilder));
Check.NotEmpty(collation, nameof(collation));
propertyBuilder.HaveAnnotation(RelationalAnnotationNames.Collation, collation);
return propertyBuilder;
}
/// <summary>
/// Configures the property to use the given collation. The database column will be created with the given
/// collation, and it will be used implicitly in all collation-sensitive operations.
/// </summary>
/// <param name="propertyBuilder"> The builder for the property being configured. </param>
/// <param name="collation"> The collation for the column. </param>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static PropertiesConfigurationBuilder<TProperty> UseCollation<TProperty>(
this PropertiesConfigurationBuilder<TProperty> propertyBuilder,
string collation)
=> (PropertiesConfigurationBuilder<TProperty>)UseCollation((PropertiesConfigurationBuilder)propertyBuilder, collation);
}
}
| 57.719626 | 136 | 0.691224 | [
"Apache-2.0"
] | 0x0309/efcore | src/EFCore.Relational/Extensions/PropertiesConfigurationBuilderExtensions.cs | 6,176 | C# |
namespace LittleBaby.Framework.Core
{
using System;
using System.Collections.Generic;
/// <summary>
/// 事件信息
/// </summary>
public class EventInfo
{
/// <summary>
/// 消息Code
/// </summary>
public Int64 MsgCode { get; private set; }
/// <summary>
/// 注册的回调不带参数
/// </summary>
public List<Action> CallbackList { get; private set; }
/// <summary>
/// 注册的回调带参数
/// </summary>
public List<Action<EventParams>> CallbackWithParamsList { get; private set; }
/// <summary>
/// 初始化
/// </summary>
/// <param name="msgCode"></param>
/// <param name="callback"></param>
public EventInfo(Int64 msgCode, Action callback)
{
this.MsgCode = msgCode;
this.CallbackList = new List<Action>() { callback };
this.CallbackWithParamsList = new List<Action<EventParams>>();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="msgCode"></param>
/// <param name="callbackWithParams"></param>
public EventInfo(Int64 msgCode, Action<EventParams> callbackWithParams)
{
this.MsgCode = msgCode;
this.CallbackList = new List<Action>();
this.CallbackWithParamsList = new List<Action<EventParams>>() { callbackWithParams };
}
/// <summary>
/// 添加回调
/// </summary>
/// <param name="callback"></param>
/// <returns></returns>
public Boolean AddCallback(Action callback)
{
if (!this.CallbackList.Contains(callback))
{
this.CallbackList.Add(callback);
return true;
}
return false;
}
/// <summary>
/// 添加回调
/// </summary>
/// <param name="callbackWithParams"></param>
/// <returns></returns>
public Boolean AddCallback(Action<EventParams> callbackWithParams)
{
if (!this.CallbackWithParamsList.Contains(callbackWithParams))
{
this.CallbackWithParamsList.Add(callbackWithParams);
return true;
}
return false;
}
/// <summary>
/// 移除回调
/// </summary>
/// <param name="callback"></param>
/// <returns></returns>
public Boolean RemoveCallback(Action callback)
{
return this.CallbackList.Remove(callback);
}
/// <summary>
/// 移除回调
/// </summary>
/// <param name="callbackWithParams"></param>
/// <returns></returns>
public Boolean RemoveCallback(Action<EventParams> callbackWithParams)
{
return this.CallbackWithParamsList.Remove(callbackWithParams);
}
}
}
| 31.336957 | 97 | 0.51821 | [
"MIT"
] | zengliugen/LittleBaby.Framework | UnityProject/Packages/LittleBaby.Framework.Core/Runtime/Core/Event/EventInfo.cs | 2,973 | C# |
using System;
namespace _10.MultiplyEvensByOdds
{
class Program
{
static void Main(string[] args)
{
int num = int.Parse(Console.ReadLine());
num = Math.Abs(num);
Console.WriteLine(GetMultipleOfEvenAndOdds(num));
}
static int GetMultipleOfEvenAndOdds(int n)
{
return GetSumOfDigits(n, 0) * GetSumOfDigits(n,1);
}
static int GetSumOfDigits(int n, int isOdd)
{
string number = n.ToString();
int sum = 0;
for (int i = 0; i < number.Length; i++)
{
int currentDigit = int.Parse(number[i].ToString());
if (currentDigit % 2 == isOdd)
{
sum += currentDigit;
}
}
return sum;
}
}
}
| 24.222222 | 67 | 0.46445 | [
"MIT"
] | yovko93/CSharp-Repo | CSharp_Fundamentals/MethodsLab/10.MultiplyEvensByOdds/Program.cs | 874 | C# |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Markdig.Helpers;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
namespace Markdig.Parsers.Inlines
{
/// <summary>
/// An inline parser for <see cref="EmphasisInline"/>.
/// </summary>
/// <seealso cref="InlineParser" />
/// <seealso cref="IPostInlineProcessor" />
public class EmphasisInlineParser : InlineParser, IPostInlineProcessor
{
private CharacterMap<EmphasisDescriptor>? emphasisMap;
private readonly DelimitersObjectCache inlinesCache = new DelimitersObjectCache();
[Obsolete("Use TryCreateEmphasisInlineDelegate instead", error: false)]
public delegate EmphasisInline CreateEmphasisInlineDelegate(char emphasisChar, bool isStrong);
public delegate EmphasisInline? TryCreateEmphasisInlineDelegate(char emphasisChar, int delimiterCount);
/// <summary>
/// Initializes a new instance of the <see cref="EmphasisInlineParser"/> class.
/// </summary>
public EmphasisInlineParser()
{
EmphasisDescriptors = new List<EmphasisDescriptor>()
{
new EmphasisDescriptor('*', 1, 2, true),
new EmphasisDescriptor('_', 1, 2, false)
};
}
/// <summary>
/// Gets the emphasis descriptors.
/// </summary>
public List<EmphasisDescriptor> EmphasisDescriptors { get; }
/// <summary>
/// Determines whether this parser is using the specified character as an emphasis delimiter.
/// </summary>
/// <param name="c">The character to look for.</param>
/// <returns><c>true</c> if this parser is using the specified character as an emphasis delimiter; otherwise <c>false</c></returns>
public bool HasEmphasisChar(char c)
{
foreach (var emphasis in EmphasisDescriptors)
{
if (emphasis.Character == c)
{
return true;
}
}
return false;
}
/// <summary>
/// Gets or sets the create emphasis inline delegate (allowing to create a different emphasis inline class)
/// </summary>
[Obsolete("Use TryCreateEmphasisInlineList instead", error: false)]
public CreateEmphasisInlineDelegate? CreateEmphasisInline { get; set; }
public readonly List<TryCreateEmphasisInlineDelegate> TryCreateEmphasisInlineList = new List<TryCreateEmphasisInlineDelegate>();
public override void Initialize()
{
OpeningCharacters = new char[EmphasisDescriptors.Count];
var tempMap = new List<KeyValuePair<char, EmphasisDescriptor>>();
for (int i = 0; i < EmphasisDescriptors.Count; i++)
{
var emphasis = EmphasisDescriptors[i];
if (Array.IndexOf(OpeningCharacters, emphasis.Character) >= 0)
{
ThrowHelper.InvalidOperationException(
$"The character `{emphasis.Character}` is already used by another emphasis descriptor");
}
OpeningCharacters[i] = emphasis.Character;
tempMap.Add(new KeyValuePair<char, EmphasisDescriptor>(emphasis.Character, emphasis));
}
emphasisMap = new CharacterMap<EmphasisDescriptor>(tempMap);
}
public bool PostProcess(InlineProcessor state, Inline? root, Inline? lastChild, int postInlineProcessorIndex, bool isFinalProcessing)
{
if (!(root is ContainerInline container))
{
return true;
}
List<EmphasisDelimiterInline>? delimiters = null;
if (container is EmphasisDelimiterInline emphasisDelimiter)
{
delimiters = inlinesCache.Get();
delimiters.Add(emphasisDelimiter);
}
// Collect all EmphasisDelimiterInline by searching from the root container
var child = container.FirstChild;
while (child != null)
{
// Stop the search on the delimitation child
if (child == lastChild)
{
break;
}
// If we have a delimiter, we search into it as we should have a tree of EmphasisDelimiterInline
if (child is EmphasisDelimiterInline delimiter)
{
delimiters ??= inlinesCache.Get();
delimiters.Add(delimiter);
child = delimiter.FirstChild;
continue;
}
child = child.NextSibling;
}
if (delimiters != null)
{
ProcessEmphasis(state, delimiters);
inlinesCache.Release(delimiters);
}
return true;
}
public override bool Match(InlineProcessor processor, ref StringSlice slice)
{
// First, some definitions.
// A delimiter run is a sequence of one or more delimiter characters that is not preceded or followed by the same delimiter character
// The amount of delimiter characters in the delimiter run may exceed emphasisDesc.MaximumCount, as that is handeled in `ProcessEmphasis`
var delimiterChar = slice.CurrentChar;
var emphasisDesc = emphasisMap![delimiterChar]!;
char pc = (char)0;
if (processor.Inline is HtmlEntityInline htmlEntityInline)
{
if (htmlEntityInline.Transcoded.Length > 0)
{
pc = htmlEntityInline.Transcoded[htmlEntityInline.Transcoded.End];
}
}
if (pc == 0)
{
pc = slice.PeekCharExtra(-1);
if (pc == delimiterChar && slice.PeekCharExtra(-2) != '\\')
{
// If we get here, we determined that either:
// a) there weren't enough delimiters in the delimiter run to satisfy the MinimumCount condition
// b) the previous character couldn't open/close
return false;
}
}
var startPosition = slice.Start;
int delimiterCount = slice.CountAndSkipChar(delimiterChar);
// If the emphasis doesn't have the minimum required character
if (delimiterCount < emphasisDesc.MinimumCount)
{
return false;
}
char c = slice.CurrentChar;
// The following character is actually an entity, we need to decode it
if (HtmlEntityParser.TryParse(ref slice, out string? htmlString, out int htmlLength))
{
c = htmlString[0];
}
// Calculate Open-Close for current character
CharHelper.CheckOpenCloseDelimiter(pc, c, emphasisDesc.EnableWithinWord, out bool canOpen, out bool canClose);
// We have potentially an open or close emphasis
if (canOpen || canClose)
{
var delimiterType = DelimiterType.Undefined;
if (canOpen) delimiterType |= DelimiterType.Open;
if (canClose) delimiterType |= DelimiterType.Close;
var delimiter = new EmphasisDelimiterInline(this, emphasisDesc)
{
DelimiterCount = delimiterCount,
Type = delimiterType,
Span = new SourceSpan(processor.GetSourcePosition(startPosition, out int line, out int column), processor.GetSourcePosition(slice.Start - 1)),
Column = column,
Line = line,
};
processor.Inline = delimiter;
return true;
}
// We don't have an emphasis
return false;
}
private void ProcessEmphasis(InlineProcessor processor, List<EmphasisDelimiterInline> delimiters)
{
// The following method is inspired by the "An algorithm for parsing nested emphasis and links"
// at the end of the CommonMark specs.
// TODO: Benchmark difference between using List and LinkedList here since there could be a few Remove calls
// Move current_position forward in the delimiter stack (if needed) until
// we find the first potential closer with delimiter * or _. (This will be the potential closer closest to the beginning of the input – the first one in parse order.)
for (int i = 0; i < delimiters.Count; i++)
{
var closeDelimiter = delimiters[i];
// Skip delimiters not supported by this instance
EmphasisDescriptor? emphasisDesc = emphasisMap![closeDelimiter.DelimiterChar];
if (emphasisDesc is null)
{
continue;
}
if ((closeDelimiter.Type & DelimiterType.Close) != 0 && closeDelimiter.DelimiterCount >= emphasisDesc.MinimumCount)
{
while (true)
{
// Now, look back in the stack (staying above stack_bottom and the openers_bottom for this delimiter type)
// for the first matching potential opener (“matching” means same delimiter).
EmphasisDelimiterInline? openDelimiter = null;
int openDelimiterIndex = -1;
for (int j = i - 1; j >= 0; j--)
{
var previousOpenDelimiter = delimiters[j];
var isOddMatch = ((closeDelimiter.Type & DelimiterType.Open) != 0 ||
(previousOpenDelimiter.Type & DelimiterType.Close) != 0) &&
previousOpenDelimiter.DelimiterCount != closeDelimiter.DelimiterCount &&
(previousOpenDelimiter.DelimiterCount + closeDelimiter.DelimiterCount) % 3 == 0 &&
(previousOpenDelimiter.DelimiterCount % 3 != 0 || closeDelimiter.DelimiterCount % 3 != 0);
if (previousOpenDelimiter.DelimiterChar == closeDelimiter.DelimiterChar &&
(previousOpenDelimiter.Type & DelimiterType.Open) != 0 &&
previousOpenDelimiter.DelimiterCount >= emphasisDesc.MinimumCount && !isOddMatch)
{
openDelimiter = previousOpenDelimiter;
openDelimiterIndex = j;
break;
}
}
if (openDelimiter != null)
{
process_delims:
Debug.Assert(openDelimiter.DelimiterCount >= emphasisDesc.MinimumCount, "Extra emphasis should have been discarded by now");
Debug.Assert(closeDelimiter.DelimiterCount >= emphasisDesc.MinimumCount, "Extra emphasis should have been discarded by now");
int delimiterDelta = Math.Min(Math.Min(openDelimiter.DelimiterCount, closeDelimiter.DelimiterCount), emphasisDesc.MaximumCount);
// Insert an emph or strong emph node accordingly, after the text node corresponding to the opener.
EmphasisInline? emphasis = null;
{
if (delimiterDelta <= 2) // We can try using the legacy delegate
{
#pragma warning disable CS0618 // Support fields marked as obsolete
emphasis = CreateEmphasisInline?.Invoke(closeDelimiter.DelimiterChar, isStrong: delimiterDelta == 2);
#pragma warning restore CS0618 // Support fields marked as obsolete
}
if (emphasis is null)
{
// Go in backwards order to give priority to newer delegates
for (int delegateIndex = TryCreateEmphasisInlineList.Count - 1; delegateIndex >= 0; delegateIndex--)
{
emphasis = TryCreateEmphasisInlineList[delegateIndex].Invoke(closeDelimiter.DelimiterChar, delimiterDelta);
if (emphasis != null) break;
}
if (emphasis is null)
{
emphasis = new EmphasisInline()
{
DelimiterChar = closeDelimiter.DelimiterChar,
DelimiterCount = delimiterDelta
};
}
}
}
Debug.Assert(emphasis != null);
// Update position for emphasis
var openDelimitercount = openDelimiter.DelimiterCount;
var closeDelimitercount = closeDelimiter.DelimiterCount;
emphasis!.Span.Start = openDelimiter.Span.Start;
emphasis.Line = openDelimiter.Line;
emphasis.Column = openDelimiter.Column;
emphasis.Span.End = closeDelimiter.Span.End - closeDelimitercount + delimiterDelta;
openDelimiter.Span.Start += delimiterDelta;
openDelimiter.Column += delimiterDelta;
closeDelimiter.Span.Start += delimiterDelta;
closeDelimiter.Column += delimiterDelta;
openDelimiter.DelimiterCount -= delimiterDelta;
closeDelimiter.DelimiterCount -= delimiterDelta;
var embracer = (ContainerInline)openDelimiter;
// Copy attributes attached to delimiter to the emphasis
var attributes = closeDelimiter.TryGetAttributes();
if (attributes != null)
{
emphasis.SetAttributes(attributes);
}
// Embrace all delimiters
embracer.EmbraceChildrenBy(emphasis);
// Remove any intermediate emphasis
for (int k = i - 1; k >= openDelimiterIndex + 1; k--)
{
var literalDelimiter = delimiters[k];
literalDelimiter.ReplaceBy(literalDelimiter.AsLiteralInline());
delimiters.RemoveAt(k);
i--;
}
if (closeDelimiter.DelimiterCount == 0)
{
var newParent = openDelimiter.DelimiterCount > 0 ? emphasis : emphasis.Parent!;
closeDelimiter.MoveChildrenAfter(newParent);
closeDelimiter.Remove();
delimiters.RemoveAt(i);
i--;
// Remove the open delimiter if it is also empty
if (openDelimiter.DelimiterCount == 0)
{
openDelimiter.MoveChildrenAfter(openDelimiter);
openDelimiter.Remove();
delimiters.RemoveAt(openDelimiterIndex);
i--;
}
break;
}
// The current delimiters are matching
if (openDelimiter.DelimiterCount >= emphasisDesc.MinimumCount)
{
goto process_delims;
}
else if (openDelimiter.DelimiterCount > 0)
{
// There are still delimiter characters left, there's just not enough of them
openDelimiter.ReplaceBy(openDelimiter.AsLiteralInline());
delimiters.RemoveAt(openDelimiterIndex);
i--;
}
else
{
// Remove the open delimiter if it is also empty
var firstChild = openDelimiter.FirstChild!;
firstChild.Remove();
openDelimiter.ReplaceBy(firstChild);
firstChild.IsClosed = true;
closeDelimiter.Remove();
firstChild.InsertAfter(closeDelimiter);
delimiters.RemoveAt(openDelimiterIndex);
i--;
}
}
else if ((closeDelimiter.Type & DelimiterType.Open) == 0)
{
closeDelimiter.ReplaceBy(closeDelimiter.AsLiteralInline());
delimiters.RemoveAt(i);
i--;
break;
}
else
{
break;
}
}
}
}
// Any delimiters left must be literal
for (int i = 0; i < delimiters.Count; i++)
{
var delimiter = delimiters[i];
delimiter.ReplaceBy(delimiter.AsLiteralInline());
}
delimiters.Clear();
}
public class DelimitersObjectCache : ObjectCache<List<EmphasisDelimiterInline>>
{
protected override List<EmphasisDelimiterInline> NewInstance()
{
return new List<EmphasisDelimiterInline>(4);
}
protected override void Reset(List<EmphasisDelimiterInline> instance)
{
instance.Clear();
}
}
}
} | 46.90534 | 178 | 0.499043 | [
"BSD-2-Clause"
] | mattj23/markdig | src/Markdig/Parsers/Inlines/EmphasisInlineParser.cs | 19,331 | C# |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.0
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace RakNet {
using System;
using System.Runtime.InteropServices;
public class RakNetListFilterQuery : IDisposable {
private HandleRef swigCPtr;
protected bool swigCMemOwn;
internal RakNetListFilterQuery(IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new HandleRef(this, cPtr);
}
internal static HandleRef getCPtr(RakNetListFilterQuery obj) {
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
~RakNetListFilterQuery() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
RakNetPINVOKE.delete_RakNetListFilterQuery(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
}
}
public FilterQuery this[int index]
{
get
{
return Get((uint)index); // use indexto retrieve and return another value.
}
set
{
Replace(value, value, (uint)index, "Not used", 0);// use index and value to set the value somewhere.
}
}
public RakNetListFilterQuery() : this(RakNetPINVOKE.new_RakNetListFilterQuery__SWIG_0(), true) {
}
public RakNetListFilterQuery(RakNetListFilterQuery original_copy) : this(RakNetPINVOKE.new_RakNetListFilterQuery__SWIG_1(RakNetListFilterQuery.getCPtr(original_copy)), true) {
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public RakNetListFilterQuery CopyData(RakNetListFilterQuery original_copy) {
RakNetListFilterQuery ret = new RakNetListFilterQuery(RakNetPINVOKE.RakNetListFilterQuery_CopyData(swigCPtr, RakNetListFilterQuery.getCPtr(original_copy)), false);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public FilterQuery Get(uint position) {
FilterQuery ret = new FilterQuery(RakNetPINVOKE.RakNetListFilterQuery_Get(swigCPtr, position), false);
return ret;
}
public void Push(FilterQuery input, string file, uint line) {
RakNetPINVOKE.RakNetListFilterQuery_Push(swigCPtr, FilterQuery.getCPtr(input), file, line);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public FilterQuery Pop() {
FilterQuery ret = new FilterQuery(RakNetPINVOKE.RakNetListFilterQuery_Pop(swigCPtr), false);
return ret;
}
public void Insert(FilterQuery input, uint position, string file, uint line) {
RakNetPINVOKE.RakNetListFilterQuery_Insert__SWIG_0(swigCPtr, FilterQuery.getCPtr(input), position, file, line);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public void Insert(FilterQuery input, string file, uint line) {
RakNetPINVOKE.RakNetListFilterQuery_Insert__SWIG_1(swigCPtr, FilterQuery.getCPtr(input), file, line);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public void Replace(FilterQuery input, FilterQuery filler, uint position, string file, uint line) {
RakNetPINVOKE.RakNetListFilterQuery_Replace__SWIG_0(swigCPtr, FilterQuery.getCPtr(input), FilterQuery.getCPtr(filler), position, file, line);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public void Replace(FilterQuery input) {
RakNetPINVOKE.RakNetListFilterQuery_Replace__SWIG_1(swigCPtr, FilterQuery.getCPtr(input));
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public void RemoveAtIndex(uint position) {
RakNetPINVOKE.RakNetListFilterQuery_RemoveAtIndex(swigCPtr, position);
}
public void RemoveAtIndexFast(uint position) {
RakNetPINVOKE.RakNetListFilterQuery_RemoveAtIndexFast(swigCPtr, position);
}
public void RemoveFromEnd(uint num) {
RakNetPINVOKE.RakNetListFilterQuery_RemoveFromEnd__SWIG_0(swigCPtr, num);
}
public void RemoveFromEnd() {
RakNetPINVOKE.RakNetListFilterQuery_RemoveFromEnd__SWIG_1(swigCPtr);
}
public uint Size() {
uint ret = RakNetPINVOKE.RakNetListFilterQuery_Size(swigCPtr);
return ret;
}
public void Clear(bool doNotDeallocateSmallBlocks, string file, uint line) {
RakNetPINVOKE.RakNetListFilterQuery_Clear(swigCPtr, doNotDeallocateSmallBlocks, file, line);
}
public void Preallocate(uint countNeeded, string file, uint line) {
RakNetPINVOKE.RakNetListFilterQuery_Preallocate(swigCPtr, countNeeded, file, line);
}
public void Compress(string file, uint line) {
RakNetPINVOKE.RakNetListFilterQuery_Compress(swigCPtr, file, line);
}
}
}
| 37.057143 | 177 | 0.727255 | [
"MIT"
] | Stormancer/Sample_05_Relay_Unity | Relay/Assets/Stormancer/Raknet.scharp/RakNetListFilterQuery.cs | 5,188 | C# |
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Color Adjustments/Grayscale")]
public class Grayscale : ImageEffectBase {
public Texture textureRamp;
public float rampOffset;
// Called by camera to apply image effect
void OnRenderImage (RenderTexture source, RenderTexture destination) {
material.SetTexture("_RampTex", textureRamp);
material.SetFloat("_RampOffset", rampOffset);
Graphics.Blit (source, destination, material);
}
}
}
| 30.7 | 78 | 0.684039 | [
"Unlicense"
] | 23SAMY23/Drift-Into-Space | Drift Into Space/Assets/PE2D/Standard Assets/Effects/ImageEffects/Scripts/Grayscale.cs | 614 | C# |
using System.Threading.Tasks;
using Orleans;
namespace Grains.Contracts
{
// Stateless grain
public interface IDecodeGrain : IGrainWithIntegerKey
{
Task Decode(string message);
}
}
| 17.25 | 56 | 0.700483 | [
"MIT"
] | chunk1ty/FrameworkPlayground | src/Orleans/Grains.Contracts/IDecodeGrain.cs | 209 | C# |
// ReSharper disable once CheckNamespace
namespace Ingredients
{
public partial class DecimalValue
{
private const decimal NanoDivisor = 1_000_000_000m;
private DecimalValue(decimal value)
{
Units = (long) decimal.Truncate(value);
Nanos = (int) ((value - Units) * NanoDivisor);
}
public static implicit operator decimal(DecimalValue value) =>
value.Units + (value.Nanos / NanoDivisor);
public static implicit operator DecimalValue(decimal value) =>
new DecimalValue(value);
}
} | 31.15 | 71 | 0.597111 | [
"MIT"
] | sitereactor/ndc-manchester-2021 | src/Frontend/Protos/DecimalValue.cs | 623 | C# |
/*
* OpenDoc_API-文档访问
*
* API to access AnyShare 如有任何疑问,可到开发者社区提问:https://developers.aishu.cn # Authentication - 调用需要鉴权的API,必须将token放在HTTP header中:\"Authorization: Bearer ACCESS_TOKEN\" - 对于GET请求,除了将token放在HTTP header中,也可以将token放在URL query string中:\"tokenid=ACCESS_TOKEN\"
*
* The version of the OpenAPI document: 6.0.10
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = AnyShareSDK.Client.OpenAPIDateConverter;
namespace AnyShareSDK.Model
{
/// <summary>
/// LinkSetRes
/// </summary>
[DataContract]
public partial class LinkSetRes : IEquatable<LinkSetRes>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="LinkSetRes" /> class.
/// </summary>
[JsonConstructorAttribute]
protected LinkSetRes() { }
/// <summary>
/// Initializes a new instance of the <see cref="LinkSetRes" /> class.
/// </summary>
/// <param name="endtime">到期时间 (required).</param>
/// <param name="link">外链唯一标识,如FC5E038D38A57032085441E7FE7010B0 (required).</param>
/// <param name="password">空表示没有 (required).</param>
/// <param name="perm">权限值,值域为[1,7],具体说明参见开启外链中的描述 (required).</param>
/// <param name="limittimes">外链使用次数。 -1为无限制 (required).</param>
/// <param name="result">0,请求已生效,返回为最新信息 1,请求正在审核,返回为更改前信息 (required).</param>
public LinkSetRes(long? endtime = default(long?), string link = default(string), string password = default(string), long? perm = default(long?), long? limittimes = default(long?), long? result = default(long?))
{
this.Endtime = endtime;
this.Link = link;
this.Password = password;
this.Perm = perm;
this.Limittimes = limittimes;
this.Result = result;
}
/// <summary>
/// 到期时间
/// </summary>
/// <value>到期时间 </value>
[DataMember(Name="endtime", EmitDefaultValue=false)]
public long? Endtime { get; set; }
/// <summary>
/// 外链唯一标识,如FC5E038D38A57032085441E7FE7010B0
/// </summary>
/// <value>外链唯一标识,如FC5E038D38A57032085441E7FE7010B0</value>
[DataMember(Name="link", EmitDefaultValue=false)]
public string Link { get; set; }
/// <summary>
/// 空表示没有
/// </summary>
/// <value>空表示没有</value>
[DataMember(Name="password", EmitDefaultValue=false)]
public string Password { get; set; }
/// <summary>
/// 权限值,值域为[1,7],具体说明参见开启外链中的描述
/// </summary>
/// <value>权限值,值域为[1,7],具体说明参见开启外链中的描述</value>
[DataMember(Name="perm", EmitDefaultValue=false)]
public long? Perm { get; set; }
/// <summary>
/// 外链使用次数。 -1为无限制
/// </summary>
/// <value>外链使用次数。 -1为无限制 </value>
[DataMember(Name="limittimes", EmitDefaultValue=false)]
public long? Limittimes { get; set; }
/// <summary>
/// 0,请求已生效,返回为最新信息 1,请求正在审核,返回为更改前信息
/// </summary>
/// <value>0,请求已生效,返回为最新信息 1,请求正在审核,返回为更改前信息 </value>
[DataMember(Name="result", EmitDefaultValue=false)]
public long? Result { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class LinkSetRes {\n");
sb.Append(" Endtime: ").Append(Endtime).Append("\n");
sb.Append(" Link: ").Append(Link).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" Perm: ").Append(Perm).Append("\n");
sb.Append(" Limittimes: ").Append(Limittimes).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as LinkSetRes);
}
/// <summary>
/// Returns true if LinkSetRes instances are equal
/// </summary>
/// <param name="input">Instance of LinkSetRes to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(LinkSetRes input)
{
if (input == null)
return false;
return
(
this.Endtime == input.Endtime ||
(this.Endtime != null &&
this.Endtime.Equals(input.Endtime))
) &&
(
this.Link == input.Link ||
(this.Link != null &&
this.Link.Equals(input.Link))
) &&
(
this.Password == input.Password ||
(this.Password != null &&
this.Password.Equals(input.Password))
) &&
(
this.Perm == input.Perm ||
(this.Perm != null &&
this.Perm.Equals(input.Perm))
) &&
(
this.Limittimes == input.Limittimes ||
(this.Limittimes != null &&
this.Limittimes.Equals(input.Limittimes))
) &&
(
this.Result == input.Result ||
(this.Result != null &&
this.Result.Equals(input.Result))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Endtime != null)
hashCode = hashCode * 59 + this.Endtime.GetHashCode();
if (this.Link != null)
hashCode = hashCode * 59 + this.Link.GetHashCode();
if (this.Password != null)
hashCode = hashCode * 59 + this.Password.GetHashCode();
if (this.Perm != null)
hashCode = hashCode * 59 + this.Perm.GetHashCode();
if (this.Limittimes != null)
hashCode = hashCode * 59 + this.Limittimes.GetHashCode();
if (this.Result != null)
hashCode = hashCode * 59 + this.Result.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 37.171296 | 257 | 0.535434 | [
"MIT"
] | ArtyDinosaur404/AnyShareSDK | AnyShareSDK/Model/LinkSetRes.cs | 8,621 | C# |
using System.Collections.Generic;
using NeuralNetworks.Units;
using Newtonsoft.Json.Linq;
namespace NeuralNetworks.Layers {
public abstract class Layer {
public abstract LayerConnection input { get; protected set; }
public abstract LayerConnection output { get; protected set; }
public abstract IEnumerable<Unit> units { get; }
public abstract LayerType layerType { get; }
public abstract void count();
public abstract void fillParametersRandomly();
public abstract void countDerivativesOfPreviousLayer();
public abstract void countDerivatives(List<double> expectedOutput);
public abstract void applyDerivativesToParameters(double learningFactor);
public abstract List<double> getInputValues();
public abstract List<double> getOutputValues();
public virtual Unit this[int neuronIndex] => input[neuronIndex];
public abstract JObject toJObject();
public abstract Layer fillFromJObject(JObject json);
public void setUnitsIds(int layerIndex) {
int counter = 0;
foreach (Unit unit in units) {
unit.id = $"{layerIndex}_{counter}";
counter++;
}
}
}
public abstract class SameInputOutputLayer : Layer {
public sealed override LayerConnection input { get; protected set; }
public sealed override LayerConnection output { get => input; protected set => input = value; }
public sealed override List<double> getOutputValues() => getInputValues();
public override JObject toJObject() {
JObject layer = new JObject {["type"] = GetType().Name};
JArray unitsArray = new JArray();
foreach (Unit unit in input.enumerable) unitsArray.Add(unit.toJObject());
layer["units"] = unitsArray;
return layer;
}
}
public interface LayerConnection {
public IEnumerable<Unit> enumerable { get; }
public Unit this[int index] { get; set; }
public Unit this[int index, int depthIndex] { get; set; }
public int length { get; }
public int depth { get; }
}
public abstract class NoDepthLayerConnection : LayerConnection {
public abstract IEnumerable<Unit> enumerable { get; }
public abstract Unit this[int index] { get; set; }
public Unit this[int index, int depthIndex] { get => this[index]; set => this[index] = value; }
public abstract int length { get; }
public int depth => 1;
}
public enum LayerType {
simple,
dense,
convolutional,
pooling
}
} | 28.04878 | 96 | 0.74087 | [
"MIT"
] | Andrew-Levada/NeuralNetworksLibrary | NeuralNetworks/Layers/Layer.cs | 2,302 | C# |
using System;
namespace PriorityQueue
{
public class PriorityQueue
{
private Node front;
public PriorityQueue()
{
front = null;
}
public void Insert(int element, int elementPriority)
{
Node temp, p;
temp = new Node(element, elementPriority);
// Queue is empty or element to be added has priority more than first element
if (IsEmpty() || elementPriority < front.priority)
{
temp.next = front;
front = temp;
}
else
{
p = front;
while (p.next != null && p.next.priority <= elementPriority)
{
p = p.next;
}
temp.next = p.next;
p.next = temp;
}
}
public int Delete()
{
if(IsEmpty())
throw new InvalidOperationException("Queue Underflow");
int element = front.info;
front = front.next;
return element;
}
public bool IsEmpty()
{
return front == null;
}
public void Display()
{
Node p = front;
if (IsEmpty())
{
Console.WriteLine("The Queue is empty \n");
return;
}
Console.WriteLine("The queue is : ");
Console.WriteLine("Element Priority");
while (p != null)
{
Console.WriteLine($"{p.info} {p.priority}");
p = p.next;
}
Console.WriteLine();
}
}
}
| 22.649351 | 89 | 0.418005 | [
"MIT"
] | AlbertJvR/DataStructuresAndAlgorithms | StacksAndQueues/QueuesProject/PriorityQueue/PriorityQueue.cs | 1,746 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.ExcelApi
{
/// <summary>
/// Partial WorksheetFunction Max
/// </summary>
partial class WorksheetFunction : COMObject
{
#region Methods
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
/// <param name="arg28">optional object arg28</param>
/// <param name="arg29">optional object arg29</param>
/// <param name="arg30">optional object arg30</param>
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27, object arg28, object arg29, object arg30)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", arg1);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", arg1, arg2);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", arg1, arg2, arg3);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", arg1, arg2, arg3, arg4);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
/// <param name="arg28">optional object arg28</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27, object arg28)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28 });
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
/// <param name="arg28">optional object arg28</param>
/// <param name="arg29">optional object arg29</param>
[CustomMethod]
[SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)]
public Double Max(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27, object arg28, object arg29)
{
return Factory.ExecuteDoubleMethodGet(this, "Max", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29 });
}
#endregion
}
}
| 60.378517 | 436 | 0.612081 | [
"MIT"
] | DominikPalo/NetOffice | Source/Excel/DispatchInterfaces/WorksheetFunction.Max.cs | 47,218 | C# |
namespace Sidekick.Business.Apis.Poe.Models
{
public class Attribute
{
public string Id { get; set; }
public string Text { get; set; }
public string Type { get; set; }
}
}
| 20.8 | 43 | 0.586538 | [
"MIT"
] | cmos12345/Sidekick | src/Sidekick.Business/Apis/Poe/Models/Attribute.cs | 208 | C# |
//-----------------------------------------------------------------------
// <copyright file="ThreadPoolDispatcherRemoteMessagingThroughputSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using Akka.Configuration;
using Akka.Remote.Tests.Performance.Transports;
namespace Akka.Remote.Tests.Performance
{
public class ThreadPoolDispatcherRemoteMessagingThroughputSpec : TestTransportRemoteMessagingThroughputSpec
{
public static Config ThreadPoolDispatcherConfig => ConfigurationFactory.ParseString(@"
akka.remote.default-remote-dispatcher {
type = Dispatcher
}
akka.remote.backoff-remote-dispatcher {
type = Dispatcher
}
");
public override Config CreateActorSystemConfig(string actorSystemName, string ipOrHostname, int port)
{
return ThreadPoolDispatcherConfig.WithFallback(base.CreateActorSystemConfig(actorSystemName, ipOrHostname, port));
}
}
}
| 39.935484 | 126 | 0.617932 | [
"Apache-2.0"
] | Bogdan-Rotund/akka.net | src/core/Akka.Remote.Tests.Performance/ThreadPoolDispatcherRemoteMessagingThroughputSpec.cs | 1,240 | C# |
using NUnit.Framework;
namespace AncoraMVVM.Base.Tests
{
[TestFixture]
public class UrlFallbackChainTests
{
// TODO: More tests.
[Test]
public void Condition_ValidUrl_True()
{
var chain = new UrlFallbackChain("", "");
Assert.IsTrue(chain.Condition("http://www.google.es"));
}
[Test]
public void Condition_InvalidUrl_False()
{
var chain = new UrlFallbackChain("", "");
Assert.IsFalse(chain.Condition("aswwes"));
}
[Test]
public void Condition_NullUrl_False()
{
var chain = new UrlFallbackChain("", "");
Assert.IsFalse(chain.Condition(null));
}
}
}
| 23.25 | 67 | 0.541667 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | gjulianm/AncoraMVVM | AncoraMVVM.Base.Tests/UrlFallbackChainTests.cs | 746 | C# |
namespace Duality.Editor.Plugins.LogView
{
public class LogViewSettings
{
private bool showMessages = true;
private bool showWarnings = true;
private bool showErrors = true;
private bool showCore = true;
private bool showEditor = true;
private bool showGame = true;
private bool autoClear = true;
private bool pauseOnError = true;
public bool ShowMessages
{
get { return this.showMessages; }
set { this.showMessages = value; }
}
public bool ShowWarnings
{
get { return this.showWarnings; }
set { this.showWarnings = value; }
}
public bool ShowErrors
{
get { return this.showErrors; }
set { this.showErrors = value; }
}
public bool ShowCore
{
get { return this.showCore; }
set { this.showCore = value; }
}
public bool ShowEditor
{
get { return this.showEditor; }
set { this.showEditor = value; }
}
public bool ShowGame
{
get { return this.showGame; }
set { this.showGame = value; }
}
public bool AutoClear
{
get { return this.autoClear; }
set { this.autoClear = value; }
}
public bool PauseOnError
{
get { return this.pauseOnError; }
set { this.pauseOnError = value; }
}
}
}
| 21.267857 | 41 | 0.65995 | [
"MIT"
] | AdamsLair/duality | Source/Plugins/EditorModules/LogView/LogViewSettings.cs | 1,193 | C# |
// Serilog.Sinks.Seq Copyright 2017 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if DURABLE
using System;
using System.IO;
using System.Text;
using Serilog.Debugging;
namespace Serilog.Sinks.Seq.Durable
{
static class PayloadReader
{
public static string ReadPayload(
int batchPostingLimit,
long? eventBodyLimitBytes,
ref FileSetPosition position,
ref int count,
out string mimeType)
{
if (position.File.EndsWith(".json"))
{
mimeType = SeqApi.RawEventFormatMimeType;
return ReadRawPayload(batchPostingLimit, eventBodyLimitBytes, ref position, ref count);
}
mimeType = SeqApi.CompactLogEventFormatMimeType;
return ReadCompactPayload(batchPostingLimit, eventBodyLimitBytes, ref position, ref count);
}
static string ReadCompactPayload(int batchPostingLimit, long? eventBodyLimitBytes, ref FileSetPosition position, ref int count)
{
var payload = new StringWriter();
using (var current = System.IO.File.Open(position.File, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var nextLineStart = position.NextLineStart;
while (count < batchPostingLimit && TryReadLine(current, ref nextLineStart, out var nextLine))
{
position = new FileSetPosition(nextLineStart, position.File);
// Count is the indicator that work was done, so advances even in the (rare) case an
// oversized event is dropped.
++count;
if (eventBodyLimitBytes.HasValue && Encoding.UTF8.GetByteCount(nextLine) > eventBodyLimitBytes.Value)
{
SelfLog.WriteLine(
"Event JSON representation exceeds the byte size limit of {0} and will be dropped; data: {1}",
eventBodyLimitBytes, nextLine);
}
else
{
payload.WriteLine(nextLine);
}
}
}
return payload.ToString();
}
static string ReadRawPayload(int batchPostingLimit, long? eventBodyLimitBytes, ref FileSetPosition position, ref int count)
{
var payload = new StringWriter();
payload.Write("{\"Events\":[");
var delimStart = "";
using (var current = System.IO.File.Open(position.File, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var nextLineStart = position.NextLineStart;
while (count < batchPostingLimit && TryReadLine(current, ref nextLineStart, out var nextLine))
{
position = new FileSetPosition(nextLineStart, position.File);
// Count is the indicator that work was done, so advances even in the (rare) case an
// oversized event is dropped.
++count;
if (eventBodyLimitBytes.HasValue && Encoding.UTF8.GetByteCount(nextLine) > eventBodyLimitBytes.Value)
{
SelfLog.WriteLine(
"Event JSON representation exceeds the byte size limit of {0} and will be dropped; data: {1}",
eventBodyLimitBytes, nextLine);
}
else
{
payload.Write(delimStart);
payload.Write(nextLine);
delimStart = ",";
}
}
payload.Write("]}");
}
return payload.ToString();
}
// It would be ideal to chomp whitespace here, but not required.
static bool TryReadLine(Stream current, ref long nextStart, out string nextLine)
{
var includesBom = nextStart == 0;
if (current.Length <= nextStart)
{
nextLine = null;
return false;
}
current.Position = nextStart;
// Important not to dispose this StreamReader as the stream must remain open.
var reader = new StreamReader(current, Encoding.UTF8, false, 128);
nextLine = reader.ReadLine();
if (nextLine == null)
return false;
nextStart += Encoding.UTF8.GetByteCount(nextLine) + Encoding.UTF8.GetByteCount(Environment.NewLine);
if (includesBom)
nextStart += 3;
return true;
}
public static string MakeEmptyPayload(out string mimeType)
{
mimeType = SeqApi.CompactLogEventFormatMimeType;
return SeqApi.NoPayload;
}
}
}
#endif
| 37.353741 | 135 | 0.563103 | [
"Apache-2.0"
] | augustoproiete-forks/serilog--serilog-sinks-seq | src/Serilog.Sinks.Seq/Sinks/Seq/Durable/PayloadReader.cs | 5,491 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonHelpers
{
public static class TimeSpanExt
{
public static TimeSpan Seconds(this int @this)
=> TimeSpan.FromSeconds(@this);
public static TimeSpan Minutes(this int @this)
=> TimeSpan.FromMinutes(@this);
public static TimeSpan Days(this int @this)
=> TimeSpan.FromDays(@this);
public static DateTime Ago(this TimeSpan @this)
=> DateTime.UtcNow - @this;
}
}
| 24.375 | 54 | 0.647863 | [
"MIT"
] | rikace/concombinators | src/Combinators/Common/Helpers/TimeSpanExt.cs | 587 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Extensions.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Remotion.Linq.Clauses;
namespace Blueshift.EntityFrameworkCore.MongoDB.Query.ExpressionVisitors
{
/// <inheritdoc />
public class MongoDbMemberAccessBindingExpressionVisitor : MemberAccessBindingExpressionVisitor
{
private readonly IModel _model;
/// <inheritdoc />
public MongoDbMemberAccessBindingExpressionVisitor(
[NotNull] QuerySourceMapping querySourceMapping,
[NotNull] MongoDbEntityQueryModelVisitor mongoDbEntityQueryModelVisitor,
bool inProjection)
: base(
Check.NotNull(querySourceMapping, nameof(querySourceMapping)),
Check.NotNull(mongoDbEntityQueryModelVisitor, nameof(mongoDbEntityQueryModelVisitor)),
inProjection)
{
_model = mongoDbEntityQueryModelVisitor.QueryCompilationContext.Model;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
Expression newExpression = null;
if (methodCallExpression.Method.IsEFPropertyMethod())
{
var newArguments
= VisitAndConvert(
new List<Expression>
{
methodCallExpression.Arguments[0],
methodCallExpression.Arguments[1]
}.AsReadOnly(),
nameof(VisitMethodCall));
Expression targetExpression = newArguments[0];
IEntityType entityType = _model
.FindEntityType(targetExpression.Type);
IProperty property = entityType
.FindProperty((string)((ConstantExpression)newArguments[1]).Value);
PropertyInfo propertyInfo = property.PropertyInfo;
if (property.IsShadowProperty && property.IsForeignKey())
{
IForeignKey foreignKey = property.AsProperty().ForeignKeys.Single();
INavigation navigation = foreignKey.PrincipalEntityType == entityType
? foreignKey.PrincipalToDependent
: foreignKey.DependentToPrincipal;
targetExpression = Expression.MakeMemberAccess(targetExpression, navigation.PropertyInfo);
IEntityType targetEntityType = navigation.GetTargetType();
property = targetEntityType.FindPrimaryKey().Properties.Single();
propertyInfo = property.PropertyInfo;
}
newExpression = Expression.Convert(
Expression.MakeMemberAccess(targetExpression, propertyInfo),
typeof(Nullable<>).MakeGenericType(propertyInfo.PropertyType));
}
return newExpression ?? base.VisitMethodCall(methodCallExpression);
}
}
} | 43.178571 | 110 | 0.641026 | [
"Apache-2.0"
] | IvanZheng/EntityFrameworkCore | src/Blueshift.EntityFrameworkCore.MongoDB/Query/ExpressionVisitors/MongoDbMemberAccessBindingExpressionVisitor.cs | 3,629 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Channels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Log = Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcherLog;
namespace Microsoft.AspNetCore.SignalR.Internal;
internal sealed partial class DefaultHubDispatcher<THub> : HubDispatcher<THub> where THub : Hub
{
private readonly Dictionary<string, HubMethodDescriptor> _methods = new(StringComparer.OrdinalIgnoreCase);
private readonly Utf8HashLookup _cachedMethodNames = new();
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IHubContext<THub> _hubContext;
private readonly ILogger<HubDispatcher<THub>> _logger;
private readonly bool _enableDetailedErrors;
private readonly Func<HubInvocationContext, ValueTask<object?>>? _invokeMiddleware;
private readonly Func<HubLifetimeContext, Task>? _onConnectedMiddleware;
private readonly Func<HubLifetimeContext, Exception?, Task>? _onDisconnectedMiddleware;
private readonly HubLifetimeManager<THub> _hubLifetimeManager;
public DefaultHubDispatcher(IServiceScopeFactory serviceScopeFactory, IHubContext<THub> hubContext, bool enableDetailedErrors,
bool disableImplicitFromServiceParameters, ILogger<DefaultHubDispatcher<THub>> logger, List<IHubFilter>? hubFilters, HubLifetimeManager<THub> lifetimeManager)
{
_serviceScopeFactory = serviceScopeFactory;
_hubContext = hubContext;
_enableDetailedErrors = enableDetailedErrors;
_logger = logger;
_hubLifetimeManager = lifetimeManager;
DiscoverHubMethods(disableImplicitFromServiceParameters);
var count = hubFilters?.Count ?? 0;
if (count != 0)
{
_invokeMiddleware = (invocationContext) =>
{
var arguments = invocationContext.HubMethodArguments as object?[] ?? invocationContext.HubMethodArguments.ToArray();
if (invocationContext.ObjectMethodExecutor != null)
{
return ExecuteMethod(invocationContext.ObjectMethodExecutor, invocationContext.Hub, arguments);
}
return ExecuteMethod(invocationContext.HubMethod.Name, invocationContext.Hub, arguments);
};
_onConnectedMiddleware = (context) => context.Hub.OnConnectedAsync();
_onDisconnectedMiddleware = (context, exception) => context.Hub.OnDisconnectedAsync(exception);
for (var i = count - 1; i > -1; i--)
{
var resolvedFilter = hubFilters![i];
var nextFilter = _invokeMiddleware;
_invokeMiddleware = (context) => resolvedFilter.InvokeMethodAsync(context, nextFilter);
var connectedFilter = _onConnectedMiddleware;
_onConnectedMiddleware = (context) => resolvedFilter.OnConnectedAsync(context, connectedFilter);
var disconnectedFilter = _onDisconnectedMiddleware;
_onDisconnectedMiddleware = (context, exception) => resolvedFilter.OnDisconnectedAsync(context, exception, disconnectedFilter);
}
}
}
public override async Task OnConnectedAsync(HubConnectionContext connection)
{
await using var scope = _serviceScopeFactory.CreateAsyncScope();
connection.HubCallerClients = new HubCallerClients(_hubContext.Clients, connection.ConnectionId, connection.ActiveInvocationLimit is not null);
var hubActivator = scope.ServiceProvider.GetRequiredService<IHubActivator<THub>>();
var hub = hubActivator.Create();
try
{
InitializeHub(hub, connection);
if (_onConnectedMiddleware != null)
{
var context = new HubLifetimeContext(connection.HubCallerContext, scope.ServiceProvider, hub);
await _onConnectedMiddleware(context);
}
else
{
await hub.OnConnectedAsync();
}
}
finally
{
hubActivator.Release(hub);
}
}
public override async Task OnDisconnectedAsync(HubConnectionContext connection, Exception? exception)
{
await using var scope = _serviceScopeFactory.CreateAsyncScope();
var hubActivator = scope.ServiceProvider.GetRequiredService<IHubActivator<THub>>();
var hub = hubActivator.Create();
try
{
InitializeHub(hub, connection);
if (_onDisconnectedMiddleware != null)
{
var context = new HubLifetimeContext(connection.HubCallerContext, scope.ServiceProvider, hub);
await _onDisconnectedMiddleware(context, exception);
}
else
{
await hub.OnDisconnectedAsync(exception);
}
}
finally
{
hubActivator.Release(hub);
}
}
public override Task DispatchMessageAsync(HubConnectionContext connection, HubMessage hubMessage)
{
// Messages are dispatched sequentially and will stop other messages from being processed until they complete.
// Streaming methods will run sequentially until they start streaming, then they will fire-and-forget allowing other messages to run.
// With parallel invokes enabled, messages run sequentially until they go async and then the next message will be allowed to start running.
switch (hubMessage)
{
case InvocationBindingFailureMessage bindingFailureMessage:
return ProcessInvocationBindingFailure(connection, bindingFailureMessage);
case StreamBindingFailureMessage bindingFailureMessage:
return ProcessStreamBindingFailure(connection, bindingFailureMessage);
case InvocationMessage invocationMessage:
Log.ReceivedHubInvocation(_logger, invocationMessage);
return ProcessInvocation(connection, invocationMessage, isStreamResponse: false);
case StreamInvocationMessage streamInvocationMessage:
Log.ReceivedStreamHubInvocation(_logger, streamInvocationMessage);
return ProcessInvocation(connection, streamInvocationMessage, isStreamResponse: true);
case CancelInvocationMessage cancelInvocationMessage:
// Check if there is an associated active stream and cancel it if it exists.
// The cts will be removed when the streaming method completes executing
if (connection.ActiveRequestCancellationSources.TryGetValue(cancelInvocationMessage.InvocationId!, out var cts))
{
Log.CancelStream(_logger, cancelInvocationMessage.InvocationId!);
cts.Cancel();
}
else
{
// Stream can be canceled on the server while client is canceling stream.
Log.UnexpectedCancel(_logger);
}
break;
case PingMessage _:
connection.StartClientTimeout();
break;
case StreamItemMessage streamItem:
return ProcessStreamItem(connection, streamItem);
case CompletionMessage completionMessage:
// closes channels, removes from Lookup dict
// user's method can see the channel is complete and begin wrapping up
if (connection.StreamTracker.TryComplete(completionMessage))
{
Log.CompletingStream(_logger, completionMessage);
}
// InvocationId is always required on CompletionMessage, it's nullable because of the base type
else if (_hubLifetimeManager.TryGetReturnType(completionMessage.InvocationId!, out _))
{
return _hubLifetimeManager.SetConnectionResultAsync(connection.ConnectionId, completionMessage);
}
else
{
Log.UnexpectedCompletion(_logger, completionMessage.InvocationId!);
}
break;
// Other kind of message we weren't expecting
default:
Log.UnsupportedMessageReceived(_logger, hubMessage.GetType().FullName!);
throw new NotSupportedException($"Received unsupported message: {hubMessage}");
}
return Task.CompletedTask;
}
private Task ProcessInvocationBindingFailure(HubConnectionContext connection, InvocationBindingFailureMessage bindingFailureMessage)
{
Log.InvalidHubParameters(_logger, bindingFailureMessage.Target, bindingFailureMessage.BindingFailure.SourceException);
var errorMessage = ErrorMessageHelper.BuildErrorMessage($"Failed to invoke '{bindingFailureMessage.Target}' due to an error on the server.",
bindingFailureMessage.BindingFailure.SourceException, _enableDetailedErrors);
return SendInvocationError(bindingFailureMessage.InvocationId, connection, errorMessage);
}
private Task ProcessStreamBindingFailure(HubConnectionContext connection, StreamBindingFailureMessage bindingFailureMessage)
{
var errorString = ErrorMessageHelper.BuildErrorMessage(
"Failed to bind Stream message.",
bindingFailureMessage.BindingFailure.SourceException, _enableDetailedErrors);
var message = CompletionMessage.WithError(bindingFailureMessage.Id, errorString);
Log.ClosingStreamWithBindingError(_logger, message);
// ignore failure, it means the client already completed the stream or the stream never existed on the server
connection.StreamTracker.TryComplete(message);
// TODO: Send stream completion message to client when we add it
return Task.CompletedTask;
}
private Task ProcessStreamItem(HubConnectionContext connection, StreamItemMessage message)
{
if (!connection.StreamTracker.TryProcessItem(message, out var processTask))
{
Log.UnexpectedStreamItem(_logger);
return Task.CompletedTask;
}
Log.ReceivedStreamItem(_logger, message);
return processTask;
}
private Task ProcessInvocation(HubConnectionContext connection,
HubMethodInvocationMessage hubMethodInvocationMessage, bool isStreamResponse)
{
if (!_methods.TryGetValue(hubMethodInvocationMessage.Target, out var descriptor))
{
Log.UnknownHubMethod(_logger, hubMethodInvocationMessage.Target);
if (!string.IsNullOrEmpty(hubMethodInvocationMessage.InvocationId))
{
// Send an error to the client. Then let the normal completion process occur
return connection.WriteAsync(CompletionMessage.WithError(
hubMethodInvocationMessage.InvocationId, $"Unknown hub method '{hubMethodInvocationMessage.Target}'")).AsTask();
}
else
{
return Task.CompletedTask;
}
}
else
{
bool isStreamCall = descriptor.StreamingParameters != null;
if (connection.ActiveInvocationLimit != null && !isStreamCall && !isStreamResponse)
{
return connection.ActiveInvocationLimit.RunAsync(static state =>
{
var (dispatcher, descriptor, connection, invocationMessage) = state;
return dispatcher.Invoke(descriptor, connection, invocationMessage, isStreamResponse: false, isStreamCall: false);
}, (this, descriptor, connection, hubMethodInvocationMessage));
}
else
{
return Invoke(descriptor, connection, hubMethodInvocationMessage, isStreamResponse, isStreamCall);
}
}
}
private async Task Invoke(HubMethodDescriptor descriptor, HubConnectionContext connection,
HubMethodInvocationMessage hubMethodInvocationMessage, bool isStreamResponse, bool isStreamCall)
{
var methodExecutor = descriptor.MethodExecutor;
var disposeScope = true;
var scope = _serviceScopeFactory.CreateAsyncScope();
IHubActivator<THub>? hubActivator = null;
THub? hub = null;
try
{
hubActivator = scope.ServiceProvider.GetRequiredService<IHubActivator<THub>>();
hub = hubActivator.Create();
if (!await IsHubMethodAuthorized(scope.ServiceProvider, connection, descriptor, hubMethodInvocationMessage.Arguments, hub))
{
Log.HubMethodNotAuthorized(_logger, hubMethodInvocationMessage.Target);
await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
$"Failed to invoke '{hubMethodInvocationMessage.Target}' because user is unauthorized");
return;
}
if (!await ValidateInvocationMode(descriptor, isStreamResponse, hubMethodInvocationMessage, connection))
{
return;
}
try
{
var clientStreamLength = hubMethodInvocationMessage.StreamIds?.Length ?? 0;
var serverStreamLength = descriptor.StreamingParameters?.Count ?? 0;
if (clientStreamLength != serverStreamLength)
{
var ex = new HubException($"Client sent {clientStreamLength} stream(s), Hub method expects {serverStreamLength}.");
Log.InvalidHubParameters(_logger, hubMethodInvocationMessage.Target, ex);
await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, _enableDetailedErrors));
return;
}
InitializeHub(hub, connection);
Task? invocation = null;
var arguments = hubMethodInvocationMessage.Arguments;
CancellationTokenSource? cts = null;
if (descriptor.HasSyntheticArguments)
{
ReplaceArguments(descriptor, hubMethodInvocationMessage, isStreamCall, connection, scope, ref arguments, out cts);
}
if (isStreamResponse)
{
_ = StreamAsync(hubMethodInvocationMessage.InvocationId!, connection, arguments, scope, hubActivator, hub, cts, hubMethodInvocationMessage, descriptor);
}
else
{
// Invoke or Send
static async Task ExecuteInvocation(DefaultHubDispatcher<THub> dispatcher,
ObjectMethodExecutor methodExecutor,
THub hub,
object?[] arguments,
AsyncServiceScope scope,
IHubActivator<THub> hubActivator,
HubConnectionContext connection,
HubMethodInvocationMessage hubMethodInvocationMessage,
bool isStreamCall)
{
var logger = dispatcher._logger;
var enableDetailedErrors = dispatcher._enableDetailedErrors;
object? result;
try
{
result = await dispatcher.ExecuteHubMethod(methodExecutor, hub, arguments, connection, scope.ServiceProvider);
Log.SendingResult(logger, hubMethodInvocationMessage.InvocationId, methodExecutor);
}
catch (Exception ex)
{
Log.FailedInvokingHubMethod(logger, hubMethodInvocationMessage.Target, ex);
await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, enableDetailedErrors));
return;
}
finally
{
// Stream response handles cleanup in StreamResultsAsync
// And normal invocations handle cleanup below in the finally
if (isStreamCall)
{
await CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);
}
}
// No InvocationId - Send Async, no response expected
if (!string.IsNullOrEmpty(hubMethodInvocationMessage.InvocationId))
{
// Invoke Async, one reponse expected
await connection.WriteAsync(CompletionMessage.WithResult(hubMethodInvocationMessage.InvocationId, result));
}
}
invocation = ExecuteInvocation(this, methodExecutor, hub, arguments, scope, hubActivator, connection, hubMethodInvocationMessage, isStreamCall);
}
if (isStreamCall || isStreamResponse)
{
// don't await streaming invocations
// leave them running in the background, allowing dispatcher to process other messages between streaming items
disposeScope = false;
}
else
{
// complete the non-streaming calls now
await invocation!;
}
}
catch (TargetInvocationException ex)
{
Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex.InnerException ?? ex, _enableDetailedErrors));
}
catch (Exception ex)
{
Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, _enableDetailedErrors));
}
}
finally
{
if (disposeScope)
{
await CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);
}
}
}
private static ValueTask CleanupInvocation(HubConnectionContext connection, HubMethodInvocationMessage hubMessage, IHubActivator<THub>? hubActivator,
THub? hub, AsyncServiceScope scope)
{
if (hubMessage.StreamIds != null)
{
foreach (var stream in hubMessage.StreamIds)
{
connection.StreamTracker.TryComplete(CompletionMessage.Empty(stream));
}
}
if (hub != null)
{
hubActivator?.Release(hub);
}
return scope.DisposeAsync();
}
private async Task StreamAsync(string invocationId, HubConnectionContext connection, object?[] arguments, AsyncServiceScope scope,
IHubActivator<THub> hubActivator, THub hub, CancellationTokenSource? streamCts, HubMethodInvocationMessage hubMethodInvocationMessage, HubMethodDescriptor descriptor)
{
string? error = null;
streamCts ??= CancellationTokenSource.CreateLinkedTokenSource(connection.ConnectionAborted);
try
{
if (!connection.ActiveRequestCancellationSources.TryAdd(invocationId, streamCts))
{
Log.InvocationIdInUse(_logger, invocationId);
error = $"Invocation ID '{invocationId}' is already in use.";
return;
}
object? result;
try
{
result = await ExecuteHubMethod(descriptor.MethodExecutor, hub, arguments, connection, scope.ServiceProvider);
}
catch (Exception ex)
{
Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
error = ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, _enableDetailedErrors);
return;
}
if (result == null)
{
Log.InvalidReturnValueFromStreamingMethod(_logger, descriptor.MethodExecutor.MethodInfo.Name);
error = $"The value returned by the streaming method '{descriptor.MethodExecutor.MethodInfo.Name}' is not a ChannelReader<> or IAsyncEnumerable<>.";
return;
}
await using var enumerator = descriptor.FromReturnedStream(result, streamCts.Token);
Log.StreamingResult(_logger, invocationId, descriptor.MethodExecutor);
var streamItemMessage = new StreamItemMessage(invocationId, null);
while (await enumerator.MoveNextAsync())
{
streamItemMessage.Item = enumerator.Current;
// Send the stream item
await connection.WriteAsync(streamItemMessage);
}
}
catch (ChannelClosedException ex)
{
// If the channel closes from an exception in the streaming method, grab the innerException for the error from the streaming method
Log.FailedStreaming(_logger, invocationId, descriptor.MethodExecutor.MethodInfo.Name, ex.InnerException ?? ex);
error = ErrorMessageHelper.BuildErrorMessage("An error occurred on the server while streaming results.", ex.InnerException ?? ex, _enableDetailedErrors);
}
catch (Exception ex)
{
// If the streaming method was canceled we don't want to send a HubException message - this is not an error case
if (!(ex is OperationCanceledException && streamCts.IsCancellationRequested))
{
Log.FailedStreaming(_logger, invocationId, descriptor.MethodExecutor.MethodInfo.Name, ex);
error = ErrorMessageHelper.BuildErrorMessage("An error occurred on the server while streaming results.", ex, _enableDetailedErrors);
}
}
finally
{
await CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);
streamCts.Dispose();
connection.ActiveRequestCancellationSources.TryRemove(invocationId, out _);
await connection.WriteAsync(CompletionMessage.WithError(invocationId, error));
}
}
private ValueTask<object?> ExecuteHubMethod(ObjectMethodExecutor methodExecutor, THub hub, object?[] arguments, HubConnectionContext connection, IServiceProvider serviceProvider)
{
if (_invokeMiddleware != null)
{
var invocationContext = new HubInvocationContext(methodExecutor, connection.HubCallerContext, serviceProvider, hub, arguments);
return _invokeMiddleware(invocationContext);
}
// If no Hub filters are registered
return ExecuteMethod(methodExecutor, hub, arguments);
}
private ValueTask<object?> ExecuteMethod(string hubMethodName, Hub hub, object?[] arguments)
{
if (!_methods.TryGetValue(hubMethodName, out var methodDescriptor))
{
throw new HubException($"Unknown hub method '{hubMethodName}'");
}
var methodExecutor = methodDescriptor.MethodExecutor;
return ExecuteMethod(methodExecutor, hub, arguments);
}
private static async ValueTask<object?> ExecuteMethod(ObjectMethodExecutor methodExecutor, Hub hub, object?[] arguments)
{
if (methodExecutor.IsMethodAsync)
{
if (methodExecutor.MethodReturnType == typeof(Task))
{
await (Task)methodExecutor.Execute(hub, arguments)!;
return null;
}
else
{
return await methodExecutor.ExecuteAsync(hub, arguments);
}
}
else
{
return methodExecutor.Execute(hub, arguments);
}
}
private static async Task SendInvocationError(string? invocationId,
HubConnectionContext connection, string errorMessage)
{
if (string.IsNullOrEmpty(invocationId))
{
return;
}
await connection.WriteAsync(CompletionMessage.WithError(invocationId, errorMessage));
}
private void InitializeHub(THub hub, HubConnectionContext connection)
{
hub.Clients = connection.HubCallerClients;
hub.Context = connection.HubCallerContext;
hub.Groups = _hubContext.Groups;
}
private static Task<bool> IsHubMethodAuthorized(IServiceProvider provider, HubConnectionContext hubConnectionContext, HubMethodDescriptor descriptor, object?[] hubMethodArguments, Hub hub)
{
// If there are no policies we don't need to run auth
if (descriptor.Policies.Count == 0)
{
return TaskCache.True;
}
return IsHubMethodAuthorizedSlow(provider, hubConnectionContext.User, descriptor.Policies, new HubInvocationContext(hubConnectionContext.HubCallerContext, provider, hub, descriptor.MethodExecutor.MethodInfo, hubMethodArguments));
}
private static async Task<bool> IsHubMethodAuthorizedSlow(IServiceProvider provider, ClaimsPrincipal principal, IList<IAuthorizeData> policies, HubInvocationContext resource)
{
var authService = provider.GetRequiredService<IAuthorizationService>();
var policyProvider = provider.GetRequiredService<IAuthorizationPolicyProvider>();
var authorizePolicy = await AuthorizationPolicy.CombineAsync(policyProvider, policies);
// AuthorizationPolicy.CombineAsync only returns null if there are no policies and we check that above
Debug.Assert(authorizePolicy != null);
var authorizationResult = await authService.AuthorizeAsync(principal, resource, authorizePolicy);
// Only check authorization success, challenge or forbid wouldn't make sense from a hub method invocation
return authorizationResult.Succeeded;
}
private async Task<bool> ValidateInvocationMode(HubMethodDescriptor hubMethodDescriptor, bool isStreamResponse,
HubMethodInvocationMessage hubMethodInvocationMessage, HubConnectionContext connection)
{
if (hubMethodDescriptor.IsStreamResponse && !isStreamResponse)
{
// Non-null/empty InvocationId? Blocking
if (!string.IsNullOrEmpty(hubMethodInvocationMessage.InvocationId))
{
Log.StreamingMethodCalledWithInvoke(_logger, hubMethodInvocationMessage);
await connection.WriteAsync(CompletionMessage.WithError(hubMethodInvocationMessage.InvocationId,
$"The client attempted to invoke the streaming '{hubMethodInvocationMessage.Target}' method with a non-streaming invocation."));
}
return false;
}
if (!hubMethodDescriptor.IsStreamResponse && isStreamResponse)
{
Log.NonStreamingMethodCalledWithStream(_logger, hubMethodInvocationMessage);
await connection.WriteAsync(CompletionMessage.WithError(hubMethodInvocationMessage.InvocationId!,
$"The client attempted to invoke the non-streaming '{hubMethodInvocationMessage.Target}' method with a streaming invocation."));
return false;
}
return true;
}
private void ReplaceArguments(HubMethodDescriptor descriptor, HubMethodInvocationMessage hubMethodInvocationMessage, bool isStreamCall,
HubConnectionContext connection, AsyncServiceScope scope, ref object?[] arguments, out CancellationTokenSource? cts)
{
cts = null;
// In order to add the synthetic arguments we need a new array because the invocation array is too small (it doesn't know about synthetic arguments)
arguments = new object?[descriptor.OriginalParameterTypes!.Count];
var streamPointer = 0;
var hubInvocationArgumentPointer = 0;
for (var parameterPointer = 0; parameterPointer < arguments.Length; parameterPointer++)
{
if (hubMethodInvocationMessage.Arguments?.Length > hubInvocationArgumentPointer &&
(hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer] == null ||
descriptor.OriginalParameterTypes[parameterPointer].IsAssignableFrom(hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer]?.GetType())))
{
// The types match so it isn't a synthetic argument, just copy it into the arguments array
arguments[parameterPointer] = hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer];
hubInvocationArgumentPointer++;
}
else
{
if (descriptor.OriginalParameterTypes[parameterPointer] == typeof(CancellationToken))
{
cts = CancellationTokenSource.CreateLinkedTokenSource(connection.ConnectionAborted);
arguments[parameterPointer] = cts.Token;
}
else if (descriptor.IsServiceArgument(parameterPointer))
{
arguments[parameterPointer] = scope.ServiceProvider.GetRequiredService(descriptor.OriginalParameterTypes[parameterPointer]);
}
else if (isStreamCall && ReflectionHelper.IsStreamingType(descriptor.OriginalParameterTypes[parameterPointer], mustBeDirectType: true))
{
Log.StartingParameterStream(_logger, hubMethodInvocationMessage.StreamIds![streamPointer]);
var itemType = descriptor.StreamingParameters![streamPointer];
arguments[parameterPointer] = connection.StreamTracker.AddStream(hubMethodInvocationMessage.StreamIds[streamPointer],
itemType, descriptor.OriginalParameterTypes[parameterPointer]);
streamPointer++;
}
else
{
// This should never happen
Debug.Assert(false, $"Failed to bind argument of type '{descriptor.OriginalParameterTypes[parameterPointer].Name}' for hub method '{descriptor.MethodExecutor.MethodInfo.Name}'.");
}
}
}
}
private void DiscoverHubMethods(bool disableImplicitFromServiceParameters)
{
var hubType = typeof(THub);
var hubTypeInfo = hubType.GetTypeInfo();
var hubName = hubType.Name;
using var scope = _serviceScopeFactory.CreateScope();
IServiceProviderIsService? serviceProviderIsService = null;
if (!disableImplicitFromServiceParameters)
{
serviceProviderIsService = scope.ServiceProvider.GetService<IServiceProviderIsService>();
}
foreach (var methodInfo in HubReflectionHelper.GetHubMethods(hubType))
{
if (methodInfo.IsGenericMethod)
{
throw new NotSupportedException($"Method '{methodInfo.Name}' is a generic method which is not supported on a Hub.");
}
var methodName =
methodInfo.GetCustomAttribute<HubMethodNameAttribute>()?.Name ??
methodInfo.Name;
if (_methods.ContainsKey(methodName))
{
throw new NotSupportedException($"Duplicate definitions of '{methodName}'. Overloading is not supported.");
}
var executor = ObjectMethodExecutor.Create(methodInfo, hubTypeInfo);
var authorizeAttributes = methodInfo.GetCustomAttributes<AuthorizeAttribute>(inherit: true);
_methods[methodName] = new HubMethodDescriptor(executor, serviceProviderIsService, authorizeAttributes);
_cachedMethodNames.Add(methodName);
Log.HubMethodBound(_logger, hubName, methodName);
}
}
public override IReadOnlyList<Type> GetParameterTypes(string methodName)
{
if (!_methods.TryGetValue(methodName, out var descriptor))
{
throw new HubException("Method does not exist.");
}
return descriptor.ParameterTypes;
}
public override string? GetTargetName(ReadOnlySpan<byte> targetUtf8Bytes)
{
if (_cachedMethodNames.TryGetValue(targetUtf8Bytes, out var targetName))
{
return targetName;
}
return null;
}
}
| 47.166898 | 237 | 0.640374 | [
"Apache-2.0"
] | aspnet/AspNetCore | src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs | 33,913 | C# |
using System;
using System.Runtime.CompilerServices;
using Robust.Shared.Maths;
using Robust.Shared.Serialization;
namespace Content.Shared.Atmos
{
/// <summary>
/// The reason we use this over <see cref="Direction"/> is that we are going to do some heavy bitflag usage.
/// </summary>
[Flags, Serializable]
[FlagsFor(typeof(AtmosDirectionFlags))]
public enum AtmosDirection
{
Invalid = 0, // 0
North = 1 << 0, // 1
South = 1 << 1, // 2
East = 1 << 2, // 4
West = 1 << 3, // 8
NorthEast = North | East, // 5
SouthEast = South | East, // 6
NorthWest = North | West, // 9
SouthWest = South | West, // 10
All = North | South | East | West, // 15
}
public static class AtmosDirectionHelpers
{
public static AtmosDirection GetOpposite(this AtmosDirection direction)
{
return direction switch
{
AtmosDirection.North => AtmosDirection.South,
AtmosDirection.South => AtmosDirection.North,
AtmosDirection.East => AtmosDirection.West,
AtmosDirection.West => AtmosDirection.East,
AtmosDirection.NorthEast => AtmosDirection.SouthWest,
AtmosDirection.NorthWest => AtmosDirection.SouthEast,
AtmosDirection.SouthEast => AtmosDirection.NorthWest,
AtmosDirection.SouthWest => AtmosDirection.NorthEast,
_ => throw new ArgumentOutOfRangeException(nameof(direction))
};
}
public static Direction ToDirection(this AtmosDirection direction)
{
return direction switch
{
AtmosDirection.North => Direction.North,
AtmosDirection.South => Direction.South,
AtmosDirection.East => Direction.East,
AtmosDirection.West => Direction.West,
AtmosDirection.NorthEast => Direction.NorthEast,
AtmosDirection.NorthWest => Direction.NorthWest,
AtmosDirection.SouthEast => Direction.SouthEast,
AtmosDirection.SouthWest => Direction.SouthWest,
AtmosDirection.Invalid => Direction.Invalid,
_ => throw new ArgumentOutOfRangeException(nameof(direction))
};
}
public static AtmosDirection ToAtmosDirection(this Direction direction)
{
return direction switch
{
Direction.North => AtmosDirection.North,
Direction.South => AtmosDirection.South,
Direction.East => AtmosDirection.East,
Direction.West => AtmosDirection.West,
Direction.NorthEast => AtmosDirection.NorthEast,
Direction.NorthWest => AtmosDirection.NorthWest,
Direction.SouthEast => AtmosDirection.SouthEast,
Direction.SouthWest => AtmosDirection.SouthWest,
Direction.Invalid => AtmosDirection.Invalid,
_ => throw new ArgumentOutOfRangeException(nameof(direction))
};
}
/// <summary>
/// Converts a direction to an angle, where angle is -PI to +PI.
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public static Angle ToAngle(this AtmosDirection direction)
{
return direction switch
{
AtmosDirection.East => Angle.FromDegrees(0),
AtmosDirection.North => Angle.FromDegrees(90),
AtmosDirection.West => Angle.FromDegrees(180),
AtmosDirection.South => Angle.FromDegrees(270),
AtmosDirection.NorthEast => Angle.FromDegrees(45),
AtmosDirection.NorthWest => Angle.FromDegrees(135),
AtmosDirection.SouthWest => Angle.FromDegrees(225),
AtmosDirection.SouthEast => Angle.FromDegrees(315),
_ => throw new ArgumentOutOfRangeException(nameof(direction), $"It was {direction}."),
};
}
/// <summary>
/// Converts an angle to a cardinal AtmosDirection
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static AtmosDirection ToAtmosDirectionCardinal(this Angle angle)
{
return angle.GetCardinalDir().ToAtmosDirection();
}
/// <summary>
/// Converts an angle to an AtmosDirection
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static AtmosDirection ToAtmosDirection(this Angle angle)
{
return angle.GetDir().ToAtmosDirection();
}
public static int ToIndex(this AtmosDirection direction)
{
// This will throw if you pass an invalid direction. Not this method's fault, but yours!
return (int) Math.Log2((int) direction);
}
public static AtmosDirection WithFlag(this AtmosDirection direction, AtmosDirection other)
{
return direction | other;
}
public static AtmosDirection WithoutFlag(this AtmosDirection direction, AtmosDirection other)
{
return direction & ~other;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsFlagSet(this AtmosDirection direction, AtmosDirection other)
{
return (direction & other) != 0;
}
}
public sealed class AtmosDirectionFlags { }
}
| 38.704698 | 116 | 0.570487 | [
"MIT"
] | ManelNavola/space-station-14 | Content.Shared/Atmos/AtmosDirection.cs | 5,769 | C# |
namespace ManualMapUtil.Entities
{
public class UserDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
}
| 19.7 | 44 | 0.573604 | [
"MIT"
] | RanderGabriel/ManualMapUtil | Entities/UserDTO.cs | 199 | C# |
// ReSharper disable CheckNamespace
using System;
using System.Net.Http;
using EventStore.Client;
using Grpc.Core.Interceptors;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
#nullable enable
namespace Microsoft.Extensions.DependencyInjection {
/// <summary>
/// A set of extension methods for <see cref="IServiceCollection"/> which provide support for an <see cref="EventStoreProjectionManagementClient"/>.
/// </summary>
public static class EventStoreProjectionManagementClientCollectionExtensions {
/// <summary>
/// Adds an <see cref="EventStoreProjectionManagementClient"/> to the <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services"></param>
/// <param name="address"></param>
/// <param name="createHttpMessageHandler"></param>
/// <returns></returns>
public static IServiceCollection AddEventStoreProjectionManagementClient(this IServiceCollection services,
Uri address,
Func<HttpMessageHandler>? createHttpMessageHandler = null)
=> services.AddEventStoreProjectionManagementClient(options => {
options.ConnectivitySettings.Address = address;
options.CreateHttpMessageHandler = createHttpMessageHandler;
});
/// <summary>
/// Adds an <see cref="EventStoreProjectionManagementClient"/> to the <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services"></param>
/// <param name="configureSettings"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static IServiceCollection AddEventStoreProjectionManagementClient(this IServiceCollection services,
Action<EventStoreClientSettings>? configureSettings = null) {
if (services == null) {
throw new ArgumentNullException(nameof(services));
}
var settings = new EventStoreClientSettings();
configureSettings?.Invoke(settings);
services.TryAddSingleton(provider => {
settings.LoggerFactory ??= provider.GetService<ILoggerFactory>();
settings.Interceptors ??= provider.GetServices<Interceptor>();
return new EventStoreProjectionManagementClient(settings);
});
return services;
}
}
}
// ReSharper restore CheckNamespace
| 37.423729 | 149 | 0.752264 | [
"Apache-2.0"
] | BrunoZell/EventStore-Client-Dotnet | src/EventStore.Client.ProjectionManagement/EventStoreProjectionManagementClientCollectionExtensions.cs | 2,208 | C# |
using System;
using System.Data;
using Csla;
namespace SelfLoad.DataAccess.ERLevel
{
/// <summary>
/// DAL Interface for C03_Continent_Child type
/// </summary>
public partial interface IC03_Continent_ChildDal
{
/// <summary>
/// Loads a C03_Continent_Child object from the database.
/// </summary>
/// <param name="continent_ID1">The Continent ID1.</param>
/// <returns>A data reader to the C03_Continent_Child.</returns>
IDataReader Fetch(int continent_ID1);
/// <summary>
/// Inserts a new C03_Continent_Child object in the database.
/// </summary>
/// <param name="continent_ID1">The parent Continent ID1.</param>
/// <param name="continent_Child_Name">The Continent Child Name.</param>
void Insert(int continent_ID1, string continent_Child_Name);
/// <summary>
/// Updates in the database all changes made to the C03_Continent_Child object.
/// </summary>
/// <param name="continent_ID1">The parent Continent ID1.</param>
/// <param name="continent_Child_Name">The Continent Child Name.</param>
void Update(int continent_ID1, string continent_Child_Name);
/// <summary>
/// Deletes the C03_Continent_Child object from database.
/// </summary>
/// <param name="continent_ID1">The parent Continent ID1.</param>
void Delete(int continent_ID1);
}
}
| 37.525 | 88 | 0.622918 | [
"MIT"
] | CslaGenFork/CslaGenFork | trunk/Samples/DeepLoad/DAL-DR/SelfLoad.DataAccess/ERLevel/IC03_Continent_ChildDal.Designer.cs | 1,501 | C# |
using System.Collections.Generic;
using System.Linq;
using SmartChord.Parser;
using SmartChord.Parser.Models;
using SmartChord.Parser.Models.Elements;
namespace SmartChord.Transpose
{
public class SongAnalyzer
{
public Note DiscoverKeyOfSong(Song song)
{
var stats = GetStatistics(song);
var values = Extensions.GetValues<Note>();
int highestScore = 0;
var result = Note.Unknown;
foreach (var key in values)
{
var scoreCard = new KeyScoreCard(key);
var score = scoreCard.Score(stats);
if (score > highestScore)
{
highestScore = score;
result = key;
}
}
return result;
}
private void MarkBassNotes(Song song)
{
var bassNotes = (from line in song.Lines
let wordElements = line.Elements.OfType<WordElement>().Where(x => x.IsSlash)
from element in line.Elements.OfType<ChordElement>()
where wordElements.Contains(element.PreviousElement)
select element);
foreach (var bassNote in bassNotes)
{
bassNote.IsBassNote = true;
}
}
private readonly List<string> _ambiguousChords = new List<string>() { "A", "Am", "Ab", "Go", "Do" };
private void ResolveAmbiguousElements(Song song)
{
var results = from line in song.Lines
from element in line.Elements.OfType<ChordElement>()
where _ambiguousChords.Contains(element.Chord.ToString())
select new { element, line };
var resultsToResolve = from result in results
let nextWordElement = result.element.NextElement?.NextElement as WordElement
let previousWordElement = result.element.PreviousElement?.PreviousElement as WordElement
where nextWordElement != null && nextWordElement.IsFirstCharacterAlphaNumeric ||
previousWordElement != null && previousWordElement.IsLastCharacterAlphaNumeric
select result;
foreach (var result in resultsToResolve)
{
var newElementList = (from element in result.line.Elements
select element == result.element ? new WordElement(element.GetText()) : element)
.ToList();
result.line.Elements = new List<BaseElement>(newElementList);
}
}
private List<SongStat> GetStatistics(Song song)
{
ResolveAmbiguousElements(song);
MarkBassNotes(song);
return (from line in song.Lines
from element in line.Elements.OfType<ChordElement>()
where !element.IsBassNote
group element by element.Chord.BaseChord
into g
select new SongStat
{
RootNote = g.First().Chord.RootNote,
Tone = g.First().Chord.Tone,
Count = g.Count()
}).ToList();
}
}
}
| 37.673684 | 124 | 0.499301 | [
"MIT"
] | codeapologist/SmartChord | src/SmartChord.Transposer/SongAnalyzer.cs | 3,487 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lightsail.Model
{
/// <summary>
/// Describes a container deployment configuration of an Amazon Lightsail container service.
///
///
/// <para>
/// A deployment specifies the settings, such as the ports and launch command, of containers
/// that are deployed to your container service.
/// </para>
/// </summary>
public partial class ContainerServiceDeploymentRequest
{
private Dictionary<string, Container> _containers = new Dictionary<string, Container>();
private EndpointRequest _publicEndpoint;
/// <summary>
/// Gets and sets the property Containers.
/// <para>
/// An object that describes the configuration for the containers of the deployment.
/// </para>
/// </summary>
public Dictionary<string, Container> Containers
{
get { return this._containers; }
set { this._containers = value; }
}
// Check to see if Containers property is set
internal bool IsSetContainers()
{
return this._containers != null && this._containers.Count > 0;
}
/// <summary>
/// Gets and sets the property PublicEndpoint.
/// <para>
/// An object that describes the endpoint of the deployment.
/// </para>
/// </summary>
public EndpointRequest PublicEndpoint
{
get { return this._publicEndpoint; }
set { this._publicEndpoint = value; }
}
// Check to see if PublicEndpoint property is set
internal bool IsSetPublicEndpoint()
{
return this._publicEndpoint != null;
}
}
} | 32.768293 | 108 | 0.620394 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/ContainerServiceDeploymentRequest.cs | 2,687 | C# |
// Copyright (c) 2014-2020 DataStax Inc.
// Copyright (c) 2020, Rafael Almeida (ralmsdevelper)
// Licensed under the Apache License, Version 2.0. See LICENCE in the project root for license information.
namespace Scylla.Net.Requests
{
internal interface IStartupRequestFactory
{
IRequest CreateStartupRequest(ProtocolOptions protocolOptions);
}
}
| 30.75 | 107 | 0.750678 | [
"Apache-2.0"
] | ScyllaNet/ScyllaNet | src/ScyllaNet/Requests/IStartupRequestFactory.cs | 371 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using ChessLib.Core.Helpers;
using ChessLib.Core.Tests.Helpers;
using ChessLib.Core.Translate;
using ChessLib.Core.Types;
using ChessLib.Core.Types.Enums;
using NUnit.Framework;
// ReSharper disable StringLiteralTypo
namespace ChessLib.Core.Tests.MagicBitboard
{
public class MagicBitboardTestData
{
private static readonly FenTextToBoard FenReader = new FenTextToBoard();
public static IEnumerable<TestCase<ulong, Board>> GetPiecesAttackingSquareTestCases_SpecificColor()
{
var description = "Specific Color";
yield return new TestCase<ulong, Board>(0x4000ul,
FenReader.Translate("2r5/3r2k1/p3b3/1p3p2/2pPpP2/P1N1P3/1P4RP/2R3K1 b - - 1 34"),
$"{description} White Rook attacks (Black attacks from Queenside)", (ushort)54, Color.White);
yield return new TestCase<ulong, Board>(0x800000000,
FenReader.Translate("4k3/8/8/2pP4/8/8/8/4K3 w - c6 0 1"),
$"{description} White Pawn on d4 attacks the c6 square.", (ushort)42, Color.White);
yield return new TestCase<ulong, Board>(0x200000000,
FenReader.Translate("4k3/8/8/1p6/8/3P4/8/4K3 w - - 0 1"),
$"{description} Black Pawn on b5 attacks the c4 square.", (ushort)26, Color.Black);
yield return new TestCase<ulong, Board>(0x80000, FenReader.Translate("4k3/8/8/1p6/8/3P4/8/4K3 w - - 0 1"),
$"{description} White Pawn on d3 attacks the c4 square.", (ushort)26, Color.White);
yield return new TestCase<ulong, Board>(0x00, FenReader.Translate("4k3/8/8/2pP4/8/8/8/4K3 w - c6 0 1"),
$"{description} Nothing attacking d6", (ushort)43, Color.White);
yield return new TestCase<ulong, Board>(0x400000000,
FenReader.Translate("4k3/8/8/2pP4/8/8/8/4K3 w - c6 0 1"),
$"{description} Black Pawn attacks d4", (ushort)27, Color.Black);
yield return new TestCase<ulong, Board>(0x8000140000000000,
FenReader.Translate("4k2Q/8/2B1R3/8/8/8/8/4K3 b - - 0 1"),
$"{description} 3 White Pieces attack Black King", (ushort)60, Color.White);
yield return new TestCase<ulong, Board>(
0x140000000000,
FenReader.Translate("4k2q/8/2B1R3/8/8/8/8/4K3 b - - 0 1"),
$"{description} Two White pieces attack the Black Queen, one Black Queen flanks from the Kingside.",
(ushort)60,
Color.White);
var board = FenReader.Translate("8/1k6/8/3pP3/8/5K2/8/8 w - d6 0 4");
yield return new TestCase<ulong, Board>(
"e5".ToBoardIndex().GetBoardValueOfIndex(),
board,
"En Passant available from pawn on d6, after d7-d5",
"d6".ToBoardIndex(),
Color.White);
board = FenReader.Translate("4k3/8/8/2p5/3P4/8/8/4K3 w - - 0 1");
yield return new TestCase<ulong, Board>("d4".ToBoardIndex().GetBoardValueOfIndex(),
board,
"Normal pawn attack- White pawn on d4 attacks c5",
"c5".ToBoardIndex(),
Color.White);
}
public static IEnumerable<TestCase<ulong, Board>> GetPiecesAttackingSquareTestCases_AllColors()
{
var description = "All Colors";
yield return new TestCase<ulong, Board>(0x8000000004000ul,
FenReader.Translate("2r5/3r2k1/p3b3/1p3p2/2pPpP2/P1N1P3/1P4RP/2R3K1 b - - 1 34"),
$"{description} Black and White Rook Attack g7", (ushort)54, null);
yield return new TestCase<ulong, Board>(0x800000000,
FenReader.Translate("4k3/8/8/2pP4/8/8/8/4K3 w - c6 0 1"),
$"{description} White Pawn on d5 attacks the c6 square.", (ushort)42, null);
yield return new TestCase<ulong, Board>(0x00, FenReader.Translate("4k3/8/8/2pP4/8/8/8/4K3 w - c6 0 1"),
$"{description} Nothing attacking d6", (ushort)43, null);
yield return new TestCase<ulong, Board>(0x200080000,
FenReader.Translate("4k3/8/8/1p6/8/3P4/8/4K3 w - - 0 1"),
$"{description} White Pawn on d3 / Black Pawn on b5 both attack the c4 square.", (ushort)26, null);
yield return new TestCase<ulong, Board>(0x400000000,
FenReader.Translate("4k3/8/8/2pP4/8/8/8/4K3 w - c6 0 1"),
$"{description} Black Pawn attacks d4", (ushort)27, null);
yield return new TestCase<ulong, Board>(0x8000140000000000,
FenReader.Translate("4k2Q/8/2B1R3/8/8/8/8/4K3 b - - 0 1"),
$"{description} 3 White Pieces attack Black King", (ushort)60, null);
yield return new TestCase<ulong, Board>(0x8000140000000000,
FenReader.Translate("4k2q/8/2B1R3/8/8/8/8/4K3 b - - 0 1"),
$"{description} Two White pieces attack the Black Queen, one Black Queen flanks from the Kingside.",
(ushort)60,
null);
}
public static IEnumerable GetPseudoLegalMoveTestCases()
{
ushort whiteKingIndex = 4;
ushort blackKingIndex = 60;
var board = FenReader.Translate("r1bqk2r/ppp1bppp/2np1n2/4p3/2P5/2N2NP1/PP1PPPBP/R1BQK2R w KQkq - 2 6");
var kf1 = MoveHelpers.GenerateMove("e1".ToBoardIndex(), "f1".ToBoardIndex());
var castleShort = MoveHelpers.WhiteCastleKingSide;
var desc = "White should have Kf1 and O-O";
var name = "Legal Moves - White King (O-O)";
yield return new TestCaseData(board, new[] { kf1, castleShort }, whiteKingIndex)
.SetName(name)
.SetDescription(desc);
board = FenReader.Translate("r1bqk2r/ppp1bppp/3p4/8/2Ppn3/2NP2P1/PPQBPP1P/R3KB1R w KQkq - 2 9");
var kd1 = MoveHelpers.GenerateMove("e1".ToBoardIndex(), "d1".ToBoardIndex());
var castleLong = MoveHelpers.WhiteCastleQueenSide;
desc = "White should have Kd1 and O-O-O";
name = "Legal Moves - White King (O-O-O)";
yield return new TestCaseData(board, new[] { kd1, castleLong }, whiteKingIndex).SetName(name)
.SetDescription(desc);
board = FenReader.Translate("r1bqk2r/ppp1bppp/3p4/8/2Ppn3/2NP2P1/PPQBPP1P/R3KB1R b KQkq - 2 9");
var kf8 = MoveHelpers.GenerateMove("e8".ToBoardIndex(), "f8".ToBoardIndex());
castleShort = MoveHelpers.BlackCastleKingSide;
desc = "Black should have Kf8 and O-O";
name = "Legal Moves - Black King (O-O)";
yield return new TestCaseData(board, new[] { kf8, castleShort }, blackKingIndex)
.SetName(name)
.SetDescription(desc);
board = FenReader.Translate("r3kb1r/pppqpppp/3pb3/3N4/2P1P3/6P1/PPQBPP1P/R3KB1R b KQkq - 0 11");
var kd8 = MoveHelpers.GenerateMove("e8".ToBoardIndex(), "d8".ToBoardIndex());
castleLong = MoveHelpers.BlackCastleQueenSide;
desc = "Black should have Kd8 and O-O-O";
name = "Legal Moves - Black King (O-O-O)";
yield return new TestCaseData(board, new[] { kd8, castleLong }, blackKingIndex).SetName(name)
.SetDescription(desc);
board = FenReader.Translate("2kr1b1r/pppqpppp/3pb3/3N4/2P1P3/6P1/PPQBPP1P/R3KB1R w KQ - 1 12");
desc = "No moves should be returned if source square is unoccupied";
name = "Legal Moves - [null]";
yield return new TestCaseData(board, Array.Empty<Move>(), (ushort)34)
.SetDescription(desc)
.SetName(name);
board = FenReader.Translate("rnbqkbnr/ppp2ppp/8/2Ppp3/8/8/PP1PPPPP/RNBQKBNR w KQkq d6 0 3");
desc = "En Passant available on d6";
name = "Legal Moves - White En Passant";
var normalMove = MoveHelpers.GenerateMove("c5".ToBoardIndex(), "c6".ToBoardIndex());
var epMove =
MoveHelpers.GenerateMove("c5".ToBoardIndex(), "d6".ToBoardIndex(), MoveType.EnPassant);
yield return new TestCaseData(board, new[] { epMove, normalMove }, "c5".ToBoardIndex())
.SetDescription(desc)
.SetName(name);
}
}
} | 56.26 | 118 | 0.600427 | [
"MIT"
] | Hyper-Dragon/ChessLib | src/ChessLib.CoreTests/MagicBitboard/MagicBitboardTestData.cs | 8,441 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ProfitManager.Models;
namespace ProfitManager.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 23.9 | 112 | 0.641562 | [
"MIT"
] | VisualAcademy/EntityFrameworkCore | ProfitManager/ProfitManager/Controllers/HomeController.cs | 719 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RJavaIOException.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RJavaIOException.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 37 | 84 | 0.759073 | [
"MIT"
] | jonathanpeppers/RJavaIOException | RJavaIOException.Android/Properties/AssemblyInfo.cs | 1,298 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.AnalysisServices.Dataplane
{
[Serializable]
public class AsAzureEnvironment
{
public AsAzureEnvironment(string Name)
{
this.Name = Name;
this.Endpoints = new Hashtable();
}
public string Name { get; set; }
public Hashtable Endpoints { get; set; }
public enum AsRolloutEndpoints
{
AdAuthorityBaseUrl,
RestartEndpointFormat,
LogfileEndpointFormat
}
}
}
| 33.380952 | 87 | 0.581312 | [
"MIT"
] | yugangw-msft/azure-powershell | src/ResourceManager/AnalysisServices/Commands.AnalysisServices.Dataplane/Models/AsAzureEnvironment.cs | 1,363 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Ec2.Outputs
{
[OutputType]
public sealed class GetCoipPoolsFilterResult
{
/// <summary>
/// The name of the field to filter by, as defined by
/// [the underlying AWS API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeCoipPools.html).
/// </summary>
public readonly string Name;
/// <summary>
/// Set of values that are accepted for the given field.
/// A COIP Pool will be selected if any one of the given values matches.
/// </summary>
public readonly ImmutableArray<string> Values;
[OutputConstructor]
private GetCoipPoolsFilterResult(
string name,
ImmutableArray<string> values)
{
Name = name;
Values = values;
}
}
}
| 30.421053 | 120 | 0.635813 | [
"ECL-2.0",
"Apache-2.0"
] | JakeGinnivan/pulumi-aws | sdk/dotnet/Ec2/Outputs/GetCoipPoolsFilterResult.cs | 1,156 | C# |
namespace Sudoku.Solving.Manual.Searchers.Intersections;
/// <summary>
/// Defines a step searcher that searches for almost locked candidates steps.
/// </summary>
public interface IAlmostLockedCandidatesStepSearcher : IIntersectionStepSearcher
{
/// <summary>
/// Indicates whether the user checks the almost locked quadruple.
/// </summary>
bool CheckAlmostLockedQuadruple { get; set; }
/// <summary>
/// Indicates whether the searcher checks for values (givens and modifiables)
/// to form an almost locked candidates. If the value is <see langword="true"/>,
/// some possible Sue de Coqs steps will be replaced with Almost Locked Candidates ones.
/// </summary>
bool CheckForValues { get; set; }
} | 37.578947 | 89 | 0.743697 | [
"MIT"
] | SunnieShine/Sudoku | src/Sudoku.Solving/Solving/Manual/Searchers/Intersections/IAlmostLockedCandidatesStepSearcher.cs | 716 | C# |
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Conduit.Domain;
using Conduit.Features.Profiles;
using Conduit.Infrastructure;
using Conduit.Infrastructure.Errors;
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Conduit.Features.Followers
{
public class Add
{
public class Command : IRequest<ProfileEnvelope>
{
public Command(string username)
{
Username = username;
}
public string Username { get; }
}
public class CommandValidator : AbstractValidator<Command>
{
public CommandValidator()
{
RuleFor(x => x.Username).NotNull().NotEmpty();
}
}
public class QueryHandler : IRequestHandler<Command, ProfileEnvelope>
{
private readonly ConduitContext _context;
private readonly ICurrentUserAccessor _currentUserAccessor;
private readonly IProfileReader _profileReader;
public QueryHandler(ConduitContext context, ICurrentUserAccessor currentUserAccessor, IProfileReader profileReader)
{
_context = context;
_currentUserAccessor = currentUserAccessor;
_profileReader = profileReader;
}
public async Task<ProfileEnvelope> Handle(Command message, CancellationToken cancellationToken)
{
var target = await _context.Persons.FirstOrDefaultAsync(x => x.Username == message.Username, cancellationToken);
if (target == null)
{
throw new RestException(HttpStatusCode.NotFound, new { User = Constants.NOT_FOUND });
}
var observer = await _context.Persons.FirstOrDefaultAsync(x => x.Username == _currentUserAccessor.GetCurrentUsername(), cancellationToken);
var followedPeople = await _context.FollowedPeople.FirstOrDefaultAsync(x => x.ObserverId == observer.PersonId && x.TargetId == target.PersonId, cancellationToken);
if (followedPeople == null)
{
followedPeople = new FollowedPeople
{
Observer = observer,
ObserverId = observer.PersonId,
Target = target,
TargetId = target.PersonId
};
await _context.FollowedPeople.AddAsync(followedPeople, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
}
return await _profileReader.ReadProfile(message.Username);
}
}
}
} | 36.090909 | 179 | 0.596977 | [
"MIT"
] | godrose/aspnetcore-realworld-example-app | src/Conduit/Features/Followers/Add.cs | 2,779 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace QuestHelper.Server.Models
{
public class ImagesServerStatus
{
public ImagesServerStatus()
{
Images = new List<Imagefile>();
}
public ICollection<Imagefile> Images { get; set; }
public class Imagefile
{
public string Name;
public bool OnServer;
}
}
}
| 20.909091 | 58 | 0.606522 | [
"Apache-2.0"
] | gromozeka07b9/Gosh | QuestHelper/QuestHelper.Server/Models/ImagesServerStatus.cs | 462 | C# |
using System.Threading.Tasks;
namespace Xtender.Async
{
/// <summary>
/// The interface for implementing the async version of the extender is the visitor itself and contains the extensions that have registered for it. A proxy-extender is used to be passed to the extensions, this enables extensibility.
/// </summary>
/// <typeparam name="TState">Type of the visitor-state.</typeparam>
public interface IAsyncExtender<TState> : IAsyncExtender
{
/// <summary>
/// The preserved state that can be modified to store data requested for by multiple extensions or simply the result that is retieved when the extender done traversing the accepters.
/// </summary>
TState State { get; set; }
}
/// <summary>
/// The interface for implementing the async version of the extender is the visitor itself and contains the extensions that have registered for it. A proxy-extender is used to be passed to the extensions, this enables extensibility.
/// Notice that there is no state property. This extender is more lean.
/// </summary>
public interface IAsyncExtender
{
/// <summary>
/// The visit method, here called Extend, to traverse and extend accepting object with some additional functionality.
/// </summary>
/// <typeparam name="TAccepter">The type of the accepter that implements the IAsyncAccepter interface.</typeparam>
/// <param name="accepter">The accepter that implements the IAccepter interface.</param>
/// <returns>Task.</returns>
Task Extend<TAccepter>(TAccepter accepter) where TAccepter : class, IAsyncAccepter;
/// <summary>
/// The visit method, here called Extend, to traverse and extend accepting object with some additional functionality. This version is used with the accepter encapsulation functionality to extend the usage of the Extender to ordinary, non-IAccepter-implementing objects.
/// </summary>
/// <typeparam name="TValue">The type of the encapsulated object that does not implement an IAccepter interface within an accepter object.</typeparam>
/// <param name="accepter">AsyncAccepter object that encapsulates a type that does not implement an IAsyncAccepter interface.</param>
/// <returns>Task.</returns>
Task Extend<TValue>(AsyncAccepter<TValue> accepter);
}
} | 61.307692 | 277 | 0.708072 | [
"MIT"
] | emprax/Xtender | Xtender/Async/IAsyncExtender.cs | 2,393 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.ResourceManagement
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Vehicle_TypeObjectType : INotifyPropertyChanged
{
private Vehicle_TypeObjectIDType[] idField;
private string descriptorField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("ID", Order = 0)]
public Vehicle_TypeObjectIDType[] ID
{
get
{
return this.idField;
}
set
{
this.idField = value;
this.RaisePropertyChanged("ID");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Descriptor
{
get
{
return this.descriptorField;
}
set
{
this.descriptorField = value;
this.RaisePropertyChanged("Descriptor");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 21.934426 | 136 | 0.733184 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.ResourceManagement/Vehicle_TypeObjectType.cs | 1,338 | C# |
using Dapper.Contrib.Extensions;
using System;
namespace MyGeotabAPIAdapter.Database.Models
{
[Table("DriverChangeTypesT")]
public class DbDriverChangeTypeT : IDbEntity, IIdCacheableDbEntity
{
/// <inheritdoc/>
[Write(false)]
public string DatabaseTableName => "DriverChangeTypesT";
/// <inheritdoc/>
[Write(false)]
public Common.DatabaseWriteOperationType DatabaseWriteOperationType { get; set; }
/// <inheritdoc/>
[Write(false)]
public DateTime LastUpsertedUtc { get => RecordLastChangedUtc; }
[Write(false)]
public long id { get; set; }
[ExplicitKey]
public string GeotabId { get; set; }
[ChangeTracker]
public DateTime RecordLastChangedUtc { get; set; }
}
}
| 27.689655 | 89 | 0.633873 | [
"MIT"
] | costica-moldovanu/mygeotab-api-adapter | MyGeotabAPIAdapter.Database/Models/DbDriverChangeTypeT.cs | 805 | C# |
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Smarti.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Smarti.Data
{
public class DbInitializer : IDbInitializer
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public DbInitializer(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}
public void Initialize()
{
_context.Database.Migrate();
if (_userManager.Users.Any()) return;
string user = "tom@smarti.com";
string password = "Smarti1243!";
_userManager.CreateAsync(new ApplicationUser { UserName = user, Email = user, EmailConfirmed = true }, password).GetAwaiter().GetResult();
string userId =_userManager.FindByEmailAsync(user).GetAwaiter().GetResult().Id;
_context.Rooms.AddRange(
new Room { UserId = userId, Name = "Sypialnia", Sockets = new List<Socket> {
new Socket { DeviceId = "12345671234511", Name = "Lampka nocna", SocketDatas = new List<SocketData> {
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 19, 18, 0), Value = 14.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 19, 19, 0), Value = 13.8F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 19, 20, 0), Value = 14.1F },
new SocketData { TimeStamp = new DateTime(2018, 01, 19, 20, 34, 0), Value = 13.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 19, 20, 35, 0), Value = 15.8F },
new SocketData { TimeStamp = new DateTime(2018, 01, 19, 20, 36, 0), Value = 13.1F }
} }
} },
new Room { UserId = userId, Name = "Salon", Sockets = new List<Socket> {
new Socket { DeviceId = "12345671234512", Name = "Konsola", SocketDatas = new List<SocketData> {
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 21, 00, 0), Value = 46.8F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 21, 01, 0), Value = 50.2F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 21, 02, 0), Value = 49.5F },
new SocketData { TimeStamp = new DateTime(2018, 01, 20, 7, 28, 0), Value = 48.8F },
new SocketData { TimeStamp = new DateTime(2018, 01, 20, 7, 29, 0), Value = 51.2F },
new SocketData { TimeStamp = new DateTime(2018, 01, 20, 7, 30, 0), Value = 47.5F }
} },
new Socket { DeviceId = "12345671234513", Name = "Komoda", SocketDatas = new List<SocketData> {
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 16, 23, 0), Value = 19.7F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 16, 24, 0), Value = 19.8F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 16, 25, 0), Value = 19.6F },
new SocketData { TimeStamp = new DateTime(2018, 01, 17, 16, 30, 0), Value = 20.7F },
new SocketData { TimeStamp = new DateTime(2018, 01, 17, 16, 31, 0), Value = 21.8F },
new SocketData { TimeStamp = new DateTime(2018, 01, 17, 16, 32, 0), Value = 22.6F }
} },
new Socket { DeviceId = "12345671234514", Name = "Lampka", SocketDatas = new List<SocketData> {
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 16, 23, 0), Value = 40.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 16, 24, 0), Value = 40.1F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 16, 25, 0), Value = 40.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 19, 18, 0), Value = 40.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 19, 19, 0), Value = 40.1F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 19, 20, 0), Value = 40.0F }
} }
}
},
new Room { UserId = userId, Name = "Kuchnia", Sockets = new List<Socket> {
new Socket { DeviceId = "12345671234515", Name = "Barek", SocketDatas = new List<SocketData> {
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 14, 57, 0), Value = 31.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 14, 58, 0), Value = 32.2F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 14, 59, 0), Value = 30.7F },
new SocketData { TimeStamp = new DateTime(2018, 01, 16, 14, 46, 0), Value = 33.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 16, 14, 47, 0), Value = 31.2F },
new SocketData { TimeStamp = new DateTime(2018, 01, 16, 14, 48, 0), Value = 29.7F }
} },
new Socket { DeviceId = "12345671234516", Name = "Ledy", SocketDatas = new List<SocketData> {
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 14, 18, 0), Value = 43.3F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 14, 19, 0), Value = 46.7F },
new SocketData { TimeStamp = new DateTime(2018, 01, 21, 14, 20, 0), Value = 45.0F },
new SocketData { TimeStamp = new DateTime(2018, 01, 14, 14, 50, 0), Value = 45.3F },
new SocketData { TimeStamp = new DateTime(2018, 01, 14, 14, 51, 0), Value = 45.7F },
new SocketData { TimeStamp = new DateTime(2018, 01, 14, 14, 52, 0), Value = 45.0F }
} }
}
} );
_context.SaveChanges();
}
}
}
| 67.70297 | 150 | 0.499561 | [
"MIT"
] | Planche95/Smarti | Smarti/Smarti/Data/DbInitializer.cs | 6,840 | C# |
/*
Copyright (c) 2014, Kevin Pope
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.ImageProcessing;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.VertexSource;
using MatterHackers.Localizations;
namespace MatterHackers.MatterControl
{
public class ImageButtonFactory
{
public bool InvertImageColor { get; set; } = true;
public static CheckBox CreateToggleSwitch(bool initialState)
{
string on = "On";
string off = "Off";
if (StaticData.Instance != null)
{
on = on.Localize();
off = off.Localize();
}
ToggleSwitchView toggleView = new ToggleSwitchView(on, off,
60 * GuiWidget.DeviceScale, 24 * GuiWidget.DeviceScale,
ActiveTheme.Instance.PrimaryBackgroundColor,
new RGBA_Bytes(220, 220, 220),
ActiveTheme.Instance.PrimaryAccentColor,
ActiveTheme.Instance.PrimaryTextColor);
CheckBox toggleBox = new CheckBox(toggleView);
toggleBox.Checked = initialState;
return toggleBox;
}
public Button Generate(string normalImageName, string hoverImageName, string pressedImageName = null, string disabledImageName = null)
{
if (hoverImageName == null)
{
hoverImageName = normalImageName;
}
if (pressedImageName == null)
{
pressedImageName = hoverImageName;
}
if (disabledImageName == null)
{
disabledImageName = normalImageName;
}
ImageBuffer normalImage = StaticData.Instance.LoadIcon(normalImageName);
ImageBuffer pressedImage = StaticData.Instance.LoadIcon(pressedImageName);
ImageBuffer hoverImage = StaticData.Instance.LoadIcon(hoverImageName);
ImageBuffer disabledImage = StaticData.Instance.LoadIcon(disabledImageName);
return Generate(normalImage, pressedImage, hoverImage, disabledImage);
}
public Button Generate(ImageBuffer normalImage, ImageBuffer hoverImage, ImageBuffer pressedImage = null, ImageBuffer disabledImage = null)
{
if(hoverImage == null)
{
hoverImage = normalImage;
}
if (pressedImage == null)
{
pressedImage = hoverImage;
}
if (disabledImage == null)
{
disabledImage = normalImage;
}
if (!ActiveTheme.Instance.IsDarkTheme && InvertImageColor)
{
normalImage.InvertLightness();
pressedImage.InvertLightness();
hoverImage.InvertLightness();
disabledImage.InvertLightness();
}
ButtonViewStates buttonViewWidget = new ButtonViewStates(
new ImageWidget(normalImage),
new ImageWidget(hoverImage),
new ImageWidget(pressedImage),
new ImageWidget(disabledImage)
);
//Create button based on view container widget
Button imageButton = new Button(0, 0, buttonViewWidget);
imageButton.Margin = new BorderDouble(0);
imageButton.Padding = new BorderDouble(0);
return imageButton;
}
}
} | 33.53125 | 140 | 0.76165 | [
"BSD-2-Clause"
] | Banbury/MatterControl | ControlElements/ImageButtonFactory.cs | 4,294 | C# |
using UnityEngine;
namespace Entities.Behaviours {
/// <inheritdoc cref="IBehaviour" />
public abstract class Behaviour
: ScriptableObject,
IBehaviour {
/// <inheritdoc />
public abstract BehaviourType Type { get; protected set; }
// TODO: find a better way how to inject
// behaviour specific dependencies
/// <inheritdoc />
public abstract void Do (
IEntity target);
}
} | 22.380952 | 66 | 0.591489 | [
"MIT"
] | andrej-szontagh/rara-unity-challenge | Assets/Scripts/Entities/Behaviours/Behaviour.cs | 470 | C# |
namespace LibSignal.Protocol.Net
{
using System;
public class NoSessionException : Exception
{
public NoSessionException(string s) : base(s) {}
public NoSessionException(Exception nested) : base(nested.Message, nested) {}
}
} | 21.666667 | 85 | 0.676923 | [
"MIT"
] | SeppPenner/LibSignal.Protocol.Net | src/LibSignal.Protocol.Net/NoSessionException.cs | 260 | C# |
// This file is auto generated, do not edit.
using System;
#pragma warning disable CA1069 // Enums values should not be duplicated
namespace Gwi.OpenGL
{
public enum ColorTableTarget : uint
{
ColorTable = GLConstants.GL_COLOR_TABLE,
PostConvolutionColorTable = GLConstants.GL_POST_CONVOLUTION_COLOR_TABLE,
PostColorMatrixColorTable = GLConstants.GL_POST_COLOR_MATRIX_COLOR_TABLE,
ProxyColorTable = GLConstants.GL_PROXY_COLOR_TABLE,
ProxyPostConvolutionColorTable = GLConstants.GL_PROXY_POST_CONVOLUTION_COLOR_TABLE,
ProxyPostColorMatrixColorTable = GLConstants.GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE
}
}
#pragma warning restore CA1069 // Enums values should not be duplicated
| 40.944444 | 91 | 0.786974 | [
"MIT"
] | odalet/Gwi | src/Gwi.OpenGL/Gwi.OpenGL/generated/enums/ColorTableTarget.cs | 737 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace BuildIt.CognitiveServices
{
using System.Threading.Tasks;
/// <summary>
/// Extension methods for VideoAPI.
/// </summary>
public static partial class VideoAPIExtensions
{
/// <summary>
/// <p>Smooths and stabilizes a video. <br/>&bull; The
/// supported input video formats include MP4, MOV, and WMV. Video file size
/// should be no larger than 100MB. <br/>&bull; Stabilization is
/// optimized for small camera motions, with or without rolling shutter
/// effects (e.g. holding a static camera, and walking with a slow speed).
/// <br/>&bull; Both width and height of the input video must be
/// even numbers. <br/>&bull; The resolution of the input video
/// should be less than or equal to 2160P (4K, 3840 X 2160).
/// <br/>&bull; Output files are deleted after 24 hours.</p>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
public static void Stabilization(this IVideoAPI operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVideoAPI)s).StabilizationAsync(subscriptionKey, ocpApimSubscriptionKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// <p>Smooths and stabilizes a video. <br/>&bull; The
/// supported input video formats include MP4, MOV, and WMV. Video file size
/// should be no larger than 100MB. <br/>&bull; Stabilization is
/// optimized for small camera motions, with or without rolling shutter
/// effects (e.g. holding a static camera, and walking with a slow speed).
/// <br/>&bull; Both width and height of the input video must be
/// even numbers. <br/>&bull; The resolution of the input video
/// should be less than or equal to 2160P (4K, 3840 X 2160).
/// <br/>&bull; Output files are deleted after 24 hours.</p>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task StabilizationAsync(this IVideoAPI operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.StabilizationWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get operation result. If succeeded, this interface returns a JSON that
/// includes time stamps and operation status. Below is an example:
///
/// Example JSON:
/// <table class="element table">
/// <thead>
/// </thead>
/// <tbody>
/// <tr>
/// {<br/>
/// "status": "Running",<br/>
/// "createdDateTime": "2015-09-30T01:28:23.4493273Z",<br/>
/// "lastActionDateTime": "2015-09-30T01:32:23.0895791Z",<br/>
/// }<br/>
/// </tr>
/// </tbody>
/// </table>
/// <br/>
/// <p>
/// Possible values of "status" field are:<br/>
/// <b>Not Started</b> - video content is received/uploaded but
/// the process has not started.<br/>
/// <b>Uploading</b> - the video content is being uploaded by the
/// URL client side provides.<br/>
/// <b>Running</b> - the process is running.<br/>
/// <b>Failed</b> - the process is failed. Detailed information
/// will be provided in "message" field.<br/>
/// <b>Succeeded</b> - the process succeeded. In this case,
/// depending on specific operation client side created, the result can be
/// retrieved in following two ways:<br/>
/// </p>
/// <table class="element table">
/// <thead>
/// <tr><th>Video Operation</th><th>How to
/// Retrieve Result</th></tr>
/// </thead>
/// <tbody>
/// <tr><td>Stabilization</td><td>The
/// result (as a video file) can be retrieved from the URL specified in
/// <b>resourceLocation</b> field.</td></tr>
/// <tr><td>Face Detection and
/// Tracking<br/>Motion Detection
/// </td><td>The result (as a JSON in string) is available in
/// <b>processingResult</b> field.</td></tr>
/// </tbody>
/// </table>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='oid'>
/// OperationId
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
public static void GetOperationResult(this IVideoAPI operations, string oid, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVideoAPI)s).GetOperationResultAsync(oid, subscriptionKey, ocpApimSubscriptionKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get operation result. If succeeded, this interface returns a JSON that
/// includes time stamps and operation status. Below is an example:
///
/// Example JSON:
/// <table class="element table">
/// <thead>
/// </thead>
/// <tbody>
/// <tr>
/// {<br/>
/// "status": "Running",<br/>
/// "createdDateTime": "2015-09-30T01:28:23.4493273Z",<br/>
/// "lastActionDateTime": "2015-09-30T01:32:23.0895791Z",<br/>
/// }<br/>
/// </tr>
/// </tbody>
/// </table>
/// <br/>
/// <p>
/// Possible values of "status" field are:<br/>
/// <b>Not Started</b> - video content is received/uploaded but
/// the process has not started.<br/>
/// <b>Uploading</b> - the video content is being uploaded by the
/// URL client side provides.<br/>
/// <b>Running</b> - the process is running.<br/>
/// <b>Failed</b> - the process is failed. Detailed information
/// will be provided in "message" field.<br/>
/// <b>Succeeded</b> - the process succeeded. In this case,
/// depending on specific operation client side created, the result can be
/// retrieved in following two ways:<br/>
/// </p>
/// <table class="element table">
/// <thead>
/// <tr><th>Video Operation</th><th>How to
/// Retrieve Result</th></tr>
/// </thead>
/// <tbody>
/// <tr><td>Stabilization</td><td>The
/// result (as a video file) can be retrieved from the URL specified in
/// <b>resourceLocation</b> field.</td></tr>
/// <tr><td>Face Detection and
/// Tracking<br/>Motion Detection
/// </td><td>The result (as a JSON in string) is available in
/// <b>processingResult</b> field.</td></tr>
/// </tbody>
/// </table>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='oid'>
/// OperationId
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetOperationResultAsync(this IVideoAPI operations, string oid, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetOperationResultWithHttpMessagesAsync(oid, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// <p>Detects and tracks human faces in a video and returns face
/// locations. <br/>&bull; The supported input video formats
/// include MP4, MOV, and WMV. Video file size should be no larger than
/// 100MB. <br/>&bull; The detectable face size range is 24x24 to
/// 2048x2048 pixels. The faces out of this range will not be detected.
/// <br/>&bull; For each video, the maximum number of faces
/// returned is 64. <br/>&bull; Some faces may not be detected due
/// to technical challenges; e.g. very large face angles (head-pose), and
/// large occlusion. Frontal and near-frontal faces have the best results.
/// <br/>&bull; Output files are deleted after 24 hours.
/// </p>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
public static void FaceDetectionandTracking(this IVideoAPI operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVideoAPI)s).FaceDetectionandTrackingAsync(subscriptionKey, ocpApimSubscriptionKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// <p>Detects and tracks human faces in a video and returns face
/// locations. <br/>&bull; The supported input video formats
/// include MP4, MOV, and WMV. Video file size should be no larger than
/// 100MB. <br/>&bull; The detectable face size range is 24x24 to
/// 2048x2048 pixels. The faces out of this range will not be detected.
/// <br/>&bull; For each video, the maximum number of faces
/// returned is 64. <br/>&bull; Some faces may not be detected due
/// to technical challenges; e.g. very large face angles (head-pose), and
/// large occlusion. Frontal and near-frontal faces have the best results.
/// <br/>&bull; Output files are deleted after 24 hours.
/// </p>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task FaceDetectionandTrackingAsync(this IVideoAPI operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.FaceDetectionandTrackingWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// <p>Detects motion in a video, and returns the frame and duration of
/// the motion that was captured. <br/>&bull; The supported input
/// video formats include MP4, MOV, and WMV. Video file size should be no
/// larger than 100MB. <br/>&bull; User can input detection zones
/// to set up as areas to detect motion. <br/>&bull; User can
/// specify motion sensitivity: high, medium, and low. Higher sensitivity
/// means more motions will be detected at a cost that more false alarms will
/// be reported.<br/>&bull; Motion Detection is optimized for
/// stationary background videos. <br/>&bull; User can specify
/// whether light change events should be detected. A light change refers to
/// a change in the frame that was caused by a light turning off and on. Some
/// developers do not want to detect this, as they consider it a false alarm.
/// Other developers want to make sure they capture any change, light changes
/// included.<br/>&bull; User can specify whether successive
/// motions should be merged together by passing in a parameter
/// (mergeTimeThreshold) For example, if a motion happens from 1 to 4 seconds
/// and the next motion happens from 5 to 10 seconds, some developers will
/// want to count that as one instance of motion.<br/>&bull; User
/// can specify which frames to be detected by passing in a parameter
/// (frameSamplingValue).<br/>&bull; Some motion may not be
/// detected due to technical challenges; e.g. semi-transparent objects, and
/// some small objects. <br/>&bull; Output files are deleted after
/// 24 hours.
/// </p>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sensitivityLevel'>
/// Specify the detection sensitivity level: “low”, “medium”, “high”. Higher
/// sensitivity means more motions will be detected at a cost that more false
/// alarms will be reported. The default value is “medium”.
/// </param>
/// <param name='frameSamplingValue'>
/// User may skip frames by setting this parameter. It can be used as a
/// tradeoff between performance and cost, skipping frames may reduce
/// processing time but result in worse detection performance. The default
/// value is 1, meaning detecting motion for every frame. If set to 2, then
/// the algorithm will detect one frame for every two frames. The upper bound
/// is 20.
/// </param>
/// <param name='detectionZones'>
/// User can setup detection zones by passing in a string like
/// “detectionZones=0,0;0.5,0;1,0;1,0.5;1,1;0.5,1;0,1;0,0.5
/// |0.3,0.3;0.55,0.3;0.8,0.3; 0.8,0.55;0.8,0.8;0.55,0.8;0.3,0.8;0.3,0.55;|
/// 0,0;1,0;1,1;0,1”, each detection zone is separated by a “|” and each
/// point is defined by a “x,y” pair and separated by a “;”. At most 8
/// detection zones are supported and each detection zone should be defined
/// by at least 3 points and no more than 16 points. The default setting is
/// “detectionZones=0,0;0.5,0;1,0;1,0.5;1,1;0.5,1;0,1;0,0.5”, i.e. the whole
/// frame defined by an 8-point polygon.
/// </param>
/// <param name='detectLightChange'>
/// Specify whether light change events should be detected. The default value
/// is false.
/// </param>
/// <param name='mergeTimeThreshold'>
/// Specify the threshold on whether successive motions should be merged
/// together, if the interval between successive motions is <=
/// mergeTimeThreshold, they will be merged. The default value is 0.0 and
/// upper bound is 10.0.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
public static void MotionDetection(this IVideoAPI operations, string sensitivityLevel = default(string), double? frameSamplingValue = default(double?), string detectionZones = default(string), bool? detectLightChange = default(bool?), double? mergeTimeThreshold = default(double?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVideoAPI)s).MotionDetectionAsync(sensitivityLevel, frameSamplingValue, detectionZones, detectLightChange, mergeTimeThreshold, subscriptionKey, ocpApimSubscriptionKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// <p>Detects motion in a video, and returns the frame and duration of
/// the motion that was captured. <br/>&bull; The supported input
/// video formats include MP4, MOV, and WMV. Video file size should be no
/// larger than 100MB. <br/>&bull; User can input detection zones
/// to set up as areas to detect motion. <br/>&bull; User can
/// specify motion sensitivity: high, medium, and low. Higher sensitivity
/// means more motions will be detected at a cost that more false alarms will
/// be reported.<br/>&bull; Motion Detection is optimized for
/// stationary background videos. <br/>&bull; User can specify
/// whether light change events should be detected. A light change refers to
/// a change in the frame that was caused by a light turning off and on. Some
/// developers do not want to detect this, as they consider it a false alarm.
/// Other developers want to make sure they capture any change, light changes
/// included.<br/>&bull; User can specify whether successive
/// motions should be merged together by passing in a parameter
/// (mergeTimeThreshold) For example, if a motion happens from 1 to 4 seconds
/// and the next motion happens from 5 to 10 seconds, some developers will
/// want to count that as one instance of motion.<br/>&bull; User
/// can specify which frames to be detected by passing in a parameter
/// (frameSamplingValue).<br/>&bull; Some motion may not be
/// detected due to technical challenges; e.g. semi-transparent objects, and
/// some small objects. <br/>&bull; Output files are deleted after
/// 24 hours.
/// </p>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sensitivityLevel'>
/// Specify the detection sensitivity level: “low”, “medium”, “high”. Higher
/// sensitivity means more motions will be detected at a cost that more false
/// alarms will be reported. The default value is “medium”.
/// </param>
/// <param name='frameSamplingValue'>
/// User may skip frames by setting this parameter. It can be used as a
/// tradeoff between performance and cost, skipping frames may reduce
/// processing time but result in worse detection performance. The default
/// value is 1, meaning detecting motion for every frame. If set to 2, then
/// the algorithm will detect one frame for every two frames. The upper bound
/// is 20.
/// </param>
/// <param name='detectionZones'>
/// User can setup detection zones by passing in a string like
/// “detectionZones=0,0;0.5,0;1,0;1,0.5;1,1;0.5,1;0,1;0,0.5
/// |0.3,0.3;0.55,0.3;0.8,0.3; 0.8,0.55;0.8,0.8;0.55,0.8;0.3,0.8;0.3,0.55;|
/// 0,0;1,0;1,1;0,1”, each detection zone is separated by a “|” and each
/// point is defined by a “x,y” pair and separated by a “;”. At most 8
/// detection zones are supported and each detection zone should be defined
/// by at least 3 points and no more than 16 points. The default setting is
/// “detectionZones=0,0;0.5,0;1,0;1,0.5;1,1;0.5,1;0,1;0,0.5”, i.e. the whole
/// frame defined by an 8-point polygon.
/// </param>
/// <param name='detectLightChange'>
/// Specify whether light change events should be detected. The default value
/// is false.
/// </param>
/// <param name='mergeTimeThreshold'>
/// Specify the threshold on whether successive motions should be merged
/// together, if the interval between successive motions is <=
/// mergeTimeThreshold, they will be merged. The default value is 0.0 and
/// upper bound is 10.0.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task MotionDetectionAsync(this IVideoAPI operations, string sensitivityLevel = default(string), double? frameSamplingValue = default(double?), string detectionZones = default(string), bool? detectLightChange = default(bool?), double? mergeTimeThreshold = default(double?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.MotionDetectionWithHttpMessagesAsync(sensitivityLevel, frameSamplingValue, detectionZones, detectLightChange, mergeTimeThreshold, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// This interface is used for getting result video content. Currently only
/// Stabilization outputs video content as result. The URL to this interface
/// should be retrieved from <b>resourceLocation</b> field of
/// JSON returned from Get Operation Result interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='oid'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
public static void GetResultVideo(this IVideoAPI operations, string oid, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVideoAPI)s).GetResultVideoAsync(oid, subscriptionKey, ocpApimSubscriptionKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// This interface is used for getting result video content. Currently only
/// Stabilization outputs video content as result. The URL to this interface
/// should be retrieved from <b>resourceLocation</b> field of
/// JSON returned from Get Operation Result interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='oid'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GetResultVideoAsync(this IVideoAPI operations, string oid, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GetResultVideoWithHttpMessagesAsync(oid, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Generates a motion thumbnail from a video. The Video Thumbnail API
/// provides an automatic summary for videos to let people see a preview or
/// snapshot quickly. Selection of scenes from a video create a preview in
/// form of a short video. <br/>
/// &bull; The supported input video formats include MP4, MOV, and WMV.
/// Video file size should be no larger than 100MB. <br/>
/// &bull; The number of scenes displayed in the thumbnail is either
/// chosen by the user or defaults to the optimal duration supported by the
/// Video API’s algorithm.<br/>
/// &bull; A scene is a collection of indexed frames. Scenes are mapped
/// according to sequence in video. <br/>
/// &bull; Fade in/fade out effects are included in the thumbnail by
/// default, but can be turned off by the user. <br/>
/// &bull; Audio is included by default, but can be turned off by the
/// user. Pauses in audio are detected to divide video into coherent scenes
/// and avoid breaking sentences of speech.<br/>
/// &bull; Output files are deleted after 24 hours.<br/>
/// <br/>
/// * Optimal Duration of Video Thumbnail Supported by Video API shown in
/// table below.
///
/// <table class="element table">
/// <thead>
/// </thead>
/// <tbody>
/// <tr>
/// <td>Motion Thumbnail</td>
/// </tr>
/// <tr>
/// <td>Video duration (d)</td>
/// <td>d < 3min</td>
/// <td>3min < d < 15min</td>
/// <td>15min < d < 30min</td>
/// <td>30min < d</td>
/// </tr>
/// <tr>
/// <td>Thumbnail duration</td>
/// <td>15sec (2-3 scenes)</td>
/// <td>30sec (3-5 scenes)</td>
/// <td>60sec (5-10 scenes)</td>
/// <td>90sec (10-15 scenes)</td>
/// </tr>
/// <tbody>
/// </table>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='maxMotionThumbnailDurationInSecs'>
/// Specifies maximum duration of output video (in seconds). The default value
/// is 0, which indicates the duration will be automatically decided by the
/// algorithm.
/// </param>
/// <param name='outputAudio'>
/// Indicates whether output video should include audio track. The default
/// value is true.
/// </param>
/// <param name='fadeInFadeOut'>
/// Indicates whether output video should have fade in/out effect during scene
/// changes. The default value is true.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
public static void Thumbnail(this IVideoAPI operations, double? maxMotionThumbnailDurationInSecs = default(double?), bool? outputAudio = default(bool?), bool? fadeInFadeOut = default(bool?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVideoAPI)s).ThumbnailAsync(maxMotionThumbnailDurationInSecs, outputAudio, fadeInFadeOut, subscriptionKey, ocpApimSubscriptionKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Generates a motion thumbnail from a video. The Video Thumbnail API
/// provides an automatic summary for videos to let people see a preview or
/// snapshot quickly. Selection of scenes from a video create a preview in
/// form of a short video. <br/>
/// &bull; The supported input video formats include MP4, MOV, and WMV.
/// Video file size should be no larger than 100MB. <br/>
/// &bull; The number of scenes displayed in the thumbnail is either
/// chosen by the user or defaults to the optimal duration supported by the
/// Video API’s algorithm.<br/>
/// &bull; A scene is a collection of indexed frames. Scenes are mapped
/// according to sequence in video. <br/>
/// &bull; Fade in/fade out effects are included in the thumbnail by
/// default, but can be turned off by the user. <br/>
/// &bull; Audio is included by default, but can be turned off by the
/// user. Pauses in audio are detected to divide video into coherent scenes
/// and avoid breaking sentences of speech.<br/>
/// &bull; Output files are deleted after 24 hours.<br/>
/// <br/>
/// * Optimal Duration of Video Thumbnail Supported by Video API shown in
/// table below.
///
/// <table class="element table">
/// <thead>
/// </thead>
/// <tbody>
/// <tr>
/// <td>Motion Thumbnail</td>
/// </tr>
/// <tr>
/// <td>Video duration (d)</td>
/// <td>d < 3min</td>
/// <td>3min < d < 15min</td>
/// <td>15min < d < 30min</td>
/// <td>30min < d</td>
/// </tr>
/// <tr>
/// <td>Thumbnail duration</td>
/// <td>15sec (2-3 scenes)</td>
/// <td>30sec (3-5 scenes)</td>
/// <td>60sec (5-10 scenes)</td>
/// <td>90sec (10-15 scenes)</td>
/// </tr>
/// <tbody>
/// </table>
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='maxMotionThumbnailDurationInSecs'>
/// Specifies maximum duration of output video (in seconds). The default value
/// is 0, which indicates the duration will be automatically decided by the
/// algorithm.
/// </param>
/// <param name='outputAudio'>
/// Indicates whether output video should include audio track. The default
/// value is true.
/// </param>
/// <param name='fadeInFadeOut'>
/// Indicates whether output video should have fade in/out effect during scene
/// changes. The default value is true.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task ThumbnailAsync(this IVideoAPI operations, double? maxMotionThumbnailDurationInSecs = default(double?), bool? outputAudio = default(bool?), bool? fadeInFadeOut = default(bool?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.ThumbnailWithHttpMessagesAsync(maxMotionThumbnailDurationInSecs, outputAudio, fadeInFadeOut, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false);
}
}
}
| 61.168317 | 518 | 0.580366 | [
"MIT"
] | builttoroam/BuildIt | src/BuildIt.CognitiveServices/BuildIt.CognitiveServices/CognitiveServicesSwagger/VideoAPIExtensions.cs | 37,144 | C# |
namespace ExtractorSharp.View.SettingPane {
partial class LanguagePane {
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent() {
this.languageBox = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// comboBox1
//
this.languageBox.FormattingEnabled = true;
this.languageBox.Location = new System.Drawing.Point(26, 24);
this.languageBox.Name = "comboBox1";
this.languageBox.Size = new System.Drawing.Size(159, 20);
this.languageBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.languageBox.TabIndex = 0;
//
// LanguagePane
//
this.Controls.Add(this.languageBox);
this.Parent = "Language";
this.Size = new System.Drawing.Size(241, 151);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox languageBox;
}
}
| 31.423077 | 93 | 0.542228 | [
"MIT"
] | Kritsu/ExtractorSharp | ExtractorSharp/View/SettingPane/LanguagePane.Designer.cs | 1,790 | C# |
namespace UglyToad.PdfPig.Images.Png
{
/// <summary>
/// The method used to compress the image data.
/// </summary>
internal enum CompressionMethod : byte
{
/// <summary>
/// Deflate/inflate compression with a sliding window of at most 32768 bytes.
/// </summary>
DeflateWithSlidingWindow = 0
}
} | 27.153846 | 85 | 0.606232 | [
"Apache-2.0"
] | BobLd/PdfP | src/UglyToad.PdfPig/Images/Png/CompressionMethod.cs | 355 | C# |
using System;
namespace WeekDay
{
class WeekDay
{
static void Main(string[] args)
{
int dayNumber = int.Parse(Console.ReadLine());
switch (dayNumber)
{
case 1:Console.WriteLine("Monday"); break;
case 2:Console.WriteLine("Tuesday"); break;
case 3:Console.WriteLine("Wednesday"); break;
case 4:Console.WriteLine("Thursday"); break;
case 5:Console.WriteLine("Friday"); break;
case 6:Console.WriteLine("Saturday"); break;
case 7:Console.WriteLine("Sunday"); break;
default: Console.WriteLine("The week has only 7 days!"); break;
}
}
}
}
//Ден от седмицата
//Напишете програма, която чете цяло число, въведено от потребителя, и отпечатва ден от седмицата(на
//английски език), в граници[1...7] или отпечатва "Error" в случай, че въведеното число е невалидно. | 35.571429 | 110 | 0.571285 | [
"MIT"
] | FanyaKk/CSharpUniProjects | Projects/Conditional-Statements/WeekDay/WeekDay.cs | 1,160 | C# |
using System;
using System.Runtime.InteropServices;
namespace Xilium.CefGlue.Avalonia.Platform.MacOS
{
[StructLayout(LayoutKind.Sequential, Pack = 8)]
internal struct CGPoint
{
public double X;
public double Y;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct CGSize
{
public double Width;
public double Height;
}
internal struct CGRect
{
public CGPoint Origin;
public CGSize Size;
}
internal class NSView : IHandleHolder
{
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, CGRect arg);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr objc_getClass(string className);
[DllImport("/usr/lib/libobjc.dylib")]
private static extern void objc_release(IntPtr handle);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
private static extern IntPtr sel_registerName(string selectorName);
private static readonly IntPtr NsViewClass = objc_getClass("NSView");
private static readonly IntPtr InitSelector = sel_registerName("init");
private static readonly IntPtr AllocSelector = sel_registerName("alloc");
private static readonly IntPtr SetFrameSelector = sel_registerName("setFrame:");
public NSView()
{
var nsViewType = objc_msgSend(NsViewClass, AllocSelector);
Handle = objc_msgSend(nsViewType, InitSelector);
}
public NSView(double width, double height) : this()
{
SetFrame(new CGRect()
{
Size = new CGSize()
{
Width = width,
Height = height,
}
});
}
public IntPtr Handle { get; }
public void SetFrame(CGRect frame)
{
objc_msgSend(Handle, SetFrameSelector, frame);
}
public void Dispose()
{
objc_release(Handle);
}
}
}
| 28.180723 | 96 | 0.61864 | [
"MIT"
] | OutSystems/CefGlue | CefGlue.Avalonia/Platform/MacOS/NSView.cs | 2,341 | C# |
using ScottPlot.Drawing;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScottPlot.Plottable
{
public class ErrorBar : IPlottable, IHasLine, IHasMarker, IHasColor
{
public double[] Xs { get; set; }
public double[] Ys { get; set; }
public double[] XErrorsPositive { get; set; }
public double[] XErrorsNegative { get; set; }
public double[] YErrorsPositive { get; set; }
public double[] YErrorsNegative { get; set; }
public int CapSize { get; set; } = 3;
public bool IsVisible { get; set; } = true;
public int XAxisIndex { get; set; } = 0;
public int YAxisIndex { get; set; } = 0;
public double LineWidth { get; set; } = 1;
public Color Color { get; set; } = Color.Gray;
public Color LineColor { get => Color; set { Color = value; } }
public LineStyle LineStyle { get; set; } = LineStyle.Solid;
public MarkerShape MarkerShape { get; set; } = MarkerShape.filledCircle;
public float MarkerLineWidth { get; set; } = 1;
public float MarkerSize { get; set; } = 0;
public Color MarkerColor { get => Color; set { Color = value; } }
public ErrorBar(double[] xs, double[] ys, double[] xErrorsPositive, double[] xErrorsNegative, double[] yErrorsPositive, double[] yErrorsNegative)
{
Xs = xs;
Ys = ys;
XErrorsPositive = xErrorsPositive;
XErrorsNegative = xErrorsNegative;
YErrorsPositive = yErrorsPositive;
YErrorsNegative = yErrorsNegative;
}
public AxisLimits GetAxisLimits()
{
double xMin = double.PositiveInfinity;
double xMax = double.NegativeInfinity;
double yMin = double.PositiveInfinity;
double yMax = double.NegativeInfinity;
for (int i = 0; i < Xs.Length; i++)
{
xMin = Math.Min(xMin, Xs[i] - (XErrorsNegative?[i] ?? 0));
xMax = Math.Max(xMax, Xs[i] + (XErrorsPositive?[i] ?? 0));
yMin = Math.Min(yMin, Ys[i] - (YErrorsNegative?[i] ?? 0));
yMax = Math.Max(yMax, Ys[i] + (YErrorsPositive?[i] ?? 0));
}
return new AxisLimits(xMin, xMax, yMin, yMax);
}
public LegendItem[] GetLegendItems() => Array.Empty<LegendItem>();
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false)
{
using Graphics gfx = GDI.Graphics(bmp, dims, lowQuality, clipToDataArea: true);
using Pen pen = GDI.Pen(Color, LineWidth, LineStyle, true);
if (XErrorsPositive is not null && XErrorsNegative is not null)
{
DrawErrorBars(dims, gfx, pen, XErrorsPositive, XErrorsNegative, true);
}
if (YErrorsPositive is not null && YErrorsNegative is not null)
{
DrawErrorBars(dims, gfx, pen, YErrorsPositive, YErrorsNegative, false);
}
if (MarkerSize > 0 && MarkerShape != MarkerShape.none)
{
DrawMarkers(dims, gfx);
}
}
private void DrawErrorBars(PlotDimensions dims, Graphics gfx, Pen pen, double[] errorPositive, double[] errorNegative, bool onXAxis)
{
for (int i = 0; i < Xs.Length; i++)
{
// Pixel centre = dims.GetPixel(new Coordinate(Xs[i], Ys[i]));
if (onXAxis)
{
Pixel left = dims.GetPixel(new Coordinate(Xs[i] - errorNegative[i], Ys[i]));
Pixel right = dims.GetPixel(new Coordinate(Xs[i] + errorPositive[i], Ys[i]));
gfx.DrawLine(pen, left.X, left.Y, right.X, right.Y);
gfx.DrawLine(pen, left.X, left.Y - CapSize, left.X, left.Y + CapSize);
gfx.DrawLine(pen, right.X, right.Y - CapSize, right.X, right.Y + CapSize);
}
else
{
Pixel top = dims.GetPixel(new Coordinate(Xs[i], Ys[i] - errorNegative[i]));
Pixel bottom = dims.GetPixel(new Coordinate(Xs[i], Ys[i] + errorPositive[i]));
gfx.DrawLine(pen, top.X, top.Y, bottom.X, bottom.Y);
gfx.DrawLine(pen, top.X - CapSize, top.Y, top.X + CapSize, top.Y);
gfx.DrawLine(pen, bottom.X - CapSize, bottom.Y, bottom.X + CapSize, bottom.Y);
}
}
}
private void DrawMarkers(PlotDimensions dims, Graphics gfx)
{
PointF[] pixels = new PointF[Xs.Length];
for (int i = 0; i < Xs.Length; i++)
{
float xPixel = dims.GetPixelX(Xs[i]);
float yPixel = dims.GetPixelY(Ys[i]);
pixels[i] = new(xPixel, yPixel);
}
MarkerTools.DrawMarkers(gfx, pixels, MarkerShape, MarkerSize, Color, MarkerLineWidth);
}
public void ValidateData(bool deep = false)
{
Validate.AssertHasElements(nameof(Xs), Xs);
Validate.AssertHasElements(nameof(Ys), Ys);
Validate.AssertEqualLength($"{nameof(Xs)}, {nameof(Ys)}", Xs, Ys);
if (XErrorsPositive is not null || XErrorsNegative is not null)
{
Validate.AssertHasElements(nameof(XErrorsPositive), XErrorsPositive);
Validate.AssertHasElements(nameof(XErrorsNegative), XErrorsNegative);
Validate.AssertEqualLength($"{Xs} {nameof(XErrorsPositive)}, {nameof(XErrorsNegative)}", Xs, XErrorsPositive, XErrorsNegative);
}
if (YErrorsPositive is not null || YErrorsNegative is not null)
{
Validate.AssertHasElements(nameof(YErrorsPositive), YErrorsPositive);
Validate.AssertHasElements(nameof(YErrorsNegative), YErrorsNegative);
Validate.AssertEqualLength($"{Xs} {nameof(YErrorsPositive)}, {nameof(YErrorsNegative)}", Xs, YErrorsPositive, YErrorsNegative);
}
if (deep)
{
Validate.AssertAllReal(nameof(Xs), Xs);
Validate.AssertAllReal(nameof(Ys), Ys);
if (XErrorsPositive is not null && XErrorsNegative is not null)
{
Validate.AssertAllReal(nameof(XErrorsPositive), XErrorsPositive);
Validate.AssertAllReal(nameof(XErrorsNegative), XErrorsNegative);
}
if (YErrorsPositive is not null && YErrorsNegative is not null)
{
Validate.AssertAllReal(nameof(YErrorsPositive), YErrorsPositive);
Validate.AssertAllReal(nameof(YErrorsNegative), YErrorsNegative);
}
// TODO: Should we validate that errors are all positive?
}
}
}
}
| 42.472727 | 153 | 0.561216 | [
"MIT"
] | MareMare/ScottPlot | src/ScottPlot4/ScottPlot/Plottable/ErrorBar.cs | 7,010 | C# |
#nullable enable
using System;
using System.Threading.Tasks;
namespace Microsoft.Maui.ApplicationModel.DataTransfer
{
public interface IClipboard
{
bool HasText { get; }
Task SetTextAsync(string? text);
Task<string?> GetTextAsync();
event EventHandler<EventArgs> ClipboardContentChanged;
}
/// <include file="../../docs/Microsoft.Maui.Essentials/Clipboard.xml" path="Type[@FullName='Microsoft.Maui.Essentials.Clipboard']/Docs" />
public static class Clipboard
{
/// <include file="../../docs/Microsoft.Maui.Essentials/Clipboard.xml" path="//Member[@MemberName='SetTextAsync']/Docs" />
public static Task SetTextAsync(string? text)
=> Default.SetTextAsync(text ?? string.Empty);
/// <include file="../../docs/Microsoft.Maui.Essentials/Clipboard.xml" path="//Member[@MemberName='HasText']/Docs" />
public static bool HasText
=> Default.HasText;
/// <include file="../../docs/Microsoft.Maui.Essentials/Clipboard.xml" path="//Member[@MemberName='GetTextAsync']/Docs" />
public static Task<string?> GetTextAsync()
=> Default.GetTextAsync();
/// <include file="../../docs/Microsoft.Maui.Essentials/Clipboard.xml" path="//Member[@MemberName='ClipboardContentChanged']/Docs" />
public static event EventHandler<EventArgs> ClipboardContentChanged
{
add => Default.ClipboardContentChanged += value;
remove => Default.ClipboardContentChanged -= value;
}
static IClipboard? defaultImplementation;
public static IClipboard Default =>
defaultImplementation ??= new ClipboardImplementation();
internal static void SetDefault(IClipboard? implementation) =>
defaultImplementation = implementation;
}
partial class ClipboardImplementation : IClipboard
{
event EventHandler<EventArgs>? ClipboardContentChangedInternal;
public event EventHandler<EventArgs> ClipboardContentChanged
{
add
{
if (ClipboardContentChangedInternal == null)
StartClipboardListeners();
ClipboardContentChangedInternal += value;
}
remove
{
ClipboardContentChangedInternal -= value;
if (ClipboardContentChangedInternal == null)
StopClipboardListeners();
}
}
internal void OnClipboardContentChanged() =>
ClipboardContentChangedInternal?.Invoke(this, EventArgs.Empty);
}
}
| 30.958904 | 140 | 0.736726 | [
"MIT"
] | 10088/maui | src/Essentials/src/Clipboard/Clipboard.shared.cs | 2,260 | C# |
using System;
using UnityEngine.Events;
namespace AChildsCourage.RoomEditor
{
[Serializable]
public class MouseDownEvent : UnityEvent<MouseDownEventArgs> { }
} | 17.1 | 68 | 0.766082 | [
"MIT"
] | KingVanti/AChildsCourage | Assets/Scripts/RoomEditor/Events.cs | 173 | C# |
using OdevTakip.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace OdevTakip.Services
{
public interface IEtkinlikService
{
List<Etkinlik> Select(Etkinlik model);
Etkinlik Find(Etkinlik model);
bool Insert(Etkinlik model);
bool Update(Etkinlik model);
bool Delete(Etkinlik model);
}
public class EtkinlikService : IEtkinlikService
{
private readonly IGenericRepository _genericRepository;
public EtkinlikService(IGenericRepository genericRepository)
{
_genericRepository = genericRepository;
}
public List<Etkinlik> Select(Etkinlik model)
{
const string sql = @"SELECT id, sil, olusturmatarihi, olusturankisi, guncellemetarihi, guncelleyenkisi, baslik, aciklama, durumid, kategoriid, baslangictarihi, bitistarihi, atananid, projeid
FROM public.etkinlik where sil = @sil and olusturankisi=@olusturankisi and projeid = CASE @projeid WHEN 0 THEN projeid ELSE @projeid END;";
return _genericRepository.Select<Etkinlik>(sql, model);
}
public Etkinlik Find(Etkinlik model)
{
const string sql = @"SELECT id, sil, olusturmatarihi, olusturankisi, guncellemetarihi, guncelleyenkisi, baslik, aciklama, durumid, kategoriid, baslangictarihi, bitistarihi, atananid, projeid
FROM public.etkinlik where sil = @sil and olusturankisi=@olusturankisi and id=@id;";
return _genericRepository.First<Etkinlik>(sql, model);
}
public bool Insert(Etkinlik model)
{
const string sql = @"INSERT INTO public.etkinlik(
sil, olusturmatarihi, olusturankisi, guncellemetarihi, guncelleyenkisi, baslik, aciklama, durumid, kategoriid, baslangictarihi, bitistarihi, atananid, projeid)
VALUES (@sil, @olusturmatarihi, @olusturankisi, @guncellemetarihi, @guncelleyenkisi, @baslik, @aciklama, @durumid, @kategoriid, @baslangictarihi, @bitistarihi, @atananid, @projeid);";
return _genericRepository.Insert(sql, model);
}
public bool Update(Etkinlik model)
{
const string sql = @"UPDATE public.etkinlik
SET guncellemetarihi=@guncellemetarihi, guncelleyenkisi=@guncelleyenkisi, baslik=@baslik, aciklama=@aciklama, durumid=@durumid, kategoriid=@kategoriid, baslangictarihi=@baslangictarihi, bitistarihi=@bitistarihi, atananid=@atananid, projeid=@projeid
WHERE id=@id";
return _genericRepository.Update(sql, model);
}
public bool Delete(Etkinlik model)
{
const string sql = @"UPDATE public.etkinlik
SET sil=true
WHERE id=@id";
return _genericRepository.Delete(sql, model);
}
}
}
| 40.026667 | 281 | 0.63491 | [
"MIT",
"Unlicense"
] | NecmettinCimen/OdevTakip | OdevTakip.Services/EtkinlikService.cs | 3,004 | C# |
using System;
using System.Collections.Generic;
using Application.ViewModels;
using AutoMapper;
using Domain;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Services.Interfaces;
namespace Application.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ShelfController : ControllerBase
{
private readonly IShelfServices _shelfServices;
private readonly ILogger<ShelfController> _logger;
private readonly IMapper _mapper;
public ShelfController(IShelfServices spotServices, ILogger<ShelfController> logger, IMapper mapper)
{
_shelfServices = spotServices;
_logger = logger;
_mapper = mapper;
}
[HttpGet("{id}")]
public ActionResult<ShelfViewModel> GetById(int id)
{
try
{
_logger.LogInformation("Received get list Shelf request");
var result = _shelfServices.GetById(id);
return Ok(_mapper.Map<ShelfViewModel>(result));
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
return new StatusCodeResult(500);
}
}
[HttpGet("CustItem/{itemid}")]
public ActionResult<List<ShelfViewModel>> GetbyCustItem([FromHeader] int custid, int itemid)
{
try
{
_logger.LogInformation("Received get list Shelf request");
var result = _shelfServices.GetbyCustItem(custid, itemid);
return Ok(_mapper.Map<List<ShelfViewModel>>(result));
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
return new StatusCodeResult(500);
}
}
[HttpGet("Customer/{custid}")]
public ActionResult<List<ShelfViewModel>> GetbyCustomer(int custid)
{
try
{
_logger.LogInformation("Received get list Shelf request");
var result = _shelfServices.GetbyCustomer(custid);
return Ok(_mapper.Map<List<ShelfViewModel>>(result));
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
return new StatusCodeResult(500);
}
}
[HttpPost]
public ActionResult<string> InsertShelf([FromBody] ShelfViewModel customer)
{
try
{
_logger.LogInformation("Received post Shelf request");
_shelfServices.InsertShelf(_mapper.Map<Shelf>(customer));
return Ok("success");
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
return new StatusCodeResult(500);
}
}
[HttpPatch("Quantity/{shelfid}")]
public ActionResult<string> UpdateQty([FromHeader] int quantity, int shelfid)
{
try
{
_logger.LogInformation("Received patch Shelf quantity request");
_shelfServices.UpdateQty(shelfid, quantity);
return Ok("OK");
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
return new StatusCodeResult(500);
}
}
[HttpPatch("AvailableQuantity/{shelfid}")]
public ActionResult<string> UpdateAvailQty([FromHeader] int availableqty, int shelfid)
{
try
{
_logger.LogInformation("Received patch Shelf available quantity request");
_shelfServices.UpdateAvailQty(shelfid, availableqty);
return Ok("OK");
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
return new StatusCodeResult(500);
}
}
[HttpPatch("MarketPrice/{shelfid}")]
public ActionResult<string> UpdateMarketPrice([FromHeader] double price, int shelfid)
{
try
{
_logger.LogInformation("Received patch Shelf marketprice request");
_shelfServices.UpdateMarketPrice(shelfid, price);
return Ok("OK");
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
return new StatusCodeResult(500);
}
}
}
} | 33.791367 | 108 | 0.556313 | [
"MIT"
] | Thijapones/MTG4Us | MTG4Us/MTG4Us/Controllers/ShelfController.cs | 4,699 | C# |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CN_Repository;
namespace CoffeeNewspaper_UnitTest.DomainTest
{
[TestFixture]
public class TimeSliceProviderTest
{
[Test]
public void TimeSliceProviderSingletonTest()
{
TimeSliceProvider tsProvider1 = null;
TimeSliceProvider tsProvider2 = null;
for (int i = 0; i < 1000; i++)
{
Parallel.Invoke(() =>
{
tsProvider1 = TimeSliceProvider.GetProvider();
}, () =>
{
tsProvider2 = TimeSliceProvider.GetProvider();
});
Assert.AreEqual(tsProvider1, tsProvider2);
}
}
[Test]
public void TimeSliceProviderCreate()
{
var tsProvider = TimeSliceProvider.GetProvider();
Assert.IsNotNull(tsProvider);
Assert.AreEqual(tsProvider.Today,DateTime.Now.ToString("yyyy-MM-dd"));
}
[Test]
public void Time
}
}
| 26.409091 | 82 | 0.555077 | [
"MIT"
] | engimaxp/CoffeeNewspaper | CoffeeNewspaper/CoffeeNewspaper_UnitTest/DomainTest/TimeSliceProviderTest.cs | 1,164 | C# |
using CoreSharp.Common.Attributes;
using CoreSharp.NHibernate;
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
namespace CoreSharp.Breeze.Tests.Entities
{
public class OrderProductFk : Entity
{
[NotNull]
public virtual Order Order { get; set; }
public virtual long OrderId { get; set; }
[NotNull]
public virtual Product Product { get; set; }
public virtual long ProductId { get; set; }
public virtual int Quantity { get; set; }
public virtual decimal TotalPrice { get; set; }
public virtual string ProductCategory => Product.Category;
}
public class OrderProductFkOverride : IAutoMappingOverride<OrderProductFk>
{
public void Override(AutoMapping<OrderProductFk> mapping)
{
mapping.Map(o => o.OrderId).ReadOnly();
mapping.Map(o => o.ProductId).ReadOnly();
}
}
}
| 26.416667 | 78 | 0.6551 | [
"MIT"
] | cime/CoreSharp | CoreSharp.Breeze.Tests/Entities/OrderProductFk.cs | 953 | C# |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Windows.Input;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace Avalonia.Controls
{
/// <summary>
/// Defines how a <see cref="Button"/> reacts to clicks.
/// </summary>
public enum ClickMode
{
/// <summary>
/// The <see cref="Button.Click"/> event is raised when the pointer is released.
/// </summary>
Release,
/// <summary>
/// The <see cref="Button.Click"/> event is raised when the pointer is pressed.
/// </summary>
Press,
}
/// <summary>
/// A button control.
/// </summary>
public class Button : ContentControl
{
/// <summary>
/// Defines the <see cref="ClickMode"/> property.
/// </summary>
public static readonly StyledProperty<ClickMode> ClickModeProperty =
AvaloniaProperty.Register<Button, ClickMode>(nameof(ClickMode));
/// <summary>
/// Defines the <see cref="Command"/> property.
/// </summary>
public static readonly DirectProperty<Button, ICommand> CommandProperty =
AvaloniaProperty.RegisterDirect<Button, ICommand>(nameof(Command),
button => button.Command, (button, command) => button.Command = command, enableDataValidation: true);
/// <summary>
/// Defines the <see cref="HotKey"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture> HotKeyProperty =
HotKeyManager.HotKeyProperty.AddOwner<Button>();
/// <summary>
/// Defines the <see cref="CommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object> CommandParameterProperty =
AvaloniaProperty.Register<Button, object>(nameof(CommandParameter));
/// <summary>
/// Defines the <see cref="IsDefaultProperty"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsDefaultProperty =
AvaloniaProperty.Register<Button, bool>(nameof(IsDefault));
/// <summary>
/// Defines the <see cref="Click"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
RoutedEvent.Register<Button, RoutedEventArgs>(nameof(Click), RoutingStrategies.Bubble);
private ICommand _command;
public static readonly StyledProperty<bool> IsPressedProperty =
AvaloniaProperty.Register<Button, bool>(nameof(IsPressed));
/// <summary>
/// Initializes static members of the <see cref="Button"/> class.
/// </summary>
static Button()
{
FocusableProperty.OverrideDefaultValue(typeof(Button), true);
CommandProperty.Changed.Subscribe(CommandChanged);
IsDefaultProperty.Changed.Subscribe(IsDefaultChanged);
PseudoClass(IsPressedProperty, ":pressed");
}
/// <summary>
/// Raised when the user clicks the button.
/// </summary>
public event EventHandler<RoutedEventArgs> Click
{
add { AddHandler(ClickEvent, value); }
remove { RemoveHandler(ClickEvent, value); }
}
/// <summary>
/// Gets or sets a value indicating how the <see cref="Button"/> should react to clicks.
/// </summary>
public ClickMode ClickMode
{
get { return GetValue(ClickModeProperty); }
set { SetValue(ClickModeProperty, value); }
}
/// <summary>
/// Gets or sets an <see cref="ICommand"/> to be invoked when the button is clicked.
/// </summary>
public ICommand Command
{
get { return _command; }
set { SetAndRaise(CommandProperty, ref _command, value); }
}
/// <summary>
/// Gets or sets an <see cref="KeyGesture"/> associated with this control
/// </summary>
public KeyGesture HotKey
{
get { return GetValue(HotKeyProperty); }
set { SetValue(HotKeyProperty, value); }
}
/// <summary>
/// Gets or sets a parameter to be passed to the <see cref="Command"/>.
/// </summary>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the button is the default button for the
/// window.
/// </summary>
public bool IsDefault
{
get { return GetValue(IsDefaultProperty); }
set { SetValue(IsDefaultProperty, value); }
}
public bool IsPressed
{
get { return GetValue(IsPressedProperty); }
private set { SetValue(IsPressedProperty, value); }
}
/// <inheritdoc/>
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
if (IsDefault)
{
if (e.Root is IInputElement inputElement)
{
ListenForDefault(inputElement);
}
}
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
OnClick();
e.Handled = true;
}
else if (e.Key == Key.Space)
{
if (ClickMode == ClickMode.Press)
{
OnClick();
}
IsPressed = true;
e.Handled = true;
}
base.OnKeyDown(e);
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.Key == Key.Space)
{
if (ClickMode == ClickMode.Release)
{
OnClick();
}
IsPressed = false;
e.Handled = true;
}
}
/// <inheritdoc/>
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (IsDefault)
{
if (e.Root is IInputElement inputElement)
{
StopListeningForDefault(inputElement);
}
}
}
/// <summary>
/// Invokes the <see cref="Click"/> event.
/// </summary>
protected virtual void OnClick()
{
var e = new RoutedEventArgs(ClickEvent);
RaiseEvent(e);
if (Command != null)
{
Command.Execute(CommandParameter);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (e.MouseButton == MouseButton.Left)
{
e.Device.Capture(this);
IsPressed = true;
e.Handled = true;
if (ClickMode == ClickMode.Press)
{
OnClick();
}
}
}
/// <inheritdoc/>
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (e.MouseButton == MouseButton.Left)
{
e.Device.Capture(null);
IsPressed = false;
e.Handled = true;
if (ClickMode == ClickMode.Release && new Rect(Bounds.Size).Contains(e.GetPosition(this)))
{
OnClick();
}
}
}
protected override void UpdateDataValidation(AvaloniaProperty property, BindingNotification status)
{
base.UpdateDataValidation(property, status);
if(property == CommandProperty)
{
if(status?.ErrorType == BindingErrorType.Error)
{
IsEnabled = false;
}
}
}
/// <summary>
/// Called when the <see cref="Command"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is Button button)
{
var oldCommand = e.OldValue as ICommand;
var newCommand = e.NewValue as ICommand;
if (oldCommand != null)
{
oldCommand.CanExecuteChanged -= button.CanExecuteChanged;
}
if (newCommand != null)
{
newCommand.CanExecuteChanged += button.CanExecuteChanged;
}
button.CanExecuteChanged(button, EventArgs.Empty);
}
}
/// <summary>
/// Called when the <see cref="IsDefault"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void IsDefaultChanged(AvaloniaPropertyChangedEventArgs e)
{
var button = e.Sender as Button;
var isDefault = (bool)e.NewValue;
if (button?.VisualRoot is IInputElement inputRoot)
{
if (isDefault)
{
button.ListenForDefault(inputRoot);
}
else
{
button.StopListeningForDefault(inputRoot);
}
}
}
/// <summary>
/// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void CanExecuteChanged(object sender, EventArgs e)
{
// HACK: Just set the IsEnabled property for the moment. This needs to be changed to
// use IsEnabledCore etc. but it will do for now.
IsEnabled = Command == null || Command.CanExecute(CommandParameter);
}
/// <summary>
/// Starts listening for the Enter key when the button <see cref="IsDefault"/>.
/// </summary>
/// <param name="root">The input root.</param>
private void ListenForDefault(IInputElement root)
{
root.AddHandler(KeyDownEvent, RootKeyDown);
}
/// <summary>
/// Stops listening for the Enter key when the button is no longer <see cref="IsDefault"/>.
/// </summary>
/// <param name="root">The input root.</param>
private void StopListeningForDefault(IInputElement root)
{
root.RemoveHandler(KeyDownEvent, RootKeyDown);
}
/// <summary>
/// Called when a key is pressed on the input root and the button <see cref="IsDefault"/>.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void RootKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && IsVisible && IsEnabled)
{
OnClick();
}
}
}
}
| 32.315934 | 117 | 0.527331 | [
"MIT"
] | DmitryZhelnin/Avalonia | src/Avalonia.Controls/Button.cs | 11,763 | C# |
using Dahomey.Json.Attributes;
using System;
using System.Numerics;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ch1seL.TonNet.Client.Models
{
/// <summary>
/// Not described yet..
/// </summary>
public class ParamsOfQueryCounterparties
{
/// <summary>
/// Account address
/// </summary>
[JsonPropertyName("account")]
public string Account { get; set; }
/// <summary>
/// Projection (result) string
/// </summary>
[JsonPropertyName("result")]
public string Result { get; set; }
/// <summary>
/// Number of counterparties to return
/// </summary>
[JsonPropertyName("first")]
public uint? First { get; set; }
/// <summary>
/// `cursor` field of the last received result
/// </summary>
[JsonPropertyName("after")]
public string After { get; set; }
}
} | 25.342105 | 54 | 0.563863 | [
"Apache-2.0"
] | freeton-org/ton-client-dotnet | src/ch1seL.TonNet.Client.Models/Generated/Models/ParamsOfQueryCounterparties.cs | 963 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BizHawk.Client.EmuHawk.ToolExtensions;
using BizHawk.Emulation.Common;
using BizHawk.Client.Common;
namespace BizHawk.Client.EmuHawk
{
public partial class BasicBot : ToolFormBase , IToolFormAutoConfig
{
private const string DialogTitle = "Basic Bot";
private string _currentFileName = "";
private string CurrentFileName
{
get { return _currentFileName; }
set
{
_currentFileName = value;
if (!string.IsNullOrWhiteSpace(_currentFileName))
{
Text = DialogTitle + " - " + Path.GetFileNameWithoutExtension(_currentFileName);
}
else
{
Text = DialogTitle;
}
}
}
private bool _isBotting = false;
private long _attempts = 1;
private long _frames = 0;
private int _targetFrame = 0;
private bool _oldCountingSetting = false;
private BotAttempt _currentBotAttempt = null;
private BotAttempt _bestBotAttempt = null;
private BotAttempt _comparisonBotAttempt = null;
private bool _replayMode = false;
private int _startFrame = 0;
private string _lastRom = "";
private bool _dontUpdateValues = false;
private MemoryDomain _currentDomain;
private bool _bigEndian;
private int _dataSize;
private Dictionary<string, double> _cachedControlProbabilities;
private ILogEntryGenerator _logGenerator;
#region Services and Settings
[RequiredService]
private IEmulator Emulator { get; set; }
// Unused, due to the use of MainForm to loadstate, but this needs to be kept here in order to establish an IStatable dependency
[RequiredService]
private IStatable StatableCore { get; set; }
[RequiredService]
private IMemoryDomains MemoryDomains { get; set; }
[ConfigPersist]
public BasicBotSettings Settings { get; set; }
public class BasicBotSettings
{
public BasicBotSettings()
{
RecentBotFiles = new RecentFiles();
TurboWhenBotting = true;
}
public RecentFiles RecentBotFiles { get; set; }
public bool TurboWhenBotting { get; set; }
}
#endregion
#region Initialize
public BasicBot()
{
InitializeComponent();
Text = DialogTitle;
Settings = new BasicBotSettings();
_comparisonBotAttempt = new BotAttempt();
}
private void BasicBot_Load(object sender, EventArgs e)
{
}
#endregion
#region UI Bindings
private Dictionary<string, double> ControlProbabilities
{
get
{
return ControlProbabilityPanel.Controls
.OfType<BotControlsRow>()
.ToDictionary(tkey => tkey.ButtonName, tvalue => tvalue.Probability);
}
}
private string SelectedSlot
{
get
{
char num = StartFromSlotBox.SelectedItem
.ToString()
.Last();
return "QuickSave" + num;
}
}
private long Attempts
{
get { return _attempts; }
set
{
_attempts = value;
AttemptsLabel.Text = _attempts.ToString();
}
}
private long Frames
{
get { return _frames; }
set
{
_frames = value;
FramesLabel.Text = _frames.ToString();
}
}
private int FrameLength
{
get { return (int)FrameLengthNumeric.Value; }
set { FrameLengthNumeric.Value = value; }
}
public int MaximizeAddress
{
get
{
int? addr = MaximizeAddressBox.ToRawInt();
if (addr.HasValue)
{
return addr.Value;
}
return 0;
}
set
{
MaximizeAddressBox.SetFromRawInt(value);
}
}
public int MaximizeValue
{
get
{
int? addr = MaximizeAddressBox.ToRawInt();
if (addr.HasValue)
{
return GetRamvalue(addr.Value);
}
return 0;
}
}
public int TieBreaker1Address
{
get
{
int? addr = TieBreaker1Box.ToRawInt();
if (addr.HasValue)
{
return addr.Value;
}
return 0;
}
set
{
TieBreaker1Box.SetFromRawInt(value);
}
}
public int TieBreaker1Value
{
get
{
int? addr = TieBreaker1Box.ToRawInt();
if (addr.HasValue)
{
return GetRamvalue(addr.Value);
}
return 0;
}
}
public int TieBreaker2Address
{
get
{
int? addr = TieBreaker2Box.ToRawInt();
if (addr.HasValue)
{
return addr.Value;
}
return 0;
}
set
{
TieBreaker2Box.SetFromRawInt(value);
}
}
public int TieBreaker2Value
{
get
{
int? addr = TieBreaker2Box.ToRawInt();
if (addr.HasValue)
{
return GetRamvalue(addr.Value);
}
return 0;
}
}
public int TieBreaker3Address
{
get
{
int? addr = TieBreaker3Box.ToRawInt();
if (addr.HasValue)
{
return addr.Value;
}
return 0;
}
set
{
TieBreaker3Box.SetFromRawInt(value);
}
}
public int TieBreaker3Value
{
get
{
int? addr = TieBreaker3Box.ToRawInt();
if (addr.HasValue)
{
return GetRamvalue(addr.Value);
}
return 0;
}
}
public byte MainComparisonType
{
get
{
return (byte)MainOperator.SelectedIndex;
}
set
{
if (value < 5) MainOperator.SelectedIndex = value;
else MainOperator.SelectedIndex = 0;
}
}
public byte Tie1ComparisonType
{
get
{
return (byte)Tiebreak1Operator.SelectedIndex;
}
set
{
if (value < 5) Tiebreak1Operator.SelectedIndex = value;
else Tiebreak1Operator.SelectedIndex = 0;
}
}
public byte Tie2ComparisonType
{
get
{
return (byte)Tiebreak2Operator.SelectedIndex;
}
set
{
if (value < 5) Tiebreak2Operator.SelectedIndex = value;
else Tiebreak2Operator.SelectedIndex = 0;
}
}
public byte Tie3ComparisonType
{
get
{
return (byte)Tiebreak3Operator.SelectedIndex;
}
set
{
if (value < 5) Tiebreak3Operator.SelectedIndex = value;
else Tiebreak3Operator.SelectedIndex = 0;
}
}
public string FromSlot
{
get
{
return StartFromSlotBox.SelectedItem != null
? StartFromSlotBox.SelectedItem.ToString()
: "";
}
set
{
var item = StartFromSlotBox.Items.
OfType<object>()
.FirstOrDefault(o => o.ToString() == value);
if (item != null)
{
StartFromSlotBox.SelectedItem = item;
}
else
{
StartFromSlotBox.SelectedItem = null;
}
}
}
#endregion
#region IToolForm Implementation
public bool UpdateBefore { get { return true; } }
public void NewUpdate(ToolFormUpdateType type) { }
public void UpdateValues()
{
Update(fast: false);
}
public void FastUpdate()
{
Update(fast: true);
}
public void Restart()
{
if (_currentDomain == null ||
MemoryDomains.Contains(_currentDomain))
{
_currentDomain = MemoryDomains.MainMemory;
_bigEndian = _currentDomain.EndianType == MemoryDomain.Endian.Big;
_dataSize = 1;
}
if (_isBotting)
{
StopBot();
}
else if (_replayMode)
{
FinishReplay();
}
if (_lastRom != GlobalWin.MainForm.CurrentlyOpenRom)
{
_lastRom = GlobalWin.MainForm.CurrentlyOpenRom;
SetupControlsAndProperties();
}
}
public bool AskSaveChanges()
{
return true;
}
#endregion
#region Control Events
#region FileMenu
private void FileSubMenu_DropDownOpened(object sender, EventArgs e)
{
SaveMenuItem.Enabled = !string.IsNullOrWhiteSpace(CurrentFileName);
}
private void RecentSubMenu_DropDownOpened(object sender, EventArgs e)
{
RecentSubMenu.DropDownItems.Clear();
RecentSubMenu.DropDownItems.AddRange(
Settings.RecentBotFiles.RecentMenu(LoadFileFromRecent, true));
}
private void NewMenuItem_Click(object sender, EventArgs e)
{
CurrentFileName = "";
_bestBotAttempt = null;
ControlProbabilityPanel.Controls
.OfType<BotControlsRow>()
.ToList()
.ForEach(cp => cp.Probability = 0);
FrameLength = 0;
MaximizeAddress = 0;
TieBreaker1Address = 0;
TieBreaker2Address = 0;
TieBreaker3Address = 0;
StartFromSlotBox.SelectedIndex = 0;
MainOperator.SelectedIndex = 0;
Tiebreak1Operator.SelectedIndex = 0;
Tiebreak2Operator.SelectedIndex = 0;
Tiebreak3Operator.SelectedIndex = 0;
MainBestRadio.Checked = true;
MainValueNumeric.Value = 0;
TieBreak1Numeric.Value = 0;
TieBreak2Numeric.Value = 0;
TieBreak3Numeric.Value = 0;
TieBreak1BestRadio.Checked = true;
TieBreak2BestRadio.Checked = true;
TieBreak3BestRadio.Checked = true;
UpdateBestAttempt();
UpdateComparisonBotAttempt();
}
private void OpenMenuItem_Click(object sender, EventArgs e)
{
var file = OpenFileDialog(
CurrentFileName,
PathManager.MakeAbsolutePath(Global.Config.PathEntries.ToolsPathFragment, null),
"Bot files",
"bot"
);
if (file != null)
{
LoadBotFile(file.FullName);
}
}
private void SaveMenuItem_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(CurrentFileName))
{
SaveBotFile(CurrentFileName);
}
}
private void SaveAsMenuItem_Click(object sender, EventArgs e)
{
var file = SaveFileDialog(
CurrentFileName,
PathManager.MakeAbsolutePath(Global.Config.PathEntries.ToolsPathFragment, null),
"Bot files",
"bot"
);
if (file != null)
{
SaveBotFile(file.FullName);
_currentFileName = file.FullName;
}
}
private void ExitMenuItem_Click(object sender, EventArgs e)
{
Close();
}
#endregion
#region Options Menu
private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e)
{
TurboWhileBottingMenuItem.Checked = Settings.TurboWhenBotting;
BigEndianMenuItem.Checked = _bigEndian;
}
private void MemoryDomainsMenuItem_DropDownOpened(object sender, EventArgs e)
{
MemoryDomainsMenuItem.DropDownItems.Clear();
MemoryDomainsMenuItem.DropDownItems.AddRange(
MemoryDomains.MenuItems(SetMemoryDomain, _currentDomain.Name)
.ToArray());
}
private void BigEndianMenuItem_Click(object sender, EventArgs e)
{
_bigEndian ^= true;
}
private void DataSizeMenuItem_DropDownOpened(object sender, EventArgs e)
{
_1ByteMenuItem.Checked = _dataSize == 1;
_2ByteMenuItem.Checked = _dataSize == 2;
_4ByteMenuItem.Checked = _dataSize == 4;
}
private void _1ByteMenuItem_Click(object sender, EventArgs e)
{
_dataSize = 1;
}
private void _2ByteMenuItem_Click(object sender, EventArgs e)
{
_dataSize = 2;
}
private void _4ByteMenuItem_Click(object sender, EventArgs e)
{
_dataSize = 4;
}
private void TurboWhileBottingMenuItem_Click(object sender, EventArgs e)
{
Settings.TurboWhenBotting ^= true;
}
#endregion
private void RunBtn_Click(object sender, EventArgs e)
{
StartBot();
}
private void StopBtn_Click(object sender, EventArgs e)
{
StopBot();
}
private void ClearBestButton_Click(object sender, EventArgs e)
{
_bestBotAttempt = null;
Attempts = 0;
Frames = 0;
UpdateBestAttempt();
UpdateComparisonBotAttempt();
}
private void PlayBestButton_Click(object sender, EventArgs e)
{
StopBot();
_replayMode = true;
_dontUpdateValues = true;
GlobalWin.MainForm.LoadQuickSave(SelectedSlot, false, true); // Triggers an UpdateValues call
_dontUpdateValues = false;
_startFrame = Emulator.Frame;
SetNormalSpeed();
UpdateBotStatusIcon();
MessageLabel.Text = "Replaying";
GlobalWin.MainForm.UnpauseEmulator();
}
private void FrameLengthNumeric_ValueChanged(object sender, EventArgs e)
{
AssessRunButtonStatus();
}
private void ClearStatsContextMenuItem_Click(object sender, EventArgs e)
{
Attempts = 0;
Frames = 0;
}
#endregion
#region Classes
private class BotAttempt
{
public BotAttempt()
{
Log = new List<string>();
}
public long Attempt { get; set; }
public int Maximize { get; set; }
public int TieBreak1 { get; set; }
public int TieBreak2 { get; set; }
public int TieBreak3 { get; set; }
public byte ComparisonTypeMain { get; set; }
public byte ComparisonTypeTie1 { get; set; }
public byte ComparisonTypeTie2 { get; set; }
public byte ComparisonTypeTie3 { get; set; }
public List<string> Log { get; set; }
}
private class BotData
{
public BotData()
{
MainCompareToBest = true;
TieBreaker1CompareToBest = true;
TieBreaker2CompareToBest = true;
TieBreaker3CompareToBest = true;
}
public BotAttempt Best { get; set; }
public Dictionary<string, double> ControlProbabilities { get; set; }
public int Maximize { get; set; }
public int TieBreaker1 { get; set; }
public int TieBreaker2 { get; set; }
public int TieBreaker3 { get; set; }
public byte ComparisonTypeMain { get; set; }
public byte ComparisonTypeTie1 { get; set; }
public byte ComparisonTypeTie2 { get; set; }
public byte ComparisonTypeTie3 { get; set; }
public bool MainCompareToBest { get; set; }
public bool TieBreaker1CompareToBest { get; set; }
public bool TieBreaker2CompareToBest { get; set; }
public bool TieBreaker3CompareToBest { get; set; }
public int MainCompareToValue { get; set; }
public int TieBreaker1CompareToValue { get; set; }
public int TieBreaker2CompareToValue { get; set; }
public int TieBreaker3CompareToValue { get; set; }
public int FrameLength { get; set; }
public string FromSlot { get; set; }
public long Attempts { get; set; }
public long Frames { get; set; }
public string MemoryDomain { get; set; }
public bool BigEndian { get; set; }
public int DataSize { get; set; }
}
#endregion
#region File Handling
private void LoadFileFromRecent(string path)
{
var result = LoadBotFile(path);
if (!result)
{
Settings.RecentBotFiles.HandleLoadError(path);
}
}
private bool LoadBotFile(string path)
{
var file = new FileInfo(path);
if (!file.Exists)
{
return false;
}
var json = File.ReadAllText(path);
var botData = (BotData)ConfigService.LoadWithType(json);
_bestBotAttempt = botData.Best;
var probabilityControls = ControlProbabilityPanel.Controls
.OfType<BotControlsRow>()
.ToList();
foreach (var kvp in botData.ControlProbabilities)
{
var control = probabilityControls.Single(c => c.ButtonName == kvp.Key);
control.Probability = kvp.Value;
}
MaximizeAddress = botData.Maximize;
TieBreaker1Address = botData.TieBreaker1;
TieBreaker2Address = botData.TieBreaker2;
TieBreaker3Address = botData.TieBreaker3;
try
{
MainComparisonType = botData.ComparisonTypeMain;
Tie1ComparisonType = botData.ComparisonTypeTie1;
Tie2ComparisonType = botData.ComparisonTypeTie2;
Tie3ComparisonType = botData.ComparisonTypeTie3;
MainBestRadio.Checked = botData.MainCompareToBest;
TieBreak1BestRadio.Checked = botData.TieBreaker1CompareToBest;
TieBreak2BestRadio.Checked = botData.TieBreaker2CompareToBest;
TieBreak3BestRadio.Checked = botData.TieBreaker3CompareToBest;
MainValueRadio.Checked = !botData.MainCompareToBest;
TieBreak1ValueRadio.Checked = !botData.TieBreaker1CompareToBest;
TieBreak2ValueRadio.Checked = !botData.TieBreaker2CompareToBest;
TieBreak3ValueRadio.Checked = !botData.TieBreaker3CompareToBest;
MainValueNumeric.Value = botData.MainCompareToValue;
TieBreak1Numeric.Value = botData.TieBreaker1CompareToValue;
TieBreak2Numeric.Value = botData.TieBreaker2CompareToValue;
TieBreak3Numeric.Value = botData.TieBreaker3CompareToValue;
}
catch
{
MainComparisonType = 0;
Tie1ComparisonType = 0;
Tie2ComparisonType = 0;
Tie3ComparisonType = 0;
MainBestRadio.Checked = true;
TieBreak1BestRadio.Checked = true;
TieBreak2BestRadio.Checked = true;
TieBreak3BestRadio.Checked = true;
MainBestRadio.Checked = false;
TieBreak1BestRadio.Checked = false;
TieBreak2BestRadio.Checked = false;
TieBreak3BestRadio.Checked = false;
MainValueNumeric.Value = 0;
TieBreak1Numeric.Value = 0;
TieBreak2Numeric.Value = 0;
TieBreak3Numeric.Value = 0;
}
FrameLength = botData.FrameLength;
FromSlot = botData.FromSlot;
Attempts = botData.Attempts;
Frames = botData.Frames;
_currentDomain = !string.IsNullOrWhiteSpace(botData.MemoryDomain)
? MemoryDomains[botData.MemoryDomain]
: MemoryDomains.MainMemory;
_bigEndian = botData.BigEndian;
_dataSize = botData.DataSize > 0 ? botData.DataSize : 1;
UpdateBestAttempt();
UpdateComparisonBotAttempt();
if (_bestBotAttempt != null)
{
PlayBestButton.Enabled = true;
}
CurrentFileName = path;
Settings.RecentBotFiles.Add(CurrentFileName);
MessageLabel.Text = Path.GetFileNameWithoutExtension(path) + " loaded";
AssessRunButtonStatus();
return true;
}
private void SaveBotFile(string path)
{
var data = new BotData
{
Best = _bestBotAttempt,
ControlProbabilities = ControlProbabilities,
Maximize = MaximizeAddress,
TieBreaker1 = TieBreaker1Address,
TieBreaker2 = TieBreaker2Address,
TieBreaker3 = TieBreaker3Address,
ComparisonTypeMain = MainComparisonType,
ComparisonTypeTie1 = Tie1ComparisonType,
ComparisonTypeTie2 = Tie2ComparisonType,
ComparisonTypeTie3 = Tie3ComparisonType,
MainCompareToBest = MainBestRadio.Checked,
TieBreaker1CompareToBest = TieBreak1BestRadio.Checked,
TieBreaker2CompareToBest = TieBreak2BestRadio.Checked,
TieBreaker3CompareToBest = TieBreak3BestRadio.Checked,
MainCompareToValue = (int)MainValueNumeric.Value,
TieBreaker1CompareToValue = (int)TieBreak1Numeric.Value,
TieBreaker2CompareToValue = (int)TieBreak2Numeric.Value,
TieBreaker3CompareToValue = (int)TieBreak3Numeric.Value,
FromSlot = FromSlot,
FrameLength = FrameLength,
Attempts = Attempts,
Frames = Frames,
MemoryDomain = _currentDomain.Name,
BigEndian = _bigEndian,
DataSize = _dataSize
};
var json = ConfigService.SaveWithType(data);
File.WriteAllText(path, json);
CurrentFileName = path;
Settings.RecentBotFiles.Add(CurrentFileName);
MessageLabel.Text = Path.GetFileName(CurrentFileName) + " saved";
}
#endregion
private void SetupControlsAndProperties()
{
MaximizeAddressBox.SetHexProperties(MemoryDomains.MainMemory.Size);
TieBreaker1Box.SetHexProperties(MemoryDomains.MainMemory.Size);
TieBreaker2Box.SetHexProperties(MemoryDomains.MainMemory.Size);
TieBreaker3Box.SetHexProperties(MemoryDomains.MainMemory.Size);
StartFromSlotBox.SelectedIndex = 0;
int starty = 0;
int accumulatedy = 0;
int lineHeight = 30;
int marginLeft = 15;
int count = 0;
ControlProbabilityPanel.Controls.Clear();
foreach (var button in Emulator.ControllerDefinition.BoolButtons)
{
var control = new BotControlsRow
{
ButtonName = button,
Probability = 0.0,
Location = new Point(marginLeft, starty + accumulatedy),
TabIndex = count + 1,
ProbabilityChangedCallback = AssessRunButtonStatus
};
ControlProbabilityPanel.Controls.Add(control);
accumulatedy += lineHeight;
count++;
}
if (Settings.RecentBotFiles.AutoLoad)
{
LoadFileFromRecent(Settings.RecentBotFiles.MostRecent);
}
UpdateBotStatusIcon();
}
private void SetMemoryDomain(string name)
{
_currentDomain = MemoryDomains[name];
_bigEndian = MemoryDomains[name].EndianType == MemoryDomain.Endian.Big;
}
private int GetRamvalue(int addr)
{
int val;
switch (_dataSize)
{
default:
case 1:
val = _currentDomain.PeekByte(addr);
break;
case 2:
val = _currentDomain.PeekUshort(addr, _bigEndian);
break;
case 4:
val = (int)_currentDomain.PeekUint(addr, _bigEndian);
break;
}
return val;
}
private void Update(bool fast)
{
if (_dontUpdateValues)
{
return;
}
if (_replayMode)
{
int index = Emulator.Frame - _startFrame;
if (index < _bestBotAttempt.Log.Count)
{
var logEntry = _bestBotAttempt.Log[index];
var lg = Global.MovieSession.MovieControllerInstance();
lg.SetControllersAsMnemonic(logEntry);
foreach (var button in lg.Definition.BoolButtons)
{
// TODO: make an input adapter specifically for the bot?
Global.LuaAndAdaptor.SetButton(button, lg.IsPressed(button));
}
}
else
{
FinishReplay();
}
}
else if (_isBotting)
{
if (Emulator.Frame >= _targetFrame)
{
Attempts++;
Frames += FrameLength;
_currentBotAttempt.Maximize = MaximizeValue;
_currentBotAttempt.TieBreak1 = TieBreaker1Value;
_currentBotAttempt.TieBreak2 = TieBreaker2Value;
_currentBotAttempt.TieBreak3 = TieBreaker3Value;
PlayBestButton.Enabled = true;
if (_bestBotAttempt == null || IsBetter(_bestBotAttempt, _currentBotAttempt))
{
_bestBotAttempt = _currentBotAttempt;
UpdateBestAttempt();
}
_currentBotAttempt = new BotAttempt { Attempt = Attempts };
GlobalWin.MainForm.LoadQuickSave(SelectedSlot, false, true);
}
PressButtons();
}
}
private void FinishReplay()
{
GlobalWin.MainForm.PauseEmulator();
_startFrame = 0;
_replayMode = false;
UpdateBotStatusIcon();
MessageLabel.Text = "Replay stopped";
}
private bool IsBetter(BotAttempt comparison, BotAttempt current)
{
if (!TestValue(MainComparisonType, current.Maximize, comparison.Maximize))
{
return false;
}
else if (current.Maximize == comparison.Maximize)
{
if (!TestValue(Tie1ComparisonType, current.TieBreak1, comparison.TieBreak1))
{
return false;
}
else if (current.TieBreak1 == comparison.TieBreak1)
{
if (!TestValue(Tie2ComparisonType, current.TieBreak2, comparison.TieBreak2))
{
return false;
}
else if (current.TieBreak2 == comparison.TieBreak2)
{
if (!TestValue(Tie3ComparisonType, current.TieBreak3, current.TieBreak3))
{
return false;
}
}
}
}
return true;
}
private bool TestValue(byte operation, int currentValue, int bestValue)
{
switch (operation)
{
case 0:
return currentValue > bestValue;
case 1:
return currentValue >= bestValue;
case 2:
return currentValue == bestValue;
case 3:
return currentValue <= bestValue;
case 4:
return currentValue < bestValue;
}
return false;
}
private void UpdateBestAttempt()
{
if (_bestBotAttempt != null)
{
ClearBestButton.Enabled = true;
BestAttemptNumberLabel.Text = _bestBotAttempt.Attempt.ToString();
BestMaximizeBox.Text = _bestBotAttempt.Maximize.ToString();
BestTieBreak1Box.Text = _bestBotAttempt.TieBreak1.ToString();
BestTieBreak2Box.Text = _bestBotAttempt.TieBreak2.ToString();
BestTieBreak3Box.Text = _bestBotAttempt.TieBreak3.ToString();
var sb = new StringBuilder();
foreach (var logEntry in _bestBotAttempt.Log)
{
sb.AppendLine(logEntry);
}
BestAttemptLogLabel.Text = sb.ToString();
PlayBestButton.Enabled = true;
}
else
{
ClearBestButton.Enabled = false;
BestAttemptNumberLabel.Text = "";
BestMaximizeBox.Text = "";
BestTieBreak1Box.Text = "";
BestTieBreak2Box.Text = "";
BestTieBreak3Box.Text = "";
BestAttemptLogLabel.Text = "";
PlayBestButton.Enabled = false;
}
}
private void PressButtons()
{
var rand = new Random((int)DateTime.Now.Ticks);
var buttonLog = new Dictionary<string, bool>();
foreach (var button in Emulator.ControllerDefinition.BoolButtons)
{
double probability = _cachedControlProbabilities[button];
bool pressed = !(rand.Next(100) < probability);
buttonLog.Add(button, pressed);
Global.ClickyVirtualPadController.SetBool(button, pressed);
}
_currentBotAttempt.Log.Add(_logGenerator.GenerateLogEntry());
}
private void StartBot()
{
if (!CanStart())
{
MessageBox.Show("Unable to run with current settings");
return;
}
_isBotting = true;
ControlsBox.Enabled = false;
StartFromSlotBox.Enabled = false;
RunBtn.Visible = false;
StopBtn.Visible = true;
GoalGroupBox.Enabled = false;
_currentBotAttempt = new BotAttempt { Attempt = Attempts };
if (Global.MovieSession.Movie.IsRecording)
{
_oldCountingSetting = Global.MovieSession.Movie.IsCountingRerecords;
Global.MovieSession.Movie.IsCountingRerecords = false;
}
_dontUpdateValues = true;
GlobalWin.MainForm.LoadQuickSave(SelectedSlot, false, true); // Triggers an UpdateValues call
_dontUpdateValues = false;
_targetFrame = Emulator.Frame + (int)FrameLengthNumeric.Value;
GlobalWin.MainForm.UnpauseEmulator();
if (Settings.TurboWhenBotting)
{
SetMaxSpeed();
}
UpdateBotStatusIcon();
MessageLabel.Text = "Running...";
_cachedControlProbabilities = ControlProbabilities;
_logGenerator = Global.MovieSession.LogGeneratorInstance();
_logGenerator.SetSource(Global.ClickyVirtualPadController);
}
private bool CanStart()
{
if (!ControlProbabilities.Any(cp => cp.Value > 0))
{
return false;
}
if (!MaximizeAddressBox.ToRawInt().HasValue)
{
return false;
}
if (FrameLengthNumeric.Value == 0)
{
return false;
}
return true;
}
private void StopBot()
{
RunBtn.Visible = true;
StopBtn.Visible = false;
_isBotting = false;
_targetFrame = 0;
ControlsBox.Enabled = true;
StartFromSlotBox.Enabled = true;
_targetFrame = 0;
_currentBotAttempt = null;
GoalGroupBox.Enabled = true;
if (Global.MovieSession.Movie.IsRecording)
{
Global.MovieSession.Movie.IsCountingRerecords = _oldCountingSetting;
}
GlobalWin.MainForm.PauseEmulator();
SetNormalSpeed();
UpdateBotStatusIcon();
MessageLabel.Text = "Bot stopped";
}
private void UpdateBotStatusIcon()
{
if (_replayMode)
{
BotStatusButton.Image = Properties.Resources.Play;
BotStatusButton.ToolTipText = "Replaying best result";
}
else if (_isBotting)
{
BotStatusButton.Image = Properties.Resources.RecordHS;
BotStatusButton.ToolTipText = "Botting in progress";
}
else
{
BotStatusButton.Image = Properties.Resources.Pause;
BotStatusButton.ToolTipText = "Bot is currently not running";
}
}
private void SetMaxSpeed()
{
GlobalWin.MainForm.Unthrottle();
}
private void SetNormalSpeed()
{
GlobalWin.MainForm.Throttle();
}
private void AssessRunButtonStatus()
{
RunBtn.Enabled =
FrameLength > 0
&& !string.IsNullOrWhiteSpace(MaximizeAddressBox.Text)
&& ControlProbabilities.Any(kvp => kvp.Value > 0);
}
/// <summary>
/// Updates comparison bot attempt with current best bot attempt values for values where the "best" radio button is selected
/// </summary>
private void UpdateComparisonBotAttempt()
{
if(_bestBotAttempt == null)
{
if (MainBestRadio.Checked)
{
_comparisonBotAttempt.Maximize = 0;
}
if (TieBreak1BestRadio.Checked)
{
_comparisonBotAttempt.TieBreak1 = 0;
}
if (TieBreak2BestRadio.Checked)
{
_comparisonBotAttempt.TieBreak2= 0;
}
if (TieBreak3BestRadio.Checked)
{
_comparisonBotAttempt.TieBreak3 = 0;
}
}
else
{
if (MainBestRadio.Checked && _bestBotAttempt.Maximize != _comparisonBotAttempt.Maximize)
{
_comparisonBotAttempt.Maximize = _bestBotAttempt.Maximize;
}
if (TieBreak1BestRadio.Checked && _bestBotAttempt.TieBreak1 != _comparisonBotAttempt.TieBreak1)
{
_comparisonBotAttempt.TieBreak1 = _bestBotAttempt.TieBreak1;
}
if (TieBreak2BestRadio.Checked && _bestBotAttempt.TieBreak2 != _comparisonBotAttempt.TieBreak2)
{
_comparisonBotAttempt.TieBreak2 = _bestBotAttempt.TieBreak2;
}
if (TieBreak3BestRadio.Checked && _bestBotAttempt.TieBreak3 != _comparisonBotAttempt.TieBreak3)
{
_comparisonBotAttempt.TieBreak3 = _bestBotAttempt.TieBreak3;
}
}
}
private void MainBestRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.MainValueNumeric.Enabled = false;
_comparisonBotAttempt.Maximize = _bestBotAttempt == null ? 0 : _bestBotAttempt.Maximize;
}
}
private void Tiebreak1BestRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.TieBreak1Numeric.Enabled = false;
_comparisonBotAttempt.TieBreak1 = _bestBotAttempt == null ? 0 : _bestBotAttempt.TieBreak1;
}
}
private void Tiebreak2BestRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.TieBreak2Numeric.Enabled = false;
_comparisonBotAttempt.TieBreak2 = _bestBotAttempt == null ? 0 : _bestBotAttempt.TieBreak2;
}
}
private void Tiebreak3BestRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.TieBreak3Numeric.Enabled = false;
_comparisonBotAttempt.TieBreak3 = _bestBotAttempt == null ? 0 : _bestBotAttempt.TieBreak3;
}
}
private void MainValueRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.MainValueNumeric.Enabled = true;
_comparisonBotAttempt.Maximize = (int)this.MainValueNumeric.Value;
}
}
private void TieBreak1ValueRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.TieBreak1Numeric.Enabled = true;
_comparisonBotAttempt.TieBreak1 = (int)this.TieBreak1Numeric.Value;
}
}
private void TieBreak2ValueRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.TieBreak2Numeric.Enabled = true;
_comparisonBotAttempt.TieBreak2 = (int)this.TieBreak2Numeric.Value;
}
}
private void TieBreak3ValueRadio_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
this.TieBreak3Numeric.Enabled = true;
_comparisonBotAttempt.TieBreak3 = (int)this.TieBreak3Numeric.Value;
}
}
private void MainValueNumeric_ValueChanged(object sender, EventArgs e)
{
NumericUpDown numericUpDown = (NumericUpDown)sender;
this._comparisonBotAttempt.Maximize = (int)numericUpDown.Value;
}
private void TieBreak1Numeric_ValueChanged(object sender, EventArgs e)
{
NumericUpDown numericUpDown = (NumericUpDown)sender;
this._comparisonBotAttempt.TieBreak1 = (int)numericUpDown.Value;
}
private void TieBreak2Numeric_ValueChanged(object sender, EventArgs e)
{
NumericUpDown numericUpDown = (NumericUpDown)sender;
this._comparisonBotAttempt.TieBreak2 = (int)numericUpDown.Value;
}
private void TieBreak3Numeric_ValueChanged(object sender, EventArgs e)
{
NumericUpDown numericUpDown = (NumericUpDown)sender;
this._comparisonBotAttempt.TieBreak3 = (int)numericUpDown.Value;
}
}
}
| 23.405263 | 130 | 0.696296 | [
"MIT"
] | CognitiaAI/StreetFighterRL | emulator/Bizhawk/BizHawk-master/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs | 31,131 | C# |
//-----------------------------------------------------------------------
// <copyright file="TestAnnotationBadUsages.cs" company="OrbintSoft">
// Yet Another User Agent Analyzer for .NET Standard
// porting realized by Stefano Balzarotti, Copyright 2018 (C) OrbintSoft
//
// Original Author and License:
//
// Yet Another UserAgent Analyzer
// Copyright(C) 2013-2018 Niels Basjes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// <author>Stefano Balzarotti, Niels Basjes</author>
// <date>2018, 11, 24, 17:39</date>
// <summary></summary>
//-----------------------------------------------------------------------
namespace OrbintSoft.Yauaa.Testing.Tests.Annotate
{
using FluentAssertions;
using OrbintSoft.Yauaa.Analyze;
using OrbintSoft.Yauaa.Annotate;
using OrbintSoft.Yauaa.Testing.Fixtures;
using Xunit;
/// <summary>
/// Defines the <see cref="TestAnnotationBadUsages" />
/// </summary>
public class TestAnnotationBadUsages : IClassFixture<LogFixture>
{
/// <summary>
/// The TestNullInitAnalyzer
/// </summary>
[Fact]
public void TestNullInitAnalyzer()
{
UserAgentAnnotationAnalyzer<string> userAgentAnalyzer = new UserAgentAnnotationAnalyzer<string>();
userAgentAnalyzer.Invoking(u => u.Initialize(null)).Should().Throw<InvalidParserConfigurationException>().Which.Message.Should().StartWith("[Initialize] The mapper instance is null.");
}
/// <summary>
/// The TestNullInit
/// </summary>
[Fact]
public void TestNullInit()
{
UserAgentAnnotationAnalyzer<string> userAgentAnalyzer = new UserAgentAnnotationAnalyzer<string>();
userAgentAnalyzer.Map(null).Should().BeNull();
}
/// <summary>
/// The TestNoInit
/// </summary>
[Fact]
public void TestNoInit()
{
UserAgentAnnotationAnalyzer<string> userAgentAnalyzer = new UserAgentAnnotationAnalyzer<string>();
userAgentAnalyzer.Invoking(u => u.Map("Foo")).Should().Throw<InvalidParserConfigurationException>().Which.Message.Should().StartWith("[Map] The mapper instance is null.");
}
}
}
| 38.493151 | 196 | 0.626335 | [
"Apache-2.0"
] | OrbintSoft/yauaa.netcore | src/OrbintSoft.Yauaa.Testing.NetCore/Tests/Annotate/TestAnnotationBadUsages.cs | 2,812 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.