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 Newtonsoft.Json;
namespace CarMediaServer
{
public interface INetworkNotification
{
/// <summary>
/// Gets the category of this notification.
/// </summary>
[JsonIgnore]
ushort NotificationCategory { get; }
/// <summary>
/// Gets the code for this notification.
/// </summary>
[JsonIgnore]
ushort NotificationCode { get; }
/// <summary>
/// Serialises the notification.
/// </summary>
/// <returns>
/// The notification serialized as a byte array.
/// </returns>
byte[] SerialiseNotification();
}
} | 22.740741 | 51 | 0.581433 | [
"BSD-2-Clause"
] | guytp/carputer-backend | CarMediaServer/NetworkCommands/INetworkNotification.cs | 616 | C# |
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Lime.Protocol.Network;
using Lime.Transport.AspNetCore.Transport;
using Moq;
using NUnit.Framework;
using Shouldly;
using static Lime.Protocol.UnitTests.Dummy;
namespace Lime.Transport.AspNetCore.UnitTests.Transport
{
[TestFixture]
public class SenderChannelAdapterTests : TestsBase
{
[SetUp]
public void SetUp()
{
base.SetUp();
Channel = new Mock<IChannel>();
Transport = new Mock<ITransport>();
Channel
.SetupGet(c => c.Transport)
.Returns(Transport.Object);
}
[TearDown]
public new void TearDown()
{
base.TearDown();
}
private SenderChannelAdapter GetTarget() => new SenderChannelAdapter(Channel.Object);
public Mock<IChannel> Channel { get; private set; }
public Mock<ITransport> Transport { get; private set; }
[Test]
public async Task SendMessageAsync_AnyMessage_ShouldCallChannel()
{
// Arrange
var message = CreateMessage(CreateTextContent());
var target = GetTarget();
// Act
await target.SendMessageAsync(message, CancellationTokenSource.Token);
// Assert
Channel.Verify(c => c.SendMessageAsync(message, CancellationTokenSource.Token), Times.Once());
}
[Test]
public async Task SendNotificationAsync_AnyNotification_ShouldCallChannel()
{
// Arrange
var notification = CreateNotification(Event.Received);
var target = GetTarget();
// Act
await target.SendNotificationAsync(notification, CancellationTokenSource.Token);
// Assert
Channel.Verify(c => c.SendNotificationAsync(notification, CancellationTokenSource.Token), Times.Once());
}
[Test]
public async Task SendCommandAsync_AnyCommand_ShouldCallChannel()
{
// Arrange
var command = CreateCommand(CreatePing());
var target = GetTarget();
// Act
await target.SendCommandAsync(command, CancellationTokenSource.Token);
// Assert
Channel.Verify(c => c.SendCommandAsync(command, CancellationTokenSource.Token), Times.Once());
}
[Test]
public async Task ProcessCommandAsync_AnyCommand_ShouldCallChannel()
{
// Arrange
var requestCommand = CreateCommand(CreatePing());
var responseCommand = CreateCommand(status: CommandStatus.Success);
Channel
.Setup(c => c.ProcessCommandAsync(requestCommand, It.IsAny<CancellationToken>()))
.ReturnsAsync(responseCommand)
.Verifiable();
var target = GetTarget();
// Act
var actual = await target.ProcessCommandAsync(requestCommand, CancellationTokenSource.Token);
// Assert
actual.ShouldBe(responseCommand);
Channel.VerifyAll();
}
}
} | 32.782178 | 116 | 0.576865 | [
"Apache-2.0"
] | JoaoCMotaJr/lime-csharp | src/Lime.Transport.AspNetCore.UnitTests/Transport/SenderChannelAdapterTests.cs | 3,311 | C# |
using System;
using System.Collections.Generic;
namespace CymaticLabs.InfluxDB.Data
{
/// <summary>
/// Represents the result of an InfluxDB query.
/// </summary>
public class InfluxDbSeries
{
#region Fields
// Internal look-up of a column's index given its name
Dictionary<string, int> columnIndexByName;
#endregion Fields
#region Properties
/// <summary>
/// Gets the name of the resulting series.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the list of column names for the result.
/// </summary>
public IList<string> Columns { get; private set; }
/// <summary>
/// Gets the tag results for the query.
/// </summary>
public IDictionary<string, string> Tags { get; private set; }
/// <summary>
/// Gets the values for the query where the first level is the row and the second the columns.
/// </summary>
public IList<IList<object>> Values { get; private set; }
#endregion Properties
#region Constructors
public InfluxDbSeries(string name, IList<string> columns, IDictionary<string, string> tags, IList<IList<object>> values)
{
//if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name");
if (columns == null) throw new ArgumentNullException("columns");
if (tags == null) throw new ArgumentNullException("tags");
if (values == null) throw new ArgumentNullException("values");
Name = name;
Columns = columns;
Tags = tags;
Values = values;
columnIndexByName = new Dictionary<string, int>();
// Cache column name/index look-up
if (columns.Count > 0)
{
for (var i = 0; i < columns.Count; i++)
{
var colName = columns[i];
if (!columnIndexByName.ContainsKey(colName)) columnIndexByName.Add(colName, i);
}
}
}
#endregion Constructors
#region Methods
/// <summary>
/// Gets a column's index in the <see cref="Columns"/> list given its name.
/// </summary>
/// <param name="name">The column name to get the index for.</param>
/// <returns>The column's index in the <see cref="Columns"/> list if found, otherwise -1.</returns>
public int GetColumnIndex(string name)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name");
return columnIndexByName.ContainsKey(name) ? columnIndexByName[name] : -1;
}
#endregion Methods
}
}
| 32.16092 | 128 | 0.569693 | [
"MIT"
] | 573000126/InfluxDBStudio | src/CymaticLabs.InfluxDB.Studio/Data/InfluxDbSeries.cs | 2,800 | C# |
using System.Collections.Generic;
using System.Linq;
using SS3D.Content.Systems.Interactions;
using SS3D.Engine.Interactions;
using SS3D.Engine.Inventory;
using SS3D.Engine.Tile.TileRework;
using SS3D.Engine.Tiles;
using UnityEngine;
namespace SS3D.Content.Items.Functional.Tools.Generic
{
// Needs rework too
public class Wrench : Item
{
public GameObject LoadingBarPrefab;
// nope
public TileObjectSo ObjectToConstruct;
public Direction ObjectDirection;
public float Delay;
public LayerMask ObstacleMask;
public Sprite constructIcon;
public override void GenerateInteractionsFromSource(IInteractionTarget[] targets, List<InteractionEntry> interactions)
{
base.GenerateInteractionsFromSource(targets, interactions);
interactions.Insert(0, new InteractionEntry(targets[0], new ItemConstructionInteraction
{ ObjectToConstruct = ObjectToConstruct,
Delay = Delay,
LoadingBarPrefab = LoadingBarPrefab,
icon = constructIcon,
ObstacleMask = ObstacleMask,
ObjectDirection = ObjectDirection
}));
}
}
} | 32.184211 | 126 | 0.676206 | [
"MIT"
] | TimFinucane/SS3D | Assets/Content/Items/Functional/Tools/Construction/Wrench.cs | 1,225 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNative.Network.V20190901.Inputs
{
/// <summary>
/// An traffic selector policy for a virtual network gateway connection.
/// </summary>
public sealed class TrafficSelectorPolicyArgs : Pulumi.ResourceArgs
{
[Input("localAddressRanges", required: true)]
private InputList<string>? _localAddressRanges;
/// <summary>
/// A collection of local address spaces in CIDR format.
/// </summary>
public InputList<string> LocalAddressRanges
{
get => _localAddressRanges ?? (_localAddressRanges = new InputList<string>());
set => _localAddressRanges = value;
}
[Input("remoteAddressRanges", required: true)]
private InputList<string>? _remoteAddressRanges;
/// <summary>
/// A collection of remote address spaces in CIDR format.
/// </summary>
public InputList<string> RemoteAddressRanges
{
get => _remoteAddressRanges ?? (_remoteAddressRanges = new InputList<string>());
set => _remoteAddressRanges = value;
}
public TrafficSelectorPolicyArgs()
{
}
}
}
| 31.744681 | 92 | 0.642761 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20190901/Inputs/TrafficSelectorPolicyArgs.cs | 1,492 | C# |
using Umbraco.Cms.Infrastructure.Migrations.Expressions.Common;
namespace Umbraco.Cms.Infrastructure.Migrations.Expressions.Create.Index
{
public interface ICreateIndexOnColumnBuilder : IFluentBuilder, IExecutableBuilder
{
/// <summary>
/// Specifies the index column.
/// </summary>
ICreateIndexColumnOptionsBuilder OnColumn(string columnName);
/// <summary>
/// Specifies options.
/// </summary>
ICreateIndexOptionsBuilder WithOptions();
}
}
| 29.055556 | 85 | 0.678776 | [
"MIT"
] | Ambertvu/Umbraco-CMS | src/Umbraco.Infrastructure/Migrations/Expressions/Create/Index/ICreateIndexOnColumnBuilder.cs | 525 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using NUnit.Framework;
using Python.Runtime;
using PyRuntime = Python.Runtime.Runtime;
//
// This test case is disabled on .NET Standard because it doesn't have all the
// APIs we use. We could work around that, but .NET Core doesn't implement
// domain creation, so it's not worth it.
//
// Unfortunately this means no continuous integration testing for this case.
//
#if NETFRAMEWORK
namespace Python.EmbeddingTest
{
class TestDomainReload
{
abstract class CrossCaller : MarshalByRefObject
{
public abstract ValueType Execute(ValueType arg);
}
/// <summary>
/// Test that the python runtime can survive a C# domain reload without crashing.
///
/// At the time this test was written, there was a very annoying
/// seemingly random crash bug when integrating pythonnet into Unity.
///
/// The repro steps that David Lassonde, Viktoria Kovecses and
/// Benoit Hudson eventually worked out:
/// 1. Write a HelloWorld.cs script that uses Python.Runtime to access
/// some C# data from python: C# calls python, which calls C#.
/// 2. Execute the script (e.g. make it a MenuItem and click it).
/// 3. Touch HelloWorld.cs on disk, forcing Unity to recompile scripts.
/// 4. Wait several seconds for Unity to be done recompiling and
/// reloading the C# domain.
/// 5. Make python run the gc (e.g. by calling gc.collect()).
///
/// The reason:
/// A. In step 2, Python.Runtime registers a bunch of new types with
/// their tp_traverse slot pointing to managed code, and allocates
/// some objects of those types.
/// B. In step 4, Unity unloads the C# domain. That frees the managed
/// code. But at the time of the crash investigation, pythonnet
/// leaked the python side of the objects allocated in step 1.
/// C. In step 5, python sees some pythonnet objects in its gc list of
/// potentially-leaked objects. It calls tp_traverse on those objects.
/// But tp_traverse was freed in step 3 => CRASH.
///
/// This test distills what's going on without needing Unity around (we'd see
/// similar behaviour if we were using pythonnet on a .NET web server that did
/// a hot reload).
/// </summary>
[Test]
public static void DomainReloadAndGC()
{
Assert.IsFalse(PythonEngine.IsInitialized);
RunAssemblyAndUnload("test1");
Assert.That(PyRuntime.Py_IsInitialized() != 0,
"On soft-shutdown mode, Python runtime should still running");
RunAssemblyAndUnload("test2");
Assert.That(PyRuntime.Py_IsInitialized() != 0,
"On soft-shutdown mode, Python runtime should still running");
}
#region CrossDomainObject
class CrossDomainObjectStep1 : CrossCaller
{
public override ValueType Execute(ValueType arg)
{
try
{
// Create a C# user-defined object in Python. Asssing some values.
Type type = typeof(Python.EmbeddingTest.Domain.MyClass);
string code = string.Format(@"
import clr
clr.AddReference('{0}')
from Python.EmbeddingTest.Domain import MyClass
obj = MyClass()
obj.Method()
obj.StaticMethod()
obj.Property = 1
obj.Field = 10
", Assembly.GetExecutingAssembly().FullName);
using (Py.GIL())
using (var scope = Py.CreateScope())
{
scope.Exec(code);
using (PyObject obj = scope.Get("obj"))
{
Debug.Assert(obj.AsManagedObject(type).GetType() == type);
// We only needs its Python handle
PyRuntime.XIncref(obj);
return obj.Handle;
}
}
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
}
}
class CrossDomainObjectStep2 : CrossCaller
{
public override ValueType Execute(ValueType arg)
{
// handle refering a clr object created in previous domain,
// it should had been deserialized and became callable agian.
using var handle = NewReference.DangerousFromPointer((IntPtr)arg);
try
{
using (Py.GIL())
{
BorrowedReference tp = Runtime.Runtime.PyObject_TYPE(handle.Borrow());
IntPtr tp_clear = Util.ReadIntPtr(tp, TypeOffset.tp_clear);
Assert.That(tp_clear, Is.Not.Null);
using (PyObject obj = new PyObject(handle.Steal()))
{
obj.InvokeMethod("Method");
obj.InvokeMethod("StaticMethod");
using (var scope = Py.CreateScope())
{
scope.Set("obj", obj);
scope.Exec(@"
obj.Method()
obj.StaticMethod()
obj.Property += 1
obj.Field += 10
");
}
var clrObj = obj.As<Domain.MyClass>();
Assert.AreEqual(clrObj.Property, 2);
Assert.AreEqual(clrObj.Field, 20);
}
}
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
return 0;
}
}
/// <summary>
/// Create a C# custom object in a domain, in python code.
/// Unload the domain, create a new domain.
/// Make sure the C# custom object created in the previous domain has been re-created
/// </summary>
[Test]
public static void CrossDomainObject()
{
RunDomainReloadSteps<CrossDomainObjectStep1, CrossDomainObjectStep2>();
}
#endregion
/// <summary>
/// This is a magic incantation required to run code in an application
/// domain other than the current one.
/// </summary>
class Proxy : MarshalByRefObject
{
public void RunPython()
{
Console.WriteLine("[Proxy] Entering RunPython");
PythonRunner.RunPython();
Console.WriteLine("[Proxy] Leaving RunPython");
}
public object Call(string methodName, params object[] args)
{
var pythonrunner = typeof(PythonRunner);
var method = pythonrunner.GetMethod(methodName);
return method.Invoke(null, args);
}
}
static T CreateInstanceInstanceAndUnwrap<T>(AppDomain domain)
{
Type type = typeof(T);
var theProxy = (T)domain.CreateInstanceAndUnwrap(
type.Assembly.FullName,
type.FullName);
return theProxy;
}
/// <summary>
/// Create a domain, run the assembly in it (the RunPython function),
/// and unload the domain.
/// </summary>
static void RunAssemblyAndUnload(string domainName)
{
Console.WriteLine($"[Program.Main] === creating domain {domainName}");
AppDomain domain = CreateDomain(domainName);
// Create a Proxy object in the new domain, where we want the
// assembly (and Python .NET) to reside
var theProxy = CreateInstanceInstanceAndUnwrap<Proxy>(domain);
theProxy.Call(nameof(PythonRunner.InitPython), PyRuntime.PythonDLL);
// From now on use the Proxy to call into the new assembly
theProxy.RunPython();
theProxy.Call("ShutdownPython");
Console.WriteLine($"[Program.Main] Before Domain Unload on {domainName}");
AppDomain.Unload(domain);
Console.WriteLine($"[Program.Main] After Domain Unload on {domainName}");
// Validate that the assembly does not exist anymore
try
{
Console.WriteLine($"[Program.Main] The Proxy object is valid ({theProxy}). Unexpected domain unload behavior");
Assert.Fail($"{theProxy} should be invlaid now");
}
catch (AppDomainUnloadedException)
{
Console.WriteLine("[Program.Main] The Proxy object is not valid anymore, domain unload complete.");
}
}
private static AppDomain CreateDomain(string name)
{
// Create the domain. Make sure to set PrivateBinPath to a relative
// path from the CWD (namely, 'bin').
// See https://stackoverflow.com/questions/24760543/createinstanceandunwrap-in-another-domain
var currentDomain = AppDomain.CurrentDomain;
var domainsetup = new AppDomainSetup()
{
ApplicationBase = currentDomain.SetupInformation.ApplicationBase,
ConfigurationFile = currentDomain.SetupInformation.ConfigurationFile,
LoaderOptimization = LoaderOptimization.SingleDomain,
PrivateBinPath = "."
};
var domain = AppDomain.CreateDomain(
$"My Domain {name}",
currentDomain.Evidence,
domainsetup);
return domain;
}
/// <summary>
/// Resolves the assembly. Why doesn't this just work normally?
/// </summary>
static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in loadedAssemblies)
{
if (assembly.FullName == args.Name)
{
return assembly;
}
}
return null;
}
static void RunDomainReloadSteps<T1, T2>() where T1 : CrossCaller where T2 : CrossCaller
{
ValueType arg = null;
Type type = typeof(Proxy);
{
AppDomain domain = CreateDomain("test_domain_reload_1");
try
{
var theProxy = CreateInstanceInstanceAndUnwrap<Proxy>(domain);
theProxy.Call(nameof(PythonRunner.InitPython), PyRuntime.PythonDLL);
var caller = CreateInstanceInstanceAndUnwrap<T1>(domain);
arg = caller.Execute(arg);
theProxy.Call("ShutdownPython");
}
finally
{
AppDomain.Unload(domain);
}
}
{
AppDomain domain = CreateDomain("test_domain_reload_2");
try
{
var theProxy = CreateInstanceInstanceAndUnwrap<Proxy>(domain);
theProxy.Call(nameof(PythonRunner.InitPython), PyRuntime.PythonDLL);
var caller = CreateInstanceInstanceAndUnwrap<T2>(domain);
caller.Execute(arg);
theProxy.Call("ShutdownPythonCompletely");
}
finally
{
AppDomain.Unload(domain);
}
}
Assert.IsTrue(PyRuntime.Py_IsInitialized() != 0);
}
}
//
// The code we'll test. All that really matters is
// using GIL { Python.Exec(pyScript); }
// but the rest is useful for debugging.
//
// What matters in the python code is gc.collect and clr.AddReference.
//
// Note that the language version is 2.0, so no $"foo{bar}" syntax.
//
static class PythonRunner
{
public static void RunPython()
{
AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;
string name = AppDomain.CurrentDomain.FriendlyName;
Console.WriteLine("[{0} in .NET] In PythonRunner.RunPython", name);
using (Py.GIL())
{
try
{
var pyScript = string.Format("import clr\n"
+ "print('[{0} in python] imported clr')\n"
+ "clr.AddReference('System')\n"
+ "print('[{0} in python] allocated a clr object')\n"
+ "import gc\n"
+ "gc.collect()\n"
+ "print('[{0} in python] collected garbage')\n",
name);
PythonEngine.Exec(pyScript);
}
catch (Exception e)
{
Console.WriteLine(string.Format("[{0} in .NET] Caught exception: {1}", name, e));
throw;
}
}
}
private static IntPtr _state;
public static void InitPython(string dllName)
{
PyRuntime.PythonDLL = dllName;
PythonEngine.Initialize();
_state = PythonEngine.BeginAllowThreads();
}
public static void ShutdownPython()
{
PythonEngine.EndAllowThreads(_state);
PythonEngine.Shutdown();
}
public static void ShutdownPythonCompletely()
{
PythonEngine.EndAllowThreads(_state);
PythonEngine.Shutdown();
}
static void OnDomainUnload(object sender, EventArgs e)
{
Console.WriteLine(string.Format("[{0} in .NET] unloading", AppDomain.CurrentDomain.FriendlyName));
}
}
}
namespace Python.EmbeddingTest.Domain
{
[Serializable]
public class MyClass
{
public int Property { get; set; }
public int Field;
public void Method() { }
public static void StaticMethod() { }
}
}
#endif
| 35.928218 | 127 | 0.530899 | [
"MIT"
] | L-Net-1992/pythonnet | src/embed_tests/TestDomainReload.cs | 14,515 | C# |
/*
* LUSID API
*
* # Introduction This page documents the [LUSID APIs](https://www.lusid.com/api/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages and frameworks: * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) * [Angular](https://github.com/finbourne/lusid-sdk-angular) # Data Model The LUSID API has a relatively lightweight but extremely powerful data model. One of the goals of LUSID was not to enforce on clients a single rigid data model but rather to provide a flexible foundation onto which clients can map their own data models. The core entities in LUSID provide a minimal structure and set of relationships, and the data model can be extended using Properties. The LUSID data model is exposed through the LUSID APIs. The APIs provide access to both business objects and the meta data used to configure the systems behaviours. The key business entities are: - * **Portfolios** A portfolio is a container for transactions and holdings (a **Transaction Portfolio**) or constituents (a **Reference Portfolio**). * **Derived Portfolios**. Derived Portfolios allow Portfolios to be created based on other Portfolios, by overriding or adding specific items. * **Holdings** A Holding is a quantity of an Instrument or a balance of cash within a Portfolio. Holdings can only be adjusted via Transactions. * **Transactions** A Transaction is an economic event that occurs in a Portfolio, causing its holdings to change. * **Corporate Actions** A corporate action is a market event which occurs to an Instrument and thus applies to all portfolios which holding the instrument. Examples are stock splits or mergers. * **Constituents** A constituent is a record in a Reference Portfolio containing an Instrument and an associated weight. * **Instruments** An instrument represents a currency, tradable instrument or OTC contract that is attached to a transaction and a holding. * **Properties** All major entities allow additional user defined properties to be associated with them. For example, a Portfolio manager may be associated with a portfolio. Meta data includes: - * **Transaction Types** Transactions are booked with a specific transaction type. The types are client defined and are used to map the Transaction to a series of movements which update the portfolio holdings. * **Properties Types** Types of user defined properties used within the system. ## Scope All data in LUSID is segregated at the client level. Entities in LUSID are identifiable by a unique code. Every entity lives within a logical data partition known as a Scope. Scope is an identity namespace allowing two entities with the same unique code to co-exist within individual address spaces. For example, prices for equities from different vendors may be uploaded into different scopes such as `client/vendor1` and `client/vendor2`. A portfolio may then be valued using either of the price sources by referencing the appropriate scope. LUSID Clients cannot access scopes of other clients. ## Instruments LUSID has its own built-in instrument master which you can use to master your own instrument universe. Every instrument must be created with one or more unique market identifiers, such as [FIGI](https://openfigi.com/). For any non-listed instruments (eg OTCs), you can upload an instrument against a custom ID of your choosing. In addition, LUSID will allocate each instrument a unique 'LUSID instrument identifier'. The LUSID instrument identifier is what is used when uploading transactions, holdings, prices, etc. The API exposes an `instrument/lookup` endpoint which can be used to lookup these LUSID identifiers using their market identifiers. Cash can be referenced using the ISO currency code prefixed with \"`CCY_`\" e.g. `CCY_GBP` ## Instrument Data Instrument data can be uploaded to the system using the [Instrument Properties](#operation/UpsertInstrumentsProperties) endpoint. | Field|Type|Description | | - --|- --|- -- | | Key|propertykey|The key of the property. This takes the format {domain}/{scope}/{code} e.g. 'Instrument/system/Name' or 'Transaction/strategy/quantsignal'. | | Value|string|The value of the property. | | EffectiveFrom|datetimeoffset|The effective datetime from which the property is valid. | | EffectiveUntil|datetimeoffset|The effective datetime until which the property is valid. If not supplied this will be valid indefinitely, or until the next 'effectiveFrom' datetime of the property. | ## Transaction Portfolios Portfolios are the top-level entity containers within LUSID, containing transactions, corporate actions and holdings. The transactions build up the portfolio holdings on which valuations, analytics profit & loss and risk can be calculated. Properties can be associated with Portfolios to add in additional data. Portfolio properties can be changed over time, for example to allow a Portfolio Manager to be linked with a Portfolio. Additionally, portfolios can be securitised and held by other portfolios, allowing LUSID to perform \"drill-through\" into underlying fund holdings ### Derived Portfolios LUSID also allows for a portfolio to be composed of another portfolio via derived portfolios. A derived portfolio can contain its own transactions and also inherits any transactions from its parent portfolio. Any changes made to the parent portfolio are automatically reflected in derived portfolio. Derived portfolios in conjunction with scopes are a powerful construct. For example, to do pre-trade what-if analysis, a derived portfolio could be created a new namespace linked to the underlying live (parent) portfolio. Analysis can then be undertaken on the derived portfolio without affecting the live portfolio. ### Transactions A transaction represents an economic activity against a Portfolio. Transactions are processed according to a configuration. This will tell the LUSID engine how to interpret the transaction and correctly update the holdings. LUSID comes with a set of transaction types you can use out of the box, or you can configure your own set(s) of transactions. For more details see the [LUSID Getting Started Guide for transaction configuration.](https://support.lusid.com/configuring-transaction-types) | Field|Type|Description | | - --|- --|- -- | | TransactionId|string|The unique identifier for the transaction. | | Type|string|The type of the transaction e.g. 'Buy', 'Sell'. The transaction type should have been pre-configured via the System Configuration API endpoint. If it hasn't been pre-configured the transaction will still be updated or inserted however you will be unable to generate the resultant holdings for the portfolio that contains this transaction as LUSID does not know how to process it. | | InstrumentIdentifiers|map|A set of instrument identifiers to use to resolve the transaction to a unique instrument. | | TransactionDate|dateorcutlabel|The date of the transaction. | | SettlementDate|dateorcutlabel|The settlement date of the transaction. | | Units|decimal|The number of units transacted in the associated instrument. | | TransactionPrice|transactionprice|The price for each unit of the transacted instrument in the transaction currency. | | TotalConsideration|currencyandamount|The total value of the transaction in the settlement currency. | | ExchangeRate|decimal|The exchange rate between the transaction and settlement currency (settlement currency being represented by the TotalConsideration.Currency). For example if the transaction currency is in USD and the settlement currency is in GBP this this the USD/GBP rate. | | TransactionCurrency|currency|The transaction currency. | | Properties|map|Set of unique transaction properties and associated values to store with the transaction. Each property must be from the 'Transaction' domain. | | CounterpartyId|string|The identifier for the counterparty of the transaction. | | Source|string|The source of the transaction. This is used to look up the appropriate transaction group set in the transaction type configuration. | From these fields, the following values can be calculated * **Transaction value in Transaction currency**: TotalConsideration / ExchangeRate * **Transaction value in Portfolio currency**: Transaction value in Transaction currency * TradeToPortfolioRate #### Example Transactions ##### A Common Purchase Example Three example transactions are shown in the table below. They represent a purchase of USD denominated IBM shares within a Sterling denominated portfolio. * The first two transactions are for separate buy and fx trades * Buying 500 IBM shares for $71,480.00 * A spot foreign exchange conversion to fund the IBM purchase. (Buy $71,480.00 for £54,846.60) * The third transaction is an alternate version of the above trades. Buying 500 IBM shares and settling directly in Sterling. | Column | Buy Trade | Fx Trade | Buy Trade with foreign Settlement | | - -- -- | - -- -- | - -- -- | - -- -- | | TransactionId | FBN00001 | FBN00002 | FBN00003 | | Type | Buy | FxBuy | Buy | | InstrumentIdentifiers | { \"figi\", \"BBG000BLNNH6\" } | { \"CCY\", \"CCY_USD\" } | { \"figi\", \"BBG000BLNNH6\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | 2018-08-02 | | SettlementDate | 2018-08-06 | 2018-08-06 | 2018-08-06 | | Units | 500 | 71480 | 500 | | TransactionPrice | 142.96 | 1 | 142.96 | | TradeCurrency | USD | USD | USD | | ExchangeRate | 1 | 0.7673 | 0.7673 | | TotalConsideration.Amount | 71480.00 | 54846.60 | 54846.60 | | TotalConsideration.Currency | USD | GBP | GBP | | Trade/default/TradeToPortfolioRate* | 0.7673 | 0.7673 | 0.7673 | [* This is a property field] ##### A Forward FX Example LUSID has a flexible transaction modelling system, meaning there are a number of different ways of modelling forward fx trades. The default LUSID transaction types are FwdFxBuy and FwdFxSell. Using these transaction types, LUSID will generate two holdings for each Forward FX trade, one for each currency in the trade. An example Forward Fx trade to sell GBP for USD in a JPY-denominated portfolio is shown below: | Column | Forward 'Sell' Trade | Notes | | - -- -- | - -- -- | - -- - | | TransactionId | FBN00004 | | | Type | FwdFxSell | | | InstrumentIdentifiers | { \"Instrument/default/Currency\", \"GBP\" } | | | TransactionDate | 2018-08-02 | | | SettlementDate | 2019-02-06 | Six month forward | | Units | 10000.00 | Units of GBP | | TransactionPrice | 1 | | | TradeCurrency | GBP | Currency being sold | | ExchangeRate | 1.3142 | Agreed rate between GBP and USD | | TotalConsideration.Amount | 13142.00 | Amount in the settlement currency, USD | | TotalConsideration.Currency | USD | Settlement currency | | Trade/default/TradeToPortfolioRate | 142.88 | Rate between trade currency, GBP and portfolio base currency, JPY | Please note that exactly the same economic behaviour could be modelled using the FwdFxBuy Transaction Type with the amounts and rates reversed. ### Holdings A holding represents a position in an instrument or cash on a given date. | Field|Type|Description | | - --|- --|- -- | | InstrumentUid|string|The unqiue Lusid Instrument Id (LUID) of the instrument that the holding is in. | | SubHoldingKeys|map|The sub-holding properties which identify the holding. Each property will be from the 'Transaction' domain. These are configured when a transaction portfolio is created. | | Properties|map|The properties which have been requested to be decorated onto the holding. These will be from the 'Instrument' or 'Holding' domain. | | HoldingType|string|The type of the holding e.g. Position, Balance, CashCommitment, Receivable, ForwardFX etc. | | Units|decimal|The total number of units of the holding. | | SettledUnits|decimal|The total number of settled units of the holding. | | Cost|currencyandamount|The total cost of the holding in the transaction currency. | | CostPortfolioCcy|currencyandamount|The total cost of the holding in the portfolio currency. | | Transaction|transaction|The transaction associated with an unsettled holding. | | Currency|currency|The holding currency. | ## Corporate Actions Corporate actions are represented within LUSID in terms of a set of instrument-specific 'transitions'. These transitions are used to specify the participants of the corporate action, and the effect that the corporate action will have on holdings in those participants. ### Corporate Action | Field|Type|Description | | - --|- --|- -- | | CorporateActionCode|code|The unique identifier of this corporate action | | Description|string| | | AnnouncementDate|datetimeoffset|The announcement date of the corporate action | | ExDate|datetimeoffset|The ex date of the corporate action | | RecordDate|datetimeoffset|The record date of the corporate action | | PaymentDate|datetimeoffset|The payment date of the corporate action | | Transitions|corporateactiontransition[]|The transitions that result from this corporate action | ### Transition | Field|Type|Description | | - --|- --|- -- | | InputTransition|corporateactiontransitioncomponent|Indicating the basis of the corporate action - which security and how many units | | OutputTransitions|corporateactiontransitioncomponent[]|What will be generated relative to the input transition | ### Example Corporate Action Transitions #### A Dividend Action Transition In this example, for each share of IBM, 0.20 units (or 20 pence) of GBP are generated. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"ccy\" : \"CCY_GBP\" } | | Units Factor | 1 | 0.20 | | Cost Factor | 1 | 0 | #### A Split Action Transition In this example, for each share of IBM, we end up with 2 units (2 shares) of IBM, with total value unchanged. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | | Units Factor | 1 | 2 | | Cost Factor | 1 | 1 | #### A Spinoff Action Transition In this example, for each share of IBM, we end up with 1 unit (1 share) of IBM and 3 units (3 shares) of Celestica, with 85% of the value remaining on the IBM share, and 5% in each Celestica share (15% total). | Column | Input Transition | Output Transition 1 | Output Transition 2 | | - -- -- | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000HBGRF3\" } | | Units Factor | 1 | 1 | 3 | | Cost Factor | 1 | 0.85 | 0.15 | ## Reference Portfolios Reference portfolios are portfolios that contain constituents with weights. They are designed to represent entities such as indices and benchmarks. ### Constituents | Field|Type|Description | | - --|- --|- -- | | InstrumentIdentifiers|map|Unique instrument identifiers | | InstrumentUid|string|LUSID's internal unique instrument identifier, resolved from the instrument identifiers | | Currency|decimal| | | Weight|decimal| | | FloatingWeight|decimal| | ## Portfolio Groups Portfolio groups allow the construction of a hierarchy from portfolios and groups. Portfolio operations on the group are executed on an aggregated set of portfolios in the hierarchy. For example: * Global Portfolios _(group)_ * APAC _(group)_ * Hong Kong _(portfolio)_ * Japan _(portfolio)_ * Europe _(group)_ * France _(portfolio)_ * Germany _(portfolio)_ * UK _(portfolio)_ In this example **Global Portfolios** is a group that consists of an aggregate of **Hong Kong**, **Japan**, **France**, **Germany** and **UK** portfolios. ## Properties Properties are key-value pairs that can be applied to any entity within a domain (where a domain is `trade`, `portfolio`, `security` etc). Properties must be defined before use with a `PropertyDefinition` and can then subsequently be added to entities. ## Schema A detailed description of the entities used by the API and parameters for endpoints which take a JSON document can be retrieved via the `schema` endpoint. ## Meta data The following headers are returned on all responses from LUSID | Name | Purpose | | - -- | - -- | | lusid-meta-duration | Duration of the request | | lusid-meta-success | Whether or not LUSID considered the request to be successful | | lusid-meta-requestId | The unique identifier for the request | | lusid-schema-url | Url of the schema for the data being returned | | lusid-property-schema-url | Url of the schema for any properties | # Error Codes | Code|Name|Description | | - --|- --|- -- | | <a name=\"-10\">-10</a>|Server Configuration Error| | | <a name=\"-1\">-1</a>|Unknown error|An unexpected error was encountered on our side. | | <a name=\"102\">102</a>|Version Not Found| | | <a name=\"103\">103</a>|Api Rate Limit Violation| | | <a name=\"104\">104</a>|Instrument Not Found| | | <a name=\"105\">105</a>|Property Not Found| | | <a name=\"106\">106</a>|Portfolio Recursion Depth| | | <a name=\"108\">108</a>|Group Not Found| | | <a name=\"109\">109</a>|Portfolio Not Found| | | <a name=\"110\">110</a>|Property Schema Not Found| | | <a name=\"111\">111</a>|Portfolio Ancestry Not Found| | | <a name=\"112\">112</a>|Portfolio With Id Already Exists| | | <a name=\"113\">113</a>|Orphaned Portfolio| | | <a name=\"119\">119</a>|Missing Base Claims| | | <a name=\"121\">121</a>|Property Not Defined| | | <a name=\"122\">122</a>|Cannot Delete System Property| | | <a name=\"123\">123</a>|Cannot Modify Immutable Property Field| | | <a name=\"124\">124</a>|Property Already Exists| | | <a name=\"125\">125</a>|Invalid Property Life Time| | | <a name=\"126\">126</a>|Property Constraint Style Excludes Properties| | | <a name=\"127\">127</a>|Cannot Modify Default Data Type| | | <a name=\"128\">128</a>|Group Already Exists| | | <a name=\"129\">129</a>|No Such Data Type| | | <a name=\"130\">130</a>|Undefined Value For Data Type| | | <a name=\"131\">131</a>|Unsupported Value Type Defined On Data Type| | | <a name=\"132\">132</a>|Validation Error| | | <a name=\"133\">133</a>|Loop Detected In Group Hierarchy| | | <a name=\"134\">134</a>|Undefined Acceptable Values| | | <a name=\"135\">135</a>|Sub Group Already Exists| | | <a name=\"138\">138</a>|Price Source Not Found| | | <a name=\"139\">139</a>|Analytic Store Not Found| | | <a name=\"141\">141</a>|Analytic Store Already Exists| | | <a name=\"143\">143</a>|Client Instrument Already Exists| | | <a name=\"144\">144</a>|Duplicate In Parameter Set| | | <a name=\"147\">147</a>|Results Not Found| | | <a name=\"148\">148</a>|Order Field Not In Result Set| | | <a name=\"149\">149</a>|Operation Failed| | | <a name=\"150\">150</a>|Elastic Search Error| | | <a name=\"151\">151</a>|Invalid Parameter Value| | | <a name=\"153\">153</a>|Command Processing Failure| | | <a name=\"154\">154</a>|Entity State Construction Failure| | | <a name=\"155\">155</a>|Entity Timeline Does Not Exist| | | <a name=\"156\">156</a>|Concurrency Conflict Failure| | | <a name=\"157\">157</a>|Invalid Request| | | <a name=\"158\">158</a>|Event Publish Unknown| | | <a name=\"159\">159</a>|Event Query Failure| | | <a name=\"160\">160</a>|Blob Did Not Exist| | | <a name=\"162\">162</a>|Sub System Request Failure| | | <a name=\"163\">163</a>|Sub System Configuration Failure| | | <a name=\"165\">165</a>|Failed To Delete| | | <a name=\"166\">166</a>|Upsert Client Instrument Failure| | | <a name=\"167\">167</a>|Illegal As At Interval| | | <a name=\"168\">168</a>|Illegal Bitemporal Query| | | <a name=\"169\">169</a>|Invalid Alternate Id| | | <a name=\"170\">170</a>|Cannot Add Source Portfolio Property Explicitly| | | <a name=\"171\">171</a>|Entity Already Exists In Group| | | <a name=\"173\">173</a>|Entity With Id Already Exists| | | <a name=\"174\">174</a>|Derived Portfolio Details Do Not Exist| | | <a name=\"176\">176</a>|Portfolio With Name Already Exists| | | <a name=\"177\">177</a>|Invalid Transactions| | | <a name=\"178\">178</a>|Reference Portfolio Not Found| | | <a name=\"179\">179</a>|Duplicate Id| | | <a name=\"180\">180</a>|Command Retrieval Failure| | | <a name=\"181\">181</a>|Data Filter Application Failure| | | <a name=\"182\">182</a>|Search Failed| | | <a name=\"183\">183</a>|Movements Engine Configuration Key Failure| | | <a name=\"184\">184</a>|Fx Rate Source Not Found| | | <a name=\"185\">185</a>|Accrual Source Not Found| | | <a name=\"186\">186</a>|Access Denied| | | <a name=\"187\">187</a>|Invalid Identity Token| | | <a name=\"188\">188</a>|Invalid Request Headers| | | <a name=\"189\">189</a>|Price Not Found| | | <a name=\"190\">190</a>|Invalid Sub Holding Keys Provided| | | <a name=\"191\">191</a>|Duplicate Sub Holding Keys Provided| | | <a name=\"192\">192</a>|Cut Definition Not Found| | | <a name=\"193\">193</a>|Cut Definition Invalid| | | <a name=\"194\">194</a>|Time Variant Property Deletion Date Unspecified| | | <a name=\"195\">195</a>|Perpetual Property Deletion Date Specified| | | <a name=\"196\">196</a>|Time Variant Property Upsert Date Unspecified| | | <a name=\"197\">197</a>|Perpetual Property Upsert Date Specified| | | <a name=\"200\">200</a>|Invalid Unit For Data Type| | | <a name=\"201\">201</a>|Invalid Type For Data Type| | | <a name=\"202\">202</a>|Invalid Value For Data Type| | | <a name=\"203\">203</a>|Unit Not Defined For Data Type| | | <a name=\"204\">204</a>|Units Not Supported On Data Type| | | <a name=\"205\">205</a>|Cannot Specify Units On Data Type| | | <a name=\"206\">206</a>|Unit Schema Inconsistent With Data Type| | | <a name=\"207\">207</a>|Unit Definition Not Specified| | | <a name=\"208\">208</a>|Duplicate Unit Definitions Specified| | | <a name=\"209\">209</a>|Invalid Units Definition| | | <a name=\"210\">210</a>|Invalid Instrument Identifier Unit| | | <a name=\"211\">211</a>|Holdings Adjustment Does Not Exist| | | <a name=\"212\">212</a>|Could Not Build Excel Url| | | <a name=\"213\">213</a>|Could Not Get Excel Version| | | <a name=\"214\">214</a>|Instrument By Code Not Found| | | <a name=\"215\">215</a>|Entity Schema Does Not Exist| | | <a name=\"216\">216</a>|Feature Not Supported On Portfolio Type| | | <a name=\"217\">217</a>|Quote Not Found| | | <a name=\"218\">218</a>|Invalid Quote Identifier| | | <a name=\"219\">219</a>|Invalid Metric For Data Type| | | <a name=\"220\">220</a>|Invalid Instrument Definition| | | <a name=\"221\">221</a>|Instrument Upsert Failure| | | <a name=\"222\">222</a>|Reference Portfolio Request Not Supported| | | <a name=\"223\">223</a>|Transaction Portfolio Request Not Supported| | | <a name=\"224\">224</a>|Invalid Property Value Assignment| | | <a name=\"230\">230</a>|Transaction Type Not Found| | | <a name=\"231\">231</a>|Transaction Type Duplication| | | <a name=\"232\">232</a>|Portfolio Does Not Exist At Given Date| | | <a name=\"233\">233</a>|Query Parser Failure| | | <a name=\"234\">234</a>|Duplicate Constituent| | | <a name=\"235\">235</a>|Unresolved Instrument Constituent| | | <a name=\"236\">236</a>|Unresolved Instrument In Transition| | | <a name=\"237\">237</a>|Missing Side Definitions| | | <a name=\"299\">299</a>|Invalid Recipe| | | <a name=\"300\">300</a>|Missing Recipe| | | <a name=\"301\">301</a>|Dependencies| | | <a name=\"304\">304</a>|Portfolio Preprocess Failure| | | <a name=\"310\">310</a>|Valuation Engine Failure| | | <a name=\"311\">311</a>|Task Factory Failure| | | <a name=\"312\">312</a>|Task Evaluation Failure| | | <a name=\"313\">313</a>|Task Generation Failure| | | <a name=\"314\">314</a>|Engine Configuration Failure| | | <a name=\"315\">315</a>|Model Specification Failure| | | <a name=\"320\">320</a>|Market Data Key Failure| | | <a name=\"321\">321</a>|Market Resolver Failure| | | <a name=\"322\">322</a>|Market Data Failure| | | <a name=\"330\">330</a>|Curve Failure| | | <a name=\"331\">331</a>|Volatility Surface Failure| | | <a name=\"332\">332</a>|Volatility Cube Failure| | | <a name=\"350\">350</a>|Instrument Failure| | | <a name=\"351\">351</a>|Cash Flows Failure| | | <a name=\"352\">352</a>|Reference Data Failure| | | <a name=\"360\">360</a>|Aggregation Failure| | | <a name=\"361\">361</a>|Aggregation Measure Failure| | | <a name=\"370\">370</a>|Result Retrieval Failure| | | <a name=\"371\">371</a>|Result Processing Failure| | | <a name=\"372\">372</a>|Vendor Result Processing Failure| | | <a name=\"373\">373</a>|Vendor Result Mapping Failure| | | <a name=\"374\">374</a>|Vendor Library Unauthorised| | | <a name=\"375\">375</a>|Vendor Connectivity Error| | | <a name=\"376\">376</a>|Vendor Interface Error| | | <a name=\"377\">377</a>|Vendor Pricing Failure| | | <a name=\"378\">378</a>|Vendor Translation Failure| | | <a name=\"379\">379</a>|Vendor Key Mapping Failure| | | <a name=\"380\">380</a>|Vendor Reflection Failure| | | <a name=\"390\">390</a>|Attempt To Upsert Duplicate Quotes| | | <a name=\"391\">391</a>|Corporate Action Source Does Not Exist| | | <a name=\"392\">392</a>|Corporate Action Source Already Exists| | | <a name=\"393\">393</a>|Instrument Identifier Already In Use| | | <a name=\"394\">394</a>|Properties Not Found| | | <a name=\"395\">395</a>|Batch Operation Aborted| | | <a name=\"400\">400</a>|Invalid Iso4217 Currency Code| | | <a name=\"401\">401</a>|Cannot Assign Instrument Identifier To Currency| | | <a name=\"402\">402</a>|Cannot Assign Currency Identifier To Non Currency| | | <a name=\"403\">403</a>|Currency Instrument Cannot Be Deleted| | | <a name=\"404\">404</a>|Currency Instrument Cannot Have Economic Definition| | | <a name=\"405\">405</a>|Currency Instrument Cannot Have Lookthrough Portfolio| | | <a name=\"406\">406</a>|Cannot Create Currency Instrument With Multiple Identifiers| | | <a name=\"407\">407</a>|Specified Currency Is Undefined| | | <a name=\"410\">410</a>|Index Does Not Exist| | | <a name=\"411\">411</a>|Sort Field Does Not Exist| | | <a name=\"413\">413</a>|Negative Pagination Parameters| | | <a name=\"414\">414</a>|Invalid Search Syntax| | | <a name=\"415\">415</a>|Filter Execution Timeout| | | <a name=\"420\">420</a>|Side Definition Inconsistent| | | <a name=\"450\">450</a>|Invalid Quote Access Metadata Rule| | | <a name=\"451\">451</a>|Access Metadata Not Found| | | <a name=\"452\">452</a>|Invalid Access Metadata Identifier| | | <a name=\"460\">460</a>|Standard Resource Not Found| | | <a name=\"461\">461</a>|Standard Resource Conflict| | | <a name=\"462\">462</a>|Calendar Not Found| | | <a name=\"463\">463</a>|Date In A Calendar Not Found| | | <a name=\"464\">464</a>|Invalid Date Source Data| | | <a name=\"465\">465</a>|Invalid Timezone| | | <a name=\"601\">601</a>|Person Identifier Already In Use| | | <a name=\"602\">602</a>|Person Not Found| | | <a name=\"603\">603</a>|Cannot Set Identifier| | | <a name=\"617\">617</a>|Invalid Recipe Specification In Request| | | <a name=\"618\">618</a>|Inline Recipe Deserialisation Failure| | | <a name=\"619\">619</a>|Identifier Types Not Set For Entity| | | <a name=\"620\">620</a>|Cannot Delete All Client Defined Identifiers| | | <a name=\"650\">650</a>|The Order requested was not found.| | | <a name=\"654\">654</a>|The Allocation requested was not found.| | | <a name=\"655\">655</a>|Cannot build the fx forward target with the given holdings.| | | <a name=\"656\">656</a>|Group does not contain expected entities.| | | <a name=\"667\">667</a>|Relation definition already exists| | | <a name=\"673\">673</a>|Missing entitlements for entities in Group| | | <a name=\"674\">674</a>|Next Best Action not found| | | <a name=\"676\">676</a>|Relation definition not defined| | | <a name=\"677\">677</a>|Invalid entity identifier for relation| | | <a name=\"681\">681</a>|Sorting by specified field not supported|One or more of the provided fields to order by were either invalid or not supported. | | <a name=\"682\">682</a>|Too many fields to sort by|The number of fields to sort the data by exceeds the number allowed by the endpoint | | <a name=\"684\">684</a>|Sequence Not Found| | | <a name=\"685\">685</a>|Sequence Already Exists| | | <a name=\"686\">686</a>|Non-cycling sequence has been exhausted| | | <a name=\"687\">687</a>|Legal Entity Identifier Already In Use| | | <a name=\"688\">688</a>|Legal Entity Not Found| | | <a name=\"689\">689</a>|The supplied pagination token is invalid| | | <a name=\"690\">690</a>|Property Type Is Not Supported| | | <a name=\"691\">691</a>|Multiple Tax-lots For Currency Type Is Not Supported| | | <a name=\"692\">692</a>|This endpoint does not support impersonation| | | <a name=\"693\">693</a>|Entity type is not supported for Relationship| | | <a name=\"694\">694</a>|Relationship Validation Failure| | | <a name=\"695\">695</a>|Relationship Not Found| | | <a name=\"697\">697</a>|Derived Property Formula No Longer Valid| | | <a name=\"698\">698</a>|Story is not available| | | <a name=\"703\">703</a>|Corporate Action Does Not Exist| |
*
* The version of the OpenAPI document: 0.11.2863
* Contact: info@finbourne.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OpenAPIDateConverter = Lusid.Sdk.Client.OpenAPIDateConverter;
namespace Lusid.Sdk.Model
{
/// <summary>
/// WeekendMask
/// </summary>
[DataContract]
public partial class WeekendMask : IEquatable<WeekendMask>
{
/// <summary>
/// Initializes a new instance of the <see cref="WeekendMask" /> class.
/// </summary>
[JsonConstructorAttribute]
protected WeekendMask() { }
/// <summary>
/// Initializes a new instance of the <see cref="WeekendMask" /> class.
/// </summary>
/// <param name="days">days (required).</param>
/// <param name="timeZone">timeZone (required).</param>
public WeekendMask(List<DayOfWeek> days = default(List<DayOfWeek>), string timeZone = default(string))
{
// to ensure "days" is required (not null)
if (days == null)
{
throw new InvalidDataException("days is a required property for WeekendMask and cannot be null");
}
else
{
this.Days = days;
}
// to ensure "timeZone" is required (not null)
if (timeZone == null)
{
throw new InvalidDataException("timeZone is a required property for WeekendMask and cannot be null");
}
else
{
this.TimeZone = timeZone;
}
}
/// <summary>
/// Gets or Sets Days
/// </summary>
[DataMember(Name="days", EmitDefaultValue=false)]
public List<DayOfWeek> Days { get; set; }
/// <summary>
/// Gets or Sets TimeZone
/// </summary>
[DataMember(Name="timeZone", EmitDefaultValue=false)]
public string TimeZone { 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 WeekendMask {\n");
sb.Append(" Days: ").Append(Days).Append("\n");
sb.Append(" TimeZone: ").Append(TimeZone).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 WeekendMask);
}
/// <summary>
/// Returns true if WeekendMask instances are equal
/// </summary>
/// <param name="input">Instance of WeekendMask to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(WeekendMask input)
{
if (input == null)
return false;
return
(
this.Days == input.Days ||
this.Days != null &&
input.Days != null &&
this.Days.SequenceEqual(input.Days)
) &&
(
this.TimeZone == input.TimeZone ||
(this.TimeZone != null &&
this.TimeZone.Equals(input.TimeZone))
);
}
/// <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.Days != null)
hashCode = hashCode * 59 + this.Days.GetHashCode();
if (this.TimeZone != null)
hashCode = hashCode * 59 + this.TimeZone.GetHashCode();
return hashCode;
}
}
}
}
| 223.150327 | 29,340 | 0.677728 | [
"MIT"
] | bogdanLicaFinbourne/lusid-sdk-csharp-preview | sdk/Lusid.Sdk/Model/WeekendMask.cs | 34,142 | C# |
// <auto-generated />
using Intro.Data;
using Intro.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;
namespace Intro.Data.Migrations
{
[DbContext(typeof(SchoolDbContext))]
[Migration("20171215212753_ResourseLisensesChanges")]
partial class ResourseLisensesChanges
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Intro.Models.Course", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<DateTime>("EndDate");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50);
b.Property<decimal>("Price");
b.Property<DateTime>("StartDate");
b.HasKey("Id");
b.ToTable("Courses");
});
modelBuilder.Entity("Intro.Models.Department", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50);
b.HasKey("Id");
b.ToTable("Departments");
});
modelBuilder.Entity("Intro.Models.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("DepartmentId");
b.Property<int?>("ManagerId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50);
b.HasKey("Id");
b.HasIndex("DepartmentId");
b.HasIndex("ManagerId");
b.ToTable("Employees");
});
modelBuilder.Entity("Intro.Models.Homework", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Content");
b.Property<int>("ContentType");
b.Property<int>("CourseId");
b.Property<int>("StudentId");
b.Property<DateTime>("SubmissionDate");
b.HasKey("Id");
b.HasIndex("CourseId");
b.HasIndex("StudentId");
b.ToTable("Homeworks");
});
modelBuilder.Entity("Intro.Models.License", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<int>("ResourceId");
b.HasKey("Id");
b.HasIndex("ResourceId");
b.ToTable("Licenses");
});
modelBuilder.Entity("Intro.Models.Resource", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CourseId");
b.Property<string>("Name");
b.Property<int>("ResourceType");
b.Property<string>("Url");
b.HasKey("Id");
b.HasIndex("CourseId");
b.ToTable("Resources");
});
modelBuilder.Entity("Intro.Models.Student", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("BirthDay");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50);
b.Property<string>("PhoneNumber");
b.Property<DateTime>("RegisteredOn");
b.HasKey("Id");
b.ToTable("Students");
});
modelBuilder.Entity("Intro.Models.StudentCourse", b =>
{
b.Property<int>("StudentId");
b.Property<int>("CourseId");
b.HasKey("StudentId", "CourseId");
b.HasIndex("CourseId");
b.ToTable("StudentsCourseses");
});
modelBuilder.Entity("Intro.Models.Employee", b =>
{
b.HasOne("Intro.Models.Department")
.WithMany("Employees")
.HasForeignKey("DepartmentId");
b.HasOne("Intro.Models.Employee", "Manager")
.WithMany("Subordinates")
.HasForeignKey("ManagerId")
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity("Intro.Models.Homework", b =>
{
b.HasOne("Intro.Models.Course", "Course")
.WithMany("HomeworkSubmissions")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Intro.Models.Student", "Student")
.WithMany("Homeworks")
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Intro.Models.License", b =>
{
b.HasOne("Intro.Models.Resource", "Resource")
.WithMany("Licenses")
.HasForeignKey("ResourceId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Intro.Models.Resource", b =>
{
b.HasOne("Intro.Models.Course", "Course")
.WithMany("Resources")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Intro.Models.StudentCourse", b =>
{
b.HasOne("Intro.Models.Course", "Course")
.WithMany("Participants")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("Intro.Models.Student", "Student")
.WithMany("CourseParticipateIn")
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Restrict);
});
#pragma warning restore 612, 618
}
}
}
| 31.287554 | 117 | 0.446228 | [
"MIT"
] | tanyta78/CSharpWeb | IntroNetCore/Intro.Data/Migrations/20171215212753_ResourseLisensesChanges.Designer.cs | 7,292 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using Nest;
using Newtonsoft.Json.Linq;
using Tests.Core.Client;
using Tests.Domain;
using Tests.Framework;
using Xunit;
using static Tests.Core.Serialization.SerializationTestHelper;
namespace Tests.Search
{
/**[[returned-fields]]
* === Selecting fields to return
*
* Sometimes you don't need to return all of the fields of a document from a search query; for example, when showing
* most recent posts on a blog, you may only need the title of the blog to be returned from the
* query that finds the most recent posts.
*
* There are two approaches that you can take to return only some of the fields from a document i.e. a _partial_
* document (we use this term _loosely_ here); using stored fields and source filtering. Both are quite different
* in how they work.
*/
public class ReturnedFields
{
private readonly IElasticClient _client = TestClient.DisabledStreaming;
/** [[stored-fields]]
* ==== Stored fields
*
* When indexing a document, by default, Elasticsearch stores the originally sent JSON document in a special
* field called {ref_current}/mapping-source-field.html[_source]. Documents returned from
* a search query are materialized from the `_source` field returned from Elasticsearch for each hit.
*
* It is also possible to store a field from the JSON document _separately_ within Elasticsearch
* by using {ref_current}/mapping-store.html[store] on the mapping. Why would you ever want to do this?
* Well, you may disable `_source` so that the source is not stored and select to store only specific fields.
* Another possibility is that the `_source` contains a field with large values, for example, the body of
* a blog post, but typically only another field is needed, for example, the title of the blog post.
* In this case, we don't want to pay the cost of Elasticsearch deserializing the entire `_soure` just to
* get a small field.
*
* [IMPORTANT]
* --
* Opting to disable source for a type mapping means that the original JSON document sent to Elasticsearch
* is *not* stored and hence can never be retrieved. Whilst you may save disk space in doing so, certain
* features are not going to work when source is disabled such as the Reindex API or on the fly
* highlighting.
*
* Seriously consider whether disabling source is what you really want to do for your use case.
* --
*/
[U]
public void StoredFields()
{
/**
* When storing fields in this manner, the individual field values to return can be specified using
* `.StoredFields` on the search request
*/
var searchResponse = _client.Search<Project>(s => s
.StoredFields(sf => sf
.Fields(
f => f.Name,
f => f.StartedOn,
f => f.Branches
)
)
.Query(q => q
.MatchAll()
)
);
/**
* And retrieving them is possible using `.Fields` on the response
*/
foreach (var fieldValues in searchResponse.Fields)
{
var document = new // <1> Construct a partial document as an anonymous type from the stored fields requested
{
Name = fieldValues.ValueOf<Project, string>(p => p.Name),
StartedOn = fieldValues.Value<DateTime>(Infer.Field<Project>(p => p.StartedOn)),
Branches = fieldValues.Values<Project, string>(p => p.Branches.First())
};
}
}
/**
* This works when storing fields separately. A much more common scenario however is to return
* only a selection of fields from the `_source`; this is where source filtering comes in.
*
* [[source-filtering]]
* ==== Source filtering
*
* Only some of the fields of a document can be returned from a search query
* using source filtering
*/
[U]
public void SourceFiltering()
{
var searchResponse = _client.Search<Project>(s => s
.Source(sf => sf
.Includes(i => i // <1> **Include** the following fields
.Fields(
f => f.Name,
f => f.StartedOn,
f => f.Branches
)
)
.Excludes(e => e // <2> **Exclude** the following fields
.Fields("num*") // <3> Fields can be included or excluded through wildcard patterns
)
)
.Query(q => q
.MatchAll()
)
);
/**
* With source filtering specified on the request, `.Documents` will
* now contain _partial_ documents, materialized from the source fields specified to include
*/
var partialProjects = searchResponse.Documents;
/**
* It's possible to exclude `_source` from being returned altogether from a query with
*/
searchResponse = _client.Search<Project>(s => s
.Source(false)
.Query(q => q
.MatchAll()
)
);
}
}
}
| 34.923611 | 117 | 0.687413 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | tests/Tests/Search/ReturnedFields.doc.cs | 5,029 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class respawn : MonoBehaviour
{
[SerializeField]Transform respawnPoint;
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Player")
{
collision.transform.position = respawnPoint.position;
}
}
}
| 20.555556 | 65 | 0.686486 | [
"Apache-2.0"
] | BeardyKing/The-Floor-Is-Lava | firstPersonHell/Assets/respawn.cs | 372 | C# |
using System.Collections.Generic;
using System.IO;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Queries.Mlt;
using Lucene.Net.Search;
using Lucene.Net.Util;
using NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Tests.Queries.Mlt
{
public class TestMoreLikeThis : LuceneTestCase
{
private Directory directory;
private IndexReader reader;
private IndexSearcher searcher;
[SetUp]
public override void SetUp()
{
base.SetUp();
directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), directory);
// Add series of docs with specific information for MoreLikeThis
AddDoc(writer, "lucene");
AddDoc(writer, "lucene release");
reader = writer.Reader;
writer.Dispose();
searcher = NewSearcher(reader);
}
[TearDown]
public override void TearDown()
{
reader.Dispose();
directory.Dispose();
base.TearDown();
}
private static void AddDoc(RandomIndexWriter writer, string text)
{
Document doc = new Document();
doc.Add(NewTextField("text", text, Field.Store.YES));
writer.AddDocument(doc);
}
[Test]
public void TestBoostFactor()
{
IDictionary<string, float?> originalValues = OriginalValues;
MoreLikeThis mlt = new MoreLikeThis(reader);
mlt.Analyzer = new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false);
mlt.MinDocFreq = 1;
mlt.MinTermFreq = 1;
mlt.MinWordLen = 1;
mlt.FieldNames = new[] { "text" };
mlt.Boost = true;
// this mean that every term boost factor will be multiplied by this
// number
float boostFactor = 5;
mlt.BoostFactor = boostFactor;
BooleanQuery query = (BooleanQuery)mlt.Like(new StringReader("lucene release"), "text");
IList<BooleanClause> clauses = query.Clauses;
assertEquals("Expected " + originalValues.Count + " clauses.", originalValues.Count, clauses.Count);
foreach (BooleanClause clause in clauses)
{
TermQuery tq = (TermQuery)clause.Query;
float? termBoost = originalValues[tq.Term.Text()];
assertNotNull("Expected term " + tq.Term.Text(), termBoost);
float totalBoost = (float) (termBoost * boostFactor);
assertEquals("Expected boost of " + totalBoost + " for term '" + tq.Term.Text() + "' got " + tq.Boost, totalBoost, tq.Boost, 0.0001);
}
}
private IDictionary<string, float?> OriginalValues
{
get
{
IDictionary<string, float?> originalValues = new Dictionary<string, float?>();
MoreLikeThis mlt = new MoreLikeThis(reader);
mlt.Analyzer = new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false);
mlt.MinDocFreq = 1;
mlt.MinTermFreq = 1;
mlt.MinWordLen = 1;
mlt.FieldNames = new[] { "text" };
mlt.Boost = true;
BooleanQuery query = (BooleanQuery)mlt.Like(new StringReader("lucene release"), "text");
IList<BooleanClause> clauses = query.Clauses;
foreach (BooleanClause clause in clauses)
{
TermQuery tq = (TermQuery)clause.Query;
originalValues[tq.Term.Text()] = tq.Boost;
}
return originalValues;
}
}
// LUCENE-3326
[Test]
public void TestMultiFields()
{
MoreLikeThis mlt = new MoreLikeThis(reader);
mlt.Analyzer = new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false);
mlt.MinDocFreq = 1;
mlt.MinTermFreq = 1;
mlt.MinWordLen = 1;
mlt.FieldNames = new[] { "text", "foobar" };
mlt.Like(new StringReader("this is a test"), "foobar");
}
/// <summary>
/// just basic equals/hashcode etc
/// </summary>
[Test]
public void TestMoreLikeThisQuery()
{
Query query = new MoreLikeThisQuery("this is a test", new[] { "text" }, new MockAnalyzer(Random()), "text");
QueryUtils.Check(Random(), query, searcher);
}
// TODO: add tests for the MoreLikeThisQuery
}
} | 35.276119 | 149 | 0.554686 | [
"Apache-2.0"
] | CerebralMischief/lucenenet | src/Lucene.Net.Tests.Queries/Mlt/TestMoreLikeThis.cs | 4,729 | C# |
using System;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace wfMod.Items.Accessories
{
public class Guardian : ExclusiveAccessory
{
public override void SetStaticDefaults()
{
Tooltip.SetDefault("When your shield is depleted, boost it by 8% for each active minion, up to 64%");
}
public override void SetDefaults()
{
base.SetDefaults();
item.rare = 2;
item.value = Item.buyPrice(gold: 5);
}
public override void UpdateAccessory(Player player, bool hideVisual)
{
var shieldPl = player.GetModPlayer<wfPlayerShields>();
shieldPl.onShieldsDamaged.Add((shieldDmg, lifeDmg) =>
{
if (shieldPl.shield == 0 && shieldDmg >= shieldPl.maxUnderShield)
{
float shieldRegain = 0.08f * player.numMinions;
shieldRegain = shieldRegain > 0.64f ? 0.64f : shieldRegain;
shieldRegain *= shieldPl.maxUnderShield;
shieldPl.shield += shieldRegain;
}
}
);
}
}
} | 30.307692 | 113 | 0.552453 | [
"MIT"
] | wdfeer/wdfeerMod | Items/Accessories/Guardian.cs | 1,182 | C# |
#nullable disable
namespace CEo.Pokemon.HomeBalls.Data.Entities
{
public record HomeBallsPokemonAbilitySlot :
HomeBalls.Entities.HomeBallsPokemonAbilitySlot,
IHomeBallsDataType<HomeBalls.Entities.HomeBallsPokemonAbilitySlot>
{
public static Type BaseEntityType { get; } =
typeof(HomeBalls.Entities.HomeBallsPokemonAbilitySlot);
public virtual HomeBallsPokemonAbility Ability { get; init; }
public virtual UInt16 SpeciesId { get; init; }
public virtual HomeBallsPokemonSpecies Species { get; init; }
public virtual Byte FormId { get; init; }
public virtual HomeBallsPokemonForm Form { get; init; }
public virtual HomeBalls.Entities.HomeBallsPokemonAbilitySlot ToBaseType() =>
this.Adapt<HomeBalls.Entities.HomeBallsPokemonAbilitySlot>();
}
}
#nullable enable
namespace CEo.Pokemon.HomeBalls.Data.Entities.Configuration
{
public class HomeBallsPokemonAbilitySlotConfiguration :
HomeBallsEntityConfiguration<HomeBallsPokemonAbilitySlot>
{
public HomeBallsPokemonAbilitySlotConfiguration(
ILogger? logger = default) :
base(logger) { }
protected internal override void ConfigureCore()
{
base.ConfigureCore();
ConfigureAbility();
ConfigureSpecies();
ConfigureForm();
}
protected internal override void ConfigureKey() =>
Builder.HasKey(slot => new { slot.AbilityId, slot.SpeciesId, slot.FormId });
protected internal virtual void ConfigureAbility() =>
Builder.HasOne(slot => slot.Ability)
.WithMany(ability => ability.OnPokemon)
.HasForeignKey(slot => slot.AbilityId);
protected internal virtual void ConfigureSpecies() =>
Builder.HasOne(slot => slot.Species)
.WithMany(species => species.Abilities)
.HasForeignKey(slot => slot.SpeciesId);
protected internal virtual void ConfigureForm() =>
Builder.HasOne(slot => slot.Form)
.WithMany(form => form.Abilities)
.HasForeignKey(slot => new { slot.SpeciesId, slot.FormId });
}
} | 34.96875 | 88 | 0.653262 | [
"MIT"
] | blah12629/HomeBalls | src/HomeBalls.Data/Entities/HomeBallsPokemonAbilitySlot.cs | 2,238 | C# |
//******************************************************************************
//
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
using System.Threading;
namespace UITests
{
[TestClass]
public class ToggleButton : Test_Base
{
private static WindowsElement toggleButtonElement = null;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
Setup(context);
var buttonTab = session.FindElementByName("Basic Input");
buttonTab.Click();
var button = session.FindElementByName("ToggleButton");
button.Click();
toggleButtonElement = session.FindElementByAccessibilityId("Toggle1");
Assert.IsNotNull(toggleButtonElement);
Thread.Sleep(3000);
}
[ClassCleanup]
public static void ClassCleanup()
{
TearDown();
}
[TestMethod]
public void Click()
{
var buttonEventOutput = session.FindElementByAccessibilityId("Control1Output");
Assert.AreEqual("Off", buttonEventOutput.Text);
toggleButtonElement.Click();
Assert.AreEqual("On", buttonEventOutput.Text);
toggleButtonElement.Click();
Assert.AreEqual("Off", buttonEventOutput.Text);
}
[TestMethod]
public void Displayed()
{
Assert.IsTrue(toggleButtonElement.Displayed);
}
[TestMethod]
public void Enabled()
{
var disableButtonCheckbox = session.FindElementByAccessibilityId("DisableToggle1");
Assert.IsTrue(toggleButtonElement.Enabled);
disableButtonCheckbox.Click();
Assert.IsFalse(toggleButtonElement.Enabled);
disableButtonCheckbox.Click();
Assert.IsTrue(toggleButtonElement.Enabled);
}
[TestMethod]
public void Name()
{
Assert.AreEqual("ControlType.Button", toggleButtonElement.TagName);
}
[TestMethod]
public void Selected()
{
toggleButtonElement.Click();
Assert.IsTrue(toggleButtonElement.Selected);
toggleButtonElement.Click();
Assert.IsFalse(toggleButtonElement.Selected);
}
[TestMethod]
public void Size()
{
Assert.IsTrue(toggleButtonElement.Size.Width > 0);
Assert.IsTrue(toggleButtonElement.Size.Height > 0);
}
[TestMethod]
public void Text()
{
Assert.AreEqual("ToggleButton", toggleButtonElement.Text);
}
}
}
| 31.481481 | 95 | 0.595294 | [
"MIT"
] | Acidburn0zzz/Xaml-Controls-Gallery | UITests/ToggleButton.cs | 3,402 | C# |
using BLTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Security;
using BLTools.MVVM;
namespace UnitTest2015 {
/// <summary>
///This is a test class for StringExtensionTest and is intended
///to contain all NotificationTest Unit Tests
///</summary>
[TestClass()]
public class NotificationTest {
#region Test context
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext {
get {
return testContextInstance;
}
set {
testContextInstance = value;
}
}
#endregion Test context
#region NotifyProgress
public class TestNotify : MVVMBase {
public void Execute() {
NotifyExecutionProgress("Doing action...");
NotifyExecutionCompleted("Job done", true);
}
}
[TestMethod(), TestCategory("MVVM")]
public void ExecutionProgress_HookThroughBaseClass_ResultOK() {
string ProgressMessage = "";
string EndMessage = "";
bool EndStatus = false;
string Emitter = "";
MVVMBase.MinTraceLevel = ErrorLevel.Info;
EventHandler<IntAndMessageEventArgs> ExP = (o, e) => ProgressMessage = e.Message;
EventHandler<BoolAndMessageEventArgs> ExC = (o, e) => { EndMessage = e.Message; EndStatus = e.Result; Emitter = o.GetType().Name; };
MVVMBase.OnExecutionProgress += ExP;
MVVMBase.OnExecutionCompleted += ExC;
TestNotify Test = new TestNotify();
Test.Execute();
MVVMBase.OnExecutionProgress -= ExP;
MVVMBase.OnExecutionCompleted -= ExC;
Assert.AreEqual(ProgressMessage, "Doing action...");
Assert.AreEqual(EndMessage, "Job done");
Assert.AreEqual(EndStatus, true);
}
[TestMethod(), TestCategory("MVVM")]
public void ExecutionProgress_HookThroughDerivedClass_ResultOK() {
string Result = "";
TestNotify Test = new TestNotify();
TestNotify.MinTraceLevel = ErrorLevel.Info;
TestNotify.OnExecutionProgress += (o, e) => Result = e.Message;
Test.Execute();
TestNotify.OnExecutionProgress -= (o, e) => Result = e.Message;
Assert.AreEqual(Result, "Doing action...");
}
[TestMethod(), TestCategory("MVVM")]
public void ExecutionProgress_HookThroughDerivedClassUnhookFromBaseClass_ResultOK() {
string Result = "";
TestNotify Test = new TestNotify();
TestNotify.MinTraceLevel = ErrorLevel.Info;
TestNotify.OnExecutionProgress += (o, e) => Result = e.Message;
Test.Execute();
MVVMBase.OnExecutionProgress -= (o, e) => Result = e.Message;
Assert.AreEqual(Result, "Doing action...");
}
#endregion NotifyProgress
}
}
| 31.120879 | 138 | 0.665607 | [
"MIT"
] | bollylu/BLTools | UnitTest2015/MVVM/NotificationTest.cs | 2,834 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApartmentManagementClient.Models
{
public class CreateMessageModel
{
public int SenderId { get; set; }
public int ReceiverId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
}
| 22.875 | 43 | 0.669399 | [
"MIT"
] | ahmtsenlik/ApartmentManagementSystem | ApartmentManagement/ApartmentManagementClient/Models/Message/CreateMessageModel.cs | 368 | C# |
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Odco.PointOfSales.Application.GeneralDto;
using Odco.PointOfSales.Application.Purchasings.PurchaseOrders;
using Odco.PointOfSales.Application.Purchasings.Suppliers;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Odco.PointOfSales.Application.Purchasings
{
public interface IPurchasingAppService : IApplicationService
{
#region Supplier
Task<SupplierDto> CreateSupplierAsync(CreateSupplierDto input);
Task DeleteSupplierAsync(EntityDto<Guid> input);
Task<PagedResultDto<SupplierDto>> GetAllSuppliersAsync(PagedSupplierResultRequestDto input);
Task<SupplierDto> GetSupplierAsync(EntityDto<Guid> input);
Task<SupplierDto> UpdateSupplierAsync(SupplierDto input);
Task<List<CommonKeyValuePairDto>> GetPartialSuppliersAsync(string keyword);
#endregion
#region Purchase Order
Task<PurchaseOrderDto> CreatePurchaseOrderAsync(CreatePurchaseOrderDto createPurchaseOrderDto);
#endregion
}
}
| 39.214286 | 103 | 0.782332 | [
"MIT"
] | CipherLabz/Odco-PointOfSales-Material | aspnet-core/src/Odco.PointOfSales.Application/Purchasings/IPurchasingAppService.cs | 1,100 | C# |
using System;
using Newtonsoft.Json;
namespace Web.Helpers.WebRequests
{
public struct JwtToken
{
[JsonProperty("token")] private readonly string _token;
public JwtToken(string token) => _token = token;
public override string ToString() => _token;
}
} | 20 | 63 | 0.646667 | [
"MIT"
] | MrKatinas/Unnamed | Unity/Assets/_Scripts/Web/Helpers/WebRequests/JwtToken.cs | 302 | C# |
// FastZip.cs
//
// Copyright 2005 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// FastZipEvents supports all events applicable to <see cref="FastZip">FastZip</see> operations.
/// </summary>
public class FastZipEvents
{
/// <summary>
/// Delegate to invoke when processing directories.
/// </summary>
public ProcessDirectoryDelegate ProcessDirectory;
/// <summary>
/// Delegate to invoke when processing files.
/// </summary>
public ProcessFileDelegate ProcessFile;
/// <summary>
/// Delegate to invoke when processing directory failures.
/// </summary>
public DirectoryFailureDelegate DirectoryFailure;
/// <summary>
/// Delegate to invoke when processing file failures.
/// </summary>
public FileFailureDelegate FileFailure;
/// <summary>
/// Raise the <see cref="DirectoryFailure">directory failure</see> event.
/// </summary>
/// <param name="directory">The directory causing the failure.</param>
/// <param name="e">The exception for this event.</param>
/// <returns>A boolean indicating if execution should continue or not.</returns>
public bool OnDirectoryFailure(string directory, Exception e)
{
bool result = false;
if ( DirectoryFailure != null ) {
ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e);
DirectoryFailure(this, args);
result = args.ContinueRunning;
}
return result;
}
/// <summary>
/// Raises the <see cref="FileFailure">file failure delegate</see>.
/// </summary>
/// <param name="file">The file causing the failure.</param>
/// <param name="e">The exception for this failure.</param>
/// <returns>A boolean indicating if execution should continue or not.</returns>
public bool OnFileFailure(string file, Exception e)
{
bool result = false;
if ( FileFailure != null ) {
ScanFailureEventArgs args = new ScanFailureEventArgs(file, e);
FileFailure(this, args);
result = args.ContinueRunning;
}
return result;
}
/// <summary>
/// Raises the <see cref="ProcessFile">Process File delegate</see>.
/// </summary>
/// <param name="file">The file being processed.</param>
/// <returns>A boolean indicating if execution should continue or not.</returns>
public bool OnProcessFile(string file)
{
bool result = true;
if ( ProcessFile != null ) {
ScanEventArgs args = new ScanEventArgs(file);
ProcessFile(this, args);
result = args.ContinueRunning;
}
return result;
}
/// <summary>
/// Fires the <see cref="ProcessDirectory">process directory</see> delegate.
/// </summary>
/// <param name="directory">The directory being processed.</param>
/// <param name="hasMatchingFiles">Flag indicating if directory has matching files as determined by the current filter.</param>
public bool OnProcessDirectory(string directory, bool hasMatchingFiles)
{
bool result = true;
if ( ProcessDirectory != null ) {
DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles);
ProcessDirectory(this, args);
result = args.ContinueRunning;
}
return result;
}
}
/// <summary>
/// FastZip provides facilities for creating and extracting zip files.
/// </summary>
public class FastZip
{
#region Enumerations
/// <summary>
/// Defines the desired handling when overwriting files during extraction.
/// </summary>
public enum Overwrite
{
/// <summary>
/// Prompt the user to confirm overwriting
/// </summary>
Prompt,
/// <summary>
/// Never overwrite files.
/// </summary>
Never,
/// <summary>
/// Always overwrite files.
/// </summary>
Always
}
#endregion
#region Constructors
/// <summary>
/// Initialise a default instance of <see cref="FastZip"/>.
/// </summary>
public FastZip()
{
}
/// <summary>
/// Initialise a new instance of <see cref="FastZip"/>
/// </summary>
/// <param name="events">The <see cref="FastZipEvents">events</see> to use during operations.</param>
public FastZip(FastZipEvents events)
{
events_ = events;
}
#endregion
#region Properties
/// <summary>
/// Get/set a value indicating wether empty directories should be created.
/// </summary>
public bool CreateEmptyDirectories
{
get { return createEmptyDirectories_; }
set { createEmptyDirectories_ = value; }
}
#if !NETCF_1_0
/// <summary>
/// Get / set the password value.
/// </summary>
public string Password
{
get { return password_; }
set { password_ = value; }
}
#endif
/// <summary>
/// Get or set the <see cref="INameTransform"></see> active when creating Zip files.
/// </summary>
/// <seealso cref="EntryFactory"></seealso>
public INameTransform NameTransform
{
get { return entryFactory_.NameTransform; }
set {
entryFactory_.NameTransform = value;
}
}
/// <summary>
/// Get or set the <see cref="IEntryFactory"></see> active when creating Zip files.
/// </summary>
public IEntryFactory EntryFactory
{
get { return entryFactory_; }
set {
if ( value == null ) {
entryFactory_ = new ZipEntryFactory();
}
else {
entryFactory_ = value;
}
}
}
/// <summary>
/// Get/set a value indicating wether file dates and times should
/// be restored when extracting files from an archive.
/// </summary>
/// <remarks>The default value is false.</remarks>
public bool RestoreDateTimeOnExtract
{
get {
return restoreDateTimeOnExtract_;
}
set {
restoreDateTimeOnExtract_ = value;
}
}
/// <summary>
/// Get/set a value indicating wether file attributes should
/// be restored during extract operations
/// </summary>
public bool RestoreAttributesOnExtract
{
get { return restoreAttributesOnExtract_; }
set { restoreAttributesOnExtract_ = value; }
}
#endregion
#region Delegates
/// <summary>
/// Delegate called when confirming overwriting of files.
/// </summary>
public delegate bool ConfirmOverwriteDelegate(string fileName);
#endregion
#region CreateZip
/// <summary>
/// Create a zip file.
/// </summary>
/// <param name="zipFileName">The name of the zip file to create.</param>
/// <param name="sourceDirectory">The directory to source files from.</param>
/// <param name="recurse">True to recurse directories, false for no recursion.</param>
/// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param>
/// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param>
public void CreateZip(string zipFileName, string sourceDirectory,
bool recurse, string fileFilter, string directoryFilter)
{
CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, directoryFilter);
}
/// <summary>
/// Create a zip file/archive.
/// </summary>
/// <param name="zipFileName">The name of the zip file to create.</param>
/// <param name="sourceDirectory">The directory to obtain files and directories from.</param>
/// <param name="recurse">True to recurse directories, false for no recursion.</param>
/// <param name="fileFilter">The file filter to apply.</param>
public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter)
{
CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, null);
}
/// <summary>
/// Create a zip archive sending output to the <paramref name="outputStream"/> passed.
/// </summary>
/// <param name="outputStream">The stream to write archive data to.</param>
/// <param name="sourceDirectory">The directory to source files from.</param>
/// <param name="recurse">True to recurse directories, false for no recursion.</param>
/// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param>
/// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param>
public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter)
{
NameTransform = new ZipNameTransform(sourceDirectory);
sourceDirectory_ = sourceDirectory;
using ( outputStream_ = new ZipOutputStream(outputStream) ) {
#if !NETCF_1_0
if ( password_ != null ) {
outputStream_.Password = password_;
}
#endif
FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter);
scanner.ProcessFile += new ProcessFileDelegate(ProcessFile);
if ( this.CreateEmptyDirectories ) {
scanner.ProcessDirectory += new ProcessDirectoryDelegate(ProcessDirectory);
}
if (events_ != null) {
if ( events_.FileFailure != null ) {
scanner.FileFailure += events_.FileFailure;
}
if ( events_.DirectoryFailure != null ) {
scanner.DirectoryFailure += events_.DirectoryFailure;
}
}
scanner.Scan(sourceDirectory, recurse);
}
}
#endregion
#region ExtractZip
/// <summary>
/// Extract the contents of a zip file.
/// </summary>
/// <param name="zipFileName">The zip file to extract from.</param>
/// <param name="targetDirectory">The directory to save extracted information in.</param>
/// <param name="fileFilter">A filter to apply to files.</param>
public void ExtractZip(string zipFileName, string targetDirectory, string fileFilter)
{
ExtractZip(zipFileName, targetDirectory, Overwrite.Always, null, fileFilter, null, restoreDateTimeOnExtract_);
}
/// <summary>
/// Extract the contents of a zip file.
/// </summary>
/// <param name="zipFileName">The zip file to extract from.</param>
/// <param name="targetDirectory">The directory to save extracted information in.</param>
/// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
/// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
/// <param name="fileFilter">A filter to apply to files.</param>
/// <param name="directoryFilter">A filter to apply to directories.</param>
/// <param name="restoreDateTime">Flag indicating wether to restore the date and time for extracted files.</param>
public void ExtractZip(string zipFileName, string targetDirectory,
Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
string fileFilter, string directoryFilter, bool restoreDateTime)
{
if ( (overwrite == Overwrite.Prompt) && (confirmDelegate == null) ) {
throw new ArgumentNullException("confirmDelegate");
}
continueRunning_ = true;
overwrite_ = overwrite;
confirmDelegate_ = confirmDelegate;
targetDirectory_ = targetDirectory;
fileFilter_ = new NameFilter(fileFilter);
directoryFilter_ = new NameFilter(directoryFilter);
restoreDateTimeOnExtract_ = restoreDateTime;
using ( zipFile_ = new ZipFile(zipFileName) ) {
#if !NETCF_1_0
if (password_ != null) {
zipFile_.Password = password_;
}
#endif
System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator();
while ( continueRunning_ && enumerator.MoveNext()) {
ZipEntry entry = (ZipEntry) enumerator.Current;
if ( entry.IsFile )
{
if ( directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name) ) {
ExtractEntry(entry);
}
}
else if ( entry.IsDirectory ) {
if ( directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories ) {
ExtractEntry(entry);
}
}
else {
// Do nothing for volume labels etc...
}
}
}
}
#endregion
#region Internal Processing
void ProcessDirectory(object sender, DirectoryEventArgs e)
{
if ( !e.HasMatchingFiles && CreateEmptyDirectories ) {
if ( events_ != null ) {
events_.OnProcessDirectory(e.Name, e.HasMatchingFiles);
}
if ( e.ContinueRunning ) {
if (e.Name != sourceDirectory_) {
ZipEntry entry = entryFactory_.MakeDirectoryEntry(e.Name);
outputStream_.PutNextEntry(entry);
}
}
}
}
void ProcessFile(object sender, ScanEventArgs e)
{
if ( (events_ != null) && (events_.ProcessFile != null) ) {
events_.ProcessFile(sender, e);
}
if ( e.ContinueRunning ) {
ZipEntry entry = entryFactory_.MakeFileEntry(e.Name);
outputStream_.PutNextEntry(entry);
AddFileContents(e.Name);
}
}
void AddFileContents(string name)
{
if ( buffer_ == null ) {
buffer_ = new byte[4096];
}
using (FileStream stream = File.OpenRead(name)) {
StreamUtils.Copy(stream, outputStream_, buffer_);
}
}
void ExtractFileEntry(ZipEntry entry, string targetName)
{
bool proceed = true;
if ( overwrite_ != Overwrite.Always ) {
if ( File.Exists(targetName) ) {
if ( (overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null) ) {
proceed = confirmDelegate_(targetName);
}
else {
proceed = false;
}
}
}
if ( proceed ) {
if ( events_ != null ) {
continueRunning_ = events_.OnProcessFile(entry.Name);
}
if ( continueRunning_ ) {
try {
using ( FileStream outputStream = File.Create(targetName) ) {
if ( buffer_ == null ) {
buffer_ = new byte[4096];
}
StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_);
}
#if !NETCF_1_0 && !NETCF_2_0
if ( restoreDateTimeOnExtract_ ) {
File.SetLastWriteTime(targetName, entry.DateTime);
}
if ( RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) {
FileAttributes fileAttributes = (FileAttributes) entry.ExternalFileAttributes;
// TODO: FastZip - Setting of other file attributes on extraction is a little trickier.
fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden);
File.SetAttributes(targetName, fileAttributes);
}
#endif
}
catch(Exception ex) {
if ( events_ != null ) {
continueRunning_ = events_.OnFileFailure(targetName, ex);
}
else {
continueRunning_ = false;
}
}
}
}
}
void ExtractEntry(ZipEntry entry)
{
bool doExtraction = false;
string nameText = entry.Name;
if ( entry.IsFile ) {
doExtraction = NameIsValid(nameText) && entry.IsCompressionMethodSupported();
}
else if ( entry.IsDirectory ) {
doExtraction = NameIsValid(nameText);
}
// TODO: Fire delegate were compression method not supported, or name is invalid.
string dirName = null;
string targetName = null;
if ( doExtraction ) {
// Handle invalid entry names by chopping of path root.
if (Path.IsPathRooted(nameText)) {
string workName = Path.GetPathRoot(nameText);
nameText = nameText.Substring(workName.Length);
}
if ( nameText.Length > 0 ) {
targetName = Path.Combine(targetDirectory_, nameText);
if ( entry.IsDirectory ) {
dirName = targetName;
}
else {
dirName = Path.GetDirectoryName(Path.GetFullPath(targetName));
}
}
else {
doExtraction = false;
}
}
if ( doExtraction && !Directory.Exists(dirName) ) {
if ( !entry.IsDirectory || CreateEmptyDirectories ) {
try {
Directory.CreateDirectory(dirName);
}
catch (Exception ex) {
doExtraction = false;
if ( events_ != null ) {
if ( entry.IsDirectory ) {
continueRunning_ = events_.OnDirectoryFailure(targetName, ex);
}
else {
continueRunning_ = events_.OnFileFailure(targetName, ex);
}
}
else {
continueRunning_ = false;
}
}
}
}
if ( doExtraction && entry.IsFile ) {
ExtractFileEntry(entry, targetName);
}
}
static int MakeExternalAttributes(FileInfo info)
{
return (int)info.Attributes;
}
#if NET_1_0 || NET_1_1 || NETCF_1_0
static bool NameIsValid(string name)
{
return (name != null) &&
(name.Length > 0) &&
(name.IndexOfAny(Path.InvalidPathChars) < 0);
}
#else
static bool NameIsValid(string name)
{
return (name != null) &&
(name.Length > 0) &&
(name.IndexOfAny(Path.GetInvalidPathChars()) < 0);
}
#endif
#endregion
#region Instance Fields
bool continueRunning_;
byte[] buffer_;
ZipOutputStream outputStream_;
ZipFile zipFile_;
string targetDirectory_;
string sourceDirectory_;
NameFilter fileFilter_;
NameFilter directoryFilter_;
Overwrite overwrite_;
ConfirmOverwriteDelegate confirmDelegate_;
bool restoreDateTimeOnExtract_;
bool restoreAttributesOnExtract_;
bool createEmptyDirectories_;
FastZipEvents events_;
IEntryFactory entryFactory_ = new ZipEntryFactory();
#if !NETCF_1_0
string password_;
#endif
#endregion
}
}
| 32.30303 | 130 | 0.657598 | [
"BSD-3-Clause"
] | CMU-SAFARI/RamulatorSharp | src/gzip/FastZip.cs | 19,188 | C# |
// Copyright © Conatus Creative, Inc. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE.md in the project root for license terms.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Pixel3D.ActorManagement
{
/// <summary>
/// A dictionary that allows multiple pairs with the same key.
/// </summary>
public class MultiDictionary<TKey, TValue> : ILookup<TKey, TValue>
{
readonly OrderedDictionary<TKey, List<TValue>> dict;
public MultiDictionary()
{
dict = new OrderedDictionary<TKey, List<TValue>>();
}
public MultiDictionary(IEqualityComparer<TKey> comparer)
{
dict = new OrderedDictionary<TKey, List<TValue>>(comparer);
}
public bool TryGetValue(TKey key, out List<TValue> value)
{
return dict.TryGetValue(key, out value);
}
public void Add(TKey key, TValue value)
{
List<TValue> valueList;
if (!dict.TryGetValue(key, out valueList))
{
valueList = new List<TValue>();
dict.Add(key, valueList);
}
valueList.Add(value);
}
public OrderedDictionary<TKey, List<TValue>>.KeyCollection Keys
{
get { return dict.Keys; }
}
public void AddAll(TKey key, IEnumerable<TValue> values)
{
List<TValue> valueList;
if(!dict.TryGetValue(key, out valueList))
{
valueList = new List<TValue>();
dict.Add(key, valueList);
}
foreach(var value in values)
valueList.Add(value);
}
public bool RemoveAll(TKey key)
{
return dict.Remove(key);
}
public bool Remove(TKey key, TValue value)
{
List<TValue> valueList;
if (dict.TryGetValue(key, out valueList))
{
if (valueList.Remove(value))
{
if (valueList.Count == 0)
dict.Remove(key);
return true;
}
}
return false;
}
public bool ContainsKey(TKey key)
{
return dict.ContainsKey(key);
}
public bool ContainsValue(TKey key, TValue value, IEqualityComparer<TValue> comparer = null)
{
List<TValue> list;
return dict.TryGetValue(key, out list) &&
list.Contains(value, comparer ?? EqualityComparer<TValue>.Default);
}
public IEnumerable<TValue> Values
{
get
{
return dict.SelectMany(kvp => kvp.Value);
}
}
public void Clear()
{
dict.Clear();
}
#if NET_4_5
public IReadOnlyList<TValue> this[TKey key] {
#else
public List<TValue> this[TKey key]
{
#endif
get
{
List<TValue> list;
if (dict.TryGetValue(key, out list))
return list;
else
return EmptyList;
}
}
private static readonly List<TValue> EmptyList = new List<TValue>();
public int Count
{
get { return dict.Count; }
}
IEnumerable<TValue> ILookup<TKey, TValue>.this[TKey key]
{
get { return this[key]; }
}
bool ILookup<TKey, TValue>.Contains(TKey key)
{
return dict.ContainsKey(key);
}
public IEnumerator<IGrouping<TKey, TValue>> GetEnumerator()
{
foreach (var pair in dict)
yield return new Grouping(pair.Key, pair.Value);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
sealed class Grouping : IGrouping<TKey, TValue>
{
readonly TKey key;
readonly List<TValue> values;
public Grouping(TKey key, List<TValue> values)
{
this.key = key;
this.values = values;
}
public TKey Key
{
get { return key; }
}
public IEnumerator<TValue> GetEnumerator()
{
return values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return values.GetEnumerator();
}
}
}
} | 26.318182 | 100 | 0.500648 | [
"Apache-2.0"
] | caogtaa/Pixel3D | src/Pixel3D.ActorManagement/MultiDictionary.cs | 4,635 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using PepperDash.Core;
using PepperDash.Essentials.Core;
using System.Text.RegularExpressions;
namespace PepperDash.Essentials.Devices.Common.DSP
{
public class QscDspLevelControl : QscDspControlPoint, IBasicVolumeWithFeedback, IKeyed
{
bool _IsMuted;
ushort _VolumeLevel;
public BoolFeedback MuteFeedback { get; private set; }
public IntFeedback VolumeLevelFeedback { get; private set; }
public bool Enabled { get; set; }
public ePdtLevelTypes Type;
CTimer VolumeUpRepeatTimer;
CTimer VolumeDownRepeatTimer;
/// <summary>
/// Used for to identify level subscription values
/// </summary>
public string LevelCustomName { get; private set; }
/// <summary>
/// Used for to identify mute subscription values
/// </summary>
public string MuteCustomName { get; private set; }
/// <summary>
/// Minimum fader level
/// </summary>
double MinLevel;
/// <summary>
/// Maximum fader level
/// </summary>
double MaxLevel;
/// <summary>
/// Checks if a valid subscription string has been recieved for all subscriptions
/// </summary>
public bool IsSubsribed
{
get
{
bool isSubscribed = false;
if (HasMute && MuteIsSubscribed)
isSubscribed = true;
if (HasLevel && LevelIsSubscribed)
isSubscribed = true;
return isSubscribed;
}
}
public bool AutomaticUnmuteOnVolumeUp { get; private set; }
public bool HasMute { get; private set; }
public bool HasLevel { get; private set; }
bool MuteIsSubscribed;
bool LevelIsSubscribed;
//public TesiraForteLevelControl(string label, string id, int index1, int index2, bool hasMute, bool hasLevel, BiampTesiraForteDsp parent)
// : base(id, index1, index2, parent)
//{
// Initialize(label, hasMute, hasLevel);
//}
public QscDspLevelControl(string key, QscDspLevelControlBlockConfig config, QscDsp parent)
: base(config.LevelInstanceTag, config.MuteInstanceTag, parent)
{
if (!config.Disabled)
{
Initialize(key, config);
}
}
/// <summary>
/// Initializes this attribute based on config values and generates subscriptions commands and adds commands to the parent's queue.
/// </summary>
public void Initialize(string key, QscDspLevelControlBlockConfig config)
{
Key = string.Format("{0}--{1}", Parent.Key, key);
Enabled = true;
DeviceManager.AddDevice(this);
if (config.IsMic)
{
Type = ePdtLevelTypes.microphone;
}
else
{
Type = ePdtLevelTypes.speaker;
}
Debug.Console(2, this, "Adding LevelControl '{0}'", Key);
this.IsSubscribed = false;
MuteFeedback = new BoolFeedback(() => _IsMuted);
VolumeLevelFeedback = new IntFeedback(() => _VolumeLevel);
VolumeUpRepeatTimer = new CTimer(VolumeUpRepeat, Timeout.Infinite);
VolumeDownRepeatTimer = new CTimer(VolumeDownRepeat, Timeout.Infinite);
LevelCustomName = config.Label;
HasMute = config.HasMute;
HasLevel = config.HasLevel;
}
public void Subscribe()
{
// Do subscriptions and blah blah
// Subscribe to mute
if (this.HasMute)
{
SendSubscriptionCommand(this.MuteInstanceTag, "1");
// SendSubscriptionCommand(config. , "mute", 500);
}
// Subscribe to level
if (this.HasLevel)
{
SendSubscriptionCommand(this.LevelInstanceTag, "1");
// SendSubscriptionCommand(this.con, "level", 250);
//SendFullCommand("get", "minLevel", null);
//SendFullCommand("get", "maxLevel", null);
}
}
/// <summary>
/// Parses the response from the DspBase
/// </summary>
/// <param name="customName"></param>
/// <param name="value"></param>
public void ParseSubscriptionMessage(string customName, string value)
{
// Check for valid subscription response
Debug.Console(1, this, "Level {0} Response: '{1}'", customName, value);
if (customName == MuteInstanceTag)
{
if (value == "muted")
{
_IsMuted = true;
MuteIsSubscribed = true;
}
else if (value == "unmuted")
{
_IsMuted = false;
MuteIsSubscribed = true;
}
MuteFeedback.FireUpdate();
}
else if (customName == LevelInstanceTag)
{
var _value = Double.Parse(value);
_VolumeLevel = (ushort)(_value * 65535);
Debug.Console(1, this, "Level {0} VolumeLevel: '{1}'", customName, _VolumeLevel);
LevelIsSubscribed = true;
VolumeLevelFeedback.FireUpdate();
}
}
/// <summary>
/// Turns the mute off
/// </summary>
public void MuteOff()
{
SendFullCommand("csv", this.MuteInstanceTag, "0");
}
/// <summary>
/// Turns the mute on
/// </summary>
public void MuteOn()
{
SendFullCommand("csv", this.MuteInstanceTag, "1");
}
/// <summary>
/// Sets the volume to a specified level
/// </summary>
/// <param name="level"></param>
public void SetVolume(ushort level)
{
Debug.Console(1, this, "volume: {0}", level);
// Unmute volume if new level is higher than existing
if (AutomaticUnmuteOnVolumeUp && _IsMuted)
{
MuteOff();
}
double newLevel = Scale(level);
Debug.Console(1, this, "newVolume: {0}", newLevel);
SendFullCommand("csp", this.LevelInstanceTag, string.Format("{0}", newLevel));
}
/// <summary>
/// Toggles mute status
/// </summary>
public void MuteToggle()
{
if (_IsMuted)
{
SendFullCommand("csv", this.MuteInstanceTag, "0");
}
else
{
SendFullCommand("csv", this.MuteInstanceTag, "1");
}
}
public void VolumeUpRepeat(object callbackObject)
{
this.VolumeUp(true);
}
public void VolumeDownRepeat(object callbackObject)
{
this.VolumeDown(true);
}
public void VolumeDown(bool press)
{
if (press)
{
VolumeDownRepeatTimer.Reset(100);
SendFullCommand("css ", this.LevelInstanceTag, "--");
}
else
{
VolumeDownRepeatTimer.Stop();
// VolumeDownRepeatTimer.Dispose();
}
}
/// <summary>
/// Increments volume level
/// </summary>
/// <param name="pressRelease"></param>
public void VolumeUp(bool press)
{
if (press)
{
VolumeUpRepeatTimer.Reset(100);
SendFullCommand("css ", this.LevelInstanceTag, "++");
if (AutomaticUnmuteOnVolumeUp)
if (!_IsMuted)
MuteOff();
}
else
{
VolumeUpRepeatTimer.Stop();
}
}
/// <returns></returns>
double Scale(double input)
{
Debug.Console(1, this, "Scaling (double) input '{0}'",input );
var output = (input / 65535);
Debug.Console(1, this, "Scaled output '{0}'", output);
return output;
}
}
public enum ePdtLevelTypes
{
speaker = 0,
microphone = 1
}
} | 25.739414 | 146 | 0.55391 | [
"MIT"
] | JaytheSpazz/Essentials | essentials-framework/Essentials Devices Common/Essentials Devices Common/DSP/QSC/QscDspLevelControl.cs | 7,904 | C# |
namespace ChessGameLogic.ChessFigures
{
using System;
using System.Collections.Generic;
using ChessGameLogic.ChessFigures.Interfaces;
using ChessGameLogic.ChessMoves;
using ChessGameLogic.Enums;
internal class Pawn : Figure, IUnableToJumpFigure
{
internal Pawn(ChessColors color)
: base(color)
{
}
public override bool AreMovePositionsPossible(NormalChessMovePositions normalMove)
{
int differenceInHorizontal = Math.Abs(normalMove.InitialPosition.Horizontal - normalMove.TargetPosition.Horizontal);
int differenceInVertical = Math.Abs(normalMove.InitialPosition.Vertical - normalMove.TargetPosition.Vertical);
if (this.Color == ChessColors.White && normalMove.InitialPosition.Vertical == 1)
{
return false;
}
if (this.Color == ChessColors.Black && normalMove.InitialPosition.Vertical == 8)
{
return false;
}
if (differenceInHorizontal == 0 && (differenceInVertical == 1 || differenceInVertical == 2))
{
if (this.Color == ChessColors.White && normalMove.InitialPosition.Vertical == 2 && normalMove.TargetPosition.Vertical == 4)
{
return true;
}
if (this.Color == ChessColors.Black && normalMove.InitialPosition.Vertical == 7 && normalMove.TargetPosition.Vertical == 5)
{
return true;
}
if (this.Color == ChessColors.White && normalMove.InitialPosition.Vertical + 1 == normalMove.TargetPosition.Vertical)
{
return true;
}
if (this.Color == ChessColors.Black && normalMove.InitialPosition.Vertical - 1 == normalMove.TargetPosition.Vertical)
{
return true;
}
}
return false;
}
public IEnumerable<ChessBoardPosition> GetPositionsInTheWayOfMove(NormalChessMovePositions normalMove)
{
if (this.AreMovePositionsPossible(normalMove) == false && this.IsAttackingMovePossible(normalMove) == false)
{
return null;
}
if (this.IsAttackingMovePossible(normalMove))
{
return new List<ChessBoardPosition>();
}
int differenceInHorizontal = Math.Abs(normalMove.InitialPosition.Horizontal - normalMove.TargetPosition.Horizontal);
int differenceInVertical = Math.Abs(normalMove.InitialPosition.Vertical - normalMove.TargetPosition.Vertical);
if (this.Color == ChessColors.White && normalMove.InitialPosition.Vertical == 2 && normalMove.TargetPosition.Vertical == 4)
{
return new List<ChessBoardPosition>() { new ChessBoardPosition(normalMove.InitialPosition.Horizontal, 3) };
}
if (this.Color == ChessColors.Black && normalMove.InitialPosition.Vertical == 7 && normalMove.TargetPosition.Vertical == 5)
{
return new List<ChessBoardPosition>() { new ChessBoardPosition(normalMove.InitialPosition.Horizontal, 6) };
}
return new List<ChessBoardPosition>();
}
internal bool IsAttackingMovePossible(NormalChessMovePositions move)
{
if (this.Color == ChessColors.White && move.InitialPosition.Vertical == 1)
{
return false;
}
if (this.Color == ChessColors.Black && move.InitialPosition.Vertical == 8)
{
return false;
}
if (this.Color == ChessColors.White)
{
int differenceInHorizontal = Math.Abs(move.InitialPosition.Horizontal - move.TargetPosition.Horizontal);
int differenceInVertical = move.InitialPosition.Vertical - move.TargetPosition.Vertical;
if (differenceInHorizontal == 1 && differenceInVertical == -1)
{
return true;
}
}
else
{
int differenceInHorizontal = Math.Abs(move.InitialPosition.Horizontal - move.TargetPosition.Horizontal);
int differenceInVertical = move.InitialPosition.Vertical - move.TargetPosition.Vertical;
if (differenceInHorizontal == 1 && differenceInVertical == 1)
{
return true;
}
}
return false;
}
internal bool IsPositionProducable(ChessBoardPosition positionOnTheBoard)
{
if (this.Color == ChessColors.White)
{
return positionOnTheBoard.Vertical == 8;
}
else
{
return positionOnTheBoard.Vertical == 1;
}
}
}
}
| 36.97037 | 139 | 0.571629 | [
"MIT"
] | danieldamianov/ChessSystem | src/ChessSystem/ChessGameLogic/ChessFigures/Pawn.cs | 4,993 | C# |
namespace Parasite.Controller
{
partial class ControllerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.listBox1 = new System.Windows.Forms.ListBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(30)))));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.ForeColor = System.Drawing.SystemColors.Window;
this.button1.Location = new System.Drawing.Point(588, 408);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(200, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Execute command";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(60)))), ((int)(((byte)(60)))));
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox1.ForeColor = System.Drawing.SystemColors.Window;
this.textBox1.Location = new System.Drawing.Point(13, 13);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(617, 389);
this.textBox1.TabIndex = 1;
//
// button2
//
this.button2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(30)))));
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.ForeColor = System.Drawing.SystemColors.Window;
this.button2.Location = new System.Drawing.Point(12, 408);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(200, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Start Beacon Finder";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// listBox1
//
this.listBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(60)))), ((int)(((byte)(60)))));
this.listBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.listBox1.ForeColor = System.Drawing.SystemColors.Window;
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(636, 12);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(152, 390);
this.listBox1.TabIndex = 3;
//
// textBox2
//
this.textBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(60)))), ((int)(((byte)(60)))));
this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox2.ForeColor = System.Drawing.SystemColors.Window;
this.textBox2.Location = new System.Drawing.Point(218, 411);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(364, 20);
this.textBox2.TabIndex = 4;
this.textBox2.Text = "ping 127.0.0.1";
//
// ControllerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(36)))), ((int)(((byte)(36)))), ((int)(((byte)(36)))));
this.ClientSize = new System.Drawing.Size(800, 437);
this.ControlBox = false;
this.Controls.Add(this.textBox2);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "ControllerForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "ControllerForm";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.TextBox textBox2;
}
} | 47.460938 | 137 | 0.580741 | [
"MIT"
] | Naamloos/Parasite | Parasite/Parasite.Controller/ControllerForm.Designer.cs | 6,077 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts.Interfaces
{
public abstract class IHittable : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
Vector3 pos = collision.contacts[0].point;
Hit(pos, collision.gameObject);
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector3 pos = collision.contacts[0].point;
Hit(pos, collision.gameObject);
}
private void Hit(Vector3 pos, GameObject obj)
{
if (obj.tag == "Bullet")
{
OnBulletHit(pos);
}
}
protected abstract void OnBulletHit(Vector3 position);
}
}
| 20.897436 | 62 | 0.590184 | [
"MIT"
] | willem810/SpyHunt | Assets/Scripts/Interfaces/IHittable.cs | 817 | C# |
/*
* Honeybee Model Schema
*
* Documentation for Honeybee model schema
*
* Contact: info@ladybug.tools
* 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;
namespace HoneybeeSchema
{
/// <summary>
/// Base class of Abridged Radiance Properties.
/// </summary>
[Serializable]
[DataContract(Name = "_PropertiesBaseAbridged")]
public partial class PropertiesBaseAbridged : OpenAPIGenBaseModel, IEquatable<PropertiesBaseAbridged>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PropertiesBaseAbridged" /> class.
/// </summary>
/// <param name="modifier">A string for a Honeybee Radiance Modifier (default: None)..</param>
/// <param name="modifierBlk">A string for a Honeybee Radiance Modifier to be used in direct solar simulations and in isolation studies (assessingthe contribution of individual objects) (default: None)..</param>
public PropertiesBaseAbridged
(
// Required parameters
string modifier= default, string modifierBlk= default // Optional parameters
) : base()// BaseClass
{
this.Modifier = modifier;
this.ModifierBlk = modifierBlk;
// Set non-required readonly properties with defaultValue
this.Type = "_PropertiesBaseAbridged";
// check if object is valid, only check for inherited class
if (this.GetType() == typeof(PropertiesBaseAbridged))
this.IsValid(throwException: true);
}
//============================================== is ReadOnly
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name = "type")]
public override string Type { get; protected set; } = "_PropertiesBaseAbridged";
/// <summary>
/// A string for a Honeybee Radiance Modifier (default: None).
/// </summary>
/// <value>A string for a Honeybee Radiance Modifier (default: None).</value>
[DataMember(Name = "modifier")]
public string Modifier { get; set; }
/// <summary>
/// A string for a Honeybee Radiance Modifier to be used in direct solar simulations and in isolation studies (assessingthe contribution of individual objects) (default: None).
/// </summary>
/// <value>A string for a Honeybee Radiance Modifier to be used in direct solar simulations and in isolation studies (assessingthe contribution of individual objects) (default: None).</value>
[DataMember(Name = "modifier_blk")]
public string ModifierBlk { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
return "PropertiesBaseAbridged";
}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString(bool detailed)
{
if (!detailed)
return this.ToString();
var sb = new StringBuilder();
sb.Append("PropertiesBaseAbridged:\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Modifier: ").Append(Modifier).Append("\n");
sb.Append(" ModifierBlk: ").Append(ModifierBlk).Append("\n");
return sb.ToString();
}
/// <summary>
/// Returns the object from JSON string
/// </summary>
/// <returns>PropertiesBaseAbridged object</returns>
public static PropertiesBaseAbridged FromJson(string json)
{
var obj = JsonConvert.DeserializeObject<PropertiesBaseAbridged>(json, JsonSetting.AnyOfConvertSetting);
if (obj == null)
return null;
return obj.Type.ToLower() == obj.GetType().Name.ToLower() && obj.IsValid(throwException: true) ? obj : null;
}
/// <summary>
/// Creates a new instance with the same properties.
/// </summary>
/// <returns>PropertiesBaseAbridged object</returns>
public virtual PropertiesBaseAbridged DuplicatePropertiesBaseAbridged()
{
return FromJson(this.ToJson());
}
/// <summary>
/// Creates a new instance with the same properties.
/// </summary>
/// <returns>OpenAPIGenBaseModel</returns>
public override OpenAPIGenBaseModel Duplicate()
{
return DuplicatePropertiesBaseAbridged();
}
/// <summary>
/// Creates a new instance with the same properties.
/// </summary>
/// <returns>OpenAPIGenBaseModel</returns>
public override OpenAPIGenBaseModel DuplicateOpenAPIGenBaseModel()
{
return DuplicatePropertiesBaseAbridged();
}
/// <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)
{
input = input is AnyOf anyOf ? anyOf.Obj : input;
return this.Equals(input as PropertiesBaseAbridged);
}
/// <summary>
/// Returns true if PropertiesBaseAbridged instances are equal
/// </summary>
/// <param name="input">Instance of PropertiesBaseAbridged to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PropertiesBaseAbridged input)
{
if (input == null)
return false;
return base.Equals(input) &&
(
this.Modifier == input.Modifier ||
(this.Modifier != null &&
this.Modifier.Equals(input.Modifier))
) && base.Equals(input) &&
(
this.ModifierBlk == input.ModifierBlk ||
(this.ModifierBlk != null &&
this.ModifierBlk.Equals(input.ModifierBlk))
) && base.Equals(input) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = base.GetHashCode();
if (this.Modifier != null)
hashCode = hashCode * 59 + this.Modifier.GetHashCode();
if (this.ModifierBlk != null)
hashCode = hashCode * 59 + this.ModifierBlk.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.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)
{
return this.BaseValidate(validationContext);
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
protected IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> BaseValidate(ValidationContext validationContext)
{
foreach(var x in base.BaseValidate(validationContext)) yield return x;
// Type (string) pattern
Regex regexType = new Regex(@"^_PropertiesBaseAbridged$", RegexOptions.CultureInvariant);
if (this.Type != null && false == regexType.Match(this.Type).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Type, must match a pattern of " + regexType, new [] { "Type" });
}
yield break;
}
}
}
| 39.078947 | 219 | 0.584175 | [
"MIT"
] | chriswmackey/honeybee-schema-dotnet | src/HoneybeeSchema/Model/PropertiesBaseAbridged.cs | 8,910 | C# |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// package math -- go2cs converted at 2020 October 09 05:07:38 UTC
// import "math" ==> using math = go.math_package
// Original source: C:\Go\src\math\arith_s390x.go
using cpu = go.@internal.cpu_package;
using static go.builtin;
namespace go
{
public static partial class math_package
{
private static double log10TrampolineSetup(double x)
;
private static double log10Asm(double x)
;
private static double cosTrampolineSetup(double x)
;
private static double cosAsm(double x)
;
private static double coshTrampolineSetup(double x)
;
private static double coshAsm(double x)
;
private static double sinTrampolineSetup(double x)
;
private static double sinAsm(double x)
;
private static double sinhTrampolineSetup(double x)
;
private static double sinhAsm(double x)
;
private static double tanhTrampolineSetup(double x)
;
private static double tanhAsm(double x)
;
private static double log1pTrampolineSetup(double x)
;
private static double log1pAsm(double x)
;
private static double atanhTrampolineSetup(double x)
;
private static double atanhAsm(double x)
;
private static double acosTrampolineSetup(double x)
;
private static double acosAsm(double x)
;
private static double acoshTrampolineSetup(double x)
;
private static double acoshAsm(double x)
;
private static double asinTrampolineSetup(double x)
;
private static double asinAsm(double x)
;
private static double asinhTrampolineSetup(double x)
;
private static double asinhAsm(double x)
;
private static double erfTrampolineSetup(double x)
;
private static double erfAsm(double x)
;
private static double erfcTrampolineSetup(double x)
;
private static double erfcAsm(double x)
;
private static double atanTrampolineSetup(double x)
;
private static double atanAsm(double x)
;
private static double atan2TrampolineSetup(double x, double y)
;
private static double atan2Asm(double x, double y)
;
private static double cbrtTrampolineSetup(double x)
;
private static double cbrtAsm(double x)
;
private static double logTrampolineSetup(double x)
;
private static double logAsm(double x)
;
private static double tanTrampolineSetup(double x)
;
private static double tanAsm(double x)
;
private static double expTrampolineSetup(double x)
;
private static double expAsm(double x)
;
private static double expm1TrampolineSetup(double x)
;
private static double expm1Asm(double x)
;
private static double powTrampolineSetup(double x, double y)
;
private static double powAsm(double x, double y)
;
// hasVX reports whether the machine has the z/Architecture
// vector facility installed and enabled.
private static var hasVX = cpu.S390X.HasVX;
}
}
| 24.315385 | 70 | 0.693768 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/math/arith_s390x.cs | 3,161 | C# |
namespace pGina.Plugin.Kerberos
{
partial class Configuration
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.rText = new System.Windows.Forms.TextBox();
this.save = new System.Windows.Forms.Button();
this.description = new System.Windows.Forms.Label();
this.cancel = new System.Windows.Forms.Button();
this.help = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Realm:";
//
// rText
//
this.rText.Location = new System.Drawing.Point(46, 6);
this.rText.Name = "rText";
this.rText.Size = new System.Drawing.Size(214, 20);
this.rText.TabIndex = 1;
//
// save
//
this.save.Location = new System.Drawing.Point(185, 94);
this.save.Name = "save";
this.save.Size = new System.Drawing.Size(75, 23);
this.save.TabIndex = 5;
this.save.Text = "Save";
this.save.UseVisualStyleBackColor = true;
this.save.Click += new System.EventHandler(this.save_Click);
//
// description
//
this.description.Location = new System.Drawing.Point(3, 29);
this.description.Name = "description";
this.description.Size = new System.Drawing.Size(251, 38);
this.description.TabIndex = 2;
this.description.Text = "Enter the target Kerberos realm name ex: REALM.UTAH.EDU";
//
// cancel
//
this.cancel.Location = new System.Drawing.Point(104, 94);
this.cancel.Name = "cancel";
this.cancel.Size = new System.Drawing.Size(75, 23);
this.cancel.TabIndex = 4;
this.cancel.Text = "Cancel";
this.cancel.UseVisualStyleBackColor = true;
this.cancel.Click += new System.EventHandler(this.cancel_Click);
//
// help
//
this.help.Location = new System.Drawing.Point(23, 94);
this.help.Name = "help";
this.help.Size = new System.Drawing.Size(75, 23);
this.help.TabIndex = 3;
this.help.Text = "Help";
this.help.UseVisualStyleBackColor = true;
this.help.Click += new System.EventHandler(this.Btn_help);
//
// Configuration
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(269, 129);
this.Controls.Add(this.help);
this.Controls.Add(this.cancel);
this.Controls.Add(this.description);
this.Controls.Add(this.save);
this.Controls.Add(this.rText);
this.Controls.Add(this.label1);
this.Name = "Configuration";
this.Text = "KRB5 Realm Configuration";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox rText;
private System.Windows.Forms.Button save;
private System.Windows.Forms.Label description;
private System.Windows.Forms.Button cancel;
private System.Windows.Forms.Button help;
}
} | 38.733333 | 107 | 0.549484 | [
"BSD-3-Clause"
] | AdaptableApps/pgina | Plugins/Kerberos/Kerberos/Configuration.Designer.cs | 4,650 | C# |
using TickTrader.Algo.Account;
using TickTrader.Algo.Account.Fdk2;
namespace TickTrader.Algo.Server
{
public static class KnownAccountFactories
{
public static ServerInteropFactory Fdk2 => (options, loggerId) => new SfxInterop(options, loggerId);
}
}
| 24.818182 | 108 | 0.739927 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SoftFx/TTAlgo | src/csharp/core/TickTrader.Algo.Server/KnownAccountFactories.cs | 275 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microblog.Data;
namespace Microblog.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20161005123157_user relations")]
partial class userrelations
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microblog.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microblog.Models.Post", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd();
b.Property<string>("Content");
b.Property<DateTime>("PostDate");
b.Property<string>("Title");
b.Property<string>("UserId");
b.HasKey("ID");
b.HasIndex("UserId");
b.ToTable("Post");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microblog.Models.Post", b =>
{
b.HasOne("Microblog.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("Microblog.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("Microblog.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Microblog.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 33.743802 | 117 | 0.482366 | [
"MIT"
] | OmniscientJV/School-Microblog | src/Microblog/Data/Migrations/20161005123157_user relations.Designer.cs | 8,168 | C# |
using System.Web;
using System.Web.Mvc;
namespace SDJ3_3rd_tier
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19 | 80 | 0.657895 | [
"MIT"
] | SDJ3-group/SDJ3-3rd-tier | SDJ3-3rd-tier/App_Start/FilterConfig.cs | 268 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RastojanjeIzmedjuDvaPolja
{
public class Polje
{
public Int32 Indeks, Red, Kolona, Udaljenost;
public static Int32 BrojRedova, BrojKolona;
public Boolean Sanduk;
public Button Dugme;
public Polje(Int32 Ind, Int32 Br_Redova, Int32 Br_Kolona, Button DugmeSaForme)
{
Indeks = Ind;
BrojRedova = Br_Redova;
BrojKolona = Br_Kolona;
Red = (Indeks - 1) / BrojKolona + 1;
Kolona = (Indeks - 1) % BrojKolona + 1;
Udaljenost = -1;
Sanduk = false;
Dugme = DugmeSaForme;
}
}
}
| 27.103448 | 87 | 0.569975 | [
"MIT"
] | nikola-vukicevic/bfs_i_dfs_pathfinding | RastojanjeIzmedjuDvaPolja/Polje.cs | 788 | C# |
/**
* The MIT License
* Copyright (c) 2016 Population Register Centre (VRK)
*
* 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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("PTV.Framework.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PTV.Framework.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a64269d7-8946-4a5c-a68f-21793bdba1d5")]
| 46.891304 | 84 | 0.766806 | [
"MIT"
] | MikkoVirenius/ptv-1.7 | test/PTV.Framework.Tests/Properties/AssemblyInfo.cs | 2,160 | 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 System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
public class JQueryFormValueProviderFactory : IValueProviderFactory
{
public Task<IValueProvider> GetValueProviderAsync(ValueProviderFactoryContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var request = context.HttpContext.Request;
if (request.HasFormContentType)
{
return CreateValueProviderAsync(request);
}
return TaskCache<IValueProvider>.DefaultCompletedTask;
}
private static async Task<IValueProvider> CreateValueProviderAsync(HttpRequest request)
{
return new JQueryFormValueProvider(
BindingSource.Form,
await GetValueCollectionAsync(request),
CultureInfo.CurrentCulture);
}
private static async Task<IDictionary<string, StringValues>> GetValueCollectionAsync(HttpRequest request)
{
var formCollection = await request.ReadFormAsync();
var dictionary = new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in formCollection)
{
var key = NormalizeJQueryToMvc(entry.Key);
dictionary[key] = entry.Value;
}
return dictionary;
}
// This is a helper method for Model Binding over a JQuery syntax.
// Normalize from JQuery to MVC keys. The model binding infrastructure uses MVC keys.
// x[] --> x
// [] --> ""
// x[12] --> x[12]
// x[field] --> x.field, where field is not a number
private static string NormalizeJQueryToMvc(string key)
{
if (string.IsNullOrEmpty(key))
{
return string.Empty;
}
var indexOpen = key.IndexOf('[');
if (indexOpen == -1)
{
// Fast path, no normalization needed.
// This skips string conversion and allocating the string builder.
return key;
}
var builder = new StringBuilder();
var position = 0;
while (position < key.Length)
{
if (indexOpen == -1)
{
// No more brackets.
builder.Append(key, position, key.Length - position);
break;
}
builder.Append(key, position, indexOpen - position); // everything up to "["
// Find closing bracket.
var indexClose = key.IndexOf(']', indexOpen);
if (indexClose == -1)
{
throw new ArgumentException(
message: Resources.FormatJQueryFormValueProviderFactory_MissingClosingBracket(key),
paramName: "key");
}
if (indexClose == indexOpen + 1)
{
// Empty brackets signify an array. Just remove.
}
else if (char.IsDigit(key[indexOpen + 1]))
{
// Array index. Leave unchanged.
builder.Append(key, indexOpen, indexClose - indexOpen + 1);
}
else
{
// Field name. Convert to dot notation.
builder.Append('.');
builder.Append(key, indexOpen + 1, indexClose - indexOpen - 1);
}
position = indexClose + 1;
indexOpen = key.IndexOf('[', position);
}
return builder.ToString();
}
}
}
| 34.435484 | 113 | 0.535831 | [
"Apache-2.0"
] | VGGeorgiev/Mvc | src/Microsoft.AspNet.Mvc.Core/ModelBinding/JQueryFormValueProviderFactory.cs | 4,270 | C# |
/******************************************************************************
* Copyright (C) Ultraleap, Inc. 2011-2020. *
* Ultraleap proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Ultraleap and you, your company or other organization. *
******************************************************************************/
using UnityEngine;
using System.Collections;
using Leap;
namespace Leap.Unity {
/**
* A HandModel that draws lines for the bones in the hand and its fingers.
*
* The debugs lines are only drawn in the Editor Scene view (when a hand is tracked) and
* not in the Game view. Use debug hands when you aren't using visible hands in a scene
* so that you can see where the hands are in the scene view.
* */
public class DebugHand : HandModelBase {
private Hand hand_;
[SerializeField]
private bool visualizeBasis = true;
public bool VisualizeBasis { get { return visualizeBasis; } set { visualizeBasis = value; } }
/** The colors used for each bone. */
protected Color[] colors = { Color.gray, Color.yellow, Color.cyan, Color.magenta };
public override ModelType HandModelType {
get {
return ModelType.Graphics;
}
}
#pragma warning disable 0649
[SerializeField]
private Chirality handedness;
public override Chirality Handedness {
get {
return handedness;
}
set { }
}
#pragma warning restore 0649
public override Hand GetLeapHand() {
return hand_;
}
public override void SetLeapHand(Hand hand) {
hand_ = hand;
}
public override bool SupportsEditorPersistence() {
return true;
}
/**
* Initializes the hand and calls the line drawing function.
*/
public override void InitHand() {
DrawDebugLines();
}
/**
* Updates the hand and calls the line drawing function.
*/
public override void UpdateHand() {
DrawDebugLines();
}
/**
* Draws lines from elbow to wrist, wrist to palm, and normal to the palm.
*/
protected void DrawDebugLines() {
Hand hand = GetLeapHand();
Debug.DrawLine(hand.Arm.ElbowPosition.ToVector3(), hand.Arm.WristPosition.ToVector3(), Color.red); //Arm
Debug.DrawLine(hand.WristPosition.ToVector3(), hand.PalmPosition.ToVector3(), Color.white); //Wrist to palm line
Debug.DrawLine(hand.PalmPosition.ToVector3(), (hand.PalmPosition + hand.PalmNormal * hand.PalmWidth / 2).ToVector3(), Color.black); //Hand Normal
if (VisualizeBasis) {
DrawBasis(hand.PalmPosition, hand.Basis, hand.PalmWidth / 4); //Hand basis
DrawBasis(hand.Arm.ElbowPosition, hand.Arm.Basis, .01f); //Arm basis
}
for (int f = 0; f < 5; f++) { //Fingers
Finger finger = hand.Fingers[f];
for (int i = 0; i < 4; ++i) {
Bone bone = finger.Bone((Bone.BoneType)i);
Debug.DrawLine(bone.PrevJoint.ToVector3(), bone.PrevJoint.ToVector3() + bone.Direction.ToVector3() * bone.Length, colors[i]);
if (VisualizeBasis)
DrawBasis(bone.PrevJoint, bone.Basis, .01f);
}
}
}
public void DrawBasis(Vector position, LeapTransform basis, float scale) {
Vector3 origin = position.ToVector3();
Debug.DrawLine(origin, origin + basis.xBasis.ToVector3() * scale, Color.red);
Debug.DrawLine(origin, origin + basis.yBasis.ToVector3() * scale, Color.green);
Debug.DrawLine(origin, origin + basis.zBasis.ToVector3() * scale, Color.blue);
}
}
}
| 36.266055 | 152 | 0.582595 | [
"MIT"
] | HyperLethalVector/ProjectEsky-UnityIntegration | Assets/Plugins/LeapMotion/Core/Scripts/Hands/DebugHand.cs | 3,953 | C# |
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using AbMath.Calculator.Operators;
namespace AbMath.Calculator.Simplifications
{
public static class Sum
{
private static readonly RPN.Token _sum = new RPN.Token("sum", 4, RPN.Type.Function);
public static bool setUp(RPN.Node node)
{
return node.IsFunction("sum");
}
/// <summary>
/// Code from: https://rosettacode.org/wiki/Bernoulli_numbers
/// </summary>
/// <param name="nth"></param>
/// <returns></returns>
public static RPN.Node getBernoulliNumber(int n)
{
if (n < 0)
{
throw new ArgumentOutOfRangeException("The Bernoulli number is not defined for values below zero.");
}
BigInteger f;
BigInteger[] nu = new BigInteger[n + 1],
de = new BigInteger[n + 1];
for (int m = 0; m <= n; m++)
{
nu[m] = 1; de[m] = m + 1;
for (int j = m; j > 0; j--)
if ((f = BigInteger.GreatestCommonDivisor(
nu[j - 1] = j * (de[j] * nu[j - 1] - de[j - 1] * nu[j]),
de[j - 1] *= de[j])) != BigInteger.One)
{ nu[j - 1] /= f; de[j - 1] /= f; }
}
if (n == 1)
{
nu[0] = -1;
}
return new Div(new RPN.Node((double)nu[0]), new RPN.Node((double)de[0]));
}
public static bool PropagationRunnable(RPN.Node node)
{
return node[3].IsAddition() || node[3].IsSubtraction();
}
public static RPN.Node Propagation(RPN.Node node)
{
RPN.Node sum = new RPN.Node(new RPN.Node[] { node[0].Clone(), node[1].Clone(), node[2].Clone(), node[3, 1].Clone() }, _sum);
node.Replace(node[3], node[3,0]); //This saves a simplification step later
return new Add(node.Clone(), sum);
}
public static bool VariableRunnable(RPN.Node node)
{
return (node[1].IsNumber(0) || node[1].IsNumber(1)) && node[3].IsVariable() && node[3].Matches(node[2]);
}
public static RPN.Node Variable(RPN.Node node)
{
return new Div( new Mul(node[0], new Add(node[0].Clone(), new RPN.Node(1)) ), new RPN.Node(2) );
}
public static bool ConstantComplexRunnable(RPN.Node node)
{
return node[3].IsNumberOrConstant() || (node[3].IsVariable() && !node[3].Matches(node[2])) ;
}
public static RPN.Node ConstantComplex(RPN.Node node)
{
RPN.Node subtraction = new RPN.Node(new RPN.Node[] {node[1], node[0]}, new RPN.Token("-", 2, RPN.Type.Operator));
RPN.Node addition = new RPN.Node(new RPN.Node[] {subtraction, new RPN.Node(1)}, new RPN.Token("+", 2, RPN.Type.Operator));
RPN.Node multiplication = new RPN.Node(new RPN.Node[] {node[3], addition}, new RPN.Token("*", 2, RPN.Type.Operator));
return multiplication;
}
public static bool CoefficientRunnable(RPN.Node node)
{
return node[3].IsMultiplication() && node[3, 1].IsNumberOrConstant();
}
public static RPN.Node Coefficient(RPN.Node node)
{
RPN.Node sum = new RPN.Node(new RPN.Node[] {node[0].Clone(), node[1].Clone(), node[2].Clone(), node[3, 0]}, _sum);
return new Mul(node[3,1], sum);
}
public static bool CoefficientDivisionRunnable(RPN.Node node)
{
return node[3].IsDivision() && node[3, 0].IsNumberOrConstant();
}
public static RPN.Node CoefficientDivision(RPN.Node node)
{
RPN.Node sum = new RPN.Node(new RPN.Node[] { node[0].Clone(), node[1].Clone(), node[2].Clone(), node[3, 1] }, _sum);
return new Div(sum ,node[3,0]);
}
public static bool PowerRunnable(RPN.Node node)
{
return ( node[1].IsInteger(1) || node[1].IsNumber(0) ) //start point must be 0 or 1 since 0^(c) = 0 when c > 0.
&& node[3].IsExponent()
&& node[3, 0].IsInteger() &&
node[3, 0].IsGreaterThanNumber(0) && //ensures power is positive
node[3, 1].Matches(node[2]);
}
public static RPN.Node Power(RPN.Node node)
{
RPN.Node power = node[3, 0].Clone();
RPN.Node end = node[0].Clone();
RPN.Token _fac = new RPN.Token("!", 1, RPN.Type.Operator);
RPN.Token _total = new RPN.Token("total", (int)power.GetNumber(), RPN.Type.Function);
RPN.Node total = new RPN.Node(_total);
double max = power.GetNumber();
RPN.Node numeratorAddition = new RPN.Node(power.GetNumber() + 1); //(p + 1)
for (int i = 0; i <= max; i++)
{
RPN.Node j = new RPN.Node(i);
RPN.Node subtraction = new RPN.Node(power.GetNumber() - j.GetNumber()); //(p - j)
RPN.Node addition = new RPN.Node(subtraction.GetNumber() + 1); //(p - j + 1)
RPN.Node exponent = new Pow(end.Clone(), addition.Clone()); //n^(p - j + 1)
RPN.Node bernoulli = Sum.getBernoulliNumber(i); //B(j)
RPN.Node numerator = new RPN.Node(new RPN.Node[] { numeratorAddition.Clone() }, _fac); //(p + 1)!
RPN.Node denominatorFactorial = new RPN.Node(new RPN.Node[] { addition.Clone() }, _fac); //(p - j + 1)!
RPN.Node jFactorial = new RPN.Node(new RPN.Node[] { j.Clone() }, _fac); //j!
RPN.Node denominator = new Mul(jFactorial, denominatorFactorial); // j! * (p - j + 1)!
RPN.Node fraction = new Div(numerator, denominator);
RPN.Node negativeOneExponent = new Pow(new RPN.Node(-1), j.Clone()); //(-1)^j
RPN.Node multiplication = new Mul(new Mul(negativeOneExponent, fraction), new Mul(bernoulli, exponent));
total.AddChild(multiplication);
}
return new Div(total, numeratorAddition.Clone());
}
}
}
| 39.878981 | 138 | 0.524996 | [
"MIT"
] | 65001/AbMath | AbMath/Calculator/Simplifications/Sum.cs | 6,263 | C# |
///--------------------------------------------------------------------------------
///
/// Copyright (C) 2020-2021 Jose E. Gonzalez (nxoffice2021@gmail.com) - All Rights Reserved
///
/// 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.
///
///--------------------------------------------------------------------------------
/// Packet Manager Requirements
///
/// Install-Package Newtonsoft.Json -Version 12.0.3
///
using System;
using System.Collections.Generic;
using System.Linq;
using Docker.DotNet.Models;
using Newtonsoft.Json.Linq;
using NX.Shared;
namespace NX.Engine.Hive
{
/// <summary>
///
/// A bee's CV with all the information about it
///
/// </summary>
public class BeeCVClass : ChildOfClass<FieldClass>
{
#region Constructor
/// <summary>
///
/// Constructor
///
/// </summary>
/// <param name="values">The values as a JObject</param>
public BeeCVClass(FieldClass field, string id, BeeClass.Types type = BeeClass.Types.Bee)
: base(field)
{
//
this.IsGhost = type == BeeClass.Types.Ghost;
this.IsVirtual = type == BeeClass.Types.Virtual;
// Make a phony values
this.Values = new ContainerListResponse();
// Set the Id
this.Values.ID = id;
// Handle non-bee setup
if (this.IsGhost || this.IsVirtual)
{
// make phony labels
this.Labels = new Dictionary<string, string>();
// Fill
this.Labels.Add(this.TheHive.LabelID, id);
this.Labels.Add(this.TheHive.LabelUUID, "".GUID());
this.Labels.Add(this.TheHive.LabelDNA, HiveClass.ProcessorDNAName + "_");
this.Labels.Add(this.TheHive.LabelHive + "_" + this.Parent.Name, "Y");
this.Labels.Add(this.TheHive.LabelField, field.Name);
this.Labels.Add(this.TheHive.LabelProc, field.Parent.Parent.Process);
}
// And refresh
this.Refresh();
}
public BeeCVClass(FieldClass field, ContainerListResponse cv)
: base(field)
{
// Make the UUID
this.Values = cv;
//
this.BuildTickleAreas();
}
#endregion
#region Properties
/// <summary>
///
/// Obtained from Docker
///
/// </summary>
private ContainerListResponse Values { get; set; }
/// <summary>
///
/// Is this a ghost bee?
///
/// </summary>
public bool IsGhost { get; private set; }
/// <summary>
///
/// Is this a virtual bee?
///
/// </summary>
public bool IsVirtual { get; private set; }
/// <summary>
///
/// Is the bee running?
///
/// </summary>
public bool IsRunning
{
get { return this.State.IsSameValue("running"); }
}
/// <summary>
///
/// The bee is in trouble!
///
/// </summary>
public bool IsInTrouble
{
get
{
return this.State.IsSameValue("exited") ||
this.State.IsSameValue("unhealthy") ||
this.State.IsSameValue("restarting");
}
}
#endregion
#region CV
public string Id
{
get { return this.Values.ID; }
}
public List<string> Names
{
get { return this.Values.Names as List<string>; }
}
public string Image
{
get { return this.Values.Image; }
}
public string ImageID
{
get { return this.Values.ImageID; }
}
public string Command
{
get { return this.Values.Command; }
}
public DateTime Created
{
get { return this.Values.Created; }
}
public string State
{
get { return this.Values.State; }
}
public string Status
{
get { return this.Values.Status; }
}
public List<Port> Ports
{
get { return new List<Port>(this.Values.Ports); }
}
public IDictionary<string, string> Labels
{
get { return this.Values.Labels; }
private set { this.Values.Labels = value; }
}
public long SizeRw
{
get { return this.Values.SizeRw; }
}
public long SizeRootFs
{
get { return this.Values.SizeRootFs; }
}
public SummaryNetworkSettings NetworkSettings
{
get { return this.Values.NetworkSettings; }
}
public IList<MountPoint> Mounts
{
get { return this.Values.Mounts; }
}
#endregion
#region Extras
/// <summary>
///
/// The unique ID for the container
///
/// </summary>
public string NXID
{
get { return this.GetLabel(this.TheHive.LabelID); }
}
/// <summary>
///
/// The unique ID for the container
///
/// </summary>
public string GUID
{
get { return this.GetLabel(this.TheHive.LabelUUID); }
}
/// <summary>
///
/// The genome that created this container
///
/// </summary>
public string DNA
{
get { return this.GetLabel(this.TheHive.LabelDNA).IfEmpty().Replace("_", "."); }
set { this.SetLabel(this.TheHive.LabelDNA, value.IfEmpty().Replace(".", "_")); }
}
/// <summary>
///
/// The sites that created this container
///
/// </summary>
public List<string> Hives
{
get
{
// Assume none
List<string> c_Ans = new List<string>();
// Any Labels
if (this.Labels != null)
{
// Make the pattern
string sPatt = this.TheHive.LabelHive + "_";
// Loop thru
foreach (string sKey in this.Labels.Keys)
{
// Hive?
if (sKey.StartsWith(sPatt))
{
// Get the name
c_Ans.Add(sKey.Substring(sPatt.Length));
}
}
}
return c_Ans;
}
}
/// <summary>
///
/// The member that holds this container
///
/// </summary>
public string Field
{
get { return this.GetLabel(this.TheHive.LabelField); }
}
/// <summary>
///
/// The original Cmd
///
/// </summary>
public JArray Cmd
{
get { return this.GetLabel(this.TheHive.LabelCmd).ToJArray(); }
}
/// <summary>
///
/// Returns the bee proc value
///
/// </summary>
public string Proc
{
get { return this.GetLabel(this.TheHive.LabelProc); }
}
/// <summary>
///
/// The tickle areas
///
/// </summary>
public List<TickleAreaClass> TickleAreas { get; private set; }
#endregion
#region Hive
private HiveClass TheHive { get { return this.Parent.Parent; } }
#endregion
#region Methods
/// <summary>
///
/// The labels
///
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
private string GetLabel(string label)
{
// Assume none
string sAns = "";
// Do we have labels?
if (this.Labels != null && this.Labels.ContainsKey(label))
{
// Get
sAns = this.Labels[label];
}
return sAns;
}
/// <summary>
///
/// Sets a labels
///
/// </summary>
/// <param name="label">The label to set</param>
/// <param name="value">The value to set it to</param>
private void SetLabel(string label, string value)
{
// Do we have labels?
if (this.Labels == null)
{
// Make them
this.Labels = new Dictionary<string, string>();
}
//
this.Labels[label] = value;
}
/// <summary>
///
/// Waits until a container has reached a state
///
/// </summary>
/// <param name="member">The member holding the container</param>
/// <param name="id">The container Id</param>
/// <param name="cb">The callback when the container has reached a state</param>
/// <param name="states">List of states that we are looking for</param>
public void Wait(HiveClass hive, params WaitClass[] states)
{
// Make the states into a list
List<WaitClass> c_States = new List<WaitClass>(states);
// Do till no more
WaitClass.TriggerReturns eState = WaitClass.TriggerReturns.Continue;
do
{
// Wait a bit
500.MillisecondsAsTimeSpan().Sleep();
// Get info
this.Refresh();
// Loop thru
foreach (WaitClass c_Wait in c_States)
{
// Triggered?
eState = c_Wait.Trigger(this.State);
// Only one
if (eState == WaitClass.TriggerReturns.EndWait) break;
}
}
while (eState == WaitClass.TriggerReturns.Continue);
}
/// <summary>
///
/// Refreshes the CV contents
///
/// </summary>
public void Refresh()
{
// Skip if ghost or virtual
if (!this.IsGhost && !this.IsVirtual)
{
// Get client
DockerIFClass c_Client = this.Parent.DockerIF;
// Any?
if (c_Client != null)
{
// Protect
try
{
// Get
IList<ContainerListResponse> c_CVs = c_Client.ListContainersByID(this.Id);
// Any?
if (c_CVs.Count > 0)
{
// Get the first and only
this.Values = c_CVs.First();
}
}
catch { }
}
}
//
this.BuildTickleAreas();
}
/// <summary>
///
/// Makes a state change trigger
///
/// </summary>
/// <param name="cb">The callback</param>
/// <param name="states">The states that will trigger the callback</param>
/// <returns></returns>
public WaitClass MakeWait(Func<BeeCVClass, WaitClass.TriggerReturns> cb, params string[] states)
{
return new WaitClass(this, cb, states);
}
/// <summary>
///
/// Builds the list of tickle areas
///
/// </summary>
private void BuildTickleAreas()
{
// reset
this.TickleAreas = new List<TickleAreaClass>();
TickleAreaClass c_EP = null;
// Setup by type
if (this.IsGhost)
{
// If ghost, phony the URL
//this.IURL = "".GetLocalIP() + ":{0}".FormatString(this.Parent.Parent.Parent.HTTPPort).URLMake();
// Make the TickleArea
c_EP = new TickleAreaClass(this, this.Parent.Parent.Parent.HTTPPort.ToString(),
this.Parent.Parent.Parent.HTTPPort.ToString());
// Add
this.AddTickleArea(c_EP);
}
else if (this.IsVirtual)
{
// Parse
ItemClass c_Info = new ItemClass(this.Values.ID);
// Must have modifier (port)
string sPort = c_Info.Option;
if (sPort.HasValue())
{
// The key portion is the DNA
this.DNA = c_Info.Key;
// Make a tickle area with the rest
TickleAreaClass c_Tickle = new TickleAreaClass(this,
sPort,
sPort,
c_Info.Value + ":" + sPort);
// Add
this.AddTickleArea(c_Tickle);
}
}
else
{
// Loop thru
foreach (Port c_Port in this.Ports)
{
// Make the TickleArea
c_EP = new TickleAreaClass(this, c_Port.PublicPort.ToString(),
c_Port.PrivatePort.ToString());
// Is it reachable?
if (c_EP.IsAvailable)
{
// Add
this.AddTickleArea(c_EP);
}
}
}
}
private void AddTickleArea(TickleAreaClass ep)
{
// Assume not there
bool bFound = false;
// Loop thru
foreach(TickleAreaClass c_EP in this.TickleAreas)
{
//
if (c_EP != null)
{
// Same?
bFound = c_EP.ToString().IsSameValue(ep.ToString());
// Only one
if (bFound) break;
}
}
// Only if new
if (!bFound) this.TickleAreas.Add(ep);
}
#endregion
/// <summary>
///
/// Allows for a callback when a state changes
///
/// </summary>
public class WaitClass : ChildOfClass<BeeCVClass>
{
#region Constructor
internal WaitClass(BeeCVClass cv, Func<BeeCVClass, TriggerReturns> cb, params string[] states)
: base(cv)
{
// Make
this.States = new List<string>(states);
this.Callback = cb;
}
#endregion
#region Enums
public enum TriggerReturns
{
Continue,
EndWait
}
#endregion
#region Properties
/// <summary>
///
/// The states that will trigger the callback
///
/// </summary>
private List<string> States { get; set; }
/// <summary>
///
/// The callback
///
/// </summary>
private Func<BeeCVClass, TriggerReturns> Callback { get; set; }
#endregion
#region Methods
/// <summary>
///
/// Triggers a callback on a state
///
/// </summary>
/// <param name="state"></param>
/// <returns></returns>
public TriggerReturns Trigger(string state)
{
// Assume not
TriggerReturns eNext = TriggerReturns.Continue;
// In a state we are looking for?
if (this.States.Contains(state))
{
// Do we have a callback?
if (this.Callback != null)
{
// Do
eNext = this.Callback(this.Parent);
}
}
return eNext;
}
#endregion
}
}
} | 29.004926 | 115 | 0.443161 | [
"MIT"
] | nxproject/node | NX.Engine/Hive/BeeCV.cs | 17,666 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("ReswPlusLib.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReswPlusLib.UWP")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | 37.068966 | 85 | 0.72186 | [
"MIT"
] | DotNetPlus/ReswPlus | src/Library/ReswPlusLib.UWP/Properties/AssemblyInfo.cs | 1,078 | C# |
using Qsi.Tree;
using Qsi.Tree.Definition;
namespace Qsi.Hana.Tree
{
public sealed class HanaViewDefinitionNode : QsiViewDefinitionNode
{
public string Comment { get; set; }
public QsiTreeNodeProperty<QsiExpressionFragmentNode> Parameters { get; }
public QsiTreeNodeProperty<QsiExpressionFragmentNode> Associations { get; }
public QsiTreeNodeProperty<QsiExpressionFragmentNode> Masks { get; }
public QsiTreeNodeProperty<QsiExpressionFragmentNode> ExpressionMacros { get; }
public QsiTreeNodeProperty<QsiExpressionFragmentNode> Annotation { get; }
public bool StructuredPrivilegeCheck { get; set; }
public QsiTreeNodeProperty<QsiExpressionFragmentNode> Cache { get; }
public bool Force { get; set; }
public bool CheckOption { get; set; }
public bool DdlOnly { get; set; }
public bool ReadOnly { get; set; }
public QsiTreeNodeProperty<QsiExpressionFragmentNode> Anonymization { get; }
public HanaViewDefinitionNode()
{
Parameters = new QsiTreeNodeProperty<QsiExpressionFragmentNode>(this);
Associations = new QsiTreeNodeProperty<QsiExpressionFragmentNode>(this);
Masks = new QsiTreeNodeProperty<QsiExpressionFragmentNode>(this);
ExpressionMacros = new QsiTreeNodeProperty<QsiExpressionFragmentNode>(this);
Annotation = new QsiTreeNodeProperty<QsiExpressionFragmentNode>(this);
Cache = new QsiTreeNodeProperty<QsiExpressionFragmentNode>(this);
Anonymization = new QsiTreeNodeProperty<QsiExpressionFragmentNode>(this);
}
}
}
| 36.086957 | 88 | 0.706024 | [
"MIT"
] | ScriptBox99/chequer-qsi | Qsi.Hana/Tree/HanaViewDefinitionNode.cs | 1,662 | C# |
#pragma checksum "..\..\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "87B10512EF6593BD3DC3D4A789ED2ADF"
//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------
using DotNetSourceBuilder;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace DotNetSourceBuilder {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
#line 5 "..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
DotNetSourceBuilder.App app = new DotNetSourceBuilder.App();
app.InitializeComponent();
app.Run();
}
}
}
| 32.056338 | 110 | 0.619947 | [
"MIT"
] | codedsphere/DotNetSourceBuilder | DotNetSourceBuilder/DotNetSourceBuilder/obj/Debug/App.g.cs | 2,278 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using ICSharpCode.PythonBinding;
using NUnit.Framework;
using PythonBinding.Tests.Utils;
namespace PythonBinding.Tests.Designer
{
[TestFixture]
public class LoadMonthCalendarTestFixture : LoadFormTestFixtureBase
{
public override string PythonCode {
get {
return "class MainForm(System.Windows.Forms.Form):\r\n" +
" def InitializeComponent(self):\r\n" +
" self._monthCalendar1 = System.Windows.Forms.MonthCalendar()\r\n" +
" self.SuspendLayout()\r\n" +
" # \r\n" +
" # monthCalendar1\r\n" +
" # \r\n" +
" self._monthCalendar1.Location = System.Drawing.Point(0, 0)\r\n" +
" self._monthCalendar1.MonthlyBoldedDates = System.Array[System.DateTime](\r\n" +
" [System.DateTime(2009, 1, 2, 0, 0, 0, 0),\r\n" +
" System.DateTime(0)])\r\n" +
" self._monthCalendar1.Name = \"monthCalendar1\"\r\n" +
" self._monthCalendar1.SelectionRange = System.Windows.Forms.SelectionRange(System.DateTime(2009, 8, 4, 0, 0, 0, 0), System.DateTime(2009, 8, 5, 0, 0, 0, 0))\r\n" +
" self._monthCalendar1.TabIndex = 0\r\n" +
" # \r\n" +
" # MainForm\r\n" +
" # \r\n" +
" self.ClientSize = System.Drawing.Size(200, 300)\r\n" +
" self.Controls.Add(self._monthCalendar1)\r\n" +
" self.Name = \"MainForm\"\r\n" +
" self.ResumeLayout(False)\r\n" +
" self.PerformLayout()\r\n";
}
}
public MonthCalendar Calendar {
get { return Form.Controls[0] as MonthCalendar; }
}
[Test]
public void MonthlyBoldedDates()
{
DateTime[] expectedDates = new DateTime[] { new DateTime(2009, 1, 2), new DateTime(0) };
Assert.AreEqual(expectedDates, Calendar.MonthlyBoldedDates);
}
[Test]
public void SelectionRange()
{
SelectionRange expectedRange = new SelectionRange(new DateTime(2009, 8, 4, 0, 0, 0, 0), new DateTime(2009, 8, 5, 0, 0, 0, 0));
Assert.AreEqual(expectedRange.ToString(), Calendar.SelectionRange.ToString());
}
}
}
| 37.257576 | 178 | 0.620171 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | src/AddIns/BackendBindings/Python/PythonBinding/Test/Designer/LoadMonthCalendarTestFixture.cs | 2,461 | C# |
using Application.Features.Cars.Dtos;
using Core.Persistence.Paging;
namespace Application.Features.Cars.Models;
public class CarListModel : BasePageableModel
{
public IList<CarListDto> Items { get; set; }
} | 23.777778 | 48 | 0.785047 | [
"MIT"
] | ahmet-cetinkaya/rentacar-project-backend-dotnet | src/rentACar/Application/Features/Cars/Models/CarListModel.cs | 216 | C# |
/*
* Copyright 2010-2014 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 redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Container for the parameters to the DisableLogging operation.
/// Stops logging information, such as queries and connection attempts, for the specified
/// Amazon Redshift cluster.
/// </summary>
public partial class DisableLoggingRequest : AmazonRedshiftRequest
{
private string _clusterIdentifier;
/// <summary>
/// Gets and sets the property ClusterIdentifier.
/// <para>
/// The identifier of the cluster on which logging is to be stopped.
/// </para>
///
/// <para>
/// Example: <code>examplecluster</code>
/// </para>
/// </summary>
public string ClusterIdentifier
{
get { return this._clusterIdentifier; }
set { this._clusterIdentifier = value; }
}
// Check to see if ClusterIdentifier property is set
internal bool IsSetClusterIdentifier()
{
return this._clusterIdentifier != null;
}
}
} | 31.306452 | 106 | 0.658423 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | sdk/src/Services/Redshift/Generated/Model/DisableLoggingRequest.cs | 1,941 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Todo.Web.Data;
using GreenDonut;
using HotChocolate.DataLoader;
namespace Todo.Web.GraphQL.Authors
{
public class AuthorByIdDataLoader : BatchDataLoader<Guid, Author>
{
private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;
public AuthorByIdDataLoader(IBatchScheduler batchScheduler, IDbContextFactory<ApplicationDbContext> dbContextFactory) : base(batchScheduler)
{
_dbContextFactory = dbContextFactory ?? throw new ArgumentNullException(nameof(dbContextFactory));
}
protected override async Task<IReadOnlyDictionary<Guid, Author>> LoadBatchAsync(IReadOnlyList<Guid> keys, CancellationToken cancellationToken)
{
await using ApplicationDbContext dbContext = _dbContextFactory.CreateDbContext();
return await dbContext.Authors
.Where(s => keys.Contains(s.Id))
.ToDictionaryAsync(t => t.Id, cancellationToken);
}
}
}
| 35.625 | 150 | 0.734211 | [
"MIT"
] | chneau/example-todo-aspnet-react | Todo.Web/GraphQL/Authors/AuthorByIdDataLoader.cs | 1,140 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Security;
using System.IO;
using System.Diagnostics;
using MS.Internal.FontCache;
namespace MS.Internal.Shaping
{
internal struct LayoutOffset
{
public LayoutOffset(int dx, int dy) { this.dx=dx; this.dy=dy; }
public int dx;
public int dy;
}
/// <summary>
/// Tags used in OpenTypeLayout
/// </summary>
internal enum OpenTypeTags :uint
{
Null = 0x00000000,
GSUB = 0x47535542,
GPOS = 0x47504F53,
GDEF = 0x47444546,
BASE = 0x42415345,
name = 0x6e616D65,
post = 0x706F7374,
dflt = 0x64666c74,
head = 0x68656164,
//GSUB feature tags
locl = 0x6c6f636c,
ccmp = 0x63636d70,
rlig = 0x726c6967,
liga = 0x6c696761,
clig = 0x636c6967,
pwid = 0x70776964,
init = 0x696e6974,
medi = 0x6d656469,
fina = 0x66696e61,
isol = 0x69736f6c,
calt = 0x63616c74,
//Indic subst
nukt = 0x6e756b74,
akhn = 0x616b686e,
rphf = 0x72706866,
blwf = 0x626c7766,
half = 0x68616c66,
vatu = 0x76617475,
pres = 0x70726573,
abvs = 0x61627673,
blws = 0x626c7773,
psts = 0x70737473,
haln = 0x68616c6e,
//GPOS feature tags
kern = 0x6b65726e,
mark = 0x6d61726b,
mkmk = 0x6d6b6d6b,
curs = 0x63757273,
//Indic pos
abvm = 0x6162766d,
blwm = 0x626c776d,
dist = 0x64697374,
//script tags
latn = 0x6c61746e
}
/// <summary>
/// FeatureInfo flags, describing actions implemented in OT feature
/// </summary>
[Flags]
internal enum TagInfoFlags : uint
{
Substitution = 0x01, // does glyph substitution
Positioning = 0x02, // does glyph positioning
Both = 0x03, // does both substitution and positioning
None = 0x00 // neither of them
}
/* Used by commented code below
/// <summary>
/// OpenType feature information. Returned from GetFeatureList method
/// </summary>
internal struct TagInfo
{
public uint Tag;
public TagInfoFlags TagFlags;
public static bool IsNewTag(TagInfo[] Tags, uint Tag)
{
for(int i=0; i<Tags.Length; i++)
{
if (Tags[i].Tag==Tag) return false;
}
return true;
}
public static int GetTagIndex(TagInfo[] Tags, uint Tag)
{
for(ushort i=0; i<Tags.Length; i++)
{
if (Tags[i].Tag==Tag) return i;
}
return ushort.MaxValue;
}
}
*/
/// <summary>
/// Table pointer wrapper. Checking table boundaries
/// </summary>
internal unsafe class FontTable
{
public FontTable(byte[] data)
{
m_data = data;
if (data != null)
{
m_length = (uint)data.Length;
}
else
{
m_length = 0;
}
}
public const int InvalidOffset = int.MaxValue;
public const int NullOffset = 0;
public bool IsPresent
{
get
{
return (m_data!=null);
}
}
public ushort GetUShort(int offset)
{
Invariant.Assert(m_data!= null);
if ((offset + 1) >= m_length) throw new FileFormatException();
return (ushort)((m_data[offset]<<8) + m_data[offset+1]);
}
public short GetShort(int offset)
{
Invariant.Assert(m_data != null);
if ((offset + 1) >= m_length) throw new FileFormatException();
return (short)((m_data[offset]<<8) + m_data[offset+1]);
}
public uint GetUInt(int offset)
{
Invariant.Assert(m_data != null);
if ((offset + 3) >= m_length) throw new FileFormatException();
return (uint)((m_data[offset]<<24) + (m_data[offset+1]<<16) + (m_data[offset+2]<<8) + m_data[offset+3]);
}
public ushort GetOffset(int offset)
{
Invariant.Assert(m_data != null);
if ((offset+1)>=m_length) throw new FileFormatException();
return (ushort)((m_data[offset]<<8) + m_data[offset+1]);
}
private byte[] m_data;
private uint m_length;
}
/// <summary>
/// Font file access callbacks
/// </summary>
internal interface IOpenTypeFont
{
/// <summary>
/// Returns array containing font table data
/// Return empty array if table does not exist.
/// </summary>
FontTable GetFontTable(OpenTypeTags TableTag);
/// <summary>
/// Returns glyph coordinate
/// </summary>
LayoutOffset GetGlyphPointCoord(ushort Glyph, ushort PointIndex);
/// <summary>
/// Returns cache for layout table. If cache not found, return null Checked pointer
/// </summary>
byte[] GetTableCache(OpenTypeTags tableTag);
/// <summary>
/// Allocate space for layout table cache. If space is not available
/// client should return null checked pointer.
/// Only font cache implementation need to implement this interface.
/// Normal layout funcitons will not call it.
/// </summary>
byte[] AllocateTableCache(OpenTypeTags tableTag, int size);
}
/// <summary>
/// Text direction
/// </summary>
internal enum TextFlowDirection : ushort
{
LTR,
RTL,
TTB,
BTT
}
/// <summary>
/// Layout metrics
/// </summary>
internal struct LayoutMetrics
{
public TextFlowDirection Direction;
//if DesignEmHeight==0, result requested in design units
public ushort DesignEmHeight; // font design units per Em
public ushort PixelsEmWidth; // Em width in pixels
public ushort PixelsEmHeight; // Em height in pixels
public LayoutMetrics(TextFlowDirection Direction,
ushort DesignEmHeight,
ushort PixelsEmWidth,
ushort PixelsEmHeight)
{
this.Direction=Direction;
this.DesignEmHeight=DesignEmHeight;
this.PixelsEmWidth=PixelsEmWidth;
this.PixelsEmHeight=PixelsEmHeight;
}
}
internal class Feature
{
public Feature(
ushort startIndex,
ushort length,
uint tag,
uint parameter //0 if disabled
)
{
_startIndex = startIndex;
_length = length;
_tag = tag;
_parameter = parameter;
}
public uint Tag
{
get { return _tag; }
set { _tag = value; }
}
public uint Parameter
{
get { return _parameter; }
set { _parameter = value; }
}
public ushort StartIndex
{
get { return _startIndex; }
set { _startIndex = value; }
}
public ushort Length
{
get { return _length; }
set { _length = value; }
}
private ushort _startIndex; // first to be applied
private ushort _length; // length to be applied
private uint _tag; // OpenType feature tag
private uint _parameter; // feature parameter
}
/// <summary>
/// OpenTypeLayout class provides access to OpenType Layout services
/// </summary>
internal static unsafe class OpenTypeLayout
{
/// <summary>
/// </summary>
/// <param name="Font">Font</param>
/// <param name="ScriptTag">Script to find</param>
/// <returns>TagInfo, if script not present flags == None</returns>
internal static TagInfoFlags FindScript(
IOpenTypeFont Font, // In: Font access interface
uint ScriptTag // In
)
{
TagInfoFlags flags = TagInfoFlags.None;
try
{
FontTable gsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
if (gsubTable.IsPresent)
{
GSUBHeader gsubHeader = new GSUBHeader(0);
if (!gsubHeader.GetScriptList(gsubTable).FindScript(gsubTable,ScriptTag).IsNull)
{
flags |= TagInfoFlags.Substitution;
}
}
}
catch (FileFormatException)
{
return TagInfoFlags.None;
}
try
{
FontTable gposTable = Font.GetFontTable(OpenTypeTags.GPOS);
if (gposTable.IsPresent)
{
GPOSHeader gposHeader = new GPOSHeader(0);
if (!gposHeader.GetScriptList(gposTable).FindScript(gposTable,ScriptTag).IsNull)
{
flags |= TagInfoFlags.Positioning;
}
}
}
catch (FileFormatException)
{
return TagInfoFlags.None;
}
return flags;
}
/// <summary>
///
/// </summary>
/// <param name="Font">Font</param>
/// <param name="ScriptTag">Script to search in</param>
/// <param name="LangSysTag">LangGys to search for</param>
/// <returns>TagInfoFlags, if script not present == None</returns>
internal static TagInfoFlags FindLangSys(
IOpenTypeFont Font,
uint ScriptTag,
uint LangSysTag
)
{
TagInfoFlags flags = TagInfoFlags.None;
try
{
FontTable gsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
if (gsubTable.IsPresent)
{
GSUBHeader gsubHeader = new GSUBHeader(0);
ScriptTable gsubScript = gsubHeader.GetScriptList(gsubTable).FindScript(gsubTable,ScriptTag);
if (!gsubScript.IsNull && !gsubScript.FindLangSys(gsubTable,LangSysTag).IsNull)
{
flags |= TagInfoFlags.Substitution;
}
}
}
catch (FileFormatException)
{
return TagInfoFlags.None;
}
try
{
FontTable gposTable = Font.GetFontTable(OpenTypeTags.GPOS);
if (gposTable.IsPresent)
{
GPOSHeader gposHeader = new GPOSHeader(0);
ScriptTable gposScript = gposHeader.GetScriptList(gposTable).FindScript(gposTable,ScriptTag);
if (!gposScript.IsNull && !gposScript.FindLangSys(gposTable,LangSysTag).IsNull)
{
flags |= TagInfoFlags.Positioning;
}
}
}
catch (FileFormatException)
{
return TagInfoFlags.None;
}
return flags;
}
/* This is unused code, but will be used later so it is just commented out for now.
/// <summary>
/// Enumerates scripts in a font
/// </summary>
internal static OpenTypeLayoutResult GetScriptList (
IOpenTypeFont Font, // In: Font access interface
out TagInfo[] Scripts // Out: Array of scripts supported
)
{
ushort i;
ushort GposNewTags;
Scripts=null; // Assignment required, because of out attribute.
// This value should be owerwritten later.
try
{
FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
GSUBHeader GsubHeader = new GSUBHeader(0);
GPOSHeader GposHeader = new GPOSHeader(0);
ScriptList GsubScriptList;
ScriptList GposScriptList;
ushort GsubScriptCount;
ushort GposScriptCount;
if (GsubTable.IsNotPresent && GposTable.IsNotPresent)
{
Scripts = Array.Empty<TagInfo>();
return OpenTypeLayoutResult.Success;
}
if (GsubTable.IsPresent)
{
GsubScriptList = GsubHeader.GetScriptList(GsubTable);
GsubScriptCount = GsubScriptList.GetScriptCount(GsubTable);
}
else
{
GsubScriptList = new ScriptList(FontTable.InvalidOffset);
GsubScriptCount = 0;
}
if (GposTable.IsPresent)
{
GposScriptList = GposHeader.GetScriptList(GposTable);
GposScriptCount = GposScriptList.GetScriptCount(GposTable);
}
else
{
GposScriptList = new ScriptList(FontTable.InvalidOffset);
GposScriptCount = 0;
}
//This is true in most cases that there is no new tags in GPOS.
//So, we allocate this array then check GPOS for new tags
Scripts = new TagInfo[GsubScriptCount];
for(i=0; i<GsubScriptCount; i++)
{
Scripts[i].Tag = GsubScriptList.GetScriptTag(GsubTable,i);
Scripts[i].TagFlags = TagInfoFlags.Substitution;
}
//Check GPOS for tags that is not in GSUB
GposNewTags=0;
for(i=0;i<GposScriptCount;i++)
{
uint GposTag = GsubScriptList.GetScriptTag(GposTable,i);
if (TagInfo.IsNewTag(Scripts,GposTag)) GposNewTags++;
}
//append new tags to ScriptTags if any exists
if (GposNewTags>0)
{
int CurrentScriptIndex=GposScriptCount;
//Allocate new array to fit all tags
TagInfo[] tmp = Scripts;
Scripts = new TagInfo[GsubScriptCount+GposNewTags];
Array.Copy(tmp,0,Scripts,0,tmp.Length);
for(i=0;i<GposScriptCount;i++)
{
uint GposTag = GsubScriptList.GetScriptTag(GposTable,i);
if (TagInfo.IsNewTag(Scripts,GposTag))
{
Scripts[CurrentScriptIndex].Tag=GposTag;
Scripts[CurrentScriptIndex].TagFlags
= TagInfoFlags.Positioning;
++CurrentScriptIndex;
}
else
{
int ScriptIndex = TagInfo.GetTagIndex(Scripts,GposTag);
Scripts[ScriptIndex].TagFlags |= TagInfoFlags.Positioning;
}
}
Debug.Assert(CurrentScriptIndex==Scripts.Length);
}
}
catch (FileFormatException)
{
return OpenTypeLayoutResult.BadFontTable;
}
return OpenTypeLayoutResult.Success;
}
///<summary>
/// Enumerates language systems for script
/// </summary>
internal static OpenTypeLayoutResult GetLangSysList (
IOpenTypeFont Font, // In: Font access interface
uint ScriptTag, // In: Script tag
out TagInfo[] LangSystems // Out: Array of LangSystems for Script
)
{
ushort i;
ushort GposNewTags;
LangSystems=null; // Assignment required, because of out attribute.
// This value should be owerwritten later.
try
{
FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
GSUBHeader GsubHeader = new GSUBHeader(0);
GPOSHeader GposHeader = new GPOSHeader(0);
ScriptList GsubScriptList;
ScriptList GposScriptList;
ScriptTable GsubScript;
ScriptTable GposScript;
ushort GsubLangSysCount;
ushort GposLangSysCount;
if (GsubTable.IsNotPresent && GposTable.IsNotPresent)
{
return OpenTypeLayoutResult.ScriptNotFound;
}
if (GsubTable.IsPresent)
{
GsubScriptList = GsubHeader.GetScriptList(GsubTable);
GsubScript = GsubScriptList.FindScript(GsubTable,ScriptTag);
}
else
{
GsubScript = new ScriptTable(FontTable.InvalidOffset);
}
if (GposTable.IsPresent)
{
GposScriptList = GposHeader.GetScriptList(GposTable);
GposScript = GposScriptList.FindScript(GposTable,ScriptTag);
}
else
{
GposScript = new ScriptTable(FontTable.InvalidOffset);
}
if (GsubScript.IsNull && GposScript.IsNull)
{
return OpenTypeLayoutResult.ScriptNotFound;
}
if (!GsubScript.IsNull)
{
GsubLangSysCount = GsubScript.GetLangSysCount(GsubTable);
}
else
{
GsubLangSysCount = 0;
}
if (!GposScript.IsNull)
{
GposLangSysCount = GposScript.GetLangSysCount(GposTable);
}
else
{
GposLangSysCount = 0;
}
//This is true in most cases that there is no new tags in GPOS.
//So, we allocate this array then check GPOS for new tags
ushort CurrentLangSysIndex;
if (GsubScript.IsDefaultLangSysExists(GsubTable))
{
LangSystems = new TagInfo[GsubLangSysCount+1];
LangSystems[0].Tag = (uint)OpenTypeTags.dflt;
LangSystems[0].TagFlags = TagInfoFlags.Substitution;
CurrentLangSysIndex = 1;
}
else
{
LangSystems = new TagInfo[GsubLangSysCount];
CurrentLangSysIndex = 0;
}
for(i=0; i<GsubLangSysCount; i++)
{
LangSystems[CurrentLangSysIndex].Tag = GsubScript.GetLangSysTag(GsubTable,i);
LangSystems[CurrentLangSysIndex].TagFlags = TagInfoFlags.Substitution;
++CurrentLangSysIndex;
}
//Check GPOS for tags that is not in GSUB
GposNewTags=0;
if (!GposScript.IsNull)
{
if (GposScript.IsDefaultLangSysExists(GposTable) &&
TagInfo.IsNewTag(LangSystems,(uint)OpenTypeTags.dflt))
{
++GposNewTags;
}
for(i=0;i<GposLangSysCount;i++)
{
uint GposTag = GsubScript.GetLangSysTag(GposTable,i);
if (TagInfo.IsNewTag(LangSystems,GposTag))
{
++GposNewTags;
}
}
}
Debug.Assert(CurrentLangSysIndex==LangSystems.Length);
//append new tags to ScriptTags if any exists
if (GposNewTags>0)
{
//Allocate new array to fit all tags
TagInfo[] tmp = LangSystems;
LangSystems = new TagInfo[GsubLangSysCount+GposNewTags];
Array.Copy(tmp,0,LangSystems,0,tmp.Length);
if (GposScript.IsDefaultLangSysExists(GposTable))
{
if (TagInfo.IsNewTag(LangSystems,(uint)OpenTypeTags.dflt))
{
LangSystems[CurrentLangSysIndex].Tag = (uint)OpenTypeTags.dflt;
LangSystems[CurrentLangSysIndex].TagFlags = TagInfoFlags.Positioning;
++CurrentLangSysIndex;
}
else
{
int LangSysIndex = TagInfo.GetTagIndex(LangSystems,(uint)OpenTypeTags.dflt);
LangSystems[LangSysIndex].TagFlags |= TagInfoFlags.Positioning;
}
}
for(i=0;i<GposLangSysCount;i++)
{
uint GposTag = GposScript.GetLangSysTag(GposTable,i);
if (TagInfo.IsNewTag(LangSystems,GposTag))
{
LangSystems[CurrentLangSysIndex].Tag = GposTag;
LangSystems[CurrentLangSysIndex].TagFlags = TagInfoFlags.Positioning;
++CurrentLangSysIndex;
}
else
{
int LangSysIndex = TagInfo.GetTagIndex(LangSystems,GposTag);
LangSystems[LangSysIndex].TagFlags |= TagInfoFlags.Positioning;
}
}
Debug.Assert(CurrentLangSysIndex==LangSystems.Length);
}
}
catch (FileFormatException)
{
return OpenTypeLayoutResult.BadFontTable;
}
return OpenTypeLayoutResult.Success;
}
/// <summary>
/// Enumerates features in a language system
/// </summary>
internal static OpenTypeLayoutResult GetFeatureList (
IOpenTypeFont Font, // In: Font access interface
uint ScriptTag, // In: Script tag
uint LangSysTag, // In: LangSys tag
out TagInfo[] Features // Out: Array of features
)
{
ushort i;
ushort GposNewTags;
Features=null; // Assignment required, because of out attribute.
// This value should be owerwritten later.
try
{
FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
GSUBHeader GsubHeader = new GSUBHeader(0);
GPOSHeader GposHeader = new GPOSHeader(0);
ScriptList GsubScriptList;
ScriptList GposScriptList;
ScriptTable GsubScript;
ScriptTable GposScript;
LangSysTable GsubLangSys;
LangSysTable GposLangSys;
ushort GsubFeatureCount;
ushort GposFeatureCount;
FeatureList GsubFeatureList;
FeatureList GposFeatureList;
if (GsubTable.IsNotPresent && GposTable.IsNotPresent)
{
return OpenTypeLayoutResult.ScriptNotFound;
}
if (GsubTable.IsPresent)
{
GsubScriptList = GsubHeader.GetScriptList(GsubTable);
GsubScript = GsubScriptList.FindScript(GsubTable,ScriptTag);
GsubLangSys = GsubScript.FindLangSys(GsubTable,LangSysTag);
GsubFeatureList = GsubHeader.GetFeatureList(GsubTable);
}
else
{
GsubScript = new ScriptTable(FontTable.InvalidOffset);
GsubLangSys = new LangSysTable(FontTable.InvalidOffset);
GsubFeatureList = new FeatureList(FontTable.InvalidOffset);
}
if (GposTable.IsPresent)
{
GposScriptList = GposHeader.GetScriptList(GposTable);
GposScript = GposScriptList.FindScript(GposTable,ScriptTag);
GposLangSys = GposScript.FindLangSys(GposTable,LangSysTag);
GposFeatureList = GposHeader.GetFeatureList(GposTable);
}
else
{
GposScript = new ScriptTable(FontTable.InvalidOffset);
GposLangSys = new LangSysTable(FontTable.InvalidOffset);
GposFeatureList = new FeatureList(FontTable.InvalidOffset);
}
if (GsubScript.IsNull && GposScript.IsNull)
{
return OpenTypeLayoutResult.ScriptNotFound;
}
if (GsubLangSys.IsNull && GposLangSys.IsNull)
{
return OpenTypeLayoutResult.LangSysNotFound;
}
if (!GsubLangSys.IsNull)
{
GsubFeatureCount = GsubLangSys.FeatureCount(GsubTable);
}
else
{
GsubFeatureCount = 0;
}
if (!GposLangSys.IsNull)
{
GposFeatureCount = GposLangSys.FeatureCount(GposTable);
}
else
{
GposFeatureCount = 0;
}
Features = new TagInfo[GsubFeatureCount];
int CurrentFeatureIndex = 0;
for(i=0; i<GsubFeatureCount; i++)
{
ushort FeatureIndex = GsubLangSys.GetFeatureIndex(GsubTable,i);
Features[CurrentFeatureIndex].Tag = GsubFeatureList.FeatureTag(GsubTable,FeatureIndex);
Features[CurrentFeatureIndex].TagFlags = TagInfoFlags.Substitution;
++CurrentFeatureIndex;
}
Debug.Assert(CurrentFeatureIndex==Features.Length);
//Check GPOS for tags that is not in GSUB
GposNewTags=0;
if (!GposLangSys.IsNull)
{
for(i=0;i<GposFeatureCount;i++)
{
ushort FeatureIndex = GposLangSys.GetFeatureIndex(GposTable,i);
uint GposTag = GposFeatureList.FeatureTag(GposTable,FeatureIndex);
if (TagInfo.IsNewTag(Features,GposTag))
{
++GposNewTags;
}
}
}
//append new tags to ScriptTags if any exists
if (GposNewTags>0)
{
//Allocate new array to fit all tags
TagInfo[] tmp = Features;
Features = new TagInfo[GsubFeatureCount+GposNewTags];
Array.Copy(tmp,0,Features,0,tmp.Length);
for(i=0;i<GposFeatureCount;i++)
{
ushort FeatureIndex = GposLangSys.GetFeatureIndex(GposTable,i);
uint GposTag = GposFeatureList.FeatureTag(GposTable,FeatureIndex);
if (TagInfo.IsNewTag(Features,GposTag))
{
Features[CurrentFeatureIndex].Tag = GposTag;
Features[CurrentFeatureIndex].TagFlags = TagInfoFlags.Positioning;
++CurrentFeatureIndex;
}
else
{
int Index = TagInfo.GetTagIndex(Features,GposTag);
Features[Index].TagFlags |= TagInfoFlags.Positioning;
}
}
Debug.Assert(CurrentFeatureIndex==Features.Length);
}
}
catch (FileFormatException)
{
return OpenTypeLayoutResult.BadFontTable;
}
return OpenTypeLayoutResult.Success;
}
*/
/// <summary>
/// Substitutes glyphs according to features defined in the font.
/// </summary>
/// <param name="Font">In: Font access interface</param>
/// <param name="workspace">In: Workspace for layout engine</param>
/// <param name="ScriptTag">In: Script tag</param>
/// <param name="LangSysTag">In: LangSys tag</param>
/// <param name="FeatureSet">In: List of features to apply</param>
/// <param name="featureCount">In: Actual number of features in <paramref name="FeatureSet"/></param>
/// <param name="featureSetOffset">In: offset of input characters inside FeatureSet</param>
/// <param name="CharCount">In: Characters count (i.e. <paramref name="Charmap"/>.Length);</param>
/// <param name="Charmap">In/out: Char to glyph mapping</param>
/// <param name="Glyphs">In/out: List of GlyphInfo structs</param>
/// <returns>Substitution result</returns>
internal static OpenTypeLayoutResult SubstituteGlyphs(
IOpenTypeFont Font, // In: Font access interface
OpenTypeLayoutWorkspace workspace, // In: Workspace for layout engine
uint ScriptTag, // In: Script tag
uint LangSysTag, // In: LangSys tag
Feature[] FeatureSet, // In: List of features to apply
int featureCount, // In: Actual number of features in FeatureSet
int featureSetOffset,
int CharCount, // In: Characters count (i.e. Charmap.Length);
UshortList Charmap, // In/out: Char to glyph mapping
GlyphInfoList Glyphs // In/out: List of GlyphInfo structs
)
{
try
{
FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
if (!GsubTable.IsPresent) {return OpenTypeLayoutResult.ScriptNotFound;}
GSUBHeader GsubHeader = new GSUBHeader(0);
ScriptList ScriptList = GsubHeader.GetScriptList(GsubTable);
ScriptTable Script = ScriptList.FindScript(GsubTable,ScriptTag);
if (Script.IsNull) {return OpenTypeLayoutResult.ScriptNotFound;}
LangSysTable LangSys = Script.FindLangSys(GsubTable,LangSysTag);
if (LangSys.IsNull) {return OpenTypeLayoutResult.LangSysNotFound;}
FeatureList FeatureList = GsubHeader.GetFeatureList(GsubTable);
LookupList LookupList = GsubHeader.GetLookupList(GsubTable);
LayoutEngine.ApplyFeatures(
Font,
workspace,
OpenTypeTags.GSUB,
GsubTable,
new LayoutMetrics(), //it is not needed for substitution
LangSys,
FeatureList,
LookupList,
FeatureSet,
featureCount,
featureSetOffset,
CharCount,
Charmap,
Glyphs,
null,
null
);
}
catch (FileFormatException)
{
return OpenTypeLayoutResult.BadFontTable;
}
return OpenTypeLayoutResult.Success;
}
/// <summary>
/// Position glyphs according to features defined in the font.
/// </summary>
/// <param name="Font">In: Font access interface</param>
/// <param name="workspace">In: Workspace for layout engine</param>
/// <param name="ScriptTag">In: Script tag</param>
/// <param name="LangSysTag">In: LangSys tag</param>
/// <param name="Metrics">In: LayoutMetrics</param>
/// <param name="FeatureSet">In: List of features to apply</param>
/// <param name="featureCount">In: Actual number of features in <paramref name="FeatureSet"/></param>
/// <param name="featureSetOffset">In: offset of input characters inside FeatureSet</param>
/// <param name="CharCount">In: Characters count (i.e. <paramref name="Charmap"/>.Length);</param>
/// <param name="Charmap">In: Char to glyph mapping</param>
/// <param name="Glyphs">In/out: List of GlyphInfo structs</param>
/// <param name="Advances">In/out: Glyphs adv.widths</param>
/// <param name="Offsets">In/out: Glyph offsets</param>
/// <returns>Substitution result</returns>
internal static OpenTypeLayoutResult PositionGlyphs(
IOpenTypeFont Font,
OpenTypeLayoutWorkspace workspace,
uint ScriptTag,
uint LangSysTag,
LayoutMetrics Metrics,
Feature[] FeatureSet,
int featureCount,
int featureSetOffset,
int CharCount,
UshortList Charmap,
GlyphInfoList Glyphs,
int* Advances,
LayoutOffset* Offsets
)
{
try
{
FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
if (!GposTable.IsPresent) {return OpenTypeLayoutResult.ScriptNotFound;}
GPOSHeader GposHeader = new GPOSHeader(0);
ScriptList ScriptList = GposHeader.GetScriptList(GposTable);
ScriptTable Script = ScriptList.FindScript(GposTable,ScriptTag);
if (Script.IsNull) {return OpenTypeLayoutResult.ScriptNotFound;}
LangSysTable LangSys = Script.FindLangSys(GposTable,LangSysTag);
if (LangSys.IsNull) {return OpenTypeLayoutResult.LangSysNotFound;}
FeatureList FeatureList = GposHeader.GetFeatureList(GposTable);
LookupList LookupList = GposHeader.GetLookupList(GposTable);
LayoutEngine.ApplyFeatures(
Font,
workspace,
OpenTypeTags.GPOS,
GposTable,
Metrics,
LangSys,
FeatureList,
LookupList,
FeatureSet,
featureCount,
featureSetOffset,
CharCount,
Charmap,
Glyphs,
Advances,
Offsets
);
}
catch (FileFormatException)
{
return OpenTypeLayoutResult.BadFontTable;
}
return OpenTypeLayoutResult.Success;
}
///<summary>
///
///</summary>
internal static OpenTypeLayoutResult CreateLayoutCache (
IOpenTypeFont font, // In: Font access interface
int maxCacheSize // In: Maximum cache size allowed
)
{
OpenTypeLayoutCache.CreateCache(font, maxCacheSize);
return OpenTypeLayoutResult.Success;
}
///<summary>
/// Internal method to test layout tables if they are uitable for fast path.
/// Returns list of script-langauge pairs that are not optimizable.
///</summary>
internal static OpenTypeLayoutResult GetComplexLanguageList (
IOpenTypeFont Font, //In: Font access interface
uint[] featureList, //In: Feature to look in
uint[] glyphBits,
ushort minGlyphId,
ushort maxGlyphId,
out WritingSystem[] complexLanguages
// Out: List of script/langauge pair
// that are not optimizable
)
{
try
{
WritingSystem[] gsubComplexLanguages = null;
WritingSystem[] gposComplexLanguages = null;
int gsubComplexLanguagesCount = 0;
int gposComplexLanguagesCount = 0;
FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
if (GsubTable.IsPresent)
{
LayoutEngine.GetComplexLanguageList(
OpenTypeTags.GSUB,
GsubTable,
featureList,
glyphBits,
minGlyphId,
maxGlyphId,
out gsubComplexLanguages,
out gsubComplexLanguagesCount
);
}
if (GposTable.IsPresent)
{
LayoutEngine.GetComplexLanguageList(
OpenTypeTags.GPOS,
GposTable,
featureList,
glyphBits,
minGlyphId,
maxGlyphId,
out gposComplexLanguages,
out gposComplexLanguagesCount
);
}
if (gsubComplexLanguages == null && gposComplexLanguages == null)
{
complexLanguages = null;
return OpenTypeLayoutResult.Success;
}
// Both tables have complex scrips, merge results
// Count gpos unique Languages
// and pack them at the same time
// so we do not research them again.
int gposNewLanguages=0, i, j;
for(i = 0; i < gposComplexLanguagesCount ;i++)
{
bool foundInGsub = false;
for(j = 0; j < gsubComplexLanguagesCount ;j++)
{
if (gsubComplexLanguages[j].scriptTag == gposComplexLanguages[i].scriptTag &&
gsubComplexLanguages[j].langSysTag == gposComplexLanguages[i].langSysTag
)
{
foundInGsub = true;
break;
};
}
if (!foundInGsub)
{
if (gposNewLanguages < i)
{
gposComplexLanguages[gposNewLanguages] = gposComplexLanguages[i];
}
gposNewLanguages++;
}
}
//realloc array for merged results, merge both arrays
complexLanguages = new WritingSystem[gsubComplexLanguagesCount + gposNewLanguages];
for(i = 0; i < gsubComplexLanguagesCount; i++)
{
complexLanguages[i] = gsubComplexLanguages[i];
}
for(i = 0; i < gposNewLanguages; i++)
{
complexLanguages[gsubComplexLanguagesCount + i] = gposComplexLanguages[i];
}
return OpenTypeLayoutResult.Success;
}
catch (FileFormatException)
{
complexLanguages = null;
return OpenTypeLayoutResult.BadFontTable;
}
}
}
internal struct WritingSystem
{
internal uint scriptTag;
internal uint langSysTag;
}
/// <summary>
/// </summary>
internal enum OpenTypeLayoutResult
{
Success,
InvalidParameter,
TableNotFound,
ScriptNotFound,
LangSysNotFound,
BadFontTable,
UnderConstruction
}
/// <summary>
/// Class for internal OpenType use to store per font
/// information and temporary buffers.
///
/// We do not use fontcache now, so this information
/// will be recreated every time shaping engine
/// will be called, so, in the future, design interfaces to use
/// fontcache and define what information can be stored there.
/// </summary>
internal class OpenTypeLayoutWorkspace
{
/// <summary>
/// Init buffers to initial values.
/// </summary>
internal unsafe OpenTypeLayoutWorkspace()
{
_bytesPerLookup = 0;
_lookupUsageFlags = null;
_cachePointers = null;
}
/// <summary>
/// Reset all structures to the new font/OTTable/script/langsys.
///
/// Client need to call it only once per shaping engine call.
/// This is client's responsibility to ensure that workspace is
/// used for single font/OTTable/script/langsys between Init() calls
/// </summary>
///<param name="font">In: Font access interface</param>
///<param name="tableTag">In: Font table tag</param>
///<param name="scriptTag">In: Script tag</param>
///<param name="langSysTag">In: Language System tag</param>
///<returns>Success if workspace is initialized succesfully, specific error if failed</returns>
internal OpenTypeLayoutResult Init(
IOpenTypeFont font,
OpenTypeTags tableTag,
uint scriptTag,
uint langSysTag
)
{
// Currently all buffers are per call,
// no need to do anything.
return OpenTypeLayoutResult.Success;
}
#region Lookup flags
//lookup usage flags access
private const byte AggregatedFlagMask = 0x01;
private const byte RequiredFeatureFlagMask = 0x02;
private const int FeatureFlagsStartBit = 2;
public void InitLookupUsageFlags(int lookupCount, int featureCount)
{
_bytesPerLookup = (featureCount + FeatureFlagsStartBit + 7) >> 3;
int requiredLookupUsageArraySize = lookupCount * _bytesPerLookup;
if ( _lookupUsageFlags == null ||
_lookupUsageFlags.Length < requiredLookupUsageArraySize)
{
_lookupUsageFlags = new byte[requiredLookupUsageArraySize];
}
Array.Clear(_lookupUsageFlags, 0, requiredLookupUsageArraySize);
}
public bool IsAggregatedFlagSet(int lookupIndex)
{
return ((_lookupUsageFlags[lookupIndex * _bytesPerLookup] & AggregatedFlagMask) != 0);
}
public bool IsFeatureFlagSet(int lookupIndex, int featureIndex)
{
int flagIndex = featureIndex + FeatureFlagsStartBit;
int flagByte = (lookupIndex * _bytesPerLookup) + (flagIndex >> 3);
byte flagMask = (byte)(1 << (flagIndex % 8));
return ((_lookupUsageFlags[flagByte] & flagMask) != 0);
}
public bool IsRequiredFeatureFlagSet(int lookupIndex)
{
return ((_lookupUsageFlags[lookupIndex * _bytesPerLookup] & RequiredFeatureFlagMask) != 0);
}
public void SetFeatureFlag(int lookupIndex, int featureIndex)
{
int startLookupByte = lookupIndex * _bytesPerLookup;
int flagIndex = featureIndex + FeatureFlagsStartBit;
int flagByte = startLookupByte + (flagIndex >> 3);
byte flagMask = (byte)(1 << (flagIndex % 8));
if (flagByte >= _lookupUsageFlags.Length)
{
//This should be invalid font. Lookup associated with the feature is not in lookup array.
throw new FileFormatException();
}
_lookupUsageFlags[flagByte] |= flagMask;
// Also set agregated usage flag
_lookupUsageFlags[startLookupByte] |= AggregatedFlagMask;
}
public void SetRequiredFeatureFlag(int lookupIndex)
{
int flagByte = lookupIndex * _bytesPerLookup;
if (flagByte >= _lookupUsageFlags.Length)
{
//This should be invalid font. Lookup associated with the feature is not in lookup array.
throw new FileFormatException();
}
//set RequiredFeature and aggregated flag at the same time
_lookupUsageFlags[flagByte] |= (AggregatedFlagMask | RequiredFeatureFlagMask);
}
// Define cache which lookup is enabled by which feature.
// Buffer grows with number of features applied
private int _bytesPerLookup;
private byte[] _lookupUsageFlags;
#endregion Lookup flags
#region Layout cache pointers
/// <summary>
/// Allocate enough memory for array of cache pointers, parallel to glyph run.
///
/// These method should not be used directly, it is only called by OpenTypeLayputCache.
///
/// </summary>
///<param name="glyphRunLength">In: Size of a glyph run</param>
public unsafe void AllocateCachePointers(int glyphRunLength)
{
if (_cachePointers != null && _cachePointers.Length >= glyphRunLength) return;
_cachePointers = new ushort[glyphRunLength];
}
/// <summary>
/// If glyph run is cahnged, update pointers according to the change. Reallocate array if necessary.
///
/// These method should not be used directly, it is only called by OpenTypeLayputCache.
///
/// </summary>
///<param name="oldLength">In: Number of glyphs in the run before change</param>
///<param name="newLength">In: Number of glyphs in the run after change</param>
///<param name="firstGlyphChanged">In: Index of the first changed glyph</param>
///<param name="afterLastGlyphChanged">In: Index of the glyph after last changed</param>
public unsafe void UpdateCachePointers(
int oldLength,
int newLength,
int firstGlyphChanged,
int afterLastGlyphChanged
)
{
if (oldLength != newLength)
{
int oldAfterLastGlyphChanged = afterLastGlyphChanged - (newLength - oldLength);
if (_cachePointers.Length < newLength)
{
ushort[] tmp = new ushort[newLength];
Array.Copy(_cachePointers, tmp, firstGlyphChanged);
Array.Copy(_cachePointers, oldAfterLastGlyphChanged, tmp, afterLastGlyphChanged, oldLength - oldAfterLastGlyphChanged);
_cachePointers = tmp;
}
else
{
Array.Copy(_cachePointers, oldAfterLastGlyphChanged, _cachePointers, afterLastGlyphChanged, oldLength - oldAfterLastGlyphChanged);
}
}
}
public unsafe ushort[] CachePointers
{
get { return _cachePointers; }
}
public byte[] TableCacheData
{
get { return _tableCache; }
set { _tableCache = value; }
}
// Array of cache pointers, per glyph
private unsafe ushort[] _cachePointers;
// Pointer to the table cache
private byte[] _tableCache;
#endregion Layout cache pointers
}
}
| 36.525461 | 154 | 0.501818 | [
"MIT"
] | 00mjk/wpf | src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/Shaping/OpenTypeLayout.cs | 49,492 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Cheshire {
public partial class dangxuat {
}
}
| 27.1875 | 81 | 0.397701 | [
"MIT"
] | haonguyen96/laptrinhweb | dangxuat.aspx.designer.cs | 437 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client;
public sealed class IntListCFType
: CFType, IClassNameConvertible, IPropagatePropertyAccessPath
{
[JsonPropertyName("className")]
public override string? ClassName => "IntListCFType";
public IntListCFType() { }
public override void SetAccessPath(string path, bool validateHasBeenSet)
{
}
}
| 28.673913 | 81 | 0.677028 | [
"Apache-2.0"
] | JetBrains/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Dtos/IntListCFType.generated.cs | 1,319 | C# |
using QuGo.Core;
using QuGo.Core.Data;
using QuGo.Core.Infrastructure;
using QuGo.Services.Users;
using System;
using System.Web.Mvc;
namespace QuGo.Web.Framework
{
/// <summary>
/// Represents filter attribute to validate customer password expiration
/// </summary>
public class ValidatePasswordAttribute : ActionFilterAttribute
{
/// <summary>
/// Called by the ASP.NET MVC framework before the action method executes
/// </summary>
/// <param name="filterContext">The filter context</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null || filterContext.HttpContext == null || filterContext.HttpContext.Request == null)
return;
//don't apply filter to child methods
if (filterContext.IsChildAction)
return;
var actionName = filterContext.ActionDescriptor.ActionName;
if (string.IsNullOrEmpty(actionName) || actionName.Equals("ChangePassword", StringComparison.InvariantCultureIgnoreCase))
return;
var controllerName = filterContext.Controller.ToString();
if (string.IsNullOrEmpty(controllerName) || controllerName.Equals("User", StringComparison.InvariantCultureIgnoreCase))
return;
if (!DataSettingsHelper.DatabaseIsInstalled())
return;
//get current customer
var user = EngineContext.Current.Resolve<IWorkContext>().CurrentUser;
//check password expiration
if (user.PasswordIsExpired())
{
var changePasswordUrl = new UrlHelper(filterContext.RequestContext).RouteUrl("UserChangePassword");
filterContext.Result = new RedirectResult(changePasswordUrl);
}
}
}
} | 37.8 | 133 | 0.645503 | [
"MIT"
] | pcurich/QuGo | QubicGo/Presentation/QuGo.Web.Framework/ValidatePasswordAttribute.cs | 1,892 | C# |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// ReSharper disable CheckNamespace
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable CommentTypo
// ReSharper disable IdentifierTypo
// ReSharper disable InconsistentNaming
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable StringLiteralTypo
// ReSharper disable UnusedParameter.Local
/* EntryIniSection.cs --
* Ars Magna project, http://arsmagna.ru
*/
#region Using directives
using System.Text.Json.Serialization;
using System.Xml.Serialization;
using AM;
using AM.IO;
#endregion
#nullable enable
namespace ManagedIrbis.Client
{
/// <summary>
///
/// </summary>
/// <remarks>
/// Находится в серверном INI-файле irbisc.ini.
/// </remarks>
public sealed class EntryIniSection
: AbstractIniSection
{
#region Constants
/// <summary>
/// Section name.
/// </summary>
public const string SectionName = "Entry";
#endregion
#region Properties
/// <summary>
/// Имя формата для ФЛК документа в целом.
/// </summary>
[XmlElement("dbnflc")]
[JsonPropertyName("dbnflc")]
public string? DbnFlc
{
get => Section.GetValue("DBNFLC", "DBNFLC");
set => Section["DBNFLC"] = value;
}
/// <summary>
/// DefFieldNumb.
/// </summary>
[XmlElement("DefFieldNumb")]
[JsonPropertyName("DefFieldNumb")]
public int DefFieldNumb
{
get => Section.GetValue("DefFieldNumb", 10);
set => Section.SetValue("DefFieldNumb", value);
}
/// <summary>
/// MaxAddFields.
/// </summary>
[XmlElement("MaxAddFields")]
[JsonPropertyName("MaxAddFields")]
public int MaxAddFields
{
get => Section.GetValue("MaxAddFields", 10);
set => Section.SetValue("MaxAddFields", value);
}
/// <summary>
/// Признак автоматической актуализации записей
/// при корректировке.
/// </summary>
public bool RecordUpdate
{
get => Utility.ToBoolean(Section.GetValue("RECUPDIF", "1").ThrowIfNull());
set => Section.SetValue("RECUPDIF", value ? "1" : "0");
}
#endregion
#region Construction
/// <summary>
/// Constructor.
/// </summary>
public EntryIniSection()
: base(SectionName)
{
}
/// <summary>
/// Constructor.
/// </summary>
public EntryIniSection
(
IniFile iniFile
)
: base(iniFile, SectionName)
{
}
/// <summary>
/// Constructor.
/// </summary>
public EntryIniSection
(
IniFile.Section section
)
: base(section)
{
}
#endregion
}
}
| 23.847328 | 86 | 0.547375 | [
"MIT"
] | amironov73/ManagedIrbis5 | Source/Libs/ManagedIrbis5/Source/Client/EntryIniSection.cs | 3,237 | C# |
namespace Masa.Contrib.BasicAbility.Dcc;
public static class MasaConfigurationExtensions
{
public static IMasaConfigurationBuilder UseDcc(
this IMasaConfigurationBuilder builder,
IServiceCollection services,
Action<JsonSerializerOptions>? jsonSerializerOptions = null,
Action<CallerOptions>? callerOptions = null)
=> builder.UseDcc(services, "Appsettings", jsonSerializerOptions, callerOptions);
public static IMasaConfigurationBuilder UseDcc(
this IMasaConfigurationBuilder builder,
IServiceCollection services,
string defaultSectionName,
Action<JsonSerializerOptions>? jsonSerializerOptions = null,
Action<CallerOptions>? callerOptions = null)
{
if (!builder.GetSectionRelations().TryGetValue(defaultSectionName, out IConfiguration? configuration))
throw new ArgumentNullException("Failed to obtain Dcc configuration, check whether the current section is configured with Dcc");
var configurationSection = configuration.GetSection("DccOptions");
var dccOptions = configurationSection.Get<DccConfigurationOptions>();
List<DccSectionOptions> expandSections = new();
var configurationExpandSection = configuration.GetSection("ExpandSections");
if (configurationExpandSection.Exists())
{
configurationExpandSection.Bind(expandSections);
}
return builder.UseDcc(services, () => dccOptions, option =>
{
option.Environment = configuration["Environment"];
option.Cluster = configuration["Cluster"];
option.AppId = configuration["AppId"];
option.ConfigObjects = configuration.GetSection("ConfigObjects").Get<List<string>>();
option.Secret = configuration["Sectet"];
}, option => option.ExpandSections = expandSections, jsonSerializerOptions, callerOptions);
}
public static IMasaConfigurationBuilder UseDcc(
this IMasaConfigurationBuilder builder,
IServiceCollection services,
Func<DccConfigurationOptions> configureOptions,
Action<DccSectionOptions> defaultSectionOptions,
Action<DccExpandSectionOptions>? expansionSectionOptions = null,
Action<JsonSerializerOptions>? jsonSerializerOptions = null,
Action<CallerOptions>? callerOptions = null)
{
if (services.Any(service => service.ImplementationType == typeof(DccConfigurationProvider)))
return builder;
services.AddSingleton<DccConfigurationProvider>();
var config = GetDccConfigurationOption(configureOptions, defaultSectionOptions, expansionSectionOptions);
var jsonSerializerOption = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
};
jsonSerializerOptions?.Invoke(jsonSerializerOption);
services.AddCaller(options =>
{
if (callerOptions == null)
{
options.UseHttpClient(()
=> new MasaHttpClientBuilder(DEFAULT_CLIENT_NAME, string.Empty, opt => opt.BaseAddress = new Uri(config.DccConfigurationOption.ManageServiceAddress))
);
}
else
{
callerOptions.Invoke(options);
}
});
services.AddMasaRedisCache(DEFAULT_CLIENT_NAME, config.DccConfigurationOption.RedisOptions).AddSharedMasaMemoryCache(config.DccConfigurationOption.SubscribeKeyPrefix ?? DEFAULT_SUBSCRIBE_KEY_PREFIX);
TryAddConfigurationApiClient(services, config.DefaultSectionOption, config.ExpansionSectionOptions, jsonSerializerOption);
TryAddConfigurationApiManage(services, config.DefaultSectionOption, config.ExpansionSectionOptions);
var sectionOptions = new List<DccSectionOptions>()
{
config.DefaultSectionOption
}.Concat(config.ExpansionSectionOptions);
var configurationApiClient = services.BuildServiceProvider().GetRequiredService<IConfigurationApiClient>();
var loggerFactory = services.BuildServiceProvider().GetRequiredService<ILoggerFactory>();
builder.AddRepository(new DccConfigurationRepository(sectionOptions, configurationApiClient, loggerFactory));
return builder;
}
public static IServiceCollection TryAddConfigurationApiClient(IServiceCollection services,
DccSectionOptions defaultSectionOption,
List<DccSectionOptions> expansionSectionOptions,
JsonSerializerOptions jsonSerializerOption)
{
services.TryAddSingleton(serviceProvider =>
{
var client = serviceProvider.GetRequiredService<IMemoryCacheClientFactory>()
.CreateClient(DEFAULT_CLIENT_NAME);
if (client == null)
throw new ArgumentNullException(nameof(client));
return DccFactory.CreateClient(
serviceProvider,
client,
jsonSerializerOption,
defaultSectionOption,
expansionSectionOptions);
});
return services;
}
public static IServiceCollection TryAddConfigurationApiManage(IServiceCollection services,
DccSectionOptions defaultSectionOption,
List<DccSectionOptions> expansionSectionOptions)
{
services.TryAddSingleton(serviceProvider =>
{
var callerFactory = serviceProvider.GetRequiredService<ICallerFactory>();
return DccFactory.CreateManage(callerFactory, defaultSectionOption, expansionSectionOptions);
});
return services;
}
private static (DccSectionOptions DefaultSectionOption, List<DccSectionOptions> ExpansionSectionOptions, DccConfigurationOptions DccConfigurationOption) GetDccConfigurationOption(
Func<DccConfigurationOptions> configureOptions,
Action<DccSectionOptions> defaultSectionOptions,
Action<DccExpandSectionOptions>? expansionSectionOptions = null)
{
var dccConfigurationOption = configureOptions();
if (dccConfigurationOption == null)
throw new ArgumentNullException(nameof(configureOptions));
if (string.IsNullOrEmpty(dccConfigurationOption.ManageServiceAddress))
throw new ArgumentNullException(nameof(dccConfigurationOption.ManageServiceAddress));
if (dccConfigurationOption.RedisOptions == null)
throw new ArgumentNullException(nameof(dccConfigurationOption.RedisOptions));
if (dccConfigurationOption.RedisOptions.Servers == null || dccConfigurationOption.RedisOptions.Servers.Count == 0 || dccConfigurationOption.RedisOptions.Servers.Any(service => string.IsNullOrEmpty(service.Host) || service.Port <= 0))
throw new ArgumentNullException(nameof(dccConfigurationOption.RedisOptions.Servers));
if (defaultSectionOptions == null)
throw new ArgumentNullException(nameof(defaultSectionOptions));
var defaultSectionOption = new DccSectionOptions();
defaultSectionOptions.Invoke(defaultSectionOption);
if (string.IsNullOrEmpty(defaultSectionOption.AppId))
throw new ArgumentNullException("AppId cannot be empty");
if (defaultSectionOption.ConfigObjects == null || !defaultSectionOption.ConfigObjects.Any())
throw new ArgumentNullException("ConfigObjects cannot be empty");
if (string.IsNullOrEmpty(defaultSectionOption.Cluster))
defaultSectionOption.Cluster = "Default";
if (string.IsNullOrEmpty(defaultSectionOption.Environment))
defaultSectionOption.Environment = GetDefaultEnvironment();
var dccCachingOption = new DccExpandSectionOptions();
expansionSectionOptions?.Invoke(dccCachingOption);
List<DccSectionOptions> expansionOptions = new();
foreach (var expansionOption in dccCachingOption.ExpandSections ?? new())
{
if (string.IsNullOrEmpty(expansionOption.Environment))
expansionOption.Environment = defaultSectionOption.Environment;
if (string.IsNullOrEmpty(expansionOption.Cluster))
expansionOption.Cluster = defaultSectionOption.Cluster;
if (expansionOption.ConfigObjects == null || !expansionOption.ConfigObjects.Any())
throw new ArgumentNullException("ConfigObjects in the extension section cannot be empty");
if (expansionOption.AppId == defaultSectionOption.AppId ||
expansionOptions.Any(section => section.AppId == expansionOption.AppId))
throw new ArgumentNullException("The current section already exists, no need to mount repeatedly");
expansionOptions.Add(expansionOption);
}
return (defaultSectionOption, expansionOptions, dccConfigurationOption);
}
private static ICachingBuilder AddSharedMasaMemoryCache(this ICachingBuilder builder, string subscribeKeyPrefix)
{
builder.AddMasaMemoryCache(options =>
{
options.SubscribeKeyType = SubscribeKeyTypes.SpecificPrefix;
options.SubscribeKeyPrefix = subscribeKeyPrefix;
});
return builder;
}
private static string GetDefaultEnvironment()
=> System.Environment.GetEnvironmentVariable(DEFAULT_ENVIRONMENT_NAME) ??
throw new ArgumentNullException("Error getting environment information, please make sure the value of ASPNETCORE_ENVIRONMENT has been configured");
private class DccConfigurationProvider
{
}
}
| 46.536585 | 241 | 0.709015 | [
"MIT"
] | capdiem/MASA.Contrib | src/BasicAbility/Masa.Contrib.BasicAbility.Dcc/MasaConfigurationExtensions.cs | 9,540 | C# |
using System;
using System.Xml.Serialization;
namespace Nez.BitmapFontImporter
{
// ---- AngelCode BmFont XML serializer ----------------------
// ---- By DeadlyDan @ deadlydan@gmail.com -------------------
// ---- There's no license restrictions, use as you will. ----
// ---- Credits to http://www.angelcode.com/ -----------------
public class BitmapFontCommon
{
[XmlAttribute( "lineHeight" )]
public int lineHeight;
[XmlAttribute( "base" )]
public int base_;
[XmlAttribute( "scaleW" )]
public int scaleW;
[XmlAttribute( "scaleH" )]
public int scaleH;
[XmlAttribute( "pages" )]
public int pages;
[XmlAttribute( "packed" )]
public int packed;
// Littera doesnt seem to add these
[XmlAttribute( "alphaChnl" )]
public int alphaChannel;
[XmlAttribute( "redChnl" )]
public int redChannel;
[XmlAttribute( "greenChnl" )]
public int greenChannel;
[XmlAttribute( "blueChnl" )]
public int blueChannel;
}
}
| 21.288889 | 63 | 0.634656 | [
"MIT"
] | AlmostBearded/monogame-platformer | Platformer/Nez/Nez.PipelineImporter/BitmapFonts/BitmapFontCommon.cs | 958 | C# |
using System.Linq;
using Autofac.Extensions.DependencyInjection;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace CoreApi.WebApi
{
[UsedImplicitly]
public static class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
[UsedImplicitly]
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseSerilog((context, conf) =>
conf.ReadFrom.Configuration(context.Configuration)
.Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("swagger"))))
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
} | 31.8125 | 112 | 0.608055 | [
"MIT"
] | hasangedik/CoreApi | CoreApi.WebApi/Program.cs | 1,018 | 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.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute.Fluent.Models
{
using Management.ResourceManager;
using Management.ResourceManager.Fluent;
using Management.ResourceManager.Fluent.Core;
using Newtonsoft.Json;
/// <summary>
/// Defines values for IPVersion.
/// </summary>
/// <summary>
/// Determine base value for a given allowed value if exists, else return
/// the value itself
/// </summary>
[JsonConverter(typeof(Management.ResourceManager.Fluent.Core.ExpandableStringEnumConverter<IPVersion>))]
public class IPVersion : Management.ResourceManager.Fluent.Core.ExpandableStringEnum<IPVersion>
{
public static readonly IPVersion IPv4 = Parse("IPv4");
public static readonly IPVersion IPv6 = Parse("IPv6");
}
}
| 35.033333 | 108 | 0.719315 | [
"MIT"
] | AntoineGa/azure-libraries-for-net | src/ResourceManagement/Compute/Generated/Models/IPVersion.cs | 1,051 | C# |
using InvoiceSharp.Helpers;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using InvoiceSharp.Models;
using InvoiceSharp.Services.Impl;
namespace InvoiceSharp.Services
{
public class InvoiceSharpApi : IInvoiceSharpApi
{
public Invoice Invoice { get; protected set; }
public static string DefaultReference => "";
public InvoiceSharpApi(
SizeOption size = SizeOption.A4,
OrientationOption orientation = OrientationOption.Portrait,
string currency = "€"
)
{
Invoice = new Invoice();
Invoice.Title = "Facture";
Invoice.PageSize = size;
Invoice.PageOrientation = orientation;
Invoice.Currency = currency;
Invoice.InvoiceDate = DateTime.Now;
Invoice.OrderReference = DefaultReference;
Invoice.IsUnpaid = false;
Invoice.UnpaidMessage = "à payer";
Invoice.PaidMessage = "payée";
}
public IInvoicerOptions BackColor(string color)
{
Invoice.BackColor = color;
return this;
}
public IInvoicerOptions TextColor(string color)
{
Invoice.TextColor = color;
return this;
}
public IInvoicerOptions Image(string image, int width, int height)
{
Invoice.Image = image;
Invoice.ImageSize = new Size(width, height);
return this;
}
public IInvoicerOptions Title(string title)
{
Invoice.Title = title;
return this;
}
public IInvoicerOptions OrderReference(string reference)
{
Invoice.OrderReference = reference;
return this;
}
public IInvoicerOptions BillingDate(DateTime date)
{
Invoice.InvoiceDate = date;
return this;
}
public IInvoicerOptions PayedDate(DateTime dueDate)
{
Invoice.PayedDate = dueDate;
return this;
}
public IInvoicerOptions IsUnpaid(bool isUnpaind)
{
Invoice.IsUnpaid = isUnpaind;
return this;
}
public IInvoicerOptions UnpaidMessage(string message)
{
Invoice.UnpaidMessage = message;
return this;
}
public IInvoicerOptions PaidMessage(string message)
{
Invoice.PaidMessage = message;
return this;
}
public IInvoicerOptions Company(Address address)
{
Invoice.Company = address;
return this;
}
public IInvoicerOptions Client(Address address)
{
Invoice.Client = address;
return this;
}
public IInvoicerOptions CompanyOrientation(PositionOption position)
{
Invoice.CompanyOrientation = position;
return this;
}
public IInvoicerOptions Details(List<DetailRow> details)
{
Invoice.Details = details;
return this;
}
public IInvoicerOptions Footer(string title)
{
Invoice.Footer = title;
return this;
}
public IInvoicerOptions Items(List<ItemRow> items)
{
Invoice.Items = items;
return this;
}
public IInvoicerOptions Totals(List<TotalRow> totals)
{
Invoice.Totals = totals;
return this;
}
public void Save(string filename, string password = null)
{
if (filename == null || !System.IO.Path.HasExtension(filename))
filename = System.IO.Path.ChangeExtension(Invoice.OrderReference, "pdf");
new PdfInvoice(Invoice).Save(filename, password);
}
public Stream Get(string password = null)
{
return new PdfInvoice(Invoice).Get(password);
}
}
}
| 26.614379 | 89 | 0.560658 | [
"MIT"
] | Triskae/InvoiceSharp | InvoiceSharp/Services/InvoiceSharpApi.cs | 4,078 | C# |
#if NET35
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
// LZO.Net
// $Id: LZOCompressor.cs,v 1.1 2004/02/22 17:44:04 laptop Exp $
namespace Simplicit.Net.Lzo
{
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
/// <summary>
/// Wrapper class for the highly performant LZO compression library
/// </summary>
public class LZOCompressor {
private static TraceSwitch _traceSwitch = new TraceSwitch("Simplicit.Net.Lzo", "Switch for tracing of the LZOCompressor-Class");
#region Dll-Imports
[DllImport("lzo.dll")]
private static extern int __lzo_init3();
[DllImport("lzo.dll")]
private static extern string lzo_version_string();
[DllImport("lzo.dll")]
private static extern string lzo_version_date();
[DllImport("lzo.dll")]
private static extern int lzo1x_1_compress(
byte[] src,
int src_len,
byte[] dst,
ref int dst_len,
byte[] wrkmem
);
[DllImport("lzo.dll")]
private static extern int lzo1x_decompress(
byte[] src,
int src_len,
byte[] dst,
ref int dst_len,
byte[] wrkmem);
#endregion
private byte[] _workMemory = new byte[16384L * 4];
static LZOCompressor() {
int init = __lzo_init3();
if(init != 0) {
throw new Exception("Initialization of LZO-Compressor failed !");
}
}
/// <summary>
/// Constructor.
/// </summary>
public LZOCompressor() {
}
/// <summary>
/// Version string of the compression library.
/// </summary>
public string Version {
get {
return lzo_version_string();
}
}
/// <summary>
/// Version date of the compression library
/// </summary>
public string VersionDate {
get {
return lzo_version_date();
}
}
/// <summary>
/// Compresses a byte array and returns the compressed data in a new
/// array. You need the original length of the array to decompress it.
/// </summary>
/// <param name="src">Source array for compression</param>
/// <returns>Byte array containing the compressed data</returns>
public byte[] Compress(byte[] src) {
if(_traceSwitch.TraceVerbose) {
Trace.WriteLine(String.Format("LZOCompressor: trying to compress {0}", src.Length));
}
byte[] dst = new byte[src.Length + src.Length / 64 + 16 + 3 + 4];
int outlen = 0;
lzo1x_1_compress(src, src.Length, dst, ref outlen, _workMemory);
if(_traceSwitch.TraceVerbose) {
Trace.WriteLine(String.Format("LZOCompressor: compressed {0} to {1} bytes", src.Length, outlen));
}
byte[] ret = new byte[outlen + 4];
Array.Copy(dst, 0, ret, 0, outlen);
byte[] outlenarr = BitConverter.GetBytes(src.Length);
Array.Copy(outlenarr, 0, ret, outlen, 4);
return ret;
}
/// <summary>
/// Decompresses compressed data to its original state.
/// </summary>
/// <param name="src">Source array to be decompressed</param>
/// <returns>Decompressed data</returns>
public byte[] Decompress(byte[] src) {
if(_traceSwitch.TraceVerbose) {
Trace.WriteLine(String.Format("LZOCompressor: trying to decompress {0}", src.Length));
}
int origlen = BitConverter.ToInt32(src, src.Length - 4);
byte[] dst = new byte[origlen];
int outlen = origlen;
lzo1x_decompress(src, src.Length - 4, dst, ref outlen, _workMemory);
if(_traceSwitch.TraceVerbose) {
Trace.WriteLine(String.Format("LZOCompressor: decompressed {0} to {1} bytes", src.Length, origlen));
}
return dst;
}
}
}
#endif | 31.195652 | 131 | 0.66295 | [
"Apache-2.0"
] | NikolayXHD/Lucene.Net.Contrib | Lucene.Net/Support/IO/Compression/LZOCompressor.cs | 4,305 | 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 System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable enable
namespace Microsoft.EntityFrameworkCore.ChangeTracking
{
/// <summary>
/// <para>
/// Provides access to change tracking and loading information for a collection
/// navigation property that associates this entity to a collection of another entities.
/// </para>
/// <para>
/// Instances of this class are returned from methods when using the <see cref="ChangeTracker" /> API and it is
/// not designed to be directly constructed in your application code.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The type of the entity the property belongs to. </typeparam>
/// <typeparam name="TRelatedEntity"> The type of the property. </typeparam>
public class CollectionEntry<TEntity, TRelatedEntity> : CollectionEntry
where TEntity : class
where TRelatedEntity : class
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public CollectionEntry([NotNull] InternalEntityEntry internalEntry, [NotNull] string name)
: base(internalEntry, name)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public CollectionEntry([NotNull] InternalEntityEntry internalEntry, [NotNull] INavigation navigation)
: base(internalEntry, navigation)
{
}
/// <summary>
/// The <see cref="EntityEntry{TEntity}" /> to which this member belongs.
/// </summary>
/// <value> An entry for the entity that owns this member. </value>
public new virtual EntityEntry<TEntity> EntityEntry
=> new(InternalEntry);
/// <summary>
/// Gets or sets the value currently assigned to this property. If the current value is set using this property,
/// the change tracker is aware of the change and <see cref="ChangeTracker.DetectChanges" /> is not required
/// for the context to detect the change.
/// </summary>
public new virtual IEnumerable<TRelatedEntity>? CurrentValue
{
get => this.GetInfrastructure().GetCurrentValue<IEnumerable<TRelatedEntity>>(Metadata);
[param: CanBeNull] set => base.CurrentValue = value;
}
/// <summary>
/// <para>
/// Returns the query that would be used by <see cref="CollectionEntry.Load" /> to load entities referenced by
/// this navigation property.
/// </para>
/// <para>
/// The query can be composed over using LINQ to perform filtering, counting, etc. without
/// actually loading all entities from the database.
/// </para>
/// </summary>
public new virtual IQueryable<TRelatedEntity> Query()
{
InternalEntry.GetOrCreateCollection(Metadata, forMaterialization: true);
return (IQueryable<TRelatedEntity>)base.Query();
}
/// <summary>
/// The <see cref="EntityEntry{T}" /> of an entity this navigation targets.
/// </summary>
/// <param name="entity"> The entity to get the entry for. </param>
/// <value> An entry for an entity that this navigation targets. </value>
public new virtual EntityEntry<TRelatedEntity>? FindEntry([NotNull] object entity)
{
var entry = GetInternalTargetEntry(entity);
return entry == null
? null
: new EntityEntry<TRelatedEntity>(entry);
}
}
}
| 47.355769 | 126 | 0.636142 | [
"Apache-2.0"
] | Emill/efcore | src/EFCore/ChangeTracking/CollectionEntry`.cs | 4,925 | C# |
namespace Restaurant.Abstractions.ViewModels
{
public interface IMainViewModel : INavigatableViewModel
{
}
} | 20.166667 | 59 | 0.752066 | [
"MIT"
] | Jurabek/Restaurant | src/mobile/Restaurant.Client/Restaurant.Abstractions/ViewModels/IMainViewModel.cs | 123 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using a2wd.Umbraco.Models.PageModels;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
using a2wd.Umbraco.Logic.Pages;
namespace a2wd.Umbraco.Controllers
{
public class HomePageController : RenderMvcController
{
// GET: HomePage
public ActionResult Index()
{
HomePageViewModel model = HomePageLogic.Get(CurrentPage);
return CurrentTemplate(model);
}
}
} | 24 | 69 | 0.694444 | [
"MIT"
] | a2wd/umbraco-website | a2wd.Umbraco/a2wd.Umbraco.Web/Controllers/HomePageController.cs | 506 | C# |
/**
* Usage: see https://github.com/WhatIfWeDigDeeper/SonyVegasProScripting
*
* Modified from Batch Render Sample script that performs batch renders with GUI for selecting
* render templates.
*
* Revision Date: Jun. 28, 2006.
**/
using System;
using System.IO;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
using System.Media;
using Sony.Vegas;
public class EntryPoint
{
/// <summary>
/// Change the file name here if you need multiple renderers. Then save as.
/// </summary>
String _defaultInputFileName = "MyRendererInput.txt";
/// <summary>
/// directory for input file My Documents/SonyVegasRender/
/// </summary>
String _defaultInputDirectory = "SonyVegasRender";
/// <summary>
/// Writes all renderers to VegasRenderList.txt in above directory.
/// </summary>
bool _writeAllRenderers = true;
/// <summary>
/// set this to true if you want to allow files to be overwritten
/// </summary>
bool OverwriteExistingFiles = true;
/// <summary>
/// Only default. Reads render mode from 1st line in input file.
/// </summary>
RenderMode _renderMode = RenderMode.Project;
String defaultBasePath = "Untitled_";
Sony.Vegas.Vegas myVegas = null;
enum RenderMode
{
Project = 0,
Selection,
Regions,
}
public void FromVegas(Vegas vegas)
{
myVegas = vegas;
String myDocDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
String inputFileDirectory = Path.Combine(myDocDirectory, _defaultInputDirectory);
String inputFilePath = Path.Combine(inputFileDirectory, _defaultInputFileName);
String projectPath = myVegas.Project.FilePath;
if (String.IsNullOrEmpty(projectPath))
{
String dir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
defaultBasePath = Path.Combine(dir, defaultBasePath);
}
else
{
String dir = Path.GetDirectoryName(projectPath);
String fileName = Path.GetFileNameWithoutExtension(projectPath);
defaultBasePath = Path.Combine(dir, fileName + "_");
}
if (_writeAllRenderers)
WriteAvailableRenderers(inputFileDirectory);
ArrayList lookup = ReadInputFile(inputFilePath);
ArrayList selectedTemplates = FindMatchingTemplates(lookup);
if (selectedTemplates.Count == 0)
{
MessageBox.Show("No templates found.");
return;
}
DoBatchRender(selectedTemplates, defaultBasePath, _renderMode);
string soundFile = Path.Combine(inputFileDirectory, "EndSound.wav");
if (File.Exists(soundFile))
{
(new SoundPlayer(soundFile)).Play();
}
else
{
SystemSounds.Asterisk.Play();
SystemSounds.Asterisk.Play();
}
}
public ArrayList ReadInputFile(String inputFilePath)
{
String line = null;
ArrayList lookup = new ArrayList();
if (!File.Exists(inputFilePath))
{
string[] content = new string[2];
content[0] = "Project #valid choices: Project Regions Selection. Sample below, remove # to enable.";
content[1] = "# Wave (Microsoft);44,100 Hz, 24 Bit, Stereo, PCM";
File.WriteAllLines(inputFilePath, content);
MessageBox.Show("Created " + inputFilePath + " Please look in this directory for VegasRendererList.txt and add needed renderers to MyRendererInput.txt");
return lookup;
}
using (System.IO.StreamReader file = new System.IO.StreamReader(inputFilePath))
{
string firstLine = file.ReadLine();
SetProjectType(firstLine);
while ((line = file.ReadLine()) != null)
{
//skip blank lines
if (line.Trim().Length == 0)
continue;
string[] templates = line.Split(';');
if (templates.Length == 1 || templates[1].Trim().Length == 0)
{
MessageBox.Show("Invalid line in input file. Make sure you have 2 items seperated by ';' " + line);
continue;
}
String templateName = templates[0].Trim();
if (templateName.StartsWith("#"))
{
continue;
}
String formatName = templates[1].Trim();
lookup.Add(new KeyValuePair(templateName, formatName));
}
}
return lookup;
}
private ArrayList FindMatchingTemplates(ArrayList lookup)
{
ArrayList result = new ArrayList();
for (int i = 0; i < lookup.Count; i++)
{
KeyValuePair keyVal = (KeyValuePair)lookup[i];
RenderItem item = FindMatch(keyVal.RendererName, keyVal.TemplateName);
if (item == null)
{
MessageBox.Show("Could not find renderer " + keyVal.RendererName + " and template " + keyVal.TemplateName);
continue;
}
result.Add(item);
}
return result;
}
private RenderItem FindMatch(string renderRequest, string templateRequest)
{
int projectAudioChannelCount = 0;
if (AudioBusMode.Stereo == myVegas.Project.Audio.MasterBusMode)
{
projectAudioChannelCount = 2;
}
else if (AudioBusMode.Surround == myVegas.Project.Audio.MasterBusMode)
{
projectAudioChannelCount = 6;
}
bool projectHasVideo = ProjectHasVideo();
bool projectHasAudio = ProjectHasAudio();
foreach (Renderer renderer in myVegas.Renderers)
{
try
{
String rendererName = renderer.FileTypeName.Trim();
if (!rendererName.Equals(renderRequest, StringComparison.InvariantCultureIgnoreCase))
continue;
foreach (RenderTemplate template in renderer.Templates)
{
try
{
if (!IsTemplateValid(projectAudioChannelCount, projectHasVideo, projectHasAudio, template))
continue;
String templateName = template.Name;
if (!templateName.Equals(templateRequest, StringComparison.InvariantCultureIgnoreCase))
continue;
return new RenderItem(renderer, template, template.FileExtensions[0]);
}
catch (Exception e)
{
// skip it
MessageBox.Show(e.ToString());
}
}
}
catch
{
// skip it
}
}
return null;
}
private static bool IsTemplateValid(int projectAudioChannelCount, bool projectHasVideo, bool projectHasAudio, RenderTemplate template)
{
// filter out invalid templates
if (!template.IsValid())
{
return false;
}
// filter out video templates when project has
// no video.
if (!projectHasVideo && (0 < template.VideoStreamCount))
{
return false;
}
// filter out audio-only templates when project has no audio
if (!projectHasAudio && (0 == template.VideoStreamCount) && (0 < template.AudioStreamCount))
{
return false;
}
// filter out templates that have more channels than the project
if (projectAudioChannelCount < template.AudioChannelCount)
{
return false;
}
// filter out templates that don't have
// exactly one file extension
String[] extensions = template.FileExtensions;
if (1 != extensions.Length)
{
return false;
}
return true;
}
private void WriteAvailableRenderers(string outputDirectory)
{
if (!Directory.Exists(outputDirectory))
{
Directory.CreateDirectory(outputDirectory);
}
string outputFilePath = Path.Combine(outputDirectory, "VegasRendererList.txt");
using (StreamWriter writer = new StreamWriter(outputFilePath, false))
{
foreach (Renderer renderer in myVegas.Renderers)
{
try
{
String rendererName = renderer.FileTypeName;
writer.WriteLine("Renderer: " + renderer.FileTypeName);
writer.WriteLine("-----------------------------------");
foreach (RenderTemplate template in renderer.Templates)
{
try
{
// filter out invalid templates
if (!template.IsValid())
{
continue;
}
// filter out templates that don't have
// exactly one file extension
String[] extensions = template.FileExtensions;
if (1 != extensions.Length)
{
continue;
}
String templateName = template.Name;
writer.WriteLine(renderer.FileTypeName + ";" + template.Name);
}
catch (Exception e)
{
// skip it
MessageBox.Show(e.ToString());
}
}
writer.WriteLine();
writer.WriteLine();
}
catch
{
// skip it
}
}
} //using file
}
private void SetProjectType(string line)
{
int end = line.IndexOf('#');
if (end == -1)
return;
string type = line.Substring(0, end).ToLower().Trim();
if (type.Equals("selection"))
this._renderMode = RenderMode.Selection;
else if (type.Equals("regions"))
this._renderMode = RenderMode.Regions;
else
this._renderMode = RenderMode.Project;
}
void DoBatchRender(ArrayList selectedTemplates, String basePath, RenderMode renderMode)
{
String outputDirectory = Path.GetDirectoryName(basePath);
String baseFileName = Path.GetFileName(basePath);
// make sure templates are selected
if ((null == selectedTemplates) || (0 == selectedTemplates.Count))
throw new ApplicationException("No render templates selected.");
// make sure the output directory exists
if (!Directory.Exists(outputDirectory))
throw new ApplicationException("The output directory does not exist.");
RenderStatus status = RenderStatus.Canceled;
// enumerate through each selected render template
foreach (RenderItem renderItem in selectedTemplates)
{
// construct the file name (most of it)
String filename = Path.Combine(outputDirectory,
FixFileName(baseFileName) +
FixFileName(renderItem.Renderer.FileTypeName) +
"_" +
FixFileName(renderItem.Template.Name));
//ShowRenderInfo(renderItem, filename);
if (RenderMode.Regions == renderMode)
{
int regionIndex = 0;
foreach (Sony.Vegas.Region region in myVegas.Project.Regions)
{
String regionFilename = String.Format("{0}[{1}]{2}",
filename,
regionIndex.ToString(),
renderItem.Extension);
// Render the region
status = DoRender(regionFilename, renderItem, region.Position, region.Length);
if (RenderStatus.Canceled == status) break;
regionIndex++;
}
}
else
{
filename += renderItem.Extension;
Timecode renderStart, renderLength;
if (renderMode == RenderMode.Selection)
{
renderStart = myVegas.SelectionStart;
renderLength = myVegas.SelectionLength;
}
else
{
renderStart = new Timecode();
renderLength = myVegas.Project.Length;
}
status = DoRender(filename, renderItem, renderStart, renderLength);
}
if (RenderStatus.Canceled == status) break;
}
}
private static void ShowRenderInfo(RenderItem renderItem, String filename)
{
StringBuilder msg = new StringBuilder("Render info\n");
msg.Append("\n file name: ");
msg.Append(filename);
msg.Append("\n Renderer: ");
msg.Append(renderItem.Renderer.FileTypeName);
msg.Append("\n Template: ");
msg.Append(renderItem.Template.Name);
msg.Append("\n Start Time: ");
MessageBox.Show(msg.ToString());
}
// perform the render. The Render method returns a member of the
// RenderStatus enumeration. If it is anything other than OK,
// exit the loops. This will throw an error message string if the
// render does not complete successfully.
RenderStatus DoRender(String filePath, RenderItem renderItem, Timecode start, Timecode length)
{
ValidateFilePath(filePath);
// make sure the file does not already exist
if (!OverwriteExistingFiles && File.Exists(filePath))
{
throw new ApplicationException("File already exists: " + filePath);
}
// perform the render. The Render method returns
// a member of the RenderStatus enumeration. If
// it is anything other than OK, exit the loops.
RenderStatus status = myVegas.Render(filePath, renderItem.Template, start, length);
switch (status)
{
case RenderStatus.Complete:
case RenderStatus.Canceled:
break;
case RenderStatus.Failed:
default:
StringBuilder msg = new StringBuilder("Render failed:\n");
msg.Append("\n file name: ");
msg.Append(filePath);
msg.Append("\n Renderer: ");
msg.Append(renderItem.Renderer.FileTypeName);
msg.Append("\n Template: ");
msg.Append(renderItem.Template.Name);
msg.Append("\n Start Time: ");
msg.Append(start.ToString());
msg.Append("\n Length: ");
msg.Append(length.ToString());
throw new ApplicationException(msg.ToString());
}
return status;
}
String FixFileName(String name)
{
const Char replacementChar = '-';
foreach (char badChar in Path.GetInvalidFileNameChars())
{
name = name.Replace(badChar, replacementChar);
}
return name;
}
void ValidateFilePath(String filePath)
{
if (filePath.Length > 260)
throw new ApplicationException("File name too long: " + filePath);
foreach (char badChar in Path.GetInvalidPathChars())
{
if (0 <= filePath.IndexOf(badChar))
{
throw new ApplicationException("Invalid file name: " + filePath);
}
}
}
class RenderItem
{
public readonly Renderer Renderer = null;
public readonly RenderTemplate Template = null;
public readonly String Extension = null;
public RenderItem(Renderer r, RenderTemplate t, String e)
{
this.Renderer = r;
this.Template = t;
// need to strip off the extension's leading "*"
if (null != e) this.Extension = e.TrimStart('*');
}
}
bool ProjectHasVideo()
{
foreach (Track track in myVegas.Project.Tracks)
{
if (track.IsVideo())
{
return true;
}
}
return false;
}
bool ProjectHasAudio()
{
foreach (Track track in myVegas.Project.Tracks)
{
if (track.IsAudio())
{
return true;
}
}
return false;
}
}
public class KeyValuePair
{
public string RendererName;
public string TemplateName;
public KeyValuePair(string rendererName, string templateName)
{
this.RendererName = rendererName;
this.TemplateName = templateName;
}
} | 34.508876 | 166 | 0.535494 | [
"MIT"
] | WhatIfWeDigDeeper/SonyVegasProScripting | MyRenderer.cs | 17,498 | C# |
using PuppeteerSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Ranka.Services
{
// Ensure Ranka only has one instance of Chromium running upon request.
public class ChromiumService : RankaService
{
private Browser _browser;
private Page _page;
private int _chromeProcessId;
private readonly string[] _browserArg =
{
"--single-process",
"--lang=en-GB",
"--proxy-server=socks5://127.0.0.1:9050",
"--mute-audio",
"--no-first-run",
};
public async Task<Browser> NewBrowserAsync()
{
var process = Process.GetProcessesByName("usr/bin/chromium-browser/chromium-browser-v7"); // Specific to Raspbian Chromium, change this if on different platform.
if (process.Length > 0)
{
foreach (var item in process)
{
item.Kill();
}
Console.WriteLine("Previous chromium instances killed, continuing...");
}
Console.WriteLine("Launching chromium...");
_browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
Args = _browserArg,
ExecutablePath = "/usr/bin/chromium-browser"
}).ConfigureAwait(false);
await _browser.DefaultContext.OverridePermissionsAsync("https://www.facebook.com", new List<OverridePermission> { OverridePermission.Geolocation, OverridePermission.Notifications }).ConfigureAwait(false);
_page = await _browser.NewPageAsync().ConfigureAwait(false);
_page.DefaultNavigationTimeout = 0;
_page.DefaultTimeout = 0;
await _page.SetViewportAsync(new ViewPortOptions
{
Width = 1280,
Height = 1000
}).ConfigureAwait(false);
_chromeProcessId = _browser.Process.Id;
Console.WriteLine($"Chromium instance {_browser.Process.Id} ready");
return _browser;
}
public async Task<Browser> NewBrowserAsync(int height = 1000)
{
var process = Process.GetProcessesByName("usr/bin/chromium-browser/chromium-browser-v7"); // Specific to Raspbian Chromium, change this if on different platform.
if (process.Length > 0)
{
foreach (var item in process)
{
item.Kill();
}
Console.WriteLine("Previous chromium instances killed, continuing...");
}
Console.WriteLine("Launching chromium...");
_browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
Args = _browserArg,
ExecutablePath = "/usr/bin/chromium-browser"
}).ConfigureAwait(false);
await _browser.DefaultContext.OverridePermissionsAsync("https://www.facebook.com", new List<OverridePermission> { OverridePermission.Geolocation, OverridePermission.Notifications }).ConfigureAwait(false);
_page = await _browser.NewPageAsync().ConfigureAwait(false);
_page.DefaultNavigationTimeout = 0;
_page.DefaultTimeout = 0;
await _page.SetViewportAsync(new ViewPortOptions
{
Width = 1280,
Height = height
}).ConfigureAwait(false);
_chromeProcessId = _browser.Process.Id;
Console.WriteLine($"Chromium instance {_browser.Process.Id} ready");
return _browser;
}
public Page GetChromiumPage()
{
return _page;
}
public async Task FBLogin()
{
await _page.GoToAsync("https://www.facebook.com/").ConfigureAwait(false);
await _page.WaitForSelectorAsync("#email").ConfigureAwait(false);
await _page.FocusAsync("#email").ConfigureAwait(false);
await _page.Keyboard.TypeAsync(Environment.GetEnvironmentVariable("FACEBOOK_USERNAME")).ConfigureAwait(false);
await _page.WaitForSelectorAsync("#pass").ConfigureAwait(false);
await _page.FocusAsync("#pass").ConfigureAwait(false);
await _page.Keyboard.TypeAsync(Environment.GetEnvironmentVariable("FACEBOOK_PASSWORD")).ConfigureAwait(false);
await _page.WaitForSelectorAsync("#loginbutton").ConfigureAwait(false);
await _page.ClickAsync("#loginbutton").ConfigureAwait(false);
await _page.WaitForTimeoutAsync(2000).ConfigureAwait(false);
Console.WriteLine($"Chromium instance {_browser.Process.Id} has successfully logged into Facebook");
}
public async Task InstaLogin()
{
await _page.GoToAsync("https://www.instagram.com/").ConfigureAwait(false);
await _page.WaitForSelectorAsync("#react-root > section > main > article > div.rgFsT > div:nth-child(1) > div > form > div:nth-child(2) > div > label > input").ConfigureAwait(false);
await _page.FocusAsync("#react-root > section > main > article > div.rgFsT > div:nth-child(1) > div > form > div:nth-child(2) > div > label > input").ConfigureAwait(false);
await _page.Keyboard.TypeAsync(Environment.GetEnvironmentVariable("INSTAGRAM_USERNAME")).ConfigureAwait(false);
await _page.WaitForSelectorAsync("#react-root > section > main > article > div.rgFsT > div:nth-child(1) > div > form > div:nth-child(3) > div > label > input").ConfigureAwait(false);
await _page.FocusAsync("#react-root > section > main > article > div.rgFsT > div:nth-child(1) > div > form > div:nth-child(3) > div > label > input").ConfigureAwait(false);
await _page.Keyboard.TypeAsync(Environment.GetEnvironmentVariable("INSTAGRAM_PASSWORD")).ConfigureAwait(false);
await _page.ClickAsync("#react-root > section > main > article > div.rgFsT > div:nth-child(1) > div > form > div:nth-child(4) > button").ConfigureAwait(false);
await _page.WaitForNavigationAsync().ConfigureAwait(false);
Console.WriteLine($"Chromium instance {_browser.Process.Id} has successfully logged into Instagram");
}
public async Task Destroy()
{
await _page.CloseAsync().ConfigureAwait(false);
await _browser.CloseAsync().ConfigureAwait(false);
var process = Process.GetProcessesByName("usr/bin/chromium-browser/chromium-browser-v7"); // Specific to Raspbian Chromium, change this if on different platform.
foreach (var item in process)
{
item.Kill();
}
Console.WriteLine("Chromium has successfully been destroyed");
DiscordReply("Chromium instances eliminated, now ready for next request.");
}
}
} | 49.914286 | 216 | 0.617773 | [
"MIT"
] | afrojezus/Ranka | Services/ChromiumService.cs | 6,990 | C# |
using Bannerlord.BUTR.Shared.Helpers;
using MCM.Abstractions.Settings.Definitions;
using System;
using System.Diagnostics.CodeAnalysis;
// ReSharper disable once CheckNamespace
namespace MCM.Abstractions.Attributes
{
[SuppressMessage("Design", "RCS1203:Use AttributeUsageAttribute.", Justification = "Implemented in the derived attributes.")]
public abstract class BaseSettingPropertyAttribute : Attribute, IPropertyDefinitionBase
{
private string _hintText = string.Empty;
/// <inheritdoc/>
public string DisplayName { get; }
/// <inheritdoc/>
public int Order { get; set; }
/// <inheritdoc/>
public bool RequireRestart { get; set; }
/// <inheritdoc/>
public string HintText { get => _hintText; set => _hintText = TextObjectHelper.Create(value)?.ToString() ?? "ERROR"; }
protected BaseSettingPropertyAttribute(string displayName, int order = -1, bool requireRestart = true, string hintText = "")
{
DisplayName = TextObjectHelper.Create(displayName)?.ToString() ?? "ERROR";
Order = order;
RequireRestart = requireRestart;
HintText = hintText;
}
}
} | 36.787879 | 132 | 0.663921 | [
"MIT"
] | Aragas/Bannerlord.MBOptionScreen | src/MCM/Abstractions/Settings/Definitions/Attributes/BaseSettingPropertyAttribute.cs | 1,216 | C# |
using System;
using UltimaOnline.Items;
namespace UltimaOnline.Items
{
public class LeatherGorget : BaseArmor
{
public override int BasePhysicalResistance { get { return 2; } }
public override int BaseFireResistance { get { return 4; } }
public override int BaseColdResistance { get { return 3; } }
public override int BasePoisonResistance { get { return 3; } }
public override int BaseEnergyResistance { get { return 3; } }
public override int InitMinHits { get { return 30; } }
public override int InitMaxHits { get { return 40; } }
public override int AosStrReq { get { return 20; } }
public override int OldStrReq { get { return 10; } }
public override int ArmorBase { get { return 13; } }
public override ArmorMaterialType MaterialType { get { return ArmorMaterialType.Leather; } }
public override CraftResource DefaultResource { get { return CraftResource.RegularLeather; } }
public override ArmorMeditationAllowance DefMedAllowance { get { return ArmorMeditationAllowance.All; } }
[Constructable]
public LeatherGorget() : base(0x13C7)
{
Weight = 1.0;
}
public LeatherGorget(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | 34.204082 | 114 | 0.608592 | [
"MIT"
] | netcode-gamer/game.ultimaonline.io | UltimaOnline.Data/Items/Armor/Leather/LeatherGorget.cs | 1,676 | C# |
namespace Mapbox.Editor
{
using UnityEngine;
using UnityEditor;
using Mapbox.Editor.NodeEditor;
using Mapbox.Unity.MeshGeneration.Modifiers;
[CustomEditor(typeof(MaterialModifier))]
public class MaterialModifierEditor : UnityEditor.Editor
{
private MonoScript script;
private MaterialModifier _modifier;
private SerializedProperty _materials;
private SerializedProperty _projectImagery;
GUIStyle headerFoldout;
GUIStyle header;
bool[] _unfoldElements;
private string entry;
private void OnEnable()
{
script = MonoScript.FromScriptableObject((MaterialModifier)target);
_materials = serializedObject.FindProperty("_materials");
_projectImagery = serializedObject.FindProperty("_projectMapImagery");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUI.enabled = false;
script = EditorGUILayout.ObjectField("Script", script, typeof(MonoScript), false) as MonoScript;
GUI.enabled = true;
if (header == null)
{
headerFoldout = new GUIStyle("Foldout");
_unfoldElements = new bool[_materials.arraySize];
header = new GUIStyle("ShurikenModuleTitle")
{
font = (new GUIStyle("Label")).font,
border = new RectOffset(15, 7, 4, 4),
fixedHeight = 22,
contentOffset = new Vector2(20f, -2f)
};
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(_projectImagery, new GUIContent("Project Map Imagery"));
EditorGUILayout.HelpBox("If checked, it'll use the map imagery (in Unity Tile saved by ImageFactory) on the first material. Sample usecase is to have satellite imagery on building roofs.", MessageType.Info);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Materials");
EditorGUILayout.HelpBox("Material Modifier will select and apply one material from each stack below to the submesh with same index. Default demos have top polygon (i.e. roofs) as first submesh and side polygons (i.e. walls) as second submesh.", MessageType.Info);
for (int i = 0; i < _materials.arraySize; i++)
{
GUILayout.BeginHorizontal();
_unfoldElements[i] = Header("Submesh " + i + " Material", _unfoldElements[i]);
if (GUILayout.Button(new GUIContent("Remove"), header, GUILayout.Width(80)))
{
_materials.DeleteArrayElementAtIndex(i);
break;
}
GUILayout.EndHorizontal();
if (_unfoldElements[i])
{
EditorGUILayout.PropertyField(_materials.GetArrayElementAtIndex(i).FindPropertyRelative("Materials.Array.size"));
EditorGUI.indentLevel = 3;
for (int j = 0; j < _materials.GetArrayElementAtIndex(i).FindPropertyRelative("Materials.Array.size").intValue; j++)
{
var prop = _materials.GetArrayElementAtIndex(i).FindPropertyRelative("Materials").GetArrayElementAtIndex(j);
EditorGUILayout.PropertyField(prop);
}
}
EditorGUILayout.Space();
}
if (GUILayout.Button(new GUIContent("Add New Empty"), (GUIStyle)"minibuttonleft"))
{
_materials.arraySize++;
var test = (bool[])_unfoldElements.Clone();
_unfoldElements = new bool[_materials.arraySize];
for (int i = 0; i < test.Length; i++)
{
_unfoldElements[i] = test[i];
}
}
serializedObject.ApplyModifiedProperties();
}
public bool Header(string title, bool show)
{
var rect = GUILayoutUtility.GetRect(16f, 22f, header);
GUI.Box(rect, title, header);
var foldoutRect = new Rect(rect.x + 4f, rect.y + 2f, 13f, 13f);
var e = Event.current;
if (e.type == EventType.Repaint)
headerFoldout.Draw(foldoutRect, false, false, show, false);
if (e.type == EventType.MouseDown)
{
if (rect.Contains(e.mousePosition))
{
show = !show;
e.Use();
}
}
return show;
}
}
} | 30.508197 | 266 | 0.702579 | [
"Apache-2.0"
] | Anderson-RC/GGJ2018 | Assets/Mapbox/Unity/Editor/MaterialModifierEditor.cs | 3,724 | C# |
using System;
using System.Configuration;
using Akka.Actor;
using common;
namespace SomeServerNode
{
internal class Program
{
private static void Main(string[] args)
{
var myActorsystem = ConfigurationManager.AppSettings["my-actorsystem"];
var route = ConfigurationManager.AppSettings["route"];
var chatActorName = ConfigurationManager.AppSettings["chat-actor-name"];
using (var actorSystem = ActorSystem.Create(myActorsystem))
{
// actorSystem.ActorOf<ChatActor>(chatActorName);
// var router = actorSystem.ActorOf(Props.Create<ChatActor>( ).WithRouter(FromConfig.Instance), "some-group-router");
var router = actorSystem.ActorOf(Props.Create(() => new ChatActor()), chatActorName);
// actorSystem.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), chatActorName);
// actorSystem.ActorOf(Props.Empty.WithRouter(
// new ClusterRouterGroup(
// new RoundRobinGroup("/user/backend"),
// new ClusterRouterGroupSettings(10, false, "backend", ImmutableHashSet.Create("/user/backend"))
// )
//));
Console.WriteLine("Started SomeServerNode");
while (true)
{
Console.ReadLine();
}
}
}
}
} | 36.342105 | 134 | 0.60391 | [
"MIT"
] | contactsamie/AkkaRemoteThings | SomeServerNode/Program.cs | 1,383 | C# |
/*
Copyright 2015-2017 Richard S. Tallent, II
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 Synuit.Toolkit.Utils.Combs.Providers;
using Synuit.Toolkit.Utils.Combs.Strategies;
namespace Synuit.Toolkit.Utils.Combs.StaticProviders
{
public static class Provider
{
public static ICombProvider Legacy = new SqlCombProvider(new SqlDateTimeStrategy());
public static ICombProvider Sql = new SqlCombProvider(new UnixDateTimeStrategy());
public static ICombProvider PostgreSql = new PostgreSqlCombProvider(new UnixDateTimeStrategy());
}
} | 55.464286 | 132 | 0.792015 | [
"MIT"
] | Synuit-Platform/Synuit.Toolkit | Synuit.Toolkit/Utils/Comb/StaticProviders/Providers.cs | 1,553 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\dwrite.h(1965,1)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
/// <summary>
/// The DWRITE_TEXT_RANGE structure specifies a range of text positions where format is applied.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct DWRITE_TEXT_RANGE
{
/// <summary>
/// The start text position of the range.
/// </summary>
public uint startPosition;
/// <summary>
/// The number of text positions in the range.
/// </summary>
public uint length;
}
}
| 29.347826 | 101 | 0.608889 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/DWRITE_TEXT_RANGE.cs | 677 | C# |
using Pims.Dal.Entities;
using Pims.Dal.Entities.Models;
namespace Pims.Dal.Services
{
/// <summary>
/// IAccessRequestService interface, provides functions to interact with access requests within the datasource.
/// </summary>
public interface IAccessRequestService : IService<PimsAccessRequest>
{
Paged<PimsAccessRequest> Get(AccessRequestFilter filter);
PimsAccessRequest Get();
PimsAccessRequest Get(long id);
PimsAccessRequest Add(PimsAccessRequest addRequest);
PimsAccessRequest Update(PimsAccessRequest updateRequest);
PimsAccessRequest Delete(PimsAccessRequest deleteRequest);
}
}
| 34.842105 | 115 | 0.73716 | [
"Apache-2.0"
] | asanchezr/PSP | backend/dal/Services/Interfaces/IAccessRequestService.cs | 662 | C# |
using System.Collections.Generic;
using System.Linq;
namespace BetterDotNet
{
/// <summary>
/// String extensions for reflowing text.
/// </summary>
public static class StringReflowExtensions
{
/// <summary>
/// <para>
/// Strip all newlines from the input string, then return chunks
/// of text of at most <paramref name="maxChars"/> characters.
/// </para>
/// </summary>
/// <param name="text">String to reflow.</param>
/// <param name="maxChars">Maximum number of characters per line.</param>
/// <returns></returns>
public static IEnumerable<string> Reflow(this string text, int maxChars)
{
return ReflowWords(text, maxChars, null);
}
/// <summary>
/// <para>
/// Strip all newlines from the input string, then return chunks
/// of text of at most <paramref name="maxChars"/> characters.
/// </para>
/// <para>
/// If a word (defined as consecutive characters that aren't
/// spaces or tabs) is being split,
/// the line will return up to the last whole word. If a word's
/// length is longer than <paramref name="maxChars"/>, it will
/// be forced to split across multiple lines.
/// </para>
/// <para>
/// If multiple separator characters occur at a line boundary, they
/// will be removed.
/// </para>
/// </summary>
/// <param name="text">String to reflow.</param>
/// <param name="maxChars">Maximum number of characters per line.</param>
/// <returns></returns>
public static IEnumerable<string> ReflowWords(this string text, int maxChars)
{
return ReflowWords(text, maxChars, new[] { ' ', '\t' });
}
/// <summary>
/// <para>
/// Strip all newlines from the input string, then return chunks
/// of text of at most <paramref name="maxChars"/> characters.
/// </para>
/// <para>
/// If a word (defined as consecutive characters that aren't
/// given in <paramref name="separators"/>) is being split,
/// the line will return up to the last whole word. If a word's
/// length is longer than <paramref name="maxChars"/>, it will
/// be forced to split across multiple lines.
/// </para>
/// <para>
/// If multiple separator characters occur at a line boundary, they
/// will be removed.
/// </para>
/// </summary>
/// <param name="text">String to reflow.</param>
/// <param name="maxChars">Maximum number of characters per line.</param>
/// <param name="separators">Array of valid separator characters.</param>
/// <returns></returns>
public static IEnumerable<string> ReflowWords(this string text, int maxChars,
char[] separators)
{
if (separators == null)
{
separators = new char[0];
}
// Remove newlines
text = text
.Replace(@"\r\n", " ")
.Replace(@"\n", " ");
var start = FindNextNonSeparator(text, 0, separators);
for (var end = start; end < text.Length; end++)
{
if (end - start < maxChars) continue;
// There's a separator at the boundary
if (separators.Contains(text[end]))
{
var str = text.Substring(start,
FindPreviousSeparator(
text, start, end, separators) - start);
if (str.Length > 0)
{
yield return str;
}
}
// We're splitting a word up, step backwards to the beginning
// of the word.
else
{
var tmpEnd = FindPreviousNonSeparator(text, start, end, separators);
// The word must be longer than the line.
// Force a split.
if (tmpEnd == start)
{
var str = text.Substring(start, end - start);
if (str.Length > 0)
{
yield return str;
}
}
else
{
end = tmpEnd;
var str = text.Substring(start,
FindPreviousSeparator(
text, start, tmpEnd, separators) - start);
if (str.Length > 0)
{
yield return str;
}
}
}
start = FindNextNonSeparator(text, end, separators);
}
if (start != text.Length)
{
var end = text.Length - 1;
var tmpEnd = FindPreviousNonSeparator(
text, start, end, separators);
if (tmpEnd == start)
{
var str = text.Substring(start);
if (str.Length > 0)
{
yield return str;
}
}
else
{
var str = text.Substring(start,
FindPreviousSeparator(
text, start, tmpEnd, separators) - start);
if (str.Length > 0)
{
yield return str;
}
}
}
}
private static int FindNextNonSeparator(string text, int start, char[] seps)
{
while (start < text.Length && seps.Contains(text[start]))
{
start++;
}
return start;
}
private static int FindPreviousSeparator(string text, int start, int end, char[] seps)
{
while (end > start && seps.Contains(text[end - 1]))
{
end--;
}
return end;
}
private static int FindPreviousNonSeparator(string text, int start, int end, char[] seps)
{
// Step backwards to the beginning of the word
while (end > start && !seps.Contains(text[end - 1]))
{
end--;
}
return end;
}
}
}
| 36.048387 | 97 | 0.453691 | [
"MIT"
] | nemec/Better.Net | BetterDotNet/StringReflowExtensions.cs | 6,707 | C# |
using System.Collections.Generic;
namespace NExtra.Console
{
/// <summary>
/// This class can be used to parse command line args
/// into a typed CommandLineArguments instance.
/// </summary>
/// <remarks>
/// Author: Daniel Saidi [daniel.saidi@gmail.com]
/// Link: http://danielsaidi.github.com/nextra
/// </remarks>
public class TypedCommandLineArgumentParser : ICommandLineArgumentParser<CommandLineArguments>
{
private readonly ICommandLineArgumentParser<IDictionary<string, string>> _baseParser;
public TypedCommandLineArgumentParser(ICommandLineArgumentParser<IDictionary<string, string>> baseParser)
{
_baseParser = baseParser;
}
public CommandLineArguments ParseCommandLineArguments(IEnumerable<string> args)
{
var dict = _baseParser.ParseCommandLineArguments(args);
var result = new CommandLineArguments(dict);
return result;
}
}
}
| 31.939394 | 114 | 0.637571 | [
"MIT"
] | danielsaidi/nextra | NExtra/Console/TypedCommandLineArgumentParser.cs | 1,056 | 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.
// </auto-generated>
namespace Microsoft.Azure.Management.ResourceManager.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
/// <summary>
/// All resource groups and resources exist within subscriptions. These
/// operation enable you get information about your subscriptions and
/// tenants. A tenant is a dedicated instance of Azure Active Directory
/// (Azure AD) for your organization.
/// </summary>
public partial interface ISubscriptionClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// The API version to use for the operation.
/// </summary>
string ApiVersion { get; }
/// <summary>
/// The preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default
/// value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When
/// set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the ISubscriptionsOperations.
/// </summary>
ISubscriptionsOperations Subscriptions { get; }
/// <summary>
/// Gets the ITenantsOperations.
/// </summary>
ITenantsOperations Tenants { get; }
}
}
| 31.898734 | 78 | 0.609524 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/ResourceManager/Generated/ISubscriptionClient.cs | 2,520 | C# |
/*
* eZmax API Definition (Full)
*
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.7
* Contact: support-api@ezmax.ca
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using eZmaxApi.Api;
using eZmaxApi.Model;
using eZmaxApi.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace eZmaxApi.Test.Model
{
/// <summary>
/// Class for testing EzsignbulksendGetFormsDataV1ResponseMPayload
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class EzsignbulksendGetFormsDataV1ResponseMPayloadTests : IDisposable
{
// TODO uncomment below to declare an instance variable for EzsignbulksendGetFormsDataV1ResponseMPayload
//private EzsignbulksendGetFormsDataV1ResponseMPayload instance;
public EzsignbulksendGetFormsDataV1ResponseMPayloadTests()
{
// TODO uncomment below to create an instance of EzsignbulksendGetFormsDataV1ResponseMPayload
//instance = new EzsignbulksendGetFormsDataV1ResponseMPayload();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of EzsignbulksendGetFormsDataV1ResponseMPayload
/// </summary>
[Fact]
public void EzsignbulksendGetFormsDataV1ResponseMPayloadInstanceTest()
{
// TODO uncomment below to test "IsType" EzsignbulksendGetFormsDataV1ResponseMPayload
//Assert.IsType<EzsignbulksendGetFormsDataV1ResponseMPayload>(instance);
}
/// <summary>
/// Test the property 'AObjFormsDataFolder'
/// </summary>
[Fact]
public void AObjFormsDataFolderTest()
{
// TODO unit test for the property 'AObjFormsDataFolder'
}
}
}
| 29.888889 | 112 | 0.68448 | [
"MIT"
] | ezmaxinc/eZmax-SDK-csharp-netcore | src/eZmaxApi.Test/Model/EzsignbulksendGetFormsDataV1ResponseMPayloadTests.cs | 2,152 | C# |
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using WeihanLi.Common;
using WeihanLi.Common.Helpers;
using WeihanLi.Extensions;
using WeihanLi.Npoi.Configurations;
using WeihanLi.Npoi.Settings;
namespace WeihanLi.Npoi
{
internal static class NpoiHelper
{
private static SheetSetting GetSheetSetting(IDictionary<int, SheetSetting> sheetSettings, int sheetIndex)
{
return sheetIndex > 0 && sheetSettings.ContainsKey(sheetIndex)
? sheetSettings[sheetIndex]
: sheetSettings[0];
}
/// <summary>
/// Import sheet data to entity list
/// </summary>
/// <typeparam name="TEntity">entity type</typeparam>
/// <param name="sheet">excel sheet</param>
/// <param name="sheetIndex">sheetIndex</param>
/// <returns>entity list</returns>
public static List<TEntity?> SheetToEntityList<TEntity>(ISheet? sheet, int sheetIndex) where TEntity : new()
{
if (sheet is null || sheet.PhysicalNumberOfRows <= 0)
return new List<TEntity?>();
var configuration = InternalHelper.GetExcelConfigurationMapping<TEntity>();
var sheetSetting = GetSheetSetting(configuration.SheetSettings, sheetIndex);
var entities = new List<TEntity?>(sheet.LastRowNum - sheetSetting.HeaderRowIndex);
var propertyColumnDictionary = InternalHelper.GetPropertyColumnDictionary(configuration);
var propertyColumnDic = sheetSetting.HeaderRowIndex >= 0
? propertyColumnDictionary.ToDictionary(_ => _.Key, _ => new PropertyConfiguration()
{
ColumnIndex = -1,
ColumnFormatter = _.Value.ColumnFormatter,
ColumnTitle = _.Value.ColumnTitle,
ColumnWidth = _.Value.ColumnWidth,
IsIgnored = _.Value.IsIgnored
})
: propertyColumnDictionary;
var formulaEvaluator = sheet.Workbook.GetFormulaEvaluator();
var pictures = propertyColumnDic
.Any(p => p.Key.CanWrite &&
(p.Key.PropertyType == typeof(byte[]) || p.Key.PropertyType == typeof(IPictureData)))
? sheet.GetPicturesAndPosition()
: new Dictionary<CellPosition, IPictureData>();
for (var rowIndex = sheet.FirstRowNum; rowIndex <= (sheetSetting.EndRowIndex ?? sheet.LastRowNum); rowIndex++)
{
var row = sheet.GetRow(rowIndex);
if (rowIndex == sheetSetting.HeaderRowIndex) // readerHeader
{
if (row != null)
{
// adjust column index according to the imported data header
for (var i = row.FirstCellNum; i < row.LastCellNum; i++)
{
if (row.GetCell(i) is null)
{
continue;
}
var col = propertyColumnDic.GetPropertySetting(row.GetCell(i).StringCellValue.Trim());
if (null != col)
{
col.ColumnIndex = i;
}
}
}
// use default column index if no headers
if (propertyColumnDic.Values.All(_ => _.ColumnIndex < 0))
{
propertyColumnDic = propertyColumnDictionary;
}
}
else if (rowIndex >= sheetSetting.StartRowIndex)
{
if (sheetSetting.RowFilter?.Invoke(row) == false)
{
continue;
}
if (row is null)
{
entities.Add(default);
}
else
{
TEntity? entity;
if (row.Cells.Count > 0)
{
entity = new TEntity();
if (configuration.EntityType.IsValueType)
{
var obj = (object)entity;// boxing for value types
ProcessImport(obj, row, rowIndex, propertyColumnDic, sheetSetting, formulaEvaluator,
pictures);
entity = (TEntity)obj;// unboxing
}
else
{
ProcessImport(entity, row, rowIndex, propertyColumnDic, sheetSetting, formulaEvaluator,
pictures);
}
}
else
{
entity = default;
}
if (entity is not null)
{
foreach (var propertyInfo in propertyColumnDic.Keys)
{
if (propertyInfo.CanWrite)
{
var propertyValue = propertyInfo.GetValueGetter()?.Invoke(entity);
if (InternalCache.InputFormatterFuncCache.TryGetValue(propertyInfo, out var formatterFunc) && formatterFunc?.Method != null)
{
var valueSetter = propertyInfo.GetValueSetter();
if (valueSetter != null)
{
try
{
// apply custom formatterFunc
var formattedValue = formatterFunc.DynamicInvoke(entity, propertyValue);
valueSetter.Invoke(entity, formattedValue);
}
catch (Exception e)
{
Debug.WriteLine(e);
InvokeHelper.OnInvokeException?.Invoke(e);
}
}
}
}
}
}
if (configuration.DataValidationFunc?.Invoke(entity) != false)
{
entities.Add(entity);
}
}
}
}
return entities;
}
private static void ProcessImport(object entity, IRow row, int rowIndex,
Dictionary<PropertyInfo, PropertyConfiguration> propertyColumnDic, SheetSetting sheetSetting,
IFormulaEvaluator formulaEvaluator,
Dictionary<CellPosition, IPictureData> pictures)
{
foreach (var key in propertyColumnDic.Keys)
{
var colIndex = propertyColumnDic[key].ColumnIndex;
if (colIndex >= 0 && key.CanWrite)
{
var columnValue = key.PropertyType.GetDefaultValue();
var cell = row.GetCell(colIndex);
if (sheetSetting.CellFilter?.Invoke(cell) != false)
{
var valueSetter = key.GetValueSetter();
if (valueSetter != null)
{
if (key.PropertyType == typeof(byte[])
|| key.PropertyType == typeof(IPictureData))
{
if (pictures.TryGetValue(new CellPosition(rowIndex, colIndex), out var pic))
{
valueSetter.Invoke(entity, key.PropertyType == typeof(IPictureData) ? pic : pic.Data);
}
}
else
{
var valueApplied = false;
if (InternalCache.ColumnInputFormatterFuncCache.TryGetValue(key, out var formatterFunc) && formatterFunc?.Method != null)
{
var cellValue = cell.GetCellValue<string>(formulaEvaluator);
try
{
// apply custom formatterFunc
columnValue = formatterFunc.DynamicInvoke(cellValue);
valueApplied = true;
}
catch (Exception e)
{
Debug.WriteLine(e);
InvokeHelper.OnInvokeException?.Invoke(e);
}
}
if (valueApplied == false)
{
columnValue = cell.GetCellValue(key.PropertyType, formulaEvaluator);
}
valueSetter.Invoke(entity, columnValue);
}
}
}
}
}
}
/// <summary>
/// Export entity list to excel sheet
/// </summary>
/// <typeparam name="TEntity">entity type</typeparam>
/// <param name="sheet">sheet</param>
/// <param name="entityList">entity list</param>
/// <param name="sheetIndex">sheetIndex</param>
/// <returns>sheet</returns>
public static ISheet EntityListToSheet<TEntity>(ISheet sheet, IEnumerable<TEntity>? entityList, int sheetIndex)
{
Guard.NotNull(sheet, nameof(sheet));
if (entityList is null)
{
return sheet;
}
var configuration = InternalHelper.GetExcelConfigurationMapping<TEntity>();
var propertyColumnDictionary = InternalHelper.GetPropertyColumnDictionary(configuration);
if (propertyColumnDictionary.Keys.Count == 0)
{
return sheet;
}
var sheetSetting = GetSheetSetting(configuration.SheetSettings, sheetIndex);
if (sheetSetting.HeaderRowIndex >= 0)
{
var headerRow = sheet.CreateRow(sheetSetting.HeaderRowIndex);
foreach (var key in propertyColumnDictionary.Keys)
{
var cell = headerRow.CreateCell(propertyColumnDictionary[key].ColumnIndex);
cell.SetCellValue(propertyColumnDictionary[key].ColumnTitle);
sheetSetting.CellAction?.Invoke(cell);
}
sheetSetting.RowAction?.Invoke(headerRow);
}
var rowIndex = 0;
foreach (var entity in entityList)
{
var row = sheet.CreateRow(sheetSetting.StartRowIndex + rowIndex);
if (entity != null)
{
foreach (var key in propertyColumnDictionary.Keys)
{
var propertyValue = key.GetValueGetter<TEntity>()?.Invoke(entity);
if (InternalCache.OutputFormatterFuncCache.TryGetValue(key, out var formatterFunc) && formatterFunc?.Method != null)
{
try
{
// apply custom formatterFunc
propertyValue = formatterFunc.DynamicInvoke(entity, propertyValue);
}
catch (Exception e)
{
Debug.WriteLine(e);
InvokeHelper.OnInvokeException?.Invoke(e);
}
}
var cell = row.CreateCell(propertyColumnDictionary[key].ColumnIndex);
cell.SetCellValue(propertyValue, propertyColumnDictionary[key].ColumnFormatter);
sheetSetting.CellAction?.Invoke(cell);
}
}
sheetSetting.RowAction?.Invoke(row);
rowIndex++;
}
PostSheetProcess(sheet, sheetSetting, rowIndex, configuration, propertyColumnDictionary);
return sheet;
}
/// <summary>
/// Generic type data table to excel sheet
/// </summary>
/// <typeparam name="TEntity">entity type</typeparam>
/// <param name="sheet">sheet</param>
/// <param name="dataTable">data table</param>
/// <param name="sheetIndex">sheetIndex</param>
/// <returns>sheet</returns>
public static ISheet DataTableToSheet<TEntity>(ISheet sheet, DataTable? dataTable, int sheetIndex)
{
Guard.NotNull(sheet, nameof(sheet));
if (dataTable is null || dataTable.Rows.Count == 0 || dataTable.Columns.Count == 0)
{
return sheet;
}
var configuration = InternalHelper.GetExcelConfigurationMapping<TEntity>();
var propertyColumnDictionary = InternalHelper.GetPropertyColumnDictionary(configuration);
if (propertyColumnDictionary.Keys.Count == 0)
{
return sheet;
}
var sheetSetting = GetSheetSetting(configuration.SheetSettings, sheetIndex);
if (sheetSetting.HeaderRowIndex >= 0)
{
var headerRow = sheet.CreateRow(sheetSetting.HeaderRowIndex);
for (var i = 0; i < dataTable.Columns.Count; i++)
{
var col = propertyColumnDictionary.GetPropertySettingByPropertyName(dataTable.Columns[i].ColumnName);
if (null != col)
{
var cell = headerRow.CreateCell(col.ColumnIndex);
cell.SetCellValue(col.ColumnTitle);
sheetSetting.CellAction?.Invoke(cell);
}
}
sheetSetting.RowAction?.Invoke(headerRow);
}
for (var i = 0; i < dataTable.Rows.Count; i++)
{
var row = sheet.CreateRow(sheetSetting.StartRowIndex + i);
for (var j = 0; j < dataTable.Columns.Count; j++)
{
var col = propertyColumnDictionary.GetPropertySettingByPropertyName(dataTable.Columns[j].ColumnName);
var cell = row.CreateCell(col!.ColumnIndex);
cell.SetCellValue(dataTable.Rows[i][j], col.ColumnFormatter);
sheetSetting.CellAction?.Invoke(cell);
}
sheetSetting.RowAction?.Invoke(row);
}
PostSheetProcess(sheet, sheetSetting, dataTable.Rows.Count, configuration, propertyColumnDictionary);
return sheet;
}
private static void PostSheetProcess<TEntity>(ISheet sheet, SheetSetting sheetSetting, int rowsCount, ExcelConfiguration<TEntity> excelConfiguration, IDictionary<PropertyInfo, PropertyConfiguration> propertyColumnDictionary)
{
if (rowsCount > 0)
{
foreach (var setting in propertyColumnDictionary.Values)
{
if (setting.ColumnWidth > 0)
{
sheet.SetColumnWidth(setting.ColumnIndex, setting.ColumnWidth * 256);
}
else
{
if (sheetSetting.AutoColumnWidthEnabled)
{
sheet.AutoSizeColumn(setting.ColumnIndex);
}
}
}
foreach (var freezeSetting in excelConfiguration.FreezeSettings)
{
sheet.CreateFreezePane(freezeSetting.ColSplit, freezeSetting.RowSplit, freezeSetting.LeftMostColumn, freezeSetting.TopRow);
}
if (excelConfiguration.FilterSetting != null)
{
var headerIndex = sheetSetting.HeaderRowIndex >= 0 ? sheetSetting.HeaderRowIndex : 0;
sheet.SetAutoFilter(new CellRangeAddress(headerIndex, rowsCount + headerIndex, excelConfiguration.FilterSetting.FirstColumn, excelConfiguration.FilterSetting.LastColumn ?? propertyColumnDictionary.Values.Max(_ => _.ColumnIndex)));
}
}
sheetSetting.SheetAction?.Invoke(sheet);
}
}
}
| 45.002571 | 250 | 0.466354 | [
"Apache-2.0"
] | Ninjanaut/WeihanLi.Npoi | src/WeihanLi.Npoi/NpoiHelper.cs | 17,508 | C# |
using System;
namespace STak.TakEngine.Extensions
{
public static class GameExtensions
{
public static bool CanDrawStone(this IGame game, StoneType stoneType) => game.CanDrawStone(Player.None, stoneType);
public static bool CanReturnStone(this IGame game) => game.CanReturnStone(Player.None);
public static bool CanPlaceStone(this IGame game, Cell cell) => game.CanPlaceStone(Player.None, cell);
public static bool CanGrabStack(this IGame game, Cell cell, int stoneCount) => game.CanGrabStack(Player.None, cell, stoneCount);
public static bool CanDropStack(this IGame game, Cell cell, int stoneCount) => game.CanDropStack(Player.None, cell, stoneCount);
public static bool CanAbortMove(this IGame game) => game.CanAbortMove(Player.None);
public static void DrawStone(this IGame game, StoneType stoneType, int stoneId = -1) => game.DrawStone(Player.None, stoneType, stoneId);
public static void ReturnStone(this IGame game) => game.ReturnStone(Player.None);
public static void PlaceStone(this IGame game, Cell cell) => game.PlaceStone(Player.None, cell, StoneType.None);
public static void PlaceStone(this IGame game, Cell cell, StoneType stoneType) => game.PlaceStone(Player.None, cell, stoneType);
public static void GrabStack(this IGame game, Cell cell, int stoneCount) => game.GrabStack(Player.None, cell, stoneCount);
public static void DropStack(this IGame game, Cell cell, int stoneCount) => game.DropStack(Player.None, cell, stoneCount);
public static void AbortMove(this IGame game) => game.AbortMove(Player.None);
public static void TrackMove(this IGame game, BoardPosition position) => game.TrackMove(Player.None, position);
public static void SetCurrentTurn(this IGame game, int turn) => game.SetCurrentTurn(Player.None, turn);
public static void InitiateAbort(this IGame game, IMove move, int duration) => game.InitiateAbort(Player.None, move, duration);
public static void CompleteAbort(this IGame game, IMove move) => game.CompleteAbort(Player.None, move);
public static void InitiateMove(this IGame game, IMove move, int duration) => game.InitiateMove(Player.None, move, duration);
public static void CompleteMove(this IGame game, IMove move) => game.CompleteMove(Player.None, move);
public static void InitiateUndo(this IGame game, int duration) => game.InitiateUndo(Player.None, duration);
public static void CompleteUndo(this IGame game) => game.CompleteUndo(Player.None);
public static void InitiateRedo(this IGame game, int duration) => game.InitiateRedo(Player.None, duration);
public static void CompleteRedo(this IGame game) => game.CompleteRedo(Player.None);
}
}
| 86.078947 | 147 | 0.625191 | [
"MIT"
] | crasshacker/STak | src/lib/Engine/Core/Extensions/GameExtensions.cs | 3,271 | C# |
#if NET45
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
//#if !NO_DYNAMIC
//using System.Dynamic;
//#endif
namespace Serenity.Reflection
{
/// <summary>
/// Provides by-name member-access to objects of a given type
/// </summary>
public abstract class TypeAccessor
{
// hash-table has better read-without-locking semantics than dictionary
private static readonly Hashtable typeLookyp = new Hashtable();
/// <summary>
/// Does this type support new instances via a parameterless constructor?
/// </summary>
public virtual bool CreateNewSupported { get { return false; } }
/// <summary>
/// Create a new instance of this type
/// </summary>
public virtual object CreateNew() { throw new NotSupportedException(); }
/// <summary>
/// Provides a type-specific accessor, allowing by-name access for all objects of that type
/// </summary>
/// <remarks>The accessor is cached internally; a pre-existing accessor may be returned</remarks>
public static TypeAccessor Create(Type type)
{
if (type == null) throw new ArgumentNullException("type");
TypeAccessor obj = (TypeAccessor)typeLookyp[type];
if (obj != null) return obj;
lock (typeLookyp)
{
// double-check
obj = (TypeAccessor)typeLookyp[type];
if (obj != null) return obj;
obj = CreateNew(type);
typeLookyp[type] = obj;
return obj;
}
}
//#if !NO_DYNAMIC
// sealed class DynamicAccessor : TypeAccessor
// {
// public static readonly DynamicAccessor Singleton = new DynamicAccessor();
// private DynamicAccessor() { }
// public override object this[object target, string name]
// {
// get { return CallSiteCache.GetValue(name, target); }
// set { CallSiteCache.SetValue(name, target, value); }
// }
// }
//#endif
private static AssemblyBuilder assembly;
private static ModuleBuilder module;
private static int counter;
private static void WriteGetter(ILGenerator il, Type type, PropertyInfo[] props, FieldInfo[] fields, bool isStatic)
{
LocalBuilder loc = type.IsValueType ? il.DeclareLocal(type) : null;
OpCode propName = isStatic ? OpCodes.Ldarg_1 : OpCodes.Ldarg_2, target = isStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1;
foreach (PropertyInfo prop in props)
{
MethodInfo getter;
if (prop.GetIndexParameters().Length != 0 || !prop.CanRead || (getter = prop.GetGetMethod(false)) == null) continue;
Label next = il.DefineLabel();
il.Emit(propName);
il.Emit(OpCodes.Ldstr, prop.Name);
il.EmitCall(OpCodes.Call, strinqEquals, null);
il.Emit(OpCodes.Brfalse_S, next);
// match:
il.Emit(target);
Cast(il, type, loc);
il.EmitCall(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, getter, null);
if (prop.PropertyType.IsValueType)
{
il.Emit(OpCodes.Box, prop.PropertyType);
}
il.Emit(OpCodes.Ret);
// not match:
il.MarkLabel(next);
}
foreach (FieldInfo field in fields)
{
Label next = il.DefineLabel();
il.Emit(propName);
il.Emit(OpCodes.Ldstr, field.Name);
il.EmitCall(OpCodes.Call, strinqEquals, null);
il.Emit(OpCodes.Brfalse_S, next);
// match:
il.Emit(target);
Cast(il, type, loc);
il.Emit(OpCodes.Ldfld, field);
if (field.FieldType.IsValueType)
{
il.Emit(OpCodes.Box, field.FieldType);
}
il.Emit(OpCodes.Ret);
// not match:
il.MarkLabel(next);
}
il.Emit(OpCodes.Ldstr, "name");
il.Emit(OpCodes.Newobj, typeof(ArgumentOutOfRangeException).GetConstructor(new Type[] { typeof(string) }));
il.Emit(OpCodes.Throw);
}
private static void WriteSetter(ILGenerator il, Type type, PropertyInfo[] props, FieldInfo[] fields, bool isStatic)
{
if (type.IsValueType)
{
il.Emit(OpCodes.Ldstr, "Write is not supported for structs");
il.Emit(OpCodes.Newobj, typeof(NotSupportedException).GetConstructor(new Type[] { typeof(string) }));
il.Emit(OpCodes.Throw);
}
else
{
OpCode propName = isStatic ? OpCodes.Ldarg_1 : OpCodes.Ldarg_2,
target = isStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1,
value = isStatic ? OpCodes.Ldarg_2 : OpCodes.Ldarg_3;
LocalBuilder loc = type.IsValueType ? il.DeclareLocal(type) : null;
foreach (PropertyInfo prop in props)
{
MethodInfo setter;
if (prop.GetIndexParameters().Length != 0 || !prop.CanWrite || (setter = prop.GetSetMethod(false)) == null) continue;
Label next = il.DefineLabel();
il.Emit(propName);
il.Emit(OpCodes.Ldstr, prop.Name);
il.EmitCall(OpCodes.Call, strinqEquals, null);
il.Emit(OpCodes.Brfalse_S, next);
// match:
il.Emit(target);
Cast(il, type, loc);
il.Emit(value);
Cast(il, prop.PropertyType, null);
il.EmitCall(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, setter, null);
il.Emit(OpCodes.Ret);
// not match:
il.MarkLabel(next);
}
foreach (FieldInfo field in fields)
{
Label next = il.DefineLabel();
il.Emit(propName);
il.Emit(OpCodes.Ldstr, field.Name);
il.EmitCall(OpCodes.Call, strinqEquals, null);
il.Emit(OpCodes.Brfalse_S, next);
// match:
il.Emit(target);
Cast(il, type, loc);
il.Emit(value);
Cast(il, field.FieldType, null);
il.Emit(OpCodes.Stfld, field);
il.Emit(OpCodes.Ret);
// not match:
il.MarkLabel(next);
}
il.Emit(OpCodes.Ldstr, "name");
il.Emit(OpCodes.Newobj, typeof(ArgumentOutOfRangeException).GetConstructor(new Type[] { typeof(string) }));
il.Emit(OpCodes.Throw);
}
}
private static readonly MethodInfo strinqEquals = typeof(string).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) });
sealed class DelegateAccessor : TypeAccessor
{
private readonly Func<object, string, object> getter;
private readonly Action<object, string, object> setter;
private readonly Func<object> ctor;
public DelegateAccessor(Func<object, string, object> getter, Action<object, string, object> setter, Func<object> ctor)
{
this.getter = getter;
this.setter = setter;
this.ctor = ctor;
}
public override bool CreateNewSupported { get { return ctor != null; } }
public override object CreateNew()
{
return ctor != null ? ctor() : base.CreateNew();
}
public override object this[object target, string name]
{
get { return getter(target, name); }
set { setter(target, name, value); }
}
}
private static bool IsFullyPublic(Type type)
{
while (type.IsNestedPublic) type = type.DeclaringType;
return type.IsPublic;
}
static TypeAccessor CreateNew(Type type)
{
//#if !NO_DYNAMIC
// if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
// {
// return DynamicAccessor.Singleton;
// }
//#endif
PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ConstructorInfo ctor = null;
if (type.IsClass && !type.IsAbstract)
{
ctor = type.GetConstructor(Type.EmptyTypes);
}
ILGenerator il;
if (!IsFullyPublic(type))
{
DynamicMethod dynGetter = new DynamicMethod(type.FullName + "_get", typeof(object), new Type[] { typeof(object), typeof(string) }, type, true),
dynSetter = new DynamicMethod(type.FullName + "_set", null, new Type[] { typeof(object), typeof(string), typeof(object) }, type, true);
WriteGetter(dynGetter.GetILGenerator(), type, props, fields, true);
WriteSetter(dynSetter.GetILGenerator(), type, props, fields, true);
DynamicMethod dynCtor = null;
if (ctor != null)
{
dynCtor = new DynamicMethod(type.FullName + "_ctor", typeof(object), Type.EmptyTypes, type, true);
il = dynCtor.GetILGenerator();
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
}
return new DelegateAccessor(
(Func<object, string, object>)dynGetter.CreateDelegate(typeof(Func<object, string, object>)),
(Action<object, string, object>)dynSetter.CreateDelegate(typeof(Action<object, string, object>)),
dynCtor == null ? null : (Func<object>)dynCtor.CreateDelegate(typeof(Func<object>)));
}
// note this region is synchronized; only one is being created at a time so we don't need to stress about the builders
if (assembly == null)
{
AssemblyName name = new AssemblyName("FastMember_dynamic");
assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
module = assembly.DefineDynamicModule(name.Name);
}
TypeBuilder tb = module.DefineType("FastMember_dynamic." + type.Name + "_" + Interlocked.Increment(ref counter),
(typeof(TypeAccessor).Attributes | TypeAttributes.Sealed) & ~TypeAttributes.Abstract, typeof(TypeAccessor));
tb.DefineDefaultConstructor(MethodAttributes.Public);
PropertyInfo indexer = typeof(TypeAccessor).GetProperty("Item");
MethodInfo baseGetter = indexer.GetGetMethod(), baseSetter = indexer.GetSetMethod();
MethodBuilder body = tb.DefineMethod(baseGetter.Name, baseGetter.Attributes & ~MethodAttributes.Abstract, typeof(object), new Type[] { typeof(object), typeof(string) });
il = body.GetILGenerator();
WriteGetter(il, type, props, fields, false);
tb.DefineMethodOverride(body, baseGetter);
body = tb.DefineMethod(baseSetter.Name, baseSetter.Attributes & ~MethodAttributes.Abstract, null, new Type[] { typeof(object), typeof(string), typeof(object) });
il = body.GetILGenerator();
WriteSetter(il, type, props, fields, false);
tb.DefineMethodOverride(body, baseSetter);
if (ctor != null)
{
MethodInfo baseMethod = typeof(TypeAccessor).GetProperty("CreateNewSupported").GetGetMethod();
body = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes, typeof(bool), Type.EmptyTypes);
il = body.GetILGenerator();
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Ret);
tb.DefineMethodOverride(body, baseMethod);
baseMethod = typeof(TypeAccessor).GetMethod("CreateNew");
body = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes, typeof(object), Type.EmptyTypes);
il = body.GetILGenerator();
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
tb.DefineMethodOverride(body, baseMethod);
}
return (TypeAccessor)Activator.CreateInstance(tb.CreateType());
}
private static void Cast(ILGenerator il, Type type, LocalBuilder addr)
{
if (type == typeof(object)) { }
else if (type.IsValueType)
{
il.Emit(OpCodes.Unbox_Any, type);
if (addr != null)
{
il.Emit(OpCodes.Stloc, addr);
il.Emit(OpCodes.Ldloca_S, addr);
}
}
else
{
il.Emit(OpCodes.Castclass, type);
}
}
/// <summary>
/// Get or set the value of a named member on the target instance
/// </summary>
public abstract object this[object target, string name]
{
get;
set;
}
}
}
#endif | 45.163987 | 182 | 0.531539 | [
"MIT"
] | Magicianred/Serenity | Serenity.Core/Reflection/TypeAccessor.cs | 14,048 | C# |
using System.Threading.Tasks;
using JudoPayDotNet.Http;
using JudoPayDotNet.Logging;
using JudoPayDotNet.Models;
namespace JudoPayDotNet.Clients.WebPayments
{
internal abstract class BasePayments : JudoPayClient
{
private const string Baseaddress = "webpayments";
protected BasePayments(ILog logger, IClient client) : base(logger, client)
{
}
protected Task<IResult<WebPaymentResponseModel>> Create(WebPaymentRequestModel model, string transactionType)
{
var address = $"{Baseaddress}/{transactionType}";
return PostInternal<WebPaymentRequestModel, WebPaymentResponseModel>(address, model);
}
protected Task<IResult<WebPaymentRequestModel>> Update(WebPaymentRequestModel model, string transactionType)
{
var address = $"{Baseaddress}/{transactionType}";
return PutInternal<WebPaymentRequestModel, WebPaymentRequestModel>(address, model);
}
}
}
| 31.870968 | 117 | 0.703441 | [
"MIT"
] | Judopay/DotNetSDK | JudoPayDotNet/Clients/WebPayments/BasePayments.cs | 990 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.GoogleNative.Compute.Beta.Outputs
{
/// <summary>
/// The specification for fault injection introduced into traffic to test the resiliency of clients to backend service failure. As part of fault injection, when clients send requests to a backend service, delays can be introduced by the load balancer on a percentage of requests before sending those request to the backend service. Similarly requests from clients can be aborted by the load balancer for a percentage of requests.
/// </summary>
[OutputType]
public sealed class HttpFaultInjectionResponse
{
/// <summary>
/// The specification for how client requests are aborted as part of fault injection.
/// </summary>
public readonly Outputs.HttpFaultAbortResponse Abort;
/// <summary>
/// The specification for how client requests are delayed as part of fault injection, before being sent to a backend service.
/// </summary>
public readonly Outputs.HttpFaultDelayResponse Delay;
[OutputConstructor]
private HttpFaultInjectionResponse(
Outputs.HttpFaultAbortResponse abort,
Outputs.HttpFaultDelayResponse delay)
{
Abort = abort;
Delay = delay;
}
}
}
| 40.923077 | 433 | 0.701754 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Compute/Beta/Outputs/HttpFaultInjectionResponse.cs | 1,596 | C# |
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. 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.
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.Linq;
using Tensorflow.Framework.Models;
using Tensorflow.Keras.ArgsDefinition;
using Tensorflow.Keras.Engine;
using static Tensorflow.Binding;
using static Tensorflow.KerasApi;
namespace Tensorflow.Keras.Layers
{
/// <summary>
/// Layer to be used as an entry point into a Network (a graph of layers).
/// </summary>
public class InputLayer : Layer
{
InputLayerArgs args;
bool isPlaceholder;
TensorSpec typeSpec;
public InputLayer(InputLayerArgs args) :
base(args)
{
this.args = args;
built = true;
SupportsMasking = true;
if (BatchInputShape != null)
{
args.BatchSize = BatchInputShape.dims[0];
args.InputShape = BatchInputShape.dims[1..];
}
// moved to base class
if (string.IsNullOrEmpty(args.Name))
{
var prefix = "input";
name = prefix + '_' + keras.backend.get_uid(prefix);
args.Name = name;
}
if (args.DType == TF_DataType.DtInvalid)
{
args.DType = args.InputTensor == null ? tf.float32 : args.InputTensor.dtype;
}
// In graph mode, create a graph placeholder to call the layer on.
tf.Context.graph_mode();
if (args.InputTensor == null)
{
if (args.InputShape != null)
{
args.BatchInputShape = new int[] { args.BatchSize }
.Concat(args.InputShape.dims)
.ToArray();
}
else
{
args.BatchInputShape = null;
}
args.InputTensor = keras.backend.placeholder(
shape: BatchInputShape,
dtype: DType,
name: Name,
sparse: args.Sparse,
ragged: args.Ragged);
isPlaceholder = true;
}
// Create an input node to add to self.outbound_node
// and set output_tensors' _keras_history.
// input_tensor._keras_history = base_layer.KerasHistory(self, 0, 0)
// input_tensor._keras_mask = None
new Node(this, new NodeArgs
{
Outputs = args.InputTensor
});
typeSpec = new TensorSpec(args.InputTensor.TensorShape,
dtype: args.InputTensor.dtype,
name: Name);
tf.Context.restore_mode();
}
public static InputLayer from_config(LayerArgs args)
{
return new InputLayer(args as InputLayerArgs);
}
}
}
| 32.581818 | 92 | 0.527065 | [
"Apache-2.0"
] | Aangbaeck/TensorFlow.NET | src/TensorFlowNET.Keras/Layers/Core/InputLayer.cs | 3,586 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: yandex/cloud/iam/v1/api_key_service.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Yandex.Cloud.Iam.V1 {
/// <summary>Holder for reflection information generated from yandex/cloud/iam/v1/api_key_service.proto</summary>
internal static partial class ApiKeyServiceReflection {
#region Descriptor
/// <summary>File descriptor for yandex/cloud/iam/v1/api_key_service.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ApiKeyServiceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cil5YW5kZXgvY2xvdWQvaWFtL3YxL2FwaV9rZXlfc2VydmljZS5wcm90bxIT",
"eWFuZGV4LmNsb3VkLmlhbS52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5w",
"cm90bxogZ29vZ2xlL3Byb3RvYnVmL2ZpZWxkX21hc2sucHJvdG8aIHlhbmRl",
"eC9jbG91ZC9hcGkvb3BlcmF0aW9uLnByb3RvGiF5YW5kZXgvY2xvdWQvaWFt",
"L3YxL2FwaV9rZXkucHJvdG8aJnlhbmRleC9jbG91ZC9vcGVyYXRpb24vb3Bl",
"cmF0aW9uLnByb3RvGh15YW5kZXgvY2xvdWQvdmFsaWRhdGlvbi5wcm90byI0",
"ChBHZXRBcGlLZXlSZXF1ZXN0EiAKCmFwaV9rZXlfaWQYASABKAlCDOjHMQGK",
"yDEEPD01MCJ4ChJMaXN0QXBpS2V5c1JlcXVlc3QSJAoSc2VydmljZV9hY2Nv",
"dW50X2lkGAEgASgJQgiKyDEEPD01MBIdCglwYWdlX3NpemUYAiABKANCCvrH",
"MQYwLTEwMDASHQoKcGFnZV90b2tlbhgDIAEoCUIJisgxBTw9MTAwIl0KE0xp",
"c3RBcGlLZXlzUmVzcG9uc2USLQoIYXBpX2tleXMYASADKAsyGy55YW5kZXgu",
"Y2xvdWQuaWFtLnYxLkFwaUtleRIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAki",
"WwoTQ3JlYXRlQXBpS2V5UmVxdWVzdBIkChJzZXJ2aWNlX2FjY291bnRfaWQY",
"ASABKAlCCIrIMQQ8PTUwEh4KC2Rlc2NyaXB0aW9uGAIgASgJQgmKyDEFPD0y",
"NTYiVAoUQ3JlYXRlQXBpS2V5UmVzcG9uc2USLAoHYXBpX2tleRgBIAEoCzIb",
"LnlhbmRleC5jbG91ZC5pYW0udjEuQXBpS2V5Eg4KBnNlY3JldBgCIAEoCSKI",
"AQoTVXBkYXRlQXBpS2V5UmVxdWVzdBIgCgphcGlfa2V5X2lkGAEgASgJQgzo",
"xzEBisgxBDw9NTASLwoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJv",
"dG9idWYuRmllbGRNYXNrEh4KC2Rlc2NyaXB0aW9uGAMgASgJQgmKyDEFPD0y",
"NTYiKgoUVXBkYXRlQXBpS2V5TWV0YWRhdGESEgoKYXBpX2tleV9pZBgBIAEo",
"CSI3ChNEZWxldGVBcGlLZXlSZXF1ZXN0EiAKCmFwaV9rZXlfaWQYASABKAlC",
"DOjHMQGKyDEEPD01MCIqChREZWxldGVBcGlLZXlNZXRhZGF0YRISCgphcGlf",
"a2V5X2lkGAEgASgJIn0KG0xpc3RBcGlLZXlPcGVyYXRpb25zUmVxdWVzdBIg",
"CgphcGlfa2V5X2lkGAEgASgJQgzoxzEBisgxBDw9NTASHQoJcGFnZV9zaXpl",
"GAIgASgDQgr6xzEGMC0xMDAwEh0KCnBhZ2VfdG9rZW4YAyABKAlCCYrIMQU8",
"PTEwMCJuChxMaXN0QXBpS2V5T3BlcmF0aW9uc1Jlc3BvbnNlEjUKCm9wZXJh",
"dGlvbnMYASADKAsyIS55YW5kZXguY2xvdWQub3BlcmF0aW9uLk9wZXJhdGlv",
"bhIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAky6gYKDUFwaUtleVNlcnZpY2US",
"cgoETGlzdBInLnlhbmRleC5jbG91ZC5pYW0udjEuTGlzdEFwaUtleXNSZXF1",
"ZXN0GigueWFuZGV4LmNsb3VkLmlhbS52MS5MaXN0QXBpS2V5c1Jlc3BvbnNl",
"IheC0+STAhESDy9pYW0vdjEvYXBpS2V5cxJvCgNHZXQSJS55YW5kZXguY2xv",
"dWQuaWFtLnYxLkdldEFwaUtleVJlcXVlc3QaGy55YW5kZXguY2xvdWQuaWFt",
"LnYxLkFwaUtleSIkgtPkkwIeEhwvaWFtL3YxL2FwaUtleXMve2FwaV9rZXlf",
"aWR9EnkKBkNyZWF0ZRIoLnlhbmRleC5jbG91ZC5pYW0udjEuQ3JlYXRlQXBp",
"S2V5UmVxdWVzdBopLnlhbmRleC5jbG91ZC5pYW0udjEuQ3JlYXRlQXBpS2V5",
"UmVzcG9uc2UiGoLT5JMCFCIPL2lhbS92MS9hcGlLZXlzOgEqEqABCgZVcGRh",
"dGUSKC55YW5kZXguY2xvdWQuaWFtLnYxLlVwZGF0ZUFwaUtleVJlcXVlc3Qa",
"IS55YW5kZXguY2xvdWQub3BlcmF0aW9uLk9wZXJhdGlvbiJJgtPkkwIhMhwv",
"aWFtL3YxL2FwaUtleXMve2FwaV9rZXlfaWR9OgEqstIqHgoUVXBkYXRlQXBp",
"S2V5TWV0YWRhdGESBkFwaUtleRKsAQoGRGVsZXRlEigueWFuZGV4LmNsb3Vk",
"LmlhbS52MS5EZWxldGVBcGlLZXlSZXF1ZXN0GiEueWFuZGV4LmNsb3VkLm9w",
"ZXJhdGlvbi5PcGVyYXRpb24iVYLT5JMCHiocL2lhbS92MS9hcGlLZXlzL3th",
"cGlfa2V5X2lkfbLSKi0KFERlbGV0ZUFwaUtleU1ldGFkYXRhEhVnb29nbGUu",
"cHJvdG9idWYuRW1wdHkSpgEKDkxpc3RPcGVyYXRpb25zEjAueWFuZGV4LmNs",
"b3VkLmlhbS52MS5MaXN0QXBpS2V5T3BlcmF0aW9uc1JlcXVlc3QaMS55YW5k",
"ZXguY2xvdWQuaWFtLnYxLkxpc3RBcGlLZXlPcGVyYXRpb25zUmVzcG9uc2Ui",
"L4LT5JMCKRInL2lhbS92MS9hcGlLZXlzL3thcGlfa2V5X2lkfS9vcGVyYXRp",
"b25zQlYKF3lhbmRleC5jbG91ZC5hcGkuaWFtLnYxWjtnaXRodWIuY29tL3lh",
"bmRleC1jbG91ZC9nby1nZW5wcm90by95YW5kZXgvY2xvdWQvaWFtL3YxO2lh",
"bWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, global::Yandex.Cloud.Api.OperationReflection.Descriptor, global::Yandex.Cloud.Iam.V1.ApiKeyReflection.Descriptor, global::Yandex.Cloud.Operation.OperationReflection.Descriptor, global::Yandex.Cloud.ValidationReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.GetApiKeyRequest), global::Yandex.Cloud.Iam.V1.GetApiKeyRequest.Parser, new[]{ "ApiKeyId" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.ListApiKeysRequest), global::Yandex.Cloud.Iam.V1.ListApiKeysRequest.Parser, new[]{ "ServiceAccountId", "PageSize", "PageToken" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.ListApiKeysResponse), global::Yandex.Cloud.Iam.V1.ListApiKeysResponse.Parser, new[]{ "ApiKeys", "NextPageToken" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.CreateApiKeyRequest), global::Yandex.Cloud.Iam.V1.CreateApiKeyRequest.Parser, new[]{ "ServiceAccountId", "Description" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.CreateApiKeyResponse), global::Yandex.Cloud.Iam.V1.CreateApiKeyResponse.Parser, new[]{ "ApiKey", "Secret" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.UpdateApiKeyRequest), global::Yandex.Cloud.Iam.V1.UpdateApiKeyRequest.Parser, new[]{ "ApiKeyId", "UpdateMask", "Description" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.UpdateApiKeyMetadata), global::Yandex.Cloud.Iam.V1.UpdateApiKeyMetadata.Parser, new[]{ "ApiKeyId" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.DeleteApiKeyRequest), global::Yandex.Cloud.Iam.V1.DeleteApiKeyRequest.Parser, new[]{ "ApiKeyId" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.DeleteApiKeyMetadata), global::Yandex.Cloud.Iam.V1.DeleteApiKeyMetadata.Parser, new[]{ "ApiKeyId" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.ListApiKeyOperationsRequest), global::Yandex.Cloud.Iam.V1.ListApiKeyOperationsRequest.Parser, new[]{ "ApiKeyId", "PageSize", "PageToken" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Yandex.Cloud.Iam.V1.ListApiKeyOperationsResponse), global::Yandex.Cloud.Iam.V1.ListApiKeyOperationsResponse.Parser, new[]{ "Operations", "NextPageToken" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
internal sealed partial class GetApiKeyRequest : pb::IMessage<GetApiKeyRequest> {
private static readonly pb::MessageParser<GetApiKeyRequest> _parser = new pb::MessageParser<GetApiKeyRequest>(() => new GetApiKeyRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetApiKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetApiKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetApiKeyRequest(GetApiKeyRequest other) : this() {
apiKeyId_ = other.apiKeyId_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetApiKeyRequest Clone() {
return new GetApiKeyRequest(this);
}
/// <summary>Field number for the "api_key_id" field.</summary>
public const int ApiKeyIdFieldNumber = 1;
private string apiKeyId_ = "";
/// <summary>
/// ID of the API key to return.
/// To get the API key ID, use a [ApiKeyService.List] request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiKeyId {
get { return apiKeyId_; }
set {
apiKeyId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetApiKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetApiKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ApiKeyId != other.ApiKeyId) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ApiKeyId.Length != 0) hash ^= ApiKeyId.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ApiKeyId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ApiKeyId);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ApiKeyId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiKeyId);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetApiKeyRequest other) {
if (other == null) {
return;
}
if (other.ApiKeyId.Length != 0) {
ApiKeyId = other.ApiKeyId;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ApiKeyId = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ListApiKeysRequest : pb::IMessage<ListApiKeysRequest> {
private static readonly pb::MessageParser<ListApiKeysRequest> _parser = new pb::MessageParser<ListApiKeysRequest>(() => new ListApiKeysRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListApiKeysRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeysRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeysRequest(ListApiKeysRequest other) : this() {
serviceAccountId_ = other.serviceAccountId_;
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeysRequest Clone() {
return new ListApiKeysRequest(this);
}
/// <summary>Field number for the "service_account_id" field.</summary>
public const int ServiceAccountIdFieldNumber = 1;
private string serviceAccountId_ = "";
/// <summary>
/// ID of the service account to list API keys for.
/// To get the service account ID, use a [yandex.cloud.iam.v1.ServiceAccountService.List] request.
/// If not specified, it defaults to the subject that made the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ServiceAccountId {
get { return serviceAccountId_; }
set {
serviceAccountId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 2;
private long pageSize_;
/// <summary>
/// The maximum number of results per page to return. If the number of available
/// results is larger than [page_size],
/// the service returns a [ListApiKeysResponse.next_page_token]
/// that can be used to get the next page of results in subsequent list requests.
/// Default value: 100.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 3;
private string pageToken_ = "";
/// <summary>
/// Page token. To get the next page of results, set [page_token]
/// to the [ListApiKeysResponse.next_page_token]
/// returned by a previous list request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListApiKeysRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListApiKeysRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ServiceAccountId != other.ServiceAccountId) return false;
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ServiceAccountId.Length != 0) hash ^= ServiceAccountId.GetHashCode();
if (PageSize != 0L) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ServiceAccountId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ServiceAccountId);
}
if (PageSize != 0L) {
output.WriteRawTag(16);
output.WriteInt64(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(26);
output.WriteString(PageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ServiceAccountId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceAccountId);
}
if (PageSize != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListApiKeysRequest other) {
if (other == null) {
return;
}
if (other.ServiceAccountId.Length != 0) {
ServiceAccountId = other.ServiceAccountId;
}
if (other.PageSize != 0L) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ServiceAccountId = input.ReadString();
break;
}
case 16: {
PageSize = input.ReadInt64();
break;
}
case 26: {
PageToken = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ListApiKeysResponse : pb::IMessage<ListApiKeysResponse> {
private static readonly pb::MessageParser<ListApiKeysResponse> _parser = new pb::MessageParser<ListApiKeysResponse>(() => new ListApiKeysResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListApiKeysResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeysResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeysResponse(ListApiKeysResponse other) : this() {
apiKeys_ = other.apiKeys_.Clone();
nextPageToken_ = other.nextPageToken_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeysResponse Clone() {
return new ListApiKeysResponse(this);
}
/// <summary>Field number for the "api_keys" field.</summary>
public const int ApiKeysFieldNumber = 1;
private static readonly pb::FieldCodec<global::Yandex.Cloud.Iam.V1.ApiKey> _repeated_apiKeys_codec
= pb::FieldCodec.ForMessage(10, global::Yandex.Cloud.Iam.V1.ApiKey.Parser);
private readonly pbc::RepeatedField<global::Yandex.Cloud.Iam.V1.ApiKey> apiKeys_ = new pbc::RepeatedField<global::Yandex.Cloud.Iam.V1.ApiKey>();
/// <summary>
/// List of API keys.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Yandex.Cloud.Iam.V1.ApiKey> ApiKeys {
get { return apiKeys_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// This token allows you to get the next page of results for list requests. If the number of results
/// is larger than [ListApiKeysRequest.page_size], use
/// the [next_page_token] as the value
/// for the [ListApiKeysRequest.page_token] query parameter
/// in the next list request. Each subsequent list request will have its own
/// [next_page_token] to continue paging through the results.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListApiKeysResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListApiKeysResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!apiKeys_.Equals(other.apiKeys_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= apiKeys_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
apiKeys_.WriteTo(output, _repeated_apiKeys_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += apiKeys_.CalculateSize(_repeated_apiKeys_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListApiKeysResponse other) {
if (other == null) {
return;
}
apiKeys_.Add(other.apiKeys_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
apiKeys_.AddEntriesFrom(input, _repeated_apiKeys_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class CreateApiKeyRequest : pb::IMessage<CreateApiKeyRequest> {
private static readonly pb::MessageParser<CreateApiKeyRequest> _parser = new pb::MessageParser<CreateApiKeyRequest>(() => new CreateApiKeyRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CreateApiKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateApiKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateApiKeyRequest(CreateApiKeyRequest other) : this() {
serviceAccountId_ = other.serviceAccountId_;
description_ = other.description_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateApiKeyRequest Clone() {
return new CreateApiKeyRequest(this);
}
/// <summary>Field number for the "service_account_id" field.</summary>
public const int ServiceAccountIdFieldNumber = 1;
private string serviceAccountId_ = "";
/// <summary>
/// ID of the service account to create an API key for.
/// To get the service account ID, use a [yandex.cloud.iam.v1.ServiceAccountService.List] request.
/// If not specified, it defaults to the subject that made the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ServiceAccountId {
get { return serviceAccountId_; }
set {
serviceAccountId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 2;
private string description_ = "";
/// <summary>
/// Description of the API key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CreateApiKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CreateApiKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ServiceAccountId != other.ServiceAccountId) return false;
if (Description != other.Description) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ServiceAccountId.Length != 0) hash ^= ServiceAccountId.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ServiceAccountId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ServiceAccountId);
}
if (Description.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Description);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ServiceAccountId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceAccountId);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CreateApiKeyRequest other) {
if (other == null) {
return;
}
if (other.ServiceAccountId.Length != 0) {
ServiceAccountId = other.ServiceAccountId;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ServiceAccountId = input.ReadString();
break;
}
case 18: {
Description = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class CreateApiKeyResponse : pb::IMessage<CreateApiKeyResponse> {
private static readonly pb::MessageParser<CreateApiKeyResponse> _parser = new pb::MessageParser<CreateApiKeyResponse>(() => new CreateApiKeyResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CreateApiKeyResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateApiKeyResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateApiKeyResponse(CreateApiKeyResponse other) : this() {
apiKey_ = other.apiKey_ != null ? other.apiKey_.Clone() : null;
secret_ = other.secret_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateApiKeyResponse Clone() {
return new CreateApiKeyResponse(this);
}
/// <summary>Field number for the "api_key" field.</summary>
public const int ApiKeyFieldNumber = 1;
private global::Yandex.Cloud.Iam.V1.ApiKey apiKey_;
/// <summary>
/// ApiKey resource.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Yandex.Cloud.Iam.V1.ApiKey ApiKey {
get { return apiKey_; }
set {
apiKey_ = value;
}
}
/// <summary>Field number for the "secret" field.</summary>
public const int SecretFieldNumber = 2;
private string secret_ = "";
/// <summary>
/// Secret part of the API key. This secret key you may use in the requests for authentication.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Secret {
get { return secret_; }
set {
secret_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CreateApiKeyResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CreateApiKeyResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(ApiKey, other.ApiKey)) return false;
if (Secret != other.Secret) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (apiKey_ != null) hash ^= ApiKey.GetHashCode();
if (Secret.Length != 0) hash ^= Secret.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (apiKey_ != null) {
output.WriteRawTag(10);
output.WriteMessage(ApiKey);
}
if (Secret.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Secret);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (apiKey_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ApiKey);
}
if (Secret.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Secret);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CreateApiKeyResponse other) {
if (other == null) {
return;
}
if (other.apiKey_ != null) {
if (apiKey_ == null) {
ApiKey = new global::Yandex.Cloud.Iam.V1.ApiKey();
}
ApiKey.MergeFrom(other.ApiKey);
}
if (other.Secret.Length != 0) {
Secret = other.Secret;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (apiKey_ == null) {
ApiKey = new global::Yandex.Cloud.Iam.V1.ApiKey();
}
input.ReadMessage(ApiKey);
break;
}
case 18: {
Secret = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class UpdateApiKeyRequest : pb::IMessage<UpdateApiKeyRequest> {
private static readonly pb::MessageParser<UpdateApiKeyRequest> _parser = new pb::MessageParser<UpdateApiKeyRequest>(() => new UpdateApiKeyRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateApiKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateApiKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateApiKeyRequest(UpdateApiKeyRequest other) : this() {
apiKeyId_ = other.apiKeyId_;
updateMask_ = other.updateMask_ != null ? other.updateMask_.Clone() : null;
description_ = other.description_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateApiKeyRequest Clone() {
return new UpdateApiKeyRequest(this);
}
/// <summary>Field number for the "api_key_id" field.</summary>
public const int ApiKeyIdFieldNumber = 1;
private string apiKeyId_ = "";
/// <summary>
/// ID of the ApiKey resource to update.
/// To get the API key ID, use a [ApiKeyService.List] request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiKeyId {
get { return apiKeyId_; }
set {
apiKeyId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "update_mask" field.</summary>
public const int UpdateMaskFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.FieldMask updateMask_;
/// <summary>
/// Field mask that specifies which fields of the ApiKey resource are going to be updated.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.FieldMask UpdateMask {
get { return updateMask_; }
set {
updateMask_ = value;
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 3;
private string description_ = "";
/// <summary>
/// Description of the API key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateApiKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateApiKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ApiKeyId != other.ApiKeyId) return false;
if (!object.Equals(UpdateMask, other.UpdateMask)) return false;
if (Description != other.Description) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ApiKeyId.Length != 0) hash ^= ApiKeyId.GetHashCode();
if (updateMask_ != null) hash ^= UpdateMask.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ApiKeyId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ApiKeyId);
}
if (updateMask_ != null) {
output.WriteRawTag(18);
output.WriteMessage(UpdateMask);
}
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ApiKeyId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiKeyId);
}
if (updateMask_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateMask);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateApiKeyRequest other) {
if (other == null) {
return;
}
if (other.ApiKeyId.Length != 0) {
ApiKeyId = other.ApiKeyId;
}
if (other.updateMask_ != null) {
if (updateMask_ == null) {
UpdateMask = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
UpdateMask.MergeFrom(other.UpdateMask);
}
if (other.Description.Length != 0) {
Description = other.Description;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ApiKeyId = input.ReadString();
break;
}
case 18: {
if (updateMask_ == null) {
UpdateMask = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
input.ReadMessage(UpdateMask);
break;
}
case 26: {
Description = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class UpdateApiKeyMetadata : pb::IMessage<UpdateApiKeyMetadata> {
private static readonly pb::MessageParser<UpdateApiKeyMetadata> _parser = new pb::MessageParser<UpdateApiKeyMetadata>(() => new UpdateApiKeyMetadata());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateApiKeyMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateApiKeyMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateApiKeyMetadata(UpdateApiKeyMetadata other) : this() {
apiKeyId_ = other.apiKeyId_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateApiKeyMetadata Clone() {
return new UpdateApiKeyMetadata(this);
}
/// <summary>Field number for the "api_key_id" field.</summary>
public const int ApiKeyIdFieldNumber = 1;
private string apiKeyId_ = "";
/// <summary>
/// ID of the ApiKey resource that is being updated.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiKeyId {
get { return apiKeyId_; }
set {
apiKeyId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateApiKeyMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateApiKeyMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ApiKeyId != other.ApiKeyId) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ApiKeyId.Length != 0) hash ^= ApiKeyId.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ApiKeyId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ApiKeyId);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ApiKeyId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiKeyId);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateApiKeyMetadata other) {
if (other == null) {
return;
}
if (other.ApiKeyId.Length != 0) {
ApiKeyId = other.ApiKeyId;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ApiKeyId = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class DeleteApiKeyRequest : pb::IMessage<DeleteApiKeyRequest> {
private static readonly pb::MessageParser<DeleteApiKeyRequest> _parser = new pb::MessageParser<DeleteApiKeyRequest>(() => new DeleteApiKeyRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeleteApiKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteApiKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteApiKeyRequest(DeleteApiKeyRequest other) : this() {
apiKeyId_ = other.apiKeyId_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteApiKeyRequest Clone() {
return new DeleteApiKeyRequest(this);
}
/// <summary>Field number for the "api_key_id" field.</summary>
public const int ApiKeyIdFieldNumber = 1;
private string apiKeyId_ = "";
/// <summary>
/// ID of the API key to delete.
/// To get the API key ID, use a [ApiKeyService.List] request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiKeyId {
get { return apiKeyId_; }
set {
apiKeyId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeleteApiKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeleteApiKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ApiKeyId != other.ApiKeyId) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ApiKeyId.Length != 0) hash ^= ApiKeyId.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ApiKeyId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ApiKeyId);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ApiKeyId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiKeyId);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeleteApiKeyRequest other) {
if (other == null) {
return;
}
if (other.ApiKeyId.Length != 0) {
ApiKeyId = other.ApiKeyId;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ApiKeyId = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class DeleteApiKeyMetadata : pb::IMessage<DeleteApiKeyMetadata> {
private static readonly pb::MessageParser<DeleteApiKeyMetadata> _parser = new pb::MessageParser<DeleteApiKeyMetadata>(() => new DeleteApiKeyMetadata());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeleteApiKeyMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[8]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteApiKeyMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteApiKeyMetadata(DeleteApiKeyMetadata other) : this() {
apiKeyId_ = other.apiKeyId_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteApiKeyMetadata Clone() {
return new DeleteApiKeyMetadata(this);
}
/// <summary>Field number for the "api_key_id" field.</summary>
public const int ApiKeyIdFieldNumber = 1;
private string apiKeyId_ = "";
/// <summary>
/// ID of the API key that is being deleted.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiKeyId {
get { return apiKeyId_; }
set {
apiKeyId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeleteApiKeyMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeleteApiKeyMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ApiKeyId != other.ApiKeyId) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ApiKeyId.Length != 0) hash ^= ApiKeyId.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ApiKeyId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ApiKeyId);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ApiKeyId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiKeyId);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeleteApiKeyMetadata other) {
if (other == null) {
return;
}
if (other.ApiKeyId.Length != 0) {
ApiKeyId = other.ApiKeyId;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ApiKeyId = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ListApiKeyOperationsRequest : pb::IMessage<ListApiKeyOperationsRequest> {
private static readonly pb::MessageParser<ListApiKeyOperationsRequest> _parser = new pb::MessageParser<ListApiKeyOperationsRequest>(() => new ListApiKeyOperationsRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListApiKeyOperationsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[9]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeyOperationsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeyOperationsRequest(ListApiKeyOperationsRequest other) : this() {
apiKeyId_ = other.apiKeyId_;
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeyOperationsRequest Clone() {
return new ListApiKeyOperationsRequest(this);
}
/// <summary>Field number for the "api_key_id" field.</summary>
public const int ApiKeyIdFieldNumber = 1;
private string apiKeyId_ = "";
/// <summary>
/// ID of the key to list operations for.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiKeyId {
get { return apiKeyId_; }
set {
apiKeyId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 2;
private long pageSize_;
/// <summary>
/// The maximum number of results per page to return. If the number of available
/// results is larger than [page_size],
/// the service returns a [ListApiKeyOperationsResponse.next_page_token]
/// that can be used to get the next page of results in subsequent list requests.
/// Default value: 100.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 3;
private string pageToken_ = "";
/// <summary>
/// Page token. To get the next page of results, set [page_token] to the
/// [ListApiKeyOperationsResponse.next_page_token] returned by a previous list request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListApiKeyOperationsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListApiKeyOperationsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ApiKeyId != other.ApiKeyId) return false;
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ApiKeyId.Length != 0) hash ^= ApiKeyId.GetHashCode();
if (PageSize != 0L) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ApiKeyId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ApiKeyId);
}
if (PageSize != 0L) {
output.WriteRawTag(16);
output.WriteInt64(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(26);
output.WriteString(PageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ApiKeyId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiKeyId);
}
if (PageSize != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListApiKeyOperationsRequest other) {
if (other == null) {
return;
}
if (other.ApiKeyId.Length != 0) {
ApiKeyId = other.ApiKeyId;
}
if (other.PageSize != 0L) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ApiKeyId = input.ReadString();
break;
}
case 16: {
PageSize = input.ReadInt64();
break;
}
case 26: {
PageToken = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ListApiKeyOperationsResponse : pb::IMessage<ListApiKeyOperationsResponse> {
private static readonly pb::MessageParser<ListApiKeyOperationsResponse> _parser = new pb::MessageParser<ListApiKeyOperationsResponse>(() => new ListApiKeyOperationsResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListApiKeyOperationsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Yandex.Cloud.Iam.V1.ApiKeyServiceReflection.Descriptor.MessageTypes[10]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeyOperationsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeyOperationsResponse(ListApiKeyOperationsResponse other) : this() {
operations_ = other.operations_.Clone();
nextPageToken_ = other.nextPageToken_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListApiKeyOperationsResponse Clone() {
return new ListApiKeyOperationsResponse(this);
}
/// <summary>Field number for the "operations" field.</summary>
public const int OperationsFieldNumber = 1;
private static readonly pb::FieldCodec<global::Yandex.Cloud.Operation.Operation> _repeated_operations_codec
= pb::FieldCodec.ForMessage(10, global::Yandex.Cloud.Operation.Operation.Parser);
private readonly pbc::RepeatedField<global::Yandex.Cloud.Operation.Operation> operations_ = new pbc::RepeatedField<global::Yandex.Cloud.Operation.Operation>();
/// <summary>
/// List of operations for the specified API key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Yandex.Cloud.Operation.Operation> Operations {
get { return operations_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// This token allows you to get the next page of results for list requests. If the number of results
/// is larger than [ListApiKeyOperationsRequest.page_size], use the [next_page_token] as the value
/// for the [ListApiKeyOperationsRequest.page_token] query parameter in the next list request.
/// Each subsequent list request will have its own [next_page_token] to continue paging through the results.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListApiKeyOperationsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListApiKeyOperationsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!operations_.Equals(other.operations_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= operations_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
operations_.WriteTo(output, _repeated_operations_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += operations_.CalculateSize(_repeated_operations_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListApiKeyOperationsResponse other) {
if (other == null) {
return;
}
operations_.Add(other.operations_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
operations_.AddEntriesFrom(input, _repeated_operations_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 36.721633 | 395 | 0.6743 | [
"MIT"
] | mifopen/YandexCloudDotNet | src/YandexCloudDotNet/cloudapi/yandex/cloud/iam/v1/ApiKeyService.cs | 69,257 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Get a list of reseller administrators.
/// The response is either a ResellerAdminGetListResponse or an ErrorResponse.
/// <see cref="ResellerAdminGetListResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""b009175f2a2a9d38115e319a6ad64d7f:116""}]")]
public class ResellerAdminGetListRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private string _resellerId;
[XmlElement(ElementName = "resellerId", IsNullable = false, Namespace = "")]
[Group(@"b009175f2a2a9d38115e319a6ad64d7f:116")]
[MinLength(1)]
[MaxLength(30)]
public string ResellerId
{
get => _resellerId;
set
{
ResellerIdSpecified = true;
_resellerId = value;
}
}
[XmlIgnore]
protected bool ResellerIdSpecified { get; set; }
}
}
| 29.511628 | 129 | 0.638298 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/ResellerAdminGetListRequest.cs | 1,269 | C# |
using System;
using System.Threading;
using Shared;
namespace Server
{
class Program
{
static void Main(string[] args)
{
ByteTransfer.NetSettings.RegisterMessagePackResolvers(MessagePack.Resolvers.GeneratedResolver.Instance);
ByteTransfer.NetSettings.InstallPackets(typeof(Shared.ClientPackets.Login).Assembly);
var server = new ByteTransfer.NetServer<AuthSocket>("127.0.0.1", 3790);
server.StartNetwork();
while(true)
{
World.Process();
}
}
}
}
| 23.48 | 116 | 0.606474 | [
"MIT"
] | ryancheung/ByteTransfer | sample/Server/Program.cs | 589 | C# |
namespace R8
{
partial class FormFunction
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// FormFunction
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(534, 421);
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Margin = new System.Windows.Forms.Padding(2);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormFunction";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Function";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormFunction_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FormFunction_FormClosed);
this.Load += new System.EventHandler(this.FormFunction_Load);
this.ResumeLayout(false);
}
#endregion
}
} | 36.714286 | 112 | 0.588035 | [
"Unlicense"
] | alexcvig/OpenR8 | src/R8/R8_app/FormFunction.Designer.cs | 2,058 | C# |
/******************************************************************************
* Copyright (C) Ultraleap, Inc. 2011-2020. *
* Ultraleap proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Ultraleap and you, your company or other organization. *
******************************************************************************/
using UnityEditor;
using UnityEngine;
using Leap.Unity;
namespace Leap.Unity {
[InitializeOnLoad]
public class LeapUnityWindow : EditorWindow {
#region Settings & Init
private const string WINDOW_TITLE = "Leap Motion Unity Modules";
private static readonly Vector2 WINDOW_MIN_SIZE = new Vector2(600f, 600f);
private static LeapUnityWindow _currentWindow = null;
/// <summary>
/// This editor preference marks the Leap Unity SDK as having been launched. When
/// this is not detected, we can assume this is the first time the SDK has been
/// imported into an editor, so we open the window for discoverability.
/// </summary>
private const string LEAP_UNITY_WINDOW_LAUNCHED_PREF = "Leap Unity Window Launched";
/// <summary>
/// This static constructor is called as the editor launches due to the
/// InitializeOnLoad attribute on LeapUnityWindow.
/// </summary>
static LeapUnityWindow() {
EditorApplication.delayCall += () => {
if (!EditorPrefs.GetBool(LEAP_UNITY_WINDOW_LAUNCHED_PREF)) {
EditorPrefs.SetBool(LEAP_UNITY_WINDOW_LAUNCHED_PREF, true);
Init();
}
};
}
[MenuItem("Window/Leap Motion")]
public static void Init() {
var window = (LeapUnityWindow)GetWindow(typeof(LeapUnityWindow),
utility: true, title: WINDOW_TITLE, focus: true);
window.name = "Leap Motion Unity Modules Window";
window.minSize = WINDOW_MIN_SIZE;
_currentWindow = window;
}
#endregion
#region Resources
private string leapLogoResourceName {
get {
if (EditorGUIUtility.isProSkin) return "LM_Logo_White";
else return "LM_Logo_Black";
}
}
private Texture2D _backingLeapTex = null;
private Texture2D leapTex {
get {
if (_backingLeapTex == null) {
_backingLeapTex = EditorResources.Load<Texture2D>(leapLogoResourceName);
}
return _backingLeapTex;
}
}
private static GUISkin s_backingWindowSkin;
public static GUISkin windowSkin {
get {
if (s_backingWindowSkin == null) {
s_backingWindowSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene);
}
return s_backingWindowSkin;
}
}
#endregion
#region Window State
public static bool isWindowOpen {
get {
return _currentWindow != null;
}
}
private int _tabIndex = 0;
private static string[] _tabs = new string[] {
"Project Checks", "Rig Upgrader", "Preferences"
};
public static void ShowTab(int tabIndex) {
if (_currentWindow != null) {
_currentWindow._tabIndex = tabIndex;
}
}
public static int GetTabCount() { return _tabs.Length; }
private Vector2 _scrollPosition = Vector2.zero;
#endregion
#region OnGUI
private void OnGUI() {
var origSkin = GUI.skin;
try {
GUI.skin = windowSkin;
drawGUI();
}
finally {
GUI.skin = origSkin;
}
}
private void drawGUI() {
var boxStyle = windowSkin.box;
GUILayout.BeginVertical();
// Logo.
var logoStyle = windowSkin.box;
logoStyle.fixedHeight = 150;
logoStyle.stretchWidth = true;
logoStyle.alignment = TextAnchor.MiddleCenter;
logoStyle.margin = new RectOffset(0, 0, top: 20, bottom: 20);
GUILayout.Box(new GUIContent(leapTex), logoStyle, GUILayout.ExpandWidth(true),
GUILayout.MaxHeight(150f));
// Window tabs.
_tabIndex = GUILayout.Toolbar(_tabIndex, _tabs);
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition,
GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
switch (_tabIndex) {
case 0:
LeapProjectChecks.DrawProjectChecksGUI();
break;
case 1:
LeapRigUpgrader.DrawUpgraderGUI();
break;
case 2:
float prevLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 200;
LeapPreferences.DrawPreferencesGUI();
EditorGUIUtility.labelWidth = prevLabelWidth;
break;
default:
_tabIndex = 0;
break;
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
}
#endregion
}
}
| 29.760479 | 88 | 0.602616 | [
"BSD-3-Clause"
] | HyperLethalVector/ChristmasEsky | Assets/Plugins/LeapMotion/Core/Scripts/EditorTools/Editor/LeapUnityWindow.cs | 4,970 | C# |
using Newtonsoft.Json;
namespace PddOpenSdk.Models.Response.Promotion
{
public class PromotionCouponBatchCloseResponse
{
/// <summary>
/// Examples: true
/// </summary>
[JsonProperty("is_success")]
public bool IsSuccess { get; set; }
}
public class ClosePromotionCouponResponseModel
{
/// <summary>
/// Examples: {"is_success":true}
/// </summary>
[JsonProperty("promotion_coupon_batch_close_response")]
public PromotionCouponBatchCloseResponse PromotionCouponBatchCloseResponse { get; set; }
}
}
| 23.307692 | 96 | 0.635314 | [
"Apache-2.0"
] | gitter-badger/open-pdd-net-sdk | PddOpenSdk/PddOpenSdk/Models/Response/Promotion/ClosePromotionCouponResponseModel.cs | 606 | 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 Gov.Jag.Spice.Interfaces
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Companyduplicatebaserecord operations.
/// </summary>
public partial class Companyduplicatebaserecord : IServiceOperations<DynamicsClient>, ICompanyduplicatebaserecord
{
/// <summary>
/// Initializes a new instance of the Companyduplicatebaserecord class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Companyduplicatebaserecord(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get spice_company_DuplicateBaseRecord from spice_companies
/// </summary>
/// <param name='spiceCompanyid'>
/// key: spice_companyid of spice_company
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecordCollection>> GetWithHttpMessagesAsync(string spiceCompanyid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (spiceCompanyid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "spiceCompanyid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("spiceCompanyid", spiceCompanyid);
tracingParameters.Add("top", top);
tracingParameters.Add("skip", skip);
tracingParameters.Add("search", search);
tracingParameters.Add("filter", filter);
tracingParameters.Add("count", count);
tracingParameters.Add("orderby", orderby);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "spice_companies({spice_companyid})/spice_company_DuplicateBaseRecord").ToString();
_url = _url.Replace("{spice_companyid}", System.Uri.EscapeDataString(spiceCompanyid));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (skip != null)
{
_queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
}
if (search != null)
{
_queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (count != null)
{
_queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (orderby != null)
{
_queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby))));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecordCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMduplicaterecordCollection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get spice_company_DuplicateBaseRecord from spice_companies
/// </summary>
/// <param name='spiceCompanyid'>
/// key: spice_companyid of spice_company
/// </param>
/// <param name='duplicateid'>
/// key: duplicateid of duplicaterecord
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecord>> DuplicateBaseRecordByKeyWithHttpMessagesAsync(string spiceCompanyid, string duplicateid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (spiceCompanyid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "spiceCompanyid");
}
if (duplicateid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "duplicateid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("spiceCompanyid", spiceCompanyid);
tracingParameters.Add("duplicateid", duplicateid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DuplicateBaseRecordByKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "spice_companies({spice_companyid})/spice_company_DuplicateBaseRecord({duplicateid})").ToString();
_url = _url.Replace("{spice_companyid}", System.Uri.EscapeDataString(spiceCompanyid));
_url = _url.Replace("{duplicateid}", System.Uri.EscapeDataString(duplicateid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecord>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMduplicaterecord>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 44.765808 | 555 | 0.567094 | [
"Apache-2.0"
] | BrendanBeachBC/jag-spd-spice | interfaces/Dynamics-Autorest/Companyduplicatebaserecord.cs | 19,115 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModBotInstaller
{
[Serializable]
public class FirebaseModInfo
{
[JsonProperty("checked")]
public bool Checked;
[JsonProperty("creatorID")]
public string Creator;
[JsonProperty("description")]
public string Description;
[JsonProperty("downloadLink")]
public string DownloadLink;
[JsonProperty("imageLink")]
public string ImageDownloadLink;
[JsonProperty("name")]
public string ModName;
[JsonProperty("uniqueId")]
public string ModID;
}
}
| 20.628571 | 40 | 0.648199 | [
"MIT"
] | X606/ModBot-Launcher | ModBotInstaller/FirebaseModInfo.cs | 724 | C# |
using FubuCore.Configuration;
using FubuCore.Conversion;
using FubuMVC.Core.StructureMap;
using Shouldly;
using NUnit.Framework;
using StructureMap;
namespace FubuMVC.Tests.StructureMap.Internals
{
[TestFixture]
public class AppSettingProviderRegistrySmokeTester
{
[SetUp]
public void SetUp()
{
}
[Test]
public void can_build_an_app_settings_provider_object()
{
var container = new Container(new AppSettingProviderRegistry());
container.GetInstance<AppSettingsProvider>().ShouldNotBeNull();
}
[Test]
public void can_build_the_object_converter()
{
var container = new Container(new AppSettingProviderRegistry());
container.GetInstance<IObjectConverter>().ShouldNotBeNull();
}
}
} | 26.28125 | 76 | 0.662307 | [
"Apache-2.0"
] | DarthFubuMVC/fubumvc | src/FubuMVC.Tests/StructureMap/Internals/AppSettingProviderRegistrySmokeTester.cs | 841 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace WorldCities.Data.Models
{
public class City
{
#region Constructor
public City()
{
}
#endregion
#region Properties
/// <summary>
/// The unique id and primary key for this City
/// </summary>
[Key]
[Required]
public int Id { get; set; }
/// <summary>
/// City name (in UTF8 format)
/// </summary>
public string Name { get; set; }
/// <summary>
/// City name (in ASCII format)
/// </summary>
public string Name_ASCII { get; set; }
/// <summary>
/// City latitude
/// </summary>
[Column(TypeName = "decimal(7,4)")]
public decimal Lat { get; set; }
/// <summary>
/// City longitude
/// </summary>
[Column(TypeName = "decimal(7,4)")]
public decimal Lon { get; set; }
/// <summary>
/// Country Id (foreign key)
/// </summary>
[ForeignKey("Country")]
public int CountryId { get; set; }
#endregion
#region Navigation Properties
/// <summary>
/// The country related to this city.
/// </summary>
public virtual Country Country { get; set; }
#endregion
}
}
| 23.578125 | 55 | 0.526176 | [
"MIT"
] | Islam-Samy/ASP.NET-Core-3-and-Angular-9-Third-Edition | Chapter_04/WorldCities/Data/Models/City.cs | 1,511 | 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.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListSecurityProfilesForTarget operation
/// </summary>
public class ListSecurityProfilesForTargetResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListSecurityProfilesForTargetResponse response = new ListSecurityProfilesForTargetResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("nextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("securityProfileTargetMappings", targetDepth))
{
var unmarshaller = new ListUnmarshaller<SecurityProfileTargetMapping, SecurityProfileTargetMappingUnmarshaller>(SecurityProfileTargetMappingUnmarshaller.Instance);
response.SecurityProfileTargetMappings = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException"))
{
return InternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException"))
{
return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonIoTException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListSecurityProfilesForTargetResponseUnmarshaller _instance = new ListSecurityProfilesForTargetResponseUnmarshaller();
internal static ListSecurityProfilesForTargetResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListSecurityProfilesForTargetResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.421875 | 186 | 0.650321 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/ListSecurityProfilesForTargetResponseUnmarshaller.cs | 5,302 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Kraken.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
} | 42.745614 | 261 | 0.553099 | [
"MIT"
] | a-West/kraken-api | Kraken.Api/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs | 19,492 | C# |
/*
* ARXivar Workflow API
*
* ARXivar Workflow API
*
* OpenAPI spec version: v1
* Contact: info@abletech.it
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
namespace IO.Swagger.Workflow.Client
{
/// <summary>
/// Represents configuration aspects required to interact with the API endpoints.
/// </summary>
public interface IApiAccessor
{
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
Configuration Configuration {get; set;}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
String GetBasePath();
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
ExceptionFactory ExceptionFactory { get; set; }
}
}
| 25.714286 | 85 | 0.622222 | [
"Apache-2.0"
] | zanardini/ARXivarNext-WebApi | ARXivarNext-ConsumingWebApi/IO.Swagger.Workflow/Client/IApiAccessor.cs | 1,080 | C# |
using System;
class ChristmasTree
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
for (int i = 0; i <= n; i++)
{
Console.WriteLine(new string(' ', n - i) + new string('*', i) + " | " + new string('*',i));
}
}
}
| 17.875 | 104 | 0.447552 | [
"MIT"
] | pavlinpetkov88/ProgramingBasic | DrawingWithLoops/ChristmasTree/ChristmasTree.cs | 288 | C# |
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
namespace prvncher.XR_Interaction.XRToolkitExtensions
{
/// <summary>
/// Allows object to be held at the grab point, rather than object center
/// Code taken from: https://www.youtube.com/watch?v=-a36GpPkW-Q&feature=emb_title
/// </summary>
public class XROffsetGrabInteractable : XRGrabInteractable
{
private Vector3 interactorPosition = Vector3.zero;
private Quaternion interactorRotation = Quaternion.identity;
protected override void OnSelectEnter(XRBaseInteractor interactor)
{
base.OnSelectEnter(interactor);
StoreInteractor(interactor);
MatchAttachmentPoints(interactor);
}
protected override void OnSelectExit(XRBaseInteractor interactor)
{
base.OnSelectExit(interactor);
ResetAttachementPoints(interactor);
ResetInteractor();
}
private void StoreInteractor(XRBaseInteractor interactor)
{
interactorPosition = interactor.attachTransform.localPosition;
interactorRotation = interactor.attachTransform.localRotation;
}
private void ResetInteractor()
{
interactorPosition = Vector3.zero;
interactorRotation = Quaternion.identity;
}
private void MatchAttachmentPoints(XRBaseInteractor interactor)
{
bool hasAttach = attachTransform != null;
interactor.attachTransform.position = hasAttach ? attachTransform.position : transform.position;
interactor.attachTransform.rotation = hasAttach ? attachTransform.rotation : transform.rotation;
}
private void ResetAttachementPoints(XRBaseInteractor interactor)
{
interactor.attachTransform.localPosition = interactorPosition;
interactor.attachTransform.localRotation = interactorRotation;
}
}
}
| 35.392857 | 108 | 0.675076 | [
"MIT"
] | provencher/XR-Interaction | Assets/XR_Interaction/Scripts/XRToolkitExtensions/XROffsetGrabInteractable.cs | 1,984 | C# |
using Newtonsoft.Json;
namespace ComicVineApi.Models
{
public class IssueReference : ComicVineObject
{
[JsonProperty("issue_number")]
public string? IssueNumber { get; set; }
}
}
| 19 | 49 | 0.665072 | [
"MIT"
] | mattleibow/ComicVineApi | ComicVineApi/Models/Issue/IssueReference.cs | 211 | 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 comprehend-2017-11-27.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.Comprehend.Model
{
/// <summary>
/// The specified resource is not available. Check the resource and try your request again.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class ResourceUnavailableException : AmazonComprehendException
{
/// <summary>
/// Constructs a new ResourceUnavailableException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ResourceUnavailableException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ResourceUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ResourceUnavailableException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ResourceUnavailableException
/// </summary>
/// <param name="innerException"></param>
public ResourceUnavailableException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ResourceUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ResourceUnavailableException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ResourceUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ResourceUnavailableException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the ResourceUnavailableException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected ResourceUnavailableException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 48.75 | 179 | 0.66981 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Comprehend/Generated/Model/ResourceUnavailableException.cs | 6,045 | C# |
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. 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.
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.
******************************************************************************/
namespace Tensorflow
{
public class FreezeGraph
{
public static void freeze_graph(string input_graph,
string input_saver,
bool input_binary,
string input_checkpoint,
string output_node_names,
string restore_op_name,
string filename_tensor_name,
string output_graph,
bool clear_devices,
string initializer_nodes)
{
}
}
}
| 39.083333 | 79 | 0.52452 | [
"Apache-2.0"
] | Aangbaeck/TensorFlow.NET | src/TensorFlowNET.Core/Graphs/FreezeGraph.cs | 1,409 | C# |
// Instance generated by TankLibHelper.InstanceBuilder
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0x4F480255)]
public class STU_4F480255 : STUConfigVarEntityID {
}
}
| 22.777778 | 54 | 0.756098 | [
"MIT"
] | Mike111177/OWLib | TankLib/STU/Types/STU_4F480255.cs | 205 | C# |
//// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
//// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
//// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
//// See the LICENSE.md file in the project root for full license information.
//
//using System;
//
//using Stride.Core;
//using Stride.Core.IO;
//using Stride.Core.Serialization.Assets;
//using Stride.Engine;
//
//using Xunit;
//
//namespace Stride.Audio.Tests
//{
// /// <summary>
// /// Tests for <see cref="AudioEngine"/>
// /// </summary>
//// public class TestAudioEngine
// {
// [TestFixtureSetUp]
// public void Initialize()
// {
// Game.InitializeAssetDatabase();
// }
//
// /// <summary>
// /// Test that audio engine initializes and disposes correctly without exceptions.
// /// If no audio hardware is activated or no output are connected, the AudioInitializationException should be thrown.
// /// </summary>
// [Fact]
// public void ContextInitialization()
// {
// try
// {
// var engine = AudioEngineFactory.NewAudioEngine();
// engine.Dispose();
// }
// catch (Exception e)
// {
// Assert.True(e is AudioInitializationException, "Audio engine failed to initialize but did not throw AudioInitializationException");
// }
// }
//
// /// <summary>
// /// Test that there are no crashes when shutting down the engine with not disposed soundEffects.
// /// </summary>
// [Fact]
// public void TestDispose()
// {
// var crossDisposedEngine = AudioEngineFactory.NewAudioEngine();
// var engine = AudioEngineFactory.NewAudioEngine();
// crossDisposedEngine.Dispose(); // Check there no Dispose problems with sereval cross-disposed instances.
//
// // Create some SoundEffects
// SoundEffect soundEffect;
// using (var wavStream = ContentManager.FileProvider.OpenStream("EffectBip", VirtualFileMode.Open, VirtualFileAccess.Read))
// {
// soundEffect = SoundEffect.Load(engine, wavStream);
// }
// SoundEffect dispSoundEffect;
// using (var wavStream = ContentManager.FileProvider.OpenStream("EffectBip", VirtualFileMode.Open, VirtualFileAccess.Read))
// {
// dispSoundEffect = SoundEffect.Load(engine, wavStream);
// }
// dispSoundEffect.Dispose();
//
// var soundEffectInstance = soundEffect.CreateInstance();
// var dispInstance = soundEffect.CreateInstance();
// dispInstance.Dispose();
//
// // Create some SoundMusics.
// var soundMusic1 = SoundMusic.Load(engine, ContentManager.FileProvider.OpenStream("MusicBip", VirtualFileMode.Open, VirtualFileAccess.Read));
// var soundMusic2 = SoundMusic.Load(engine, ContentManager.FileProvider.OpenStream("MusicToneA", VirtualFileMode.Open, VirtualFileAccess.Read));
// soundMusic2.Dispose();
//
// // Create some dynamicSounds.
// var generator = new SoundGenerator();
// var dynSound1 = new DynamicSoundEffectInstance(engine, 44100, AudioChannels.Mono, AudioDataEncoding.PCM_8Bits);
// var dynSound2 = new DynamicSoundEffectInstance(engine, 20000, AudioChannels.Mono, AudioDataEncoding.PCM_8Bits);
// dynSound1.Play();
// dynSound1.SubmitBuffer(generator.Generate(44100, new[]{ 1000f }, 1, 120000));
// dynSound2.Dispose();
//
// // Start playing some
// soundEffectInstance.Play();
// soundMusic1.Play();
//
// for (int i = 0; i < 10; i++)
// {
// engine.Update();
// Utilities.Sleep(5);
// }
//
// Assert.DoesNotThrow(engine.Dispose, "AudioEngine crashed during disposal.");
// Assert.True(soundEffect.IsDisposed, "SoundEffect is not disposed.");
// Assert.Throws<InvalidOperationException>(engine.Dispose, "AudioEngine did not threw invalid operation exception.");
// Assert.Equal(SoundPlayState.Stopped, soundEffectInstance.PlayState, "SoundEffectInstance has not been stopped properly.");
// Assert.True(soundEffectInstance.IsDisposed, "SoundEffectInstance has not been disposed properly.");
// Assert.Equal(SoundPlayState.Stopped, soundMusic1.PlayState, "soundMusic1 has not been stopped properly.");
// Assert.True(soundMusic1.IsDisposed, "soundMusic1 has not been disposed properly.");
// //Assert.Equal(SoundPlayState.Stopped, dynSound1.PlayState, "The dynamic sound 1 has not been stopped correctly.");
// //Assert.True(dynSound1.IsDisposed, "The dynamic sound 1 has not been disposed correctly.");
// }
//
// /// <summary>
// /// Test the behavior of <see cref="AudioEngine.GetLeastSignificativeSoundEffect"/>
// /// </summary>
// [Fact]
// public void TestGetLeastSignificativeSoundEffect()
// {
// var engine = AudioEngineFactory.NewAudioEngine();
//
// //////////////////////////////////////////
// // 1. Test that it returns null by default
// Assert.Equal(null, engine.GetLeastSignificativeSoundEffect());
//
// // create a sound effect
// SoundEffect soundEffect;
// using (var wavStream = ContentManager.FileProvider.OpenStream("EffectBip", VirtualFileMode.Open, VirtualFileAccess.Read))
// soundEffect = SoundEffect.Load(engine, wavStream);
//
// /////////////////////////////////////////////////////////////////////
// // 2. Test that is returns null when there is no playing sound effect
// Assert.Equal(null, engine.GetLeastSignificativeSoundEffect());
//
// /////////////////////////////////////////////////////////////////////////////////
// // 3. Test that is returns null when there is no not looped sound effect playing
// soundEffect.IsLooped = true;
// soundEffect.Play();
// Assert.Equal(null, engine.GetLeastSignificativeSoundEffect());
//
// ////////////////////////////////////////////////////////////////////////////
// // 4. Test that the sound effect is returned if not playing and not looped
// soundEffect.Stop();
// soundEffect.IsLooped = false;
// soundEffect.Play();
// Assert.Equal(soundEffect, engine.GetLeastSignificativeSoundEffect());
//
// // create another longer sound effect
// SoundEffect longerSoundEffect;
// using (var wavStream = ContentManager.FileProvider.OpenStream("EffectStereo", VirtualFileMode.Open, VirtualFileAccess.Read))
// longerSoundEffect = SoundEffect.Load(engine, wavStream);
//
// ///////////////////////////////////////////////////////////////////////
// // 5. Test that the longest sound is returned if it is the only playing
// soundEffect.Stop();
// longerSoundEffect.Play();
// Assert.Equal(longerSoundEffect, engine.GetLeastSignificativeSoundEffect());
//
// //////////////////////////////////////////////////////////////
// // 6. Test that the shortest sound is returned if both playing
// longerSoundEffect.Play();
// soundEffect.Play();
// Assert.Equal(soundEffect, engine.GetLeastSignificativeSoundEffect());
//
// //////////////////////////////////////////////////////////////////////
// // 7. Test that the longest sound is returned if the other is looped
// soundEffect.Stop();
// soundEffect.IsLooped = true;
// soundEffect.Play();
// longerSoundEffect.Play();
// Assert.Equal(longerSoundEffect, engine.GetLeastSignificativeSoundEffect());
//
// engine.Dispose();
// }
//
// /// <summary>
// /// Test the behavior of <see cref="AudioEngine.State"/>
// /// </summary>
// [Fact]
// public void TestState()
// {
// // test initial state
// var engine = AudioEngineFactory.NewAudioEngine();
// Assert.Equal(AudioEngineState.Running, engine.State);
//
// // test state after pause
// engine.PauseAudio();
// Assert.Equal(AudioEngineState.Paused, engine.State);
//
// // test state after resume
// engine.ResumeAudio();
// Assert.Equal(AudioEngineState.Running, engine.State);
//
// // test state after dispose
// engine.Dispose();
// Assert.Equal(AudioEngineState.Disposed, engine.State);
//
// // test that state remains dispose
// engine.PauseAudio();
// Assert.Equal(AudioEngineState.Disposed, engine.State);
// engine.ResumeAudio();
// Assert.Equal(AudioEngineState.Disposed, engine.State);
// }
//
// /// <summary>
// /// Test the behavior of <see cref="AudioEngine.PauseAudio"/>
// /// </summary>
// [Fact]
// public void TestPauseAudio()
// {
// var engine = AudioEngineFactory.NewAudioEngine();
//
// // create a sound effect instance
// SoundEffect soundEffect;
// using (var wavStream = ContentManager.FileProvider.OpenStream("EffectBip", VirtualFileMode.Open, VirtualFileAccess.Read))
// soundEffect = SoundEffect.Load(engine, wavStream);
// var wave1Instance = soundEffect.CreateInstance();
//
// // create a music instance
// var music = SoundMusic.Load(engine, ContentManager.FileProvider.OpenStream("MusicFishLampMp3", VirtualFileMode.Open, VirtualFileAccess.Read));
//
// // check state
// engine.PauseAudio();
// Assert.Equal(AudioEngineState.Paused, engine.State);
//
// // check that existing instance can not be played
// wave1Instance.Play();
// Assert.Equal(SoundPlayState.Stopped, wave1Instance.PlayState);
// music.Play();
// Assert.Equal(SoundPlayState.Stopped, music.PlayState);
// TestAudioUtilities.ActiveAudioEngineUpdate(engine, 1000); // listen that nothing comes out
//
// // create a new sound effect
// SoundEffect soundEffectStereo;
// using (var wavStream = ContentManager.FileProvider.OpenStream("EffectStereo", VirtualFileMode.Open, VirtualFileAccess.Read))
// soundEffectStereo = SoundEffect.Load(engine, wavStream);
//
// // check that a new instance can not be played
// soundEffectStereo.Play();
// Assert.Equal(SoundPlayState.Stopped, soundEffectStereo.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// // check that a stopped sound stay stopped
// engine.ResumeAudio();
// soundEffectStereo.Stop();
// engine.PauseAudio();
// Assert.Equal(SoundPlayState.Stopped, soundEffectStereo.PlayState);
//
// // check that a paused sound stay paused
// engine.ResumeAudio();
// soundEffectStereo.Play();
// soundEffectStereo.Pause();
// engine.PauseAudio();
// Assert.Equal(SoundPlayState.Paused, soundEffectStereo.PlayState);
//
// // check that a playing sound is paused
// engine.ResumeAudio();
// wave1Instance.Play();
// soundEffectStereo.Play();
// music.Play();
// engine.PauseAudio();
// Assert.Equal(SoundPlayState.Paused, wave1Instance.PlayState);
// Assert.Equal(SoundPlayState.Paused, soundEffectStereo.PlayState);
// Assert.Equal(SoundPlayState.Paused, music.PlayState);
// TestAudioUtilities.ActiveAudioEngineUpdate(engine, 1000); // listen that nothing comes out
//
// // check that stopping a sound while paused is possible
// engine.PauseAudio();
// soundEffectStereo.Stop();
// Assert.Equal(SoundPlayState.Stopped, soundEffectStereo.PlayState);
//
// // check that disposing a sound while paused is possible
// engine.PauseAudio();
// music.Dispose();
// Assert.True(music.IsDisposed);
//
// soundEffect.Dispose();
// soundEffectStereo.Dispose();
// }
//
// /// <summary>
// /// Test the behavior of <see cref="AudioEngine.ResumeAudio"/>
// /// </summary>
// [Fact]
// public void TestResumeAudio()
// {
// var engine = AudioEngineFactory.NewAudioEngine();
//
// // create a sound effect instance
// SoundEffect soundEffect;
// using (var wavStream = ContentManager.FileProvider.OpenStream("EffectBip", VirtualFileMode.Open, VirtualFileAccess.Read))
// soundEffect = SoundEffect.Load(engine, wavStream);
// var wave1Instance = soundEffect.CreateInstance();
//
// // create a music instance
// var music = SoundMusic.Load(engine, ContentManager.FileProvider.OpenStream("MusicFishLampMp3", VirtualFileMode.Open, VirtualFileAccess.Read));
//
// // check that resume do not play stopped instances
// engine.PauseAudio();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Stopped, music.PlayState);
// Assert.Equal(SoundPlayState.Stopped, wave1Instance.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// // check that user paused music does not resume
// wave1Instance.Play();
// wave1Instance.Pause();
// engine.PauseAudio();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Paused, wave1Instance.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// // check that sounds paused by PauseAudio are correctly restarted
// wave1Instance.Play();
// music.Play();
// engine.PauseAudio();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Playing, wave1Instance.PlayState);
// Assert.Equal(SoundPlayState.Playing, music.PlayState);
// TestAudioUtilities.ActiveAudioEngineUpdate(engine, 3000);// listen that the sound comes out
// music.Stop();
// TestAudioUtilities.ActiveAudioEngineUpdate(engine, 100);// stop the music
//
// // check that a sound stopped during the pause does not play during the resume
// wave1Instance.Play();
// engine.PauseAudio();
// wave1Instance.Stop();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Stopped, wave1Instance.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// // check that a sound played during the pause do not play during the resume
// engine.PauseAudio();
// wave1Instance.Play();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Stopped, wave1Instance.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// // check that a two calls to resume do not have side effects (1)
// wave1Instance.Play();
// engine.PauseAudio();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Playing, wave1Instance.PlayState);
// Utilities.Sleep(2000); // wait that the sound is finished
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Stopped, wave1Instance.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// // check that a two calls to resume do not have side effects (2)
// wave1Instance.Play();
// engine.PauseAudio();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Playing, wave1Instance.PlayState);
// wave1Instance.Pause();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Paused, wave1Instance.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// // check that a several calls to pause/play do not have side effects
// wave1Instance.Play();
// engine.PauseAudio();
// engine.ResumeAudio();
// engine.PauseAudio();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Playing, wave1Instance.PlayState);
// Utilities.Sleep(2000); // listen that the sound comes out
//
// // check that the sound is not played if disposed
// wave1Instance.Play();
// engine.PauseAudio();
// wave1Instance.Dispose();
// engine.ResumeAudio();
// Assert.Equal(SoundPlayState.Stopped, wave1Instance.PlayState);
// Utilities.Sleep(1000); // listen that nothing comes out
//
// music.Dispose();
// soundEffect.Dispose();
// }
// }
//}
| 46.852941 | 156 | 0.577869 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Audio.Tests/TestAudioEngine.cs | 17,523 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// 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("ServiceCodeSupport.Core.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServiceCodeSupport.Core.Test")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3132d84f-0e0c-4c22-92eb-40f018f209ad")]
// 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")] | 39.542857 | 84 | 0.747832 | [
"MIT"
] | GuidanceAutomation/ServiceCodeSupport | tests/ServiceCodeSupport.Core.Test/Properties/AssemblyInfo.cs | 1,387 | C# |
// ------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------------------------------------------------------------------------------
namespace GraphWebApi.Common
{
internal static class Constants
{
public const string DefaultLocale = "en-US"; // default locale language
internal static class ClaimTypes
{
// User Principal Name
public const string UpnJwt = "preferred_username";
public const string UpnUriSchema = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn";
}
}
}
| 47.631579 | 154 | 0.432044 | [
"MIT"
] | LokiLabs/microsoft-graph-devx-api | GraphWebApi/Common/Constants.cs | 907 | C# |
using System;
using System.Linq;
using System.Text;
using Kafka.Client.Request;
using Kafka.Client.Util;
using NUnit.Framework;
namespace Kafka.Client.Request.Tests
{
/// <summary>
/// Tests the <see cref="OffsetRequest"/> class.
/// </summary>
[TestFixture]
public class OffsetRequestTests
{
/// <summary>
/// Tests a valid request.
/// </summary>
[Test]
public void IsValidTrue()
{
FetchRequest request = new FetchRequest("topic", 1, 10L, 100);
Assert.IsTrue(request.IsValid());
}
/// <summary>
/// Tests a invalid request with no topic.
/// </summary>
[Test]
public void IsValidNoTopic()
{
FetchRequest request = new FetchRequest(" ", 1, 10L, 100);
Assert.IsFalse(request.IsValid());
}
/// <summary>
/// Tests a invalid request with no topic.
/// </summary>
[Test]
public void IsValidNulltopic()
{
FetchRequest request = new FetchRequest(null, 1, 10L, 100);
Assert.IsFalse(request.IsValid());
}
/// <summary>
/// Validates the list of bytes meet Kafka expectations.
/// </summary>
[Test]
public void GetBytesValid()
{
string topicName = "topic";
OffsetRequest request = new OffsetRequest(topicName, 0, OffsetRequest.LatestTime, 10);
// format = len(request) + requesttype + len(topic) + topic + partition + time + max
// total byte count = 4 + (2 + 2 + 5 + 4 + 8 + 4)
byte[] bytes = request.GetBytes();
Assert.IsNotNull(bytes);
Assert.AreEqual(29, bytes.Length);
// first 4 bytes = the length of the request
Assert.AreEqual(25, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Take(4).ToArray<byte>()), 0));
// next 2 bytes = the RequestType which in this case should be Produce
Assert.AreEqual((short)RequestType.Offsets, BitConverter.ToInt16(BitWorks.ReverseBytes(bytes.Skip(4).Take(2).ToArray<byte>()), 0));
// next 2 bytes = the length of the topic
Assert.AreEqual((short)5, BitConverter.ToInt16(BitWorks.ReverseBytes(bytes.Skip(6).Take(2).ToArray<byte>()), 0));
// next 5 bytes = the topic
Assert.AreEqual(topicName, Encoding.ASCII.GetString(bytes.Skip(8).Take(5).ToArray<byte>()));
// next 4 bytes = the partition
Assert.AreEqual(0, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Skip(13).Take(4).ToArray<byte>()), 0));
// next 8 bytes = time
Assert.AreEqual(OffsetRequest.LatestTime, BitConverter.ToInt64(BitWorks.ReverseBytes(bytes.Skip(17).Take(8).ToArray<byte>()), 0));
// next 4 bytes = max offsets
Assert.AreEqual(10, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Skip(25).Take(4).ToArray<byte>()), 0));
}
}
}
| 35.964286 | 143 | 0.581927 | [
"Apache-2.0"
] | MarcAMartin/kafka | clients/csharp/src/Kafka/Tests/Kafka.Client.Tests/Request/OffsetRequestTests.cs | 3,023 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.